View.java revision 725fc438a1399db0155af9ea819abdd66861dc51
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.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.Property;
60import android.util.SparseArray;
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_longClickable
627 * @attr ref android.R.styleable#View_minHeight
628 * @attr ref android.R.styleable#View_minWidth
629 * @attr ref android.R.styleable#View_nextFocusDown
630 * @attr ref android.R.styleable#View_nextFocusLeft
631 * @attr ref android.R.styleable#View_nextFocusRight
632 * @attr ref android.R.styleable#View_nextFocusUp
633 * @attr ref android.R.styleable#View_onClick
634 * @attr ref android.R.styleable#View_padding
635 * @attr ref android.R.styleable#View_paddingBottom
636 * @attr ref android.R.styleable#View_paddingLeft
637 * @attr ref android.R.styleable#View_paddingRight
638 * @attr ref android.R.styleable#View_paddingTop
639 * @attr ref android.R.styleable#View_paddingStart
640 * @attr ref android.R.styleable#View_paddingEnd
641 * @attr ref android.R.styleable#View_saveEnabled
642 * @attr ref android.R.styleable#View_rotation
643 * @attr ref android.R.styleable#View_rotationX
644 * @attr ref android.R.styleable#View_rotationY
645 * @attr ref android.R.styleable#View_scaleX
646 * @attr ref android.R.styleable#View_scaleY
647 * @attr ref android.R.styleable#View_scrollX
648 * @attr ref android.R.styleable#View_scrollY
649 * @attr ref android.R.styleable#View_scrollbarSize
650 * @attr ref android.R.styleable#View_scrollbarStyle
651 * @attr ref android.R.styleable#View_scrollbars
652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
653 * @attr ref android.R.styleable#View_scrollbarFadeDuration
654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbVertical
657 * @attr ref android.R.styleable#View_scrollbarTrackVertical
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
660 * @attr ref android.R.styleable#View_soundEffectsEnabled
661 * @attr ref android.R.styleable#View_tag
662 * @attr ref android.R.styleable#View_textAlignment
663 * @attr ref android.R.styleable#View_transformPivotX
664 * @attr ref android.R.styleable#View_transformPivotY
665 * @attr ref android.R.styleable#View_translationX
666 * @attr ref android.R.styleable#View_translationY
667 * @attr ref android.R.styleable#View_visibility
668 *
669 * @see android.view.ViewGroup
670 */
671public class View implements Drawable.Callback, KeyEvent.Callback,
672        AccessibilityEventSource {
673    private static final boolean DBG = false;
674
675    /**
676     * The logging tag used by this class with android.util.Log.
677     */
678    protected static final String VIEW_LOG_TAG = "View";
679
680    /**
681     * When set to true, apps will draw debugging information about their layouts.
682     *
683     * @hide
684     */
685    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
686
687    /**
688     * Used to mark a View that has no ID.
689     */
690    public static final int NO_ID = -1;
691
692    /**
693     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
694     * calling setFlags.
695     */
696    private static final int NOT_FOCUSABLE = 0x00000000;
697
698    /**
699     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
700     * setFlags.
701     */
702    private static final int FOCUSABLE = 0x00000001;
703
704    /**
705     * Mask for use with setFlags indicating bits used for focus.
706     */
707    private static final int FOCUSABLE_MASK = 0x00000001;
708
709    /**
710     * This view will adjust its padding to fit sytem windows (e.g. status bar)
711     */
712    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
713
714    /**
715     * This view is visible.
716     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
717     * android:visibility}.
718     */
719    public static final int VISIBLE = 0x00000000;
720
721    /**
722     * This view is invisible, but it still takes up space for layout purposes.
723     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
724     * android:visibility}.
725     */
726    public static final int INVISIBLE = 0x00000004;
727
728    /**
729     * This view is invisible, and it doesn't take any space for layout
730     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
731     * android:visibility}.
732     */
733    public static final int GONE = 0x00000008;
734
735    /**
736     * Mask for use with setFlags indicating bits used for visibility.
737     * {@hide}
738     */
739    static final int VISIBILITY_MASK = 0x0000000C;
740
741    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
742
743    /**
744     * This view is enabled. Interpretation varies by subclass.
745     * Use with ENABLED_MASK when calling setFlags.
746     * {@hide}
747     */
748    static final int ENABLED = 0x00000000;
749
750    /**
751     * This view is disabled. Interpretation varies by subclass.
752     * Use with ENABLED_MASK when calling setFlags.
753     * {@hide}
754     */
755    static final int DISABLED = 0x00000020;
756
757   /**
758    * Mask for use with setFlags indicating bits used for indicating whether
759    * this view is enabled
760    * {@hide}
761    */
762    static final int ENABLED_MASK = 0x00000020;
763
764    /**
765     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
766     * called and further optimizations will be performed. It is okay to have
767     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
768     * {@hide}
769     */
770    static final int WILL_NOT_DRAW = 0x00000080;
771
772    /**
773     * Mask for use with setFlags indicating bits used for indicating whether
774     * this view is will draw
775     * {@hide}
776     */
777    static final int DRAW_MASK = 0x00000080;
778
779    /**
780     * <p>This view doesn't show scrollbars.</p>
781     * {@hide}
782     */
783    static final int SCROLLBARS_NONE = 0x00000000;
784
785    /**
786     * <p>This view shows horizontal scrollbars.</p>
787     * {@hide}
788     */
789    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
790
791    /**
792     * <p>This view shows vertical scrollbars.</p>
793     * {@hide}
794     */
795    static final int SCROLLBARS_VERTICAL = 0x00000200;
796
797    /**
798     * <p>Mask for use with setFlags indicating bits used for indicating which
799     * scrollbars are enabled.</p>
800     * {@hide}
801     */
802    static final int SCROLLBARS_MASK = 0x00000300;
803
804    /**
805     * Indicates that the view should filter touches when its window is obscured.
806     * Refer to the class comments for more information about this security feature.
807     * {@hide}
808     */
809    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
810
811    /**
812     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
813     * that they are optional and should be skipped if the window has
814     * requested system UI flags that ignore those insets for layout.
815     */
816    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
817
818    /**
819     * <p>This view doesn't show fading edges.</p>
820     * {@hide}
821     */
822    static final int FADING_EDGE_NONE = 0x00000000;
823
824    /**
825     * <p>This view shows horizontal fading edges.</p>
826     * {@hide}
827     */
828    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
829
830    /**
831     * <p>This view shows vertical fading edges.</p>
832     * {@hide}
833     */
834    static final int FADING_EDGE_VERTICAL = 0x00002000;
835
836    /**
837     * <p>Mask for use with setFlags indicating bits used for indicating which
838     * fading edges are enabled.</p>
839     * {@hide}
840     */
841    static final int FADING_EDGE_MASK = 0x00003000;
842
843    /**
844     * <p>Indicates this view can be clicked. When clickable, a View reacts
845     * to clicks by notifying the OnClickListener.<p>
846     * {@hide}
847     */
848    static final int CLICKABLE = 0x00004000;
849
850    /**
851     * <p>Indicates this view is caching its drawing into a bitmap.</p>
852     * {@hide}
853     */
854    static final int DRAWING_CACHE_ENABLED = 0x00008000;
855
856    /**
857     * <p>Indicates that no icicle should be saved for this view.<p>
858     * {@hide}
859     */
860    static final int SAVE_DISABLED = 0x000010000;
861
862    /**
863     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
864     * property.</p>
865     * {@hide}
866     */
867    static final int SAVE_DISABLED_MASK = 0x000010000;
868
869    /**
870     * <p>Indicates that no drawing cache should ever be created for this view.<p>
871     * {@hide}
872     */
873    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
874
875    /**
876     * <p>Indicates this view can take / keep focus when int touch mode.</p>
877     * {@hide}
878     */
879    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
880
881    /**
882     * <p>Enables low quality mode for the drawing cache.</p>
883     */
884    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
885
886    /**
887     * <p>Enables high quality mode for the drawing cache.</p>
888     */
889    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
890
891    /**
892     * <p>Enables automatic quality mode for the drawing cache.</p>
893     */
894    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
895
896    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
897            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
898    };
899
900    /**
901     * <p>Mask for use with setFlags indicating bits used for the cache
902     * quality property.</p>
903     * {@hide}
904     */
905    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
906
907    /**
908     * <p>
909     * Indicates this view can be long clicked. When long clickable, a View
910     * reacts to long clicks by notifying the OnLongClickListener or showing a
911     * context menu.
912     * </p>
913     * {@hide}
914     */
915    static final int LONG_CLICKABLE = 0x00200000;
916
917    /**
918     * <p>Indicates that this view gets its drawable states from its direct parent
919     * and ignores its original internal states.</p>
920     *
921     * @hide
922     */
923    static final int DUPLICATE_PARENT_STATE = 0x00400000;
924
925    /**
926     * The scrollbar style to display the scrollbars inside the content area,
927     * without increasing the padding. The scrollbars will be overlaid with
928     * translucency on the view's content.
929     */
930    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
931
932    /**
933     * The scrollbar style to display the scrollbars inside the padded area,
934     * increasing the padding of the view. The scrollbars will not overlap the
935     * content area of the view.
936     */
937    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
938
939    /**
940     * The scrollbar style to display the scrollbars at the edge of the view,
941     * without increasing the padding. The scrollbars will be overlaid with
942     * translucency.
943     */
944    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
945
946    /**
947     * The scrollbar style to display the scrollbars at the edge of the view,
948     * increasing the padding of the view. The scrollbars will only overlap the
949     * background, if any.
950     */
951    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
952
953    /**
954     * Mask to check if the scrollbar style is overlay or inset.
955     * {@hide}
956     */
957    static final int SCROLLBARS_INSET_MASK = 0x01000000;
958
959    /**
960     * Mask to check if the scrollbar style is inside or outside.
961     * {@hide}
962     */
963    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
964
965    /**
966     * Mask for scrollbar style.
967     * {@hide}
968     */
969    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
970
971    /**
972     * View flag indicating that the screen should remain on while the
973     * window containing this view is visible to the user.  This effectively
974     * takes care of automatically setting the WindowManager's
975     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
976     */
977    public static final int KEEP_SCREEN_ON = 0x04000000;
978
979    /**
980     * View flag indicating whether this view should have sound effects enabled
981     * for events such as clicking and touching.
982     */
983    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
984
985    /**
986     * View flag indicating whether this view should have haptic feedback
987     * enabled for events such as long presses.
988     */
989    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
990
991    /**
992     * <p>Indicates that the view hierarchy should stop saving state when
993     * it reaches this view.  If state saving is initiated immediately at
994     * the view, it will be allowed.
995     * {@hide}
996     */
997    static final int PARENT_SAVE_DISABLED = 0x20000000;
998
999    /**
1000     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1001     * {@hide}
1002     */
1003    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1004
1005    /**
1006     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1007     * should add all focusable Views regardless if they are focusable in touch mode.
1008     */
1009    public static final int FOCUSABLES_ALL = 0x00000000;
1010
1011    /**
1012     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1013     * should add only Views focusable in touch mode.
1014     */
1015    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1016
1017    /**
1018     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1019     * item.
1020     */
1021    public static final int FOCUS_BACKWARD = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1025     * item.
1026     */
1027    public static final int FOCUS_FORWARD = 0x00000002;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the left.
1031     */
1032    public static final int FOCUS_LEFT = 0x00000011;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus up.
1036     */
1037    public static final int FOCUS_UP = 0x00000021;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus to the right.
1041     */
1042    public static final int FOCUS_RIGHT = 0x00000042;
1043
1044    /**
1045     * Use with {@link #focusSearch(int)}. Move focus down.
1046     */
1047    public static final int FOCUS_DOWN = 0x00000082;
1048
1049    /**
1050     * Bits of {@link #getMeasuredWidthAndState()} and
1051     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1052     */
1053    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1054
1055    /**
1056     * Bits of {@link #getMeasuredWidthAndState()} and
1057     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1058     */
1059    public static final int MEASURED_STATE_MASK = 0xff000000;
1060
1061    /**
1062     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1063     * for functions that combine both width and height into a single int,
1064     * such as {@link #getMeasuredState()} and the childState argument of
1065     * {@link #resolveSizeAndState(int, int, int)}.
1066     */
1067    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1068
1069    /**
1070     * Bit of {@link #getMeasuredWidthAndState()} and
1071     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1072     * is smaller that the space the view would like to have.
1073     */
1074    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1075
1076    /**
1077     * Base View state sets
1078     */
1079    // Singles
1080    /**
1081     * Indicates the view has no states set. States are used with
1082     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1083     * view depending on its state.
1084     *
1085     * @see android.graphics.drawable.Drawable
1086     * @see #getDrawableState()
1087     */
1088    protected static final int[] EMPTY_STATE_SET;
1089    /**
1090     * Indicates the view is enabled. States are used with
1091     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1092     * view depending on its state.
1093     *
1094     * @see android.graphics.drawable.Drawable
1095     * @see #getDrawableState()
1096     */
1097    protected static final int[] ENABLED_STATE_SET;
1098    /**
1099     * Indicates the view is focused. States are used with
1100     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1101     * view depending on its state.
1102     *
1103     * @see android.graphics.drawable.Drawable
1104     * @see #getDrawableState()
1105     */
1106    protected static final int[] FOCUSED_STATE_SET;
1107    /**
1108     * Indicates the view is selected. States are used with
1109     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1110     * view depending on its state.
1111     *
1112     * @see android.graphics.drawable.Drawable
1113     * @see #getDrawableState()
1114     */
1115    protected static final int[] SELECTED_STATE_SET;
1116    /**
1117     * Indicates the view is pressed. States are used with
1118     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1119     * view depending on its state.
1120     *
1121     * @see android.graphics.drawable.Drawable
1122     * @see #getDrawableState()
1123     * @hide
1124     */
1125    protected static final int[] PRESSED_STATE_SET;
1126    /**
1127     * Indicates the view's window has focus. States are used with
1128     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1129     * view depending on its state.
1130     *
1131     * @see android.graphics.drawable.Drawable
1132     * @see #getDrawableState()
1133     */
1134    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1135    // Doubles
1136    /**
1137     * Indicates the view is enabled and has the focus.
1138     *
1139     * @see #ENABLED_STATE_SET
1140     * @see #FOCUSED_STATE_SET
1141     */
1142    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1143    /**
1144     * Indicates the view is enabled and selected.
1145     *
1146     * @see #ENABLED_STATE_SET
1147     * @see #SELECTED_STATE_SET
1148     */
1149    protected static final int[] ENABLED_SELECTED_STATE_SET;
1150    /**
1151     * Indicates the view is enabled and that its window has focus.
1152     *
1153     * @see #ENABLED_STATE_SET
1154     * @see #WINDOW_FOCUSED_STATE_SET
1155     */
1156    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1157    /**
1158     * Indicates the view is focused and selected.
1159     *
1160     * @see #FOCUSED_STATE_SET
1161     * @see #SELECTED_STATE_SET
1162     */
1163    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1164    /**
1165     * Indicates the view has the focus and that its window has the focus.
1166     *
1167     * @see #FOCUSED_STATE_SET
1168     * @see #WINDOW_FOCUSED_STATE_SET
1169     */
1170    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1171    /**
1172     * Indicates the view is selected and that its window has the focus.
1173     *
1174     * @see #SELECTED_STATE_SET
1175     * @see #WINDOW_FOCUSED_STATE_SET
1176     */
1177    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1178    // Triples
1179    /**
1180     * Indicates the view is enabled, focused and selected.
1181     *
1182     * @see #ENABLED_STATE_SET
1183     * @see #FOCUSED_STATE_SET
1184     * @see #SELECTED_STATE_SET
1185     */
1186    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1187    /**
1188     * Indicates the view is enabled, focused and its window has the focus.
1189     *
1190     * @see #ENABLED_STATE_SET
1191     * @see #FOCUSED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is enabled, selected and its window has the focus.
1197     *
1198     * @see #ENABLED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     * @see #WINDOW_FOCUSED_STATE_SET
1201     */
1202    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1203    /**
1204     * Indicates the view is focused, selected and its window has the focus.
1205     *
1206     * @see #FOCUSED_STATE_SET
1207     * @see #SELECTED_STATE_SET
1208     * @see #WINDOW_FOCUSED_STATE_SET
1209     */
1210    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1211    /**
1212     * Indicates the view is enabled, focused, selected and its window
1213     * has the focus.
1214     *
1215     * @see #ENABLED_STATE_SET
1216     * @see #FOCUSED_STATE_SET
1217     * @see #SELECTED_STATE_SET
1218     * @see #WINDOW_FOCUSED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1221    /**
1222     * Indicates the view is pressed and its window has the focus.
1223     *
1224     * @see #PRESSED_STATE_SET
1225     * @see #WINDOW_FOCUSED_STATE_SET
1226     */
1227    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1228    /**
1229     * Indicates the view is pressed and selected.
1230     *
1231     * @see #PRESSED_STATE_SET
1232     * @see #SELECTED_STATE_SET
1233     */
1234    protected static final int[] PRESSED_SELECTED_STATE_SET;
1235    /**
1236     * Indicates the view is pressed, selected and its window has the focus.
1237     *
1238     * @see #PRESSED_STATE_SET
1239     * @see #SELECTED_STATE_SET
1240     * @see #WINDOW_FOCUSED_STATE_SET
1241     */
1242    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1243    /**
1244     * Indicates the view is pressed and focused.
1245     *
1246     * @see #PRESSED_STATE_SET
1247     * @see #FOCUSED_STATE_SET
1248     */
1249    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is pressed, focused and its window has the focus.
1252     *
1253     * @see #PRESSED_STATE_SET
1254     * @see #FOCUSED_STATE_SET
1255     * @see #WINDOW_FOCUSED_STATE_SET
1256     */
1257    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1258    /**
1259     * Indicates the view is pressed, focused and selected.
1260     *
1261     * @see #PRESSED_STATE_SET
1262     * @see #SELECTED_STATE_SET
1263     * @see #FOCUSED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed, focused, selected and its window has the focus.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #SELECTED_STATE_SET
1272     * @see #WINDOW_FOCUSED_STATE_SET
1273     */
1274    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1275    /**
1276     * Indicates the view is pressed and enabled.
1277     *
1278     * @see #PRESSED_STATE_SET
1279     * @see #ENABLED_STATE_SET
1280     */
1281    protected static final int[] PRESSED_ENABLED_STATE_SET;
1282    /**
1283     * Indicates the view is pressed, enabled and its window has the focus.
1284     *
1285     * @see #PRESSED_STATE_SET
1286     * @see #ENABLED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is pressed, enabled and selected.
1292     *
1293     * @see #PRESSED_STATE_SET
1294     * @see #ENABLED_STATE_SET
1295     * @see #SELECTED_STATE_SET
1296     */
1297    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1298    /**
1299     * Indicates the view is pressed, enabled, selected and its window has the
1300     * focus.
1301     *
1302     * @see #PRESSED_STATE_SET
1303     * @see #ENABLED_STATE_SET
1304     * @see #SELECTED_STATE_SET
1305     * @see #WINDOW_FOCUSED_STATE_SET
1306     */
1307    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed, enabled and focused.
1310     *
1311     * @see #PRESSED_STATE_SET
1312     * @see #ENABLED_STATE_SET
1313     * @see #FOCUSED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed, enabled, focused and its window has the
1318     * focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #ENABLED_STATE_SET
1322     * @see #FOCUSED_STATE_SET
1323     * @see #WINDOW_FOCUSED_STATE_SET
1324     */
1325    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1326    /**
1327     * Indicates the view is pressed, enabled, focused and selected.
1328     *
1329     * @see #PRESSED_STATE_SET
1330     * @see #ENABLED_STATE_SET
1331     * @see #SELECTED_STATE_SET
1332     * @see #FOCUSED_STATE_SET
1333     */
1334    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1335    /**
1336     * Indicates the view is pressed, enabled, focused, selected and its window
1337     * has the focus.
1338     *
1339     * @see #PRESSED_STATE_SET
1340     * @see #ENABLED_STATE_SET
1341     * @see #SELECTED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346
1347    /**
1348     * The order here is very important to {@link #getDrawableState()}
1349     */
1350    private static final int[][] VIEW_STATE_SETS;
1351
1352    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1353    static final int VIEW_STATE_SELECTED = 1 << 1;
1354    static final int VIEW_STATE_FOCUSED = 1 << 2;
1355    static final int VIEW_STATE_ENABLED = 1 << 3;
1356    static final int VIEW_STATE_PRESSED = 1 << 4;
1357    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1358    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1359    static final int VIEW_STATE_HOVERED = 1 << 7;
1360    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1361    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1362
1363    static final int[] VIEW_STATE_IDS = new int[] {
1364        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1365        R.attr.state_selected,          VIEW_STATE_SELECTED,
1366        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1367        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1368        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1369        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1370        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1371        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1372        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1373        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1374    };
1375
1376    static {
1377        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1378            throw new IllegalStateException(
1379                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1380        }
1381        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1382        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1383            int viewState = R.styleable.ViewDrawableStates[i];
1384            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1385                if (VIEW_STATE_IDS[j] == viewState) {
1386                    orderedIds[i * 2] = viewState;
1387                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1388                }
1389            }
1390        }
1391        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1392        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1393        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1394            int numBits = Integer.bitCount(i);
1395            int[] set = new int[numBits];
1396            int pos = 0;
1397            for (int j = 0; j < orderedIds.length; j += 2) {
1398                if ((i & orderedIds[j+1]) != 0) {
1399                    set[pos++] = orderedIds[j];
1400                }
1401            }
1402            VIEW_STATE_SETS[i] = set;
1403        }
1404
1405        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1406        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1407        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1408        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1410        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1411        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1413        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1415        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1417                | VIEW_STATE_FOCUSED];
1418        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1419        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1421        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1423        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1425                | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1430                | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1436                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1437
1438        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1439        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1441        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1443        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1445                | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1450                | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1456                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1461                | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1467                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1470                | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1473                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1479                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1480                | VIEW_STATE_PRESSED];
1481    }
1482
1483    /**
1484     * Accessibility event types that are dispatched for text population.
1485     */
1486    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1487            AccessibilityEvent.TYPE_VIEW_CLICKED
1488            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1489            | AccessibilityEvent.TYPE_VIEW_SELECTED
1490            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1491            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1492            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1493            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1494            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1496            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1498
1499    /**
1500     * Temporary Rect currently for use in setBackground().  This will probably
1501     * be extended in the future to hold our own class with more than just
1502     * a Rect. :)
1503     */
1504    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1505
1506    /**
1507     * Map used to store views' tags.
1508     */
1509    private SparseArray<Object> mKeyedTags;
1510
1511    /**
1512     * The next available accessibility id.
1513     */
1514    private static int sNextAccessibilityViewId;
1515
1516    /**
1517     * The animation currently associated with this view.
1518     * @hide
1519     */
1520    protected Animation mCurrentAnimation = null;
1521
1522    /**
1523     * Width as measured during measure pass.
1524     * {@hide}
1525     */
1526    @ViewDebug.ExportedProperty(category = "measurement")
1527    int mMeasuredWidth;
1528
1529    /**
1530     * Height as measured during measure pass.
1531     * {@hide}
1532     */
1533    @ViewDebug.ExportedProperty(category = "measurement")
1534    int mMeasuredHeight;
1535
1536    /**
1537     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1538     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1539     * its display list. This flag, used only when hw accelerated, allows us to clear the
1540     * flag while retaining this information until it's needed (at getDisplayList() time and
1541     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1542     *
1543     * {@hide}
1544     */
1545    boolean mRecreateDisplayList = false;
1546
1547    /**
1548     * The view's identifier.
1549     * {@hide}
1550     *
1551     * @see #setId(int)
1552     * @see #getId()
1553     */
1554    @ViewDebug.ExportedProperty(resolveId = true)
1555    int mID = NO_ID;
1556
1557    /**
1558     * The stable ID of this view for accessibility purposes.
1559     */
1560    int mAccessibilityViewId = NO_ID;
1561
1562    /**
1563     * @hide
1564     */
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    /**
1568     * The view's tag.
1569     * {@hide}
1570     *
1571     * @see #setTag(Object)
1572     * @see #getTag()
1573     */
1574    protected Object mTag;
1575
1576    // for mPrivateFlags:
1577    /** {@hide} */
1578    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1579    /** {@hide} */
1580    static final int PFLAG_FOCUSED                     = 0x00000002;
1581    /** {@hide} */
1582    static final int PFLAG_SELECTED                    = 0x00000004;
1583    /** {@hide} */
1584    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1585    /** {@hide} */
1586    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1587    /** {@hide} */
1588    static final int PFLAG_DRAWN                       = 0x00000020;
1589    /**
1590     * When this flag is set, this view is running an animation on behalf of its
1591     * children and should therefore not cancel invalidate requests, even if they
1592     * lie outside of this view's bounds.
1593     *
1594     * {@hide}
1595     */
1596    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1597    /** {@hide} */
1598    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1599    /** {@hide} */
1600    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1601    /** {@hide} */
1602    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1603    /** {@hide} */
1604    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1605    /** {@hide} */
1606    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1607    /** {@hide} */
1608    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1609    /** {@hide} */
1610    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1611
1612    private static final int PFLAG_PRESSED             = 0x00004000;
1613
1614    /** {@hide} */
1615    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1616    /**
1617     * Flag used to indicate that this view should be drawn once more (and only once
1618     * more) after its animation has completed.
1619     * {@hide}
1620     */
1621    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1622
1623    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1624
1625    /**
1626     * Indicates that the View returned true when onSetAlpha() was called and that
1627     * the alpha must be restored.
1628     * {@hide}
1629     */
1630    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1631
1632    /**
1633     * Set by {@link #setScrollContainer(boolean)}.
1634     */
1635    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1636
1637    /**
1638     * Set by {@link #setScrollContainer(boolean)}.
1639     */
1640    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1641
1642    /**
1643     * View flag indicating whether this view was invalidated (fully or partially.)
1644     *
1645     * @hide
1646     */
1647    static final int PFLAG_DIRTY                       = 0x00200000;
1648
1649    /**
1650     * View flag indicating whether this view was invalidated by an opaque
1651     * invalidate request.
1652     *
1653     * @hide
1654     */
1655    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1656
1657    /**
1658     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1659     *
1660     * @hide
1661     */
1662    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1663
1664    /**
1665     * Indicates whether the background is opaque.
1666     *
1667     * @hide
1668     */
1669    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1670
1671    /**
1672     * Indicates whether the scrollbars are opaque.
1673     *
1674     * @hide
1675     */
1676    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1677
1678    /**
1679     * Indicates whether the view is opaque.
1680     *
1681     * @hide
1682     */
1683    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1684
1685    /**
1686     * Indicates a prepressed state;
1687     * the short time between ACTION_DOWN and recognizing
1688     * a 'real' press. Prepressed is used to recognize quick taps
1689     * even when they are shorter than ViewConfiguration.getTapTimeout().
1690     *
1691     * @hide
1692     */
1693    private static final int PFLAG_PREPRESSED          = 0x02000000;
1694
1695    /**
1696     * Indicates whether the view is temporarily detached.
1697     *
1698     * @hide
1699     */
1700    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1701
1702    /**
1703     * Indicates that we should awaken scroll bars once attached
1704     *
1705     * @hide
1706     */
1707    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1708
1709    /**
1710     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1711     * @hide
1712     */
1713    private static final int PFLAG_HOVERED             = 0x10000000;
1714
1715    /**
1716     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1717     * for transform operations
1718     *
1719     * @hide
1720     */
1721    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1722
1723    /** {@hide} */
1724    static final int PFLAG_ACTIVATED                   = 0x40000000;
1725
1726    /**
1727     * Indicates that this view was specifically invalidated, not just dirtied because some
1728     * child view was invalidated. The flag is used to determine when we need to recreate
1729     * a view's display list (as opposed to just returning a reference to its existing
1730     * display list).
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_INVALIDATED                 = 0x80000000;
1735
1736    /**
1737     * Masks for mPrivateFlags2, as generated by dumpFlags():
1738     *
1739     * -------|-------|-------|-------|
1740     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1741     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1742     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1743     *                               1  PFLAG2_DRAG_HOVERED
1744     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1745     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1746     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1747     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1748     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1749     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1750     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1751     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1752     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1753     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1754     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1755     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1756     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1757     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1758     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1759     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1760     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1761     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1762     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1763     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1764     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1765     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1766     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1767     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1768     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1769     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1770     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1771     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1772     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1773     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1774     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1775     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1776     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1777     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1778     *   1                              PFLAG2_PADDING_RESOLVED
1779     * -------|-------|-------|-------|
1780     */
1781
1782    /**
1783     * Indicates that this view has reported that it can accept the current drag's content.
1784     * Cleared when the drag operation concludes.
1785     * @hide
1786     */
1787    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1788
1789    /**
1790     * Indicates that this view is currently directly under the drag location in a
1791     * drag-and-drop operation involving content that it can accept.  Cleared when
1792     * the drag exits the view, or when the drag operation concludes.
1793     * @hide
1794     */
1795    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1796
1797    /**
1798     * Horizontal layout direction of this view is from Left to Right.
1799     * Use with {@link #setLayoutDirection}.
1800     */
1801    public static final int LAYOUT_DIRECTION_LTR = 0;
1802
1803    /**
1804     * Horizontal layout direction of this view is from Right to Left.
1805     * Use with {@link #setLayoutDirection}.
1806     */
1807    public static final int LAYOUT_DIRECTION_RTL = 1;
1808
1809    /**
1810     * Horizontal layout direction of this view is inherited from its parent.
1811     * Use with {@link #setLayoutDirection}.
1812     */
1813    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1814
1815    /**
1816     * Horizontal layout direction of this view is from deduced from the default language
1817     * script for the locale. Use with {@link #setLayoutDirection}.
1818     */
1819    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1820
1821    /**
1822     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1823     * @hide
1824     */
1825    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1826
1827    /**
1828     * Mask for use with private flags indicating bits used for horizontal layout direction.
1829     * @hide
1830     */
1831    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1832
1833    /**
1834     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1835     * right-to-left direction.
1836     * @hide
1837     */
1838    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Indicates whether the view horizontal layout direction has been resolved.
1842     * @hide
1843     */
1844    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /**
1847     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1848     * @hide
1849     */
1850    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1851            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1852
1853    /*
1854     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1855     * flag value.
1856     * @hide
1857     */
1858    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1859            LAYOUT_DIRECTION_LTR,
1860            LAYOUT_DIRECTION_RTL,
1861            LAYOUT_DIRECTION_INHERIT,
1862            LAYOUT_DIRECTION_LOCALE
1863    };
1864
1865    /**
1866     * Default horizontal layout direction.
1867     * @hide
1868     */
1869    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1870
1871    /**
1872     * Indicates that the view is tracking some sort of transient state
1873     * that the app should not need to be aware of, but that the framework
1874     * should take special care to preserve.
1875     *
1876     * @hide
1877     */
1878    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1879
1880    /**
1881     * Text direction is inherited thru {@link ViewGroup}
1882     */
1883    public static final int TEXT_DIRECTION_INHERIT = 0;
1884
1885    /**
1886     * Text direction is using "first strong algorithm". The first strong directional character
1887     * determines the paragraph direction. If there is no strong directional character, the
1888     * paragraph direction is the view's resolved layout direction.
1889     */
1890    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1891
1892    /**
1893     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1894     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1895     * If there are neither, the paragraph direction is the view's resolved layout direction.
1896     */
1897    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1898
1899    /**
1900     * Text direction is forced to LTR.
1901     */
1902    public static final int TEXT_DIRECTION_LTR = 3;
1903
1904    /**
1905     * Text direction is forced to RTL.
1906     */
1907    public static final int TEXT_DIRECTION_RTL = 4;
1908
1909    /**
1910     * Text direction is coming from the system Locale.
1911     */
1912    public static final int TEXT_DIRECTION_LOCALE = 5;
1913
1914    /**
1915     * Default text direction is inherited
1916     */
1917    public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1918
1919    /**
1920     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1921     * @hide
1922     */
1923    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1924
1925    /**
1926     * Mask for use with private flags indicating bits used for text direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1930            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1931
1932    /**
1933     * Array of text direction flags for mapping attribute "textDirection" to correct
1934     * flag value.
1935     * @hide
1936     */
1937    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1938            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1939            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1940            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1941            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1942            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1943            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1944    };
1945
1946    /**
1947     * Indicates whether the view text direction has been resolved.
1948     * @hide
1949     */
1950    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1951            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1952
1953    /**
1954     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1955     * @hide
1956     */
1957    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1958
1959    /**
1960     * Mask for use with private flags indicating bits used for resolved text direction.
1961     * @hide
1962     */
1963    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1964            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1965
1966    /**
1967     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1968     * @hide
1969     */
1970    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1971            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1972
1973    /*
1974     * Default text alignment. The text alignment of this View is inherited from its parent.
1975     * Use with {@link #setTextAlignment(int)}
1976     */
1977    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1978
1979    /**
1980     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1981     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1982     *
1983     * Use with {@link #setTextAlignment(int)}
1984     */
1985    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1986
1987    /**
1988     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1989     *
1990     * Use with {@link #setTextAlignment(int)}
1991     */
1992    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1993
1994    /**
1995     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1996     *
1997     * Use with {@link #setTextAlignment(int)}
1998     */
1999    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2000
2001    /**
2002     * Center the paragraph, e.g. ALIGN_CENTER.
2003     *
2004     * Use with {@link #setTextAlignment(int)}
2005     */
2006    public static final int TEXT_ALIGNMENT_CENTER = 4;
2007
2008    /**
2009     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2010     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     */
2014    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2015
2016    /**
2017     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2018     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2019     *
2020     * Use with {@link #setTextAlignment(int)}
2021     */
2022    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2023
2024    /**
2025     * Default text alignment is inherited
2026     */
2027    public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2028
2029    /**
2030      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2031      * @hide
2032      */
2033    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2034
2035    /**
2036      * Mask for use with private flags indicating bits used for text alignment.
2037      * @hide
2038      */
2039    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2040
2041    /**
2042     * Array of text direction flags for mapping attribute "textAlignment" to correct
2043     * flag value.
2044     * @hide
2045     */
2046    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2047            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2048            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2049            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2050            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2051            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2052            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2053            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2054    };
2055
2056    /**
2057     * Indicates whether the view text alignment has been resolved.
2058     * @hide
2059     */
2060    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2061
2062    /**
2063     * Bit shift to get the resolved text alignment.
2064     * @hide
2065     */
2066    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2067
2068    /**
2069     * Mask for use with private flags indicating bits used for text alignment.
2070     * @hide
2071     */
2072    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2073            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2074
2075    /**
2076     * Indicates whether if the view text alignment has been resolved to gravity
2077     */
2078    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2079            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2080
2081    // Accessiblity constants for mPrivateFlags2
2082
2083    /**
2084     * Shift for the bits in {@link #mPrivateFlags2} related to the
2085     * "importantForAccessibility" attribute.
2086     */
2087    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2088
2089    /**
2090     * Automatically determine whether a view is important for accessibility.
2091     */
2092    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2093
2094    /**
2095     * The view is important for accessibility.
2096     */
2097    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2098
2099    /**
2100     * The view is not important for accessibility.
2101     */
2102    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2103
2104    /**
2105     * The default whether the view is important for accessibility.
2106     */
2107    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2108
2109    /**
2110     * Mask for obtainig the bits which specify how to determine
2111     * whether a view is important for accessibility.
2112     */
2113    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2114        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2115        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2116
2117    /**
2118     * Flag indicating whether a view has accessibility focus.
2119     */
2120    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2121
2122    /**
2123     * Flag indicating whether a view state for accessibility has changed.
2124     */
2125    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2126            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2127
2128    /**
2129     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2130     * is used to check whether later changes to the view's transform should invalidate the
2131     * view to force the quickReject test to run again.
2132     */
2133    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2134
2135    /**
2136     * Flag indicating that start/end padding has been resolved into left/right padding
2137     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2138     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2139     * during measurement. In some special cases this is required such as when an adapter-based
2140     * view measures prospective children without attaching them to a window.
2141     */
2142    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2143
2144    /**
2145     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2146     */
2147    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2148
2149    /**
2150     * Group of bits indicating that RTL properties resolution is done.
2151     */
2152    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2153            PFLAG2_TEXT_DIRECTION_RESOLVED |
2154            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2155            PFLAG2_PADDING_RESOLVED |
2156            PFLAG2_DRAWABLE_RESOLVED;
2157
2158    // There are a couple of flags left in mPrivateFlags2
2159
2160    /* End of masks for mPrivateFlags2 */
2161
2162    /* Masks for mPrivateFlags3 */
2163
2164    /**
2165     * Flag indicating that view has a transform animation set on it. This is used to track whether
2166     * an animation is cleared between successive frames, in order to tell the associated
2167     * DisplayList to clear its animation matrix.
2168     */
2169    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2170
2171    /**
2172     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2173     * animation is cleared between successive frames, in order to tell the associated
2174     * DisplayList to restore its alpha value.
2175     */
2176    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2177
2178
2179    /* End of masks for mPrivateFlags3 */
2180
2181    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2182
2183    /**
2184     * Always allow a user to over-scroll this view, provided it is a
2185     * view that can scroll.
2186     *
2187     * @see #getOverScrollMode()
2188     * @see #setOverScrollMode(int)
2189     */
2190    public static final int OVER_SCROLL_ALWAYS = 0;
2191
2192    /**
2193     * Allow a user to over-scroll this view only if the content is large
2194     * enough to meaningfully scroll, provided it is a view that can scroll.
2195     *
2196     * @see #getOverScrollMode()
2197     * @see #setOverScrollMode(int)
2198     */
2199    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2200
2201    /**
2202     * Never allow a user to over-scroll this view.
2203     *
2204     * @see #getOverScrollMode()
2205     * @see #setOverScrollMode(int)
2206     */
2207    public static final int OVER_SCROLL_NEVER = 2;
2208
2209    /**
2210     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2211     * requested the system UI (status bar) to be visible (the default).
2212     *
2213     * @see #setSystemUiVisibility(int)
2214     */
2215    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2216
2217    /**
2218     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2219     * system UI to enter an unobtrusive "low profile" mode.
2220     *
2221     * <p>This is for use in games, book readers, video players, or any other
2222     * "immersive" application where the usual system chrome is deemed too distracting.
2223     *
2224     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2225     *
2226     * @see #setSystemUiVisibility(int)
2227     */
2228    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2229
2230    /**
2231     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2232     * system navigation be temporarily hidden.
2233     *
2234     * <p>This is an even less obtrusive state than that called for by
2235     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2236     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2237     * those to disappear. This is useful (in conjunction with the
2238     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2239     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2240     * window flags) for displaying content using every last pixel on the display.
2241     *
2242     * <p>There is a limitation: because navigation controls are so important, the least user
2243     * interaction will cause them to reappear immediately.  When this happens, both
2244     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2245     * so that both elements reappear at the same time.
2246     *
2247     * @see #setSystemUiVisibility(int)
2248     */
2249    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2250
2251    /**
2252     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2253     * into the normal fullscreen mode so that its content can take over the screen
2254     * while still allowing the user to interact with the application.
2255     *
2256     * <p>This has the same visual effect as
2257     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2258     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2259     * meaning that non-critical screen decorations (such as the status bar) will be
2260     * hidden while the user is in the View's window, focusing the experience on
2261     * that content.  Unlike the window flag, if you are using ActionBar in
2262     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2263     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2264     * hide the action bar.
2265     *
2266     * <p>This approach to going fullscreen is best used over the window flag when
2267     * it is a transient state -- that is, the application does this at certain
2268     * points in its user interaction where it wants to allow the user to focus
2269     * on content, but not as a continuous state.  For situations where the application
2270     * would like to simply stay full screen the entire time (such as a game that
2271     * wants to take over the screen), the
2272     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2273     * is usually a better approach.  The state set here will be removed by the system
2274     * in various situations (such as the user moving to another application) like
2275     * the other system UI states.
2276     *
2277     * <p>When using this flag, the application should provide some easy facility
2278     * for the user to go out of it.  A common example would be in an e-book
2279     * reader, where tapping on the screen brings back whatever screen and UI
2280     * decorations that had been hidden while the user was immersed in reading
2281     * the book.
2282     *
2283     * @see #setSystemUiVisibility(int)
2284     */
2285    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2286
2287    /**
2288     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2289     * flags, we would like a stable view of the content insets given to
2290     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2291     * will always represent the worst case that the application can expect
2292     * as a continuous state.  In the stock Android UI this is the space for
2293     * the system bar, nav bar, and status bar, but not more transient elements
2294     * such as an input method.
2295     *
2296     * The stable layout your UI sees is based on the system UI modes you can
2297     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2298     * then you will get a stable layout for changes of the
2299     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2300     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2301     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2302     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2303     * with a stable layout.  (Note that you should avoid using
2304     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2305     *
2306     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2307     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2308     * then a hidden status bar will be considered a "stable" state for purposes
2309     * here.  This allows your UI to continually hide the status bar, while still
2310     * using the system UI flags to hide the action bar while still retaining
2311     * a stable layout.  Note that changing the window fullscreen flag will never
2312     * provide a stable layout for a clean transition.
2313     *
2314     * <p>If you are using ActionBar in
2315     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2316     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2317     * insets it adds to those given to the application.
2318     */
2319    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2320
2321    /**
2322     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2323     * to be layed out as if it has requested
2324     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2325     * allows it to avoid artifacts when switching in and out of that mode, at
2326     * the expense that some of its user interface may be covered by screen
2327     * decorations when they are shown.  You can perform layout of your inner
2328     * UI elements to account for the navagation system UI through the
2329     * {@link #fitSystemWindows(Rect)} method.
2330     */
2331    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2332
2333    /**
2334     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2335     * to be layed out as if it has requested
2336     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2337     * allows it to avoid artifacts when switching in and out of that mode, at
2338     * the expense that some of its user interface may be covered by screen
2339     * decorations when they are shown.  You can perform layout of your inner
2340     * UI elements to account for non-fullscreen system UI through the
2341     * {@link #fitSystemWindows(Rect)} method.
2342     */
2343    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2344
2345    /**
2346     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2347     */
2348    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2349
2350    /**
2351     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2352     */
2353    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2354
2355    /**
2356     * @hide
2357     *
2358     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2359     * out of the public fields to keep the undefined bits out of the developer's way.
2360     *
2361     * Flag to make the status bar not expandable.  Unless you also
2362     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2363     */
2364    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2365
2366    /**
2367     * @hide
2368     *
2369     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2370     * out of the public fields to keep the undefined bits out of the developer's way.
2371     *
2372     * Flag to hide notification icons and scrolling ticker text.
2373     */
2374    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2375
2376    /**
2377     * @hide
2378     *
2379     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2380     * out of the public fields to keep the undefined bits out of the developer's way.
2381     *
2382     * Flag to disable incoming notification alerts.  This will not block
2383     * icons, but it will block sound, vibrating and other visual or aural notifications.
2384     */
2385    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2386
2387    /**
2388     * @hide
2389     *
2390     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2391     * out of the public fields to keep the undefined bits out of the developer's way.
2392     *
2393     * Flag to hide only the scrolling ticker.  Note that
2394     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2395     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2396     */
2397    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2398
2399    /**
2400     * @hide
2401     *
2402     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2403     * out of the public fields to keep the undefined bits out of the developer's way.
2404     *
2405     * Flag to hide the center system info area.
2406     */
2407    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2408
2409    /**
2410     * @hide
2411     *
2412     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2413     * out of the public fields to keep the undefined bits out of the developer's way.
2414     *
2415     * Flag to hide only the home button.  Don't use this
2416     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2417     */
2418    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2419
2420    /**
2421     * @hide
2422     *
2423     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2424     * out of the public fields to keep the undefined bits out of the developer's way.
2425     *
2426     * Flag to hide only the back button. Don't use this
2427     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2428     */
2429    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2430
2431    /**
2432     * @hide
2433     *
2434     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2435     * out of the public fields to keep the undefined bits out of the developer's way.
2436     *
2437     * Flag to hide only the clock.  You might use this if your activity has
2438     * its own clock making the status bar's clock redundant.
2439     */
2440    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2441
2442    /**
2443     * @hide
2444     *
2445     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2446     * out of the public fields to keep the undefined bits out of the developer's way.
2447     *
2448     * Flag to hide only the recent apps button. Don't use this
2449     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2450     */
2451    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2452
2453    /**
2454     * @hide
2455     */
2456    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2457
2458    /**
2459     * These are the system UI flags that can be cleared by events outside
2460     * of an application.  Currently this is just the ability to tap on the
2461     * screen while hiding the navigation bar to have it return.
2462     * @hide
2463     */
2464    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2465            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2466            | SYSTEM_UI_FLAG_FULLSCREEN;
2467
2468    /**
2469     * Flags that can impact the layout in relation to system UI.
2470     */
2471    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2472            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2473            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2474
2475    /**
2476     * Find views that render the specified text.
2477     *
2478     * @see #findViewsWithText(ArrayList, CharSequence, int)
2479     */
2480    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2481
2482    /**
2483     * Find find views that contain the specified content description.
2484     *
2485     * @see #findViewsWithText(ArrayList, CharSequence, int)
2486     */
2487    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2488
2489    /**
2490     * Find views that contain {@link AccessibilityNodeProvider}. Such
2491     * a View is a root of virtual view hierarchy and may contain the searched
2492     * text. If this flag is set Views with providers are automatically
2493     * added and it is a responsibility of the client to call the APIs of
2494     * the provider to determine whether the virtual tree rooted at this View
2495     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2496     * represeting the virtual views with this text.
2497     *
2498     * @see #findViewsWithText(ArrayList, CharSequence, int)
2499     *
2500     * @hide
2501     */
2502    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2503
2504    /**
2505     * The undefined cursor position.
2506     */
2507    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2508
2509    /**
2510     * Indicates that the screen has changed state and is now off.
2511     *
2512     * @see #onScreenStateChanged(int)
2513     */
2514    public static final int SCREEN_STATE_OFF = 0x0;
2515
2516    /**
2517     * Indicates that the screen has changed state and is now on.
2518     *
2519     * @see #onScreenStateChanged(int)
2520     */
2521    public static final int SCREEN_STATE_ON = 0x1;
2522
2523    /**
2524     * Controls the over-scroll mode for this view.
2525     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2526     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2527     * and {@link #OVER_SCROLL_NEVER}.
2528     */
2529    private int mOverScrollMode;
2530
2531    /**
2532     * The parent this view is attached to.
2533     * {@hide}
2534     *
2535     * @see #getParent()
2536     */
2537    protected ViewParent mParent;
2538
2539    /**
2540     * {@hide}
2541     */
2542    AttachInfo mAttachInfo;
2543
2544    /**
2545     * {@hide}
2546     */
2547    @ViewDebug.ExportedProperty(flagMapping = {
2548        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2549                name = "FORCE_LAYOUT"),
2550        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2551                name = "LAYOUT_REQUIRED"),
2552        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2553            name = "DRAWING_CACHE_INVALID", outputIf = false),
2554        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2555        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2556        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2557        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2558    })
2559    int mPrivateFlags;
2560    int mPrivateFlags2;
2561    int mPrivateFlags3;
2562
2563    /**
2564     * This view's request for the visibility of the status bar.
2565     * @hide
2566     */
2567    @ViewDebug.ExportedProperty(flagMapping = {
2568        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2569                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2570                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2571        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2572                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2573                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2574        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2575                                equals = SYSTEM_UI_FLAG_VISIBLE,
2576                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2577    })
2578    int mSystemUiVisibility;
2579
2580    /**
2581     * Reference count for transient state.
2582     * @see #setHasTransientState(boolean)
2583     */
2584    int mTransientStateCount = 0;
2585
2586    /**
2587     * Count of how many windows this view has been attached to.
2588     */
2589    int mWindowAttachCount;
2590
2591    /**
2592     * The layout parameters associated with this view and used by the parent
2593     * {@link android.view.ViewGroup} to determine how this view should be
2594     * laid out.
2595     * {@hide}
2596     */
2597    protected ViewGroup.LayoutParams mLayoutParams;
2598
2599    /**
2600     * The view flags hold various views states.
2601     * {@hide}
2602     */
2603    @ViewDebug.ExportedProperty
2604    int mViewFlags;
2605
2606    static class TransformationInfo {
2607        /**
2608         * The transform matrix for the View. This transform is calculated internally
2609         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2610         * is used by default. Do *not* use this variable directly; instead call
2611         * getMatrix(), which will automatically recalculate the matrix if necessary
2612         * to get the correct matrix based on the latest rotation and scale properties.
2613         */
2614        private final Matrix mMatrix = new Matrix();
2615
2616        /**
2617         * The transform matrix for the View. This transform is calculated internally
2618         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2619         * is used by default. Do *not* use this variable directly; instead call
2620         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2621         * to get the correct matrix based on the latest rotation and scale properties.
2622         */
2623        private Matrix mInverseMatrix;
2624
2625        /**
2626         * An internal variable that tracks whether we need to recalculate the
2627         * transform matrix, based on whether the rotation or scaleX/Y properties
2628         * have changed since the matrix was last calculated.
2629         */
2630        boolean mMatrixDirty = false;
2631
2632        /**
2633         * An internal variable that tracks whether we need to recalculate the
2634         * transform matrix, based on whether the rotation or scaleX/Y properties
2635         * have changed since the matrix was last calculated.
2636         */
2637        private boolean mInverseMatrixDirty = true;
2638
2639        /**
2640         * A variable that tracks whether we need to recalculate the
2641         * transform matrix, based on whether the rotation or scaleX/Y properties
2642         * have changed since the matrix was last calculated. This variable
2643         * is only valid after a call to updateMatrix() or to a function that
2644         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2645         */
2646        private boolean mMatrixIsIdentity = true;
2647
2648        /**
2649         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2650         */
2651        private Camera mCamera = null;
2652
2653        /**
2654         * This matrix is used when computing the matrix for 3D rotations.
2655         */
2656        private Matrix matrix3D = null;
2657
2658        /**
2659         * These prev values are used to recalculate a centered pivot point when necessary. The
2660         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2661         * set), so thes values are only used then as well.
2662         */
2663        private int mPrevWidth = -1;
2664        private int mPrevHeight = -1;
2665
2666        /**
2667         * The degrees rotation around the vertical axis through the pivot point.
2668         */
2669        @ViewDebug.ExportedProperty
2670        float mRotationY = 0f;
2671
2672        /**
2673         * The degrees rotation around the horizontal axis through the pivot point.
2674         */
2675        @ViewDebug.ExportedProperty
2676        float mRotationX = 0f;
2677
2678        /**
2679         * The degrees rotation around the pivot point.
2680         */
2681        @ViewDebug.ExportedProperty
2682        float mRotation = 0f;
2683
2684        /**
2685         * The amount of translation of the object away from its left property (post-layout).
2686         */
2687        @ViewDebug.ExportedProperty
2688        float mTranslationX = 0f;
2689
2690        /**
2691         * The amount of translation of the object away from its top property (post-layout).
2692         */
2693        @ViewDebug.ExportedProperty
2694        float mTranslationY = 0f;
2695
2696        /**
2697         * The amount of scale in the x direction around the pivot point. A
2698         * value of 1 means no scaling is applied.
2699         */
2700        @ViewDebug.ExportedProperty
2701        float mScaleX = 1f;
2702
2703        /**
2704         * The amount of scale in the y direction around the pivot point. A
2705         * value of 1 means no scaling is applied.
2706         */
2707        @ViewDebug.ExportedProperty
2708        float mScaleY = 1f;
2709
2710        /**
2711         * The x location of the point around which the view is rotated and scaled.
2712         */
2713        @ViewDebug.ExportedProperty
2714        float mPivotX = 0f;
2715
2716        /**
2717         * The y location of the point around which the view is rotated and scaled.
2718         */
2719        @ViewDebug.ExportedProperty
2720        float mPivotY = 0f;
2721
2722        /**
2723         * The opacity of the View. This is a value from 0 to 1, where 0 means
2724         * completely transparent and 1 means completely opaque.
2725         */
2726        @ViewDebug.ExportedProperty
2727        float mAlpha = 1f;
2728    }
2729
2730    TransformationInfo mTransformationInfo;
2731
2732    private boolean mLastIsOpaque;
2733
2734    /**
2735     * Convenience value to check for float values that are close enough to zero to be considered
2736     * zero.
2737     */
2738    private static final float NONZERO_EPSILON = .001f;
2739
2740    /**
2741     * The distance in pixels from the left edge of this view's parent
2742     * to the left edge of this view.
2743     * {@hide}
2744     */
2745    @ViewDebug.ExportedProperty(category = "layout")
2746    protected int mLeft;
2747    /**
2748     * The distance in pixels from the left edge of this view's parent
2749     * to the right edge of this view.
2750     * {@hide}
2751     */
2752    @ViewDebug.ExportedProperty(category = "layout")
2753    protected int mRight;
2754    /**
2755     * The distance in pixels from the top edge of this view's parent
2756     * to the top edge of this view.
2757     * {@hide}
2758     */
2759    @ViewDebug.ExportedProperty(category = "layout")
2760    protected int mTop;
2761    /**
2762     * The distance in pixels from the top edge of this view's parent
2763     * to the bottom edge of this view.
2764     * {@hide}
2765     */
2766    @ViewDebug.ExportedProperty(category = "layout")
2767    protected int mBottom;
2768
2769    /**
2770     * The offset, in pixels, by which the content of this view is scrolled
2771     * horizontally.
2772     * {@hide}
2773     */
2774    @ViewDebug.ExportedProperty(category = "scrolling")
2775    protected int mScrollX;
2776    /**
2777     * The offset, in pixels, by which the content of this view is scrolled
2778     * vertically.
2779     * {@hide}
2780     */
2781    @ViewDebug.ExportedProperty(category = "scrolling")
2782    protected int mScrollY;
2783
2784    /**
2785     * The left padding in pixels, that is the distance in pixels between the
2786     * left edge of this view and the left edge of its content.
2787     * {@hide}
2788     */
2789    @ViewDebug.ExportedProperty(category = "padding")
2790    protected int mPaddingLeft = 0;
2791    /**
2792     * The right padding in pixels, that is the distance in pixels between the
2793     * right edge of this view and the right edge of its content.
2794     * {@hide}
2795     */
2796    @ViewDebug.ExportedProperty(category = "padding")
2797    protected int mPaddingRight = 0;
2798    /**
2799     * The top padding in pixels, that is the distance in pixels between the
2800     * top edge of this view and the top edge of its content.
2801     * {@hide}
2802     */
2803    @ViewDebug.ExportedProperty(category = "padding")
2804    protected int mPaddingTop;
2805    /**
2806     * The bottom padding in pixels, that is the distance in pixels between the
2807     * bottom edge of this view and the bottom edge of its content.
2808     * {@hide}
2809     */
2810    @ViewDebug.ExportedProperty(category = "padding")
2811    protected int mPaddingBottom;
2812
2813    /**
2814     * The layout insets in pixels, that is the distance in pixels between the
2815     * visible edges of this view its bounds.
2816     */
2817    private Insets mLayoutInsets;
2818
2819    /**
2820     * Briefly describes the view and is primarily used for accessibility support.
2821     */
2822    private CharSequence mContentDescription;
2823
2824    /**
2825     * Specifies the id of a view for which this view serves as a label for
2826     * accessibility purposes.
2827     */
2828    private int mLabelForId = View.NO_ID;
2829
2830    /**
2831     * Predicate for matching labeled view id with its label for
2832     * accessibility purposes.
2833     */
2834    private MatchLabelForPredicate mMatchLabelForPredicate;
2835
2836    /**
2837     * Predicate for matching a view by its id.
2838     */
2839    private MatchIdPredicate mMatchIdPredicate;
2840
2841    /**
2842     * Cache the paddingRight set by the user to append to the scrollbar's size.
2843     *
2844     * @hide
2845     */
2846    @ViewDebug.ExportedProperty(category = "padding")
2847    protected int mUserPaddingRight;
2848
2849    /**
2850     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2851     *
2852     * @hide
2853     */
2854    @ViewDebug.ExportedProperty(category = "padding")
2855    protected int mUserPaddingBottom;
2856
2857    /**
2858     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2859     *
2860     * @hide
2861     */
2862    @ViewDebug.ExportedProperty(category = "padding")
2863    protected int mUserPaddingLeft;
2864
2865    /**
2866     * Cache the paddingStart set by the user to append to the scrollbar's size.
2867     *
2868     */
2869    @ViewDebug.ExportedProperty(category = "padding")
2870    int mUserPaddingStart;
2871
2872    /**
2873     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2874     *
2875     */
2876    @ViewDebug.ExportedProperty(category = "padding")
2877    int mUserPaddingEnd;
2878
2879    /**
2880     * Cache initial left padding.
2881     *
2882     * @hide
2883     */
2884    int mUserPaddingLeftInitial = UNDEFINED_PADDING;
2885
2886    /**
2887     * Cache initial right padding.
2888     *
2889     * @hide
2890     */
2891    int mUserPaddingRightInitial = UNDEFINED_PADDING;
2892
2893    /**
2894     * Default undefined padding
2895     */
2896    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2897
2898    /**
2899     * @hide
2900     */
2901    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2902    /**
2903     * @hide
2904     */
2905    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2906
2907    private Drawable mBackground;
2908
2909    private int mBackgroundResource;
2910    private boolean mBackgroundSizeChanged;
2911
2912    static class ListenerInfo {
2913        /**
2914         * Listener used to dispatch focus change events.
2915         * This field should be made private, so it is hidden from the SDK.
2916         * {@hide}
2917         */
2918        protected OnFocusChangeListener mOnFocusChangeListener;
2919
2920        /**
2921         * Listeners for layout change events.
2922         */
2923        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2924
2925        /**
2926         * Listeners for attach events.
2927         */
2928        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2929
2930        /**
2931         * Listener used to dispatch click events.
2932         * This field should be made private, so it is hidden from the SDK.
2933         * {@hide}
2934         */
2935        public OnClickListener mOnClickListener;
2936
2937        /**
2938         * Listener used to dispatch long click events.
2939         * This field should be made private, so it is hidden from the SDK.
2940         * {@hide}
2941         */
2942        protected OnLongClickListener mOnLongClickListener;
2943
2944        /**
2945         * Listener used to build the context menu.
2946         * This field should be made private, so it is hidden from the SDK.
2947         * {@hide}
2948         */
2949        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2950
2951        private OnKeyListener mOnKeyListener;
2952
2953        private OnTouchListener mOnTouchListener;
2954
2955        private OnHoverListener mOnHoverListener;
2956
2957        private OnGenericMotionListener mOnGenericMotionListener;
2958
2959        private OnDragListener mOnDragListener;
2960
2961        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2962    }
2963
2964    ListenerInfo mListenerInfo;
2965
2966    /**
2967     * The application environment this view lives in.
2968     * This field should be made private, so it is hidden from the SDK.
2969     * {@hide}
2970     */
2971    protected Context mContext;
2972
2973    private final Resources mResources;
2974
2975    private ScrollabilityCache mScrollCache;
2976
2977    private int[] mDrawableState = null;
2978
2979    /**
2980     * Set to true when drawing cache is enabled and cannot be created.
2981     *
2982     * @hide
2983     */
2984    public boolean mCachingFailed;
2985
2986    private Bitmap mDrawingCache;
2987    private Bitmap mUnscaledDrawingCache;
2988    private HardwareLayer mHardwareLayer;
2989    DisplayList mDisplayList;
2990
2991    /**
2992     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2993     * the user may specify which view to go to next.
2994     */
2995    private int mNextFocusLeftId = View.NO_ID;
2996
2997    /**
2998     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2999     * the user may specify which view to go to next.
3000     */
3001    private int mNextFocusRightId = View.NO_ID;
3002
3003    /**
3004     * When this view has focus and the next focus is {@link #FOCUS_UP},
3005     * the user may specify which view to go to next.
3006     */
3007    private int mNextFocusUpId = View.NO_ID;
3008
3009    /**
3010     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3011     * the user may specify which view to go to next.
3012     */
3013    private int mNextFocusDownId = View.NO_ID;
3014
3015    /**
3016     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3017     * the user may specify which view to go to next.
3018     */
3019    int mNextFocusForwardId = View.NO_ID;
3020
3021    private CheckForLongPress mPendingCheckForLongPress;
3022    private CheckForTap mPendingCheckForTap = null;
3023    private PerformClick mPerformClick;
3024    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3025
3026    private UnsetPressedState mUnsetPressedState;
3027
3028    /**
3029     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3030     * up event while a long press is invoked as soon as the long press duration is reached, so
3031     * a long press could be performed before the tap is checked, in which case the tap's action
3032     * should not be invoked.
3033     */
3034    private boolean mHasPerformedLongPress;
3035
3036    /**
3037     * The minimum height of the view. We'll try our best to have the height
3038     * of this view to at least this amount.
3039     */
3040    @ViewDebug.ExportedProperty(category = "measurement")
3041    private int mMinHeight;
3042
3043    /**
3044     * The minimum width of the view. We'll try our best to have the width
3045     * of this view to at least this amount.
3046     */
3047    @ViewDebug.ExportedProperty(category = "measurement")
3048    private int mMinWidth;
3049
3050    /**
3051     * The delegate to handle touch events that are physically in this view
3052     * but should be handled by another view.
3053     */
3054    private TouchDelegate mTouchDelegate = null;
3055
3056    /**
3057     * Solid color to use as a background when creating the drawing cache. Enables
3058     * the cache to use 16 bit bitmaps instead of 32 bit.
3059     */
3060    private int mDrawingCacheBackgroundColor = 0;
3061
3062    /**
3063     * Special tree observer used when mAttachInfo is null.
3064     */
3065    private ViewTreeObserver mFloatingTreeObserver;
3066
3067    /**
3068     * Cache the touch slop from the context that created the view.
3069     */
3070    private int mTouchSlop;
3071
3072    /**
3073     * Object that handles automatic animation of view properties.
3074     */
3075    private ViewPropertyAnimator mAnimator = null;
3076
3077    /**
3078     * Flag indicating that a drag can cross window boundaries.  When
3079     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3080     * with this flag set, all visible applications will be able to participate
3081     * in the drag operation and receive the dragged content.
3082     *
3083     * @hide
3084     */
3085    public static final int DRAG_FLAG_GLOBAL = 1;
3086
3087    /**
3088     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3089     */
3090    private float mVerticalScrollFactor;
3091
3092    /**
3093     * Position of the vertical scroll bar.
3094     */
3095    private int mVerticalScrollbarPosition;
3096
3097    /**
3098     * Position the scroll bar at the default position as determined by the system.
3099     */
3100    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3101
3102    /**
3103     * Position the scroll bar along the left edge.
3104     */
3105    public static final int SCROLLBAR_POSITION_LEFT = 1;
3106
3107    /**
3108     * Position the scroll bar along the right edge.
3109     */
3110    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3111
3112    /**
3113     * Indicates that the view does not have a layer.
3114     *
3115     * @see #getLayerType()
3116     * @see #setLayerType(int, android.graphics.Paint)
3117     * @see #LAYER_TYPE_SOFTWARE
3118     * @see #LAYER_TYPE_HARDWARE
3119     */
3120    public static final int LAYER_TYPE_NONE = 0;
3121
3122    /**
3123     * <p>Indicates that the view has a software layer. A software layer is backed
3124     * by a bitmap and causes the view to be rendered using Android's software
3125     * rendering pipeline, even if hardware acceleration is enabled.</p>
3126     *
3127     * <p>Software layers have various usages:</p>
3128     * <p>When the application is not using hardware acceleration, a software layer
3129     * is useful to apply a specific color filter and/or blending mode and/or
3130     * translucency to a view and all its children.</p>
3131     * <p>When the application is using hardware acceleration, a software layer
3132     * is useful to render drawing primitives not supported by the hardware
3133     * accelerated pipeline. It can also be used to cache a complex view tree
3134     * into a texture and reduce the complexity of drawing operations. For instance,
3135     * when animating a complex view tree with a translation, a software layer can
3136     * be used to render the view tree only once.</p>
3137     * <p>Software layers should be avoided when the affected view tree updates
3138     * often. Every update will require to re-render the software layer, which can
3139     * potentially be slow (particularly when hardware acceleration is turned on
3140     * since the layer will have to be uploaded into a hardware texture after every
3141     * update.)</p>
3142     *
3143     * @see #getLayerType()
3144     * @see #setLayerType(int, android.graphics.Paint)
3145     * @see #LAYER_TYPE_NONE
3146     * @see #LAYER_TYPE_HARDWARE
3147     */
3148    public static final int LAYER_TYPE_SOFTWARE = 1;
3149
3150    /**
3151     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3152     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3153     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3154     * rendering pipeline, but only if hardware acceleration is turned on for the
3155     * view hierarchy. When hardware acceleration is turned off, hardware layers
3156     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3157     *
3158     * <p>A hardware layer is useful to apply a specific color filter and/or
3159     * blending mode and/or translucency to a view and all its children.</p>
3160     * <p>A hardware layer can be used to cache a complex view tree into a
3161     * texture and reduce the complexity of drawing operations. For instance,
3162     * when animating a complex view tree with a translation, a hardware layer can
3163     * be used to render the view tree only once.</p>
3164     * <p>A hardware layer can also be used to increase the rendering quality when
3165     * rotation transformations are applied on a view. It can also be used to
3166     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3167     *
3168     * @see #getLayerType()
3169     * @see #setLayerType(int, android.graphics.Paint)
3170     * @see #LAYER_TYPE_NONE
3171     * @see #LAYER_TYPE_SOFTWARE
3172     */
3173    public static final int LAYER_TYPE_HARDWARE = 2;
3174
3175    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3176            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3177            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3178            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3179    })
3180    int mLayerType = LAYER_TYPE_NONE;
3181    Paint mLayerPaint;
3182    Rect mLocalDirtyRect;
3183
3184    /**
3185     * Set to true when the view is sending hover accessibility events because it
3186     * is the innermost hovered view.
3187     */
3188    private boolean mSendingHoverAccessibilityEvents;
3189
3190    /**
3191     * Delegate for injecting accessibility functionality.
3192     */
3193    AccessibilityDelegate mAccessibilityDelegate;
3194
3195    /**
3196     * Consistency verifier for debugging purposes.
3197     * @hide
3198     */
3199    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3200            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3201                    new InputEventConsistencyVerifier(this, 0) : null;
3202
3203    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3204
3205    /**
3206     * Simple constructor to use when creating a view from code.
3207     *
3208     * @param context The Context the view is running in, through which it can
3209     *        access the current theme, resources, etc.
3210     */
3211    public View(Context context) {
3212        mContext = context;
3213        mResources = context != null ? context.getResources() : null;
3214        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3215        // Set layout and text direction defaults
3216        mPrivateFlags2 =
3217                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3218                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3219                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3220                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3221                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3222                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3223        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3224        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3225        mUserPaddingStart = UNDEFINED_PADDING;
3226        mUserPaddingEnd = UNDEFINED_PADDING;
3227    }
3228
3229    /**
3230     * Constructor that is called when inflating a view from XML. This is called
3231     * when a view is being constructed from an XML file, supplying attributes
3232     * that were specified in the XML file. This version uses a default style of
3233     * 0, so the only attribute values applied are those in the Context's Theme
3234     * and the given AttributeSet.
3235     *
3236     * <p>
3237     * The method onFinishInflate() will be called after all children have been
3238     * added.
3239     *
3240     * @param context The Context the view is running in, through which it can
3241     *        access the current theme, resources, etc.
3242     * @param attrs The attributes of the XML tag that is inflating the view.
3243     * @see #View(Context, AttributeSet, int)
3244     */
3245    public View(Context context, AttributeSet attrs) {
3246        this(context, attrs, 0);
3247    }
3248
3249    /**
3250     * Perform inflation from XML and apply a class-specific base style. This
3251     * constructor of View allows subclasses to use their own base style when
3252     * they are inflating. For example, a Button class's constructor would call
3253     * this version of the super class constructor and supply
3254     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3255     * the theme's button style to modify all of the base view attributes (in
3256     * particular its background) as well as the Button class's attributes.
3257     *
3258     * @param context The Context the view is running in, through which it can
3259     *        access the current theme, resources, etc.
3260     * @param attrs The attributes of the XML tag that is inflating the view.
3261     * @param defStyle The default style to apply to this view. If 0, no style
3262     *        will be applied (beyond what is included in the theme). This may
3263     *        either be an attribute resource, whose value will be retrieved
3264     *        from the current theme, or an explicit style resource.
3265     * @see #View(Context, AttributeSet)
3266     */
3267    public View(Context context, AttributeSet attrs, int defStyle) {
3268        this(context);
3269
3270        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3271                defStyle, 0);
3272
3273        Drawable background = null;
3274
3275        int leftPadding = -1;
3276        int topPadding = -1;
3277        int rightPadding = -1;
3278        int bottomPadding = -1;
3279        int startPadding = UNDEFINED_PADDING;
3280        int endPadding = UNDEFINED_PADDING;
3281
3282        int padding = -1;
3283
3284        int viewFlagValues = 0;
3285        int viewFlagMasks = 0;
3286
3287        boolean setScrollContainer = false;
3288
3289        int x = 0;
3290        int y = 0;
3291
3292        float tx = 0;
3293        float ty = 0;
3294        float rotation = 0;
3295        float rotationX = 0;
3296        float rotationY = 0;
3297        float sx = 1f;
3298        float sy = 1f;
3299        boolean transformSet = false;
3300
3301        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3302        int overScrollMode = mOverScrollMode;
3303        boolean initializeScrollbars = false;
3304
3305        boolean leftPaddingDefined = false;
3306        boolean rightPaddingDefined = false;
3307        boolean startPaddingDefined = false;
3308        boolean endPaddingDefined = false;
3309
3310        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3311
3312        final int N = a.getIndexCount();
3313        for (int i = 0; i < N; i++) {
3314            int attr = a.getIndex(i);
3315            switch (attr) {
3316                case com.android.internal.R.styleable.View_background:
3317                    background = a.getDrawable(attr);
3318                    break;
3319                case com.android.internal.R.styleable.View_padding:
3320                    padding = a.getDimensionPixelSize(attr, -1);
3321                    mUserPaddingLeftInitial = padding;
3322                    mUserPaddingRightInitial = padding;
3323                    leftPaddingDefined = true;
3324                    rightPaddingDefined = true;
3325                    break;
3326                 case com.android.internal.R.styleable.View_paddingLeft:
3327                    leftPadding = a.getDimensionPixelSize(attr, -1);
3328                    mUserPaddingLeftInitial = leftPadding;
3329                    leftPaddingDefined = true;
3330                    break;
3331                case com.android.internal.R.styleable.View_paddingTop:
3332                    topPadding = a.getDimensionPixelSize(attr, -1);
3333                    break;
3334                case com.android.internal.R.styleable.View_paddingRight:
3335                    rightPadding = a.getDimensionPixelSize(attr, -1);
3336                    mUserPaddingRightInitial = rightPadding;
3337                    rightPaddingDefined = true;
3338                    break;
3339                case com.android.internal.R.styleable.View_paddingBottom:
3340                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3341                    break;
3342                case com.android.internal.R.styleable.View_paddingStart:
3343                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3344                    startPaddingDefined = true;
3345                    break;
3346                case com.android.internal.R.styleable.View_paddingEnd:
3347                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3348                    endPaddingDefined = true;
3349                    break;
3350                case com.android.internal.R.styleable.View_scrollX:
3351                    x = a.getDimensionPixelOffset(attr, 0);
3352                    break;
3353                case com.android.internal.R.styleable.View_scrollY:
3354                    y = a.getDimensionPixelOffset(attr, 0);
3355                    break;
3356                case com.android.internal.R.styleable.View_alpha:
3357                    setAlpha(a.getFloat(attr, 1f));
3358                    break;
3359                case com.android.internal.R.styleable.View_transformPivotX:
3360                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3361                    break;
3362                case com.android.internal.R.styleable.View_transformPivotY:
3363                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3364                    break;
3365                case com.android.internal.R.styleable.View_translationX:
3366                    tx = a.getDimensionPixelOffset(attr, 0);
3367                    transformSet = true;
3368                    break;
3369                case com.android.internal.R.styleable.View_translationY:
3370                    ty = a.getDimensionPixelOffset(attr, 0);
3371                    transformSet = true;
3372                    break;
3373                case com.android.internal.R.styleable.View_rotation:
3374                    rotation = a.getFloat(attr, 0);
3375                    transformSet = true;
3376                    break;
3377                case com.android.internal.R.styleable.View_rotationX:
3378                    rotationX = a.getFloat(attr, 0);
3379                    transformSet = true;
3380                    break;
3381                case com.android.internal.R.styleable.View_rotationY:
3382                    rotationY = a.getFloat(attr, 0);
3383                    transformSet = true;
3384                    break;
3385                case com.android.internal.R.styleable.View_scaleX:
3386                    sx = a.getFloat(attr, 1f);
3387                    transformSet = true;
3388                    break;
3389                case com.android.internal.R.styleable.View_scaleY:
3390                    sy = a.getFloat(attr, 1f);
3391                    transformSet = true;
3392                    break;
3393                case com.android.internal.R.styleable.View_id:
3394                    mID = a.getResourceId(attr, NO_ID);
3395                    break;
3396                case com.android.internal.R.styleable.View_tag:
3397                    mTag = a.getText(attr);
3398                    break;
3399                case com.android.internal.R.styleable.View_fitsSystemWindows:
3400                    if (a.getBoolean(attr, false)) {
3401                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3402                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3403                    }
3404                    break;
3405                case com.android.internal.R.styleable.View_focusable:
3406                    if (a.getBoolean(attr, false)) {
3407                        viewFlagValues |= FOCUSABLE;
3408                        viewFlagMasks |= FOCUSABLE_MASK;
3409                    }
3410                    break;
3411                case com.android.internal.R.styleable.View_focusableInTouchMode:
3412                    if (a.getBoolean(attr, false)) {
3413                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3414                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3415                    }
3416                    break;
3417                case com.android.internal.R.styleable.View_clickable:
3418                    if (a.getBoolean(attr, false)) {
3419                        viewFlagValues |= CLICKABLE;
3420                        viewFlagMasks |= CLICKABLE;
3421                    }
3422                    break;
3423                case com.android.internal.R.styleable.View_longClickable:
3424                    if (a.getBoolean(attr, false)) {
3425                        viewFlagValues |= LONG_CLICKABLE;
3426                        viewFlagMasks |= LONG_CLICKABLE;
3427                    }
3428                    break;
3429                case com.android.internal.R.styleable.View_saveEnabled:
3430                    if (!a.getBoolean(attr, true)) {
3431                        viewFlagValues |= SAVE_DISABLED;
3432                        viewFlagMasks |= SAVE_DISABLED_MASK;
3433                    }
3434                    break;
3435                case com.android.internal.R.styleable.View_duplicateParentState:
3436                    if (a.getBoolean(attr, false)) {
3437                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3438                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3439                    }
3440                    break;
3441                case com.android.internal.R.styleable.View_visibility:
3442                    final int visibility = a.getInt(attr, 0);
3443                    if (visibility != 0) {
3444                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3445                        viewFlagMasks |= VISIBILITY_MASK;
3446                    }
3447                    break;
3448                case com.android.internal.R.styleable.View_layoutDirection:
3449                    // Clear any layout direction flags (included resolved bits) already set
3450                    mPrivateFlags2 &=
3451                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3452                    // Set the layout direction flags depending on the value of the attribute
3453                    final int layoutDirection = a.getInt(attr, -1);
3454                    final int value = (layoutDirection != -1) ?
3455                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3456                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3457                    break;
3458                case com.android.internal.R.styleable.View_drawingCacheQuality:
3459                    final int cacheQuality = a.getInt(attr, 0);
3460                    if (cacheQuality != 0) {
3461                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3462                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3463                    }
3464                    break;
3465                case com.android.internal.R.styleable.View_contentDescription:
3466                    setContentDescription(a.getString(attr));
3467                    break;
3468                case com.android.internal.R.styleable.View_labelFor:
3469                    setLabelFor(a.getResourceId(attr, NO_ID));
3470                    break;
3471                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3472                    if (!a.getBoolean(attr, true)) {
3473                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3474                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3475                    }
3476                    break;
3477                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3478                    if (!a.getBoolean(attr, true)) {
3479                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3480                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3481                    }
3482                    break;
3483                case R.styleable.View_scrollbars:
3484                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3485                    if (scrollbars != SCROLLBARS_NONE) {
3486                        viewFlagValues |= scrollbars;
3487                        viewFlagMasks |= SCROLLBARS_MASK;
3488                        initializeScrollbars = true;
3489                    }
3490                    break;
3491                //noinspection deprecation
3492                case R.styleable.View_fadingEdge:
3493                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3494                        // Ignore the attribute starting with ICS
3495                        break;
3496                    }
3497                    // With builds < ICS, fall through and apply fading edges
3498                case R.styleable.View_requiresFadingEdge:
3499                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3500                    if (fadingEdge != FADING_EDGE_NONE) {
3501                        viewFlagValues |= fadingEdge;
3502                        viewFlagMasks |= FADING_EDGE_MASK;
3503                        initializeFadingEdge(a);
3504                    }
3505                    break;
3506                case R.styleable.View_scrollbarStyle:
3507                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3508                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3509                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3510                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3511                    }
3512                    break;
3513                case R.styleable.View_isScrollContainer:
3514                    setScrollContainer = true;
3515                    if (a.getBoolean(attr, false)) {
3516                        setScrollContainer(true);
3517                    }
3518                    break;
3519                case com.android.internal.R.styleable.View_keepScreenOn:
3520                    if (a.getBoolean(attr, false)) {
3521                        viewFlagValues |= KEEP_SCREEN_ON;
3522                        viewFlagMasks |= KEEP_SCREEN_ON;
3523                    }
3524                    break;
3525                case R.styleable.View_filterTouchesWhenObscured:
3526                    if (a.getBoolean(attr, false)) {
3527                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3528                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3529                    }
3530                    break;
3531                case R.styleable.View_nextFocusLeft:
3532                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3533                    break;
3534                case R.styleable.View_nextFocusRight:
3535                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3536                    break;
3537                case R.styleable.View_nextFocusUp:
3538                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3539                    break;
3540                case R.styleable.View_nextFocusDown:
3541                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3542                    break;
3543                case R.styleable.View_nextFocusForward:
3544                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3545                    break;
3546                case R.styleable.View_minWidth:
3547                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3548                    break;
3549                case R.styleable.View_minHeight:
3550                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3551                    break;
3552                case R.styleable.View_onClick:
3553                    if (context.isRestricted()) {
3554                        throw new IllegalStateException("The android:onClick attribute cannot "
3555                                + "be used within a restricted context");
3556                    }
3557
3558                    final String handlerName = a.getString(attr);
3559                    if (handlerName != null) {
3560                        setOnClickListener(new OnClickListener() {
3561                            private Method mHandler;
3562
3563                            public void onClick(View v) {
3564                                if (mHandler == null) {
3565                                    try {
3566                                        mHandler = getContext().getClass().getMethod(handlerName,
3567                                                View.class);
3568                                    } catch (NoSuchMethodException e) {
3569                                        int id = getId();
3570                                        String idText = id == NO_ID ? "" : " with id '"
3571                                                + getContext().getResources().getResourceEntryName(
3572                                                    id) + "'";
3573                                        throw new IllegalStateException("Could not find a method " +
3574                                                handlerName + "(View) in the activity "
3575                                                + getContext().getClass() + " for onClick handler"
3576                                                + " on view " + View.this.getClass() + idText, e);
3577                                    }
3578                                }
3579
3580                                try {
3581                                    mHandler.invoke(getContext(), View.this);
3582                                } catch (IllegalAccessException e) {
3583                                    throw new IllegalStateException("Could not execute non "
3584                                            + "public method of the activity", e);
3585                                } catch (InvocationTargetException e) {
3586                                    throw new IllegalStateException("Could not execute "
3587                                            + "method of the activity", e);
3588                                }
3589                            }
3590                        });
3591                    }
3592                    break;
3593                case R.styleable.View_overScrollMode:
3594                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3595                    break;
3596                case R.styleable.View_verticalScrollbarPosition:
3597                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3598                    break;
3599                case R.styleable.View_layerType:
3600                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3601                    break;
3602                case R.styleable.View_textDirection:
3603                    // Clear any text direction flag already set
3604                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3605                    // Set the text direction flags depending on the value of the attribute
3606                    final int textDirection = a.getInt(attr, -1);
3607                    if (textDirection != -1) {
3608                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3609                    }
3610                    break;
3611                case R.styleable.View_textAlignment:
3612                    // Clear any text alignment flag already set
3613                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3614                    // Set the text alignment flag depending on the value of the attribute
3615                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3616                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3617                    break;
3618                case R.styleable.View_importantForAccessibility:
3619                    setImportantForAccessibility(a.getInt(attr,
3620                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3621                    break;
3622            }
3623        }
3624
3625        setOverScrollMode(overScrollMode);
3626
3627        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3628        // the resolved layout direction). Those cached values will be used later during padding
3629        // resolution.
3630        mUserPaddingStart = startPadding;
3631        mUserPaddingEnd = endPadding;
3632
3633        if (background != null) {
3634            setBackground(background);
3635        }
3636
3637        if (padding >= 0) {
3638            leftPadding = padding;
3639            topPadding = padding;
3640            rightPadding = padding;
3641            bottomPadding = padding;
3642            mUserPaddingLeftInitial = padding;
3643            mUserPaddingRightInitial = padding;
3644        }
3645
3646        // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3647        // left / right padding are used if defined (meaning here nothing to do). If they are not
3648        // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3649        // start / end and resolve them as left / right (layout direction is not taken into account).
3650        if (isRtlCompatibilityMode()) {
3651            if (!leftPaddingDefined && startPaddingDefined) {
3652                leftPadding = startPadding;
3653            }
3654            if (!rightPaddingDefined && endPaddingDefined) {
3655                rightPadding = endPadding;
3656            }
3657        }
3658
3659        // If the user specified the padding (either with android:padding or
3660        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3661        // use the default padding or the padding from the background drawable
3662        // (stored at this point in mPadding*). Padding resolution will happen later if
3663        // RTL is supported.
3664        mUserPaddingLeftInitial = leftPadding >= 0 ? leftPadding : mPaddingLeft;
3665        mUserPaddingRightInitial = rightPadding >= 0 ? rightPadding : mPaddingRight;
3666        internalSetPadding(
3667                mUserPaddingLeftInitial,
3668                topPadding >= 0 ? topPadding : mPaddingTop,
3669                mUserPaddingRightInitial,
3670                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3671
3672        if (viewFlagMasks != 0) {
3673            setFlags(viewFlagValues, viewFlagMasks);
3674        }
3675
3676        if (initializeScrollbars) {
3677            initializeScrollbars(a);
3678        }
3679
3680        a.recycle();
3681
3682        // Needs to be called after mViewFlags is set
3683        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3684            recomputePadding();
3685        }
3686
3687        if (x != 0 || y != 0) {
3688            scrollTo(x, y);
3689        }
3690
3691        if (transformSet) {
3692            setTranslationX(tx);
3693            setTranslationY(ty);
3694            setRotation(rotation);
3695            setRotationX(rotationX);
3696            setRotationY(rotationY);
3697            setScaleX(sx);
3698            setScaleY(sy);
3699        }
3700
3701        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3702            setScrollContainer(true);
3703        }
3704
3705        computeOpaqueFlags();
3706    }
3707
3708    /**
3709     * Non-public constructor for use in testing
3710     */
3711    View() {
3712        mResources = null;
3713    }
3714
3715    public String toString() {
3716        StringBuilder out = new StringBuilder(128);
3717        out.append(getClass().getName());
3718        out.append('{');
3719        out.append(Integer.toHexString(System.identityHashCode(this)));
3720        out.append(' ');
3721        switch (mViewFlags&VISIBILITY_MASK) {
3722            case VISIBLE: out.append('V'); break;
3723            case INVISIBLE: out.append('I'); break;
3724            case GONE: out.append('G'); break;
3725            default: out.append('.'); break;
3726        }
3727        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3728        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3729        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3730        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3731        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3732        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3733        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3734        out.append(' ');
3735        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3736        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3737        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3738        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3739            out.append('p');
3740        } else {
3741            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3742        }
3743        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3744        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3745        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3746        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3747        out.append(' ');
3748        out.append(mLeft);
3749        out.append(',');
3750        out.append(mTop);
3751        out.append('-');
3752        out.append(mRight);
3753        out.append(',');
3754        out.append(mBottom);
3755        final int id = getId();
3756        if (id != NO_ID) {
3757            out.append(" #");
3758            out.append(Integer.toHexString(id));
3759            final Resources r = mResources;
3760            if (id != 0 && r != null) {
3761                try {
3762                    String pkgname;
3763                    switch (id&0xff000000) {
3764                        case 0x7f000000:
3765                            pkgname="app";
3766                            break;
3767                        case 0x01000000:
3768                            pkgname="android";
3769                            break;
3770                        default:
3771                            pkgname = r.getResourcePackageName(id);
3772                            break;
3773                    }
3774                    String typename = r.getResourceTypeName(id);
3775                    String entryname = r.getResourceEntryName(id);
3776                    out.append(" ");
3777                    out.append(pkgname);
3778                    out.append(":");
3779                    out.append(typename);
3780                    out.append("/");
3781                    out.append(entryname);
3782                } catch (Resources.NotFoundException e) {
3783                }
3784            }
3785        }
3786        out.append("}");
3787        return out.toString();
3788    }
3789
3790    /**
3791     * <p>
3792     * Initializes the fading edges from a given set of styled attributes. This
3793     * method should be called by subclasses that need fading edges and when an
3794     * instance of these subclasses is created programmatically rather than
3795     * being inflated from XML. This method is automatically called when the XML
3796     * is inflated.
3797     * </p>
3798     *
3799     * @param a the styled attributes set to initialize the fading edges from
3800     */
3801    protected void initializeFadingEdge(TypedArray a) {
3802        initScrollCache();
3803
3804        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3805                R.styleable.View_fadingEdgeLength,
3806                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3807    }
3808
3809    /**
3810     * Returns the size of the vertical faded edges used to indicate that more
3811     * content in this view is visible.
3812     *
3813     * @return The size in pixels of the vertical faded edge or 0 if vertical
3814     *         faded edges are not enabled for this view.
3815     * @attr ref android.R.styleable#View_fadingEdgeLength
3816     */
3817    public int getVerticalFadingEdgeLength() {
3818        if (isVerticalFadingEdgeEnabled()) {
3819            ScrollabilityCache cache = mScrollCache;
3820            if (cache != null) {
3821                return cache.fadingEdgeLength;
3822            }
3823        }
3824        return 0;
3825    }
3826
3827    /**
3828     * Set the size of the faded edge used to indicate that more content in this
3829     * view is available.  Will not change whether the fading edge is enabled; use
3830     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3831     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3832     * for the vertical or horizontal fading edges.
3833     *
3834     * @param length The size in pixels of the faded edge used to indicate that more
3835     *        content in this view is visible.
3836     */
3837    public void setFadingEdgeLength(int length) {
3838        initScrollCache();
3839        mScrollCache.fadingEdgeLength = length;
3840    }
3841
3842    /**
3843     * Returns the size of the horizontal faded edges used to indicate that more
3844     * content in this view is visible.
3845     *
3846     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3847     *         faded edges are not enabled for this view.
3848     * @attr ref android.R.styleable#View_fadingEdgeLength
3849     */
3850    public int getHorizontalFadingEdgeLength() {
3851        if (isHorizontalFadingEdgeEnabled()) {
3852            ScrollabilityCache cache = mScrollCache;
3853            if (cache != null) {
3854                return cache.fadingEdgeLength;
3855            }
3856        }
3857        return 0;
3858    }
3859
3860    /**
3861     * Returns the width of the vertical scrollbar.
3862     *
3863     * @return The width in pixels of the vertical scrollbar or 0 if there
3864     *         is no vertical scrollbar.
3865     */
3866    public int getVerticalScrollbarWidth() {
3867        ScrollabilityCache cache = mScrollCache;
3868        if (cache != null) {
3869            ScrollBarDrawable scrollBar = cache.scrollBar;
3870            if (scrollBar != null) {
3871                int size = scrollBar.getSize(true);
3872                if (size <= 0) {
3873                    size = cache.scrollBarSize;
3874                }
3875                return size;
3876            }
3877            return 0;
3878        }
3879        return 0;
3880    }
3881
3882    /**
3883     * Returns the height of the horizontal scrollbar.
3884     *
3885     * @return The height in pixels of the horizontal scrollbar or 0 if
3886     *         there is no horizontal scrollbar.
3887     */
3888    protected int getHorizontalScrollbarHeight() {
3889        ScrollabilityCache cache = mScrollCache;
3890        if (cache != null) {
3891            ScrollBarDrawable scrollBar = cache.scrollBar;
3892            if (scrollBar != null) {
3893                int size = scrollBar.getSize(false);
3894                if (size <= 0) {
3895                    size = cache.scrollBarSize;
3896                }
3897                return size;
3898            }
3899            return 0;
3900        }
3901        return 0;
3902    }
3903
3904    /**
3905     * <p>
3906     * Initializes the scrollbars from a given set of styled attributes. This
3907     * method should be called by subclasses that need scrollbars and when an
3908     * instance of these subclasses is created programmatically rather than
3909     * being inflated from XML. This method is automatically called when the XML
3910     * is inflated.
3911     * </p>
3912     *
3913     * @param a the styled attributes set to initialize the scrollbars from
3914     */
3915    protected void initializeScrollbars(TypedArray a) {
3916        initScrollCache();
3917
3918        final ScrollabilityCache scrollabilityCache = mScrollCache;
3919
3920        if (scrollabilityCache.scrollBar == null) {
3921            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3922        }
3923
3924        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3925
3926        if (!fadeScrollbars) {
3927            scrollabilityCache.state = ScrollabilityCache.ON;
3928        }
3929        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3930
3931
3932        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3933                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3934                        .getScrollBarFadeDuration());
3935        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3936                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3937                ViewConfiguration.getScrollDefaultDelay());
3938
3939
3940        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3941                com.android.internal.R.styleable.View_scrollbarSize,
3942                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3943
3944        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3945        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3946
3947        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3948        if (thumb != null) {
3949            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3950        }
3951
3952        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3953                false);
3954        if (alwaysDraw) {
3955            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3956        }
3957
3958        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3959        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3960
3961        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3962        if (thumb != null) {
3963            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3964        }
3965
3966        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3967                false);
3968        if (alwaysDraw) {
3969            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3970        }
3971
3972        // Apply layout direction to the new Drawables if needed
3973        final int layoutDirection = getLayoutDirection();
3974        if (track != null) {
3975            track.setLayoutDirection(layoutDirection);
3976        }
3977        if (thumb != null) {
3978            thumb.setLayoutDirection(layoutDirection);
3979        }
3980
3981        // Re-apply user/background padding so that scrollbar(s) get added
3982        resolvePadding();
3983    }
3984
3985    /**
3986     * <p>
3987     * Initalizes the scrollability cache if necessary.
3988     * </p>
3989     */
3990    private void initScrollCache() {
3991        if (mScrollCache == null) {
3992            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3993        }
3994    }
3995
3996    private ScrollabilityCache getScrollCache() {
3997        initScrollCache();
3998        return mScrollCache;
3999    }
4000
4001    /**
4002     * Set the position of the vertical scroll bar. Should be one of
4003     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4004     * {@link #SCROLLBAR_POSITION_RIGHT}.
4005     *
4006     * @param position Where the vertical scroll bar should be positioned.
4007     */
4008    public void setVerticalScrollbarPosition(int position) {
4009        if (mVerticalScrollbarPosition != position) {
4010            mVerticalScrollbarPosition = position;
4011            computeOpaqueFlags();
4012            resolvePadding();
4013        }
4014    }
4015
4016    /**
4017     * @return The position where the vertical scroll bar will show, if applicable.
4018     * @see #setVerticalScrollbarPosition(int)
4019     */
4020    public int getVerticalScrollbarPosition() {
4021        return mVerticalScrollbarPosition;
4022    }
4023
4024    ListenerInfo getListenerInfo() {
4025        if (mListenerInfo != null) {
4026            return mListenerInfo;
4027        }
4028        mListenerInfo = new ListenerInfo();
4029        return mListenerInfo;
4030    }
4031
4032    /**
4033     * Register a callback to be invoked when focus of this view changed.
4034     *
4035     * @param l The callback that will run.
4036     */
4037    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4038        getListenerInfo().mOnFocusChangeListener = l;
4039    }
4040
4041    /**
4042     * Add a listener that will be called when the bounds of the view change due to
4043     * layout processing.
4044     *
4045     * @param listener The listener that will be called when layout bounds change.
4046     */
4047    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4048        ListenerInfo li = getListenerInfo();
4049        if (li.mOnLayoutChangeListeners == null) {
4050            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4051        }
4052        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4053            li.mOnLayoutChangeListeners.add(listener);
4054        }
4055    }
4056
4057    /**
4058     * Remove a listener for layout changes.
4059     *
4060     * @param listener The listener for layout bounds change.
4061     */
4062    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4063        ListenerInfo li = mListenerInfo;
4064        if (li == null || li.mOnLayoutChangeListeners == null) {
4065            return;
4066        }
4067        li.mOnLayoutChangeListeners.remove(listener);
4068    }
4069
4070    /**
4071     * Add a listener for attach state changes.
4072     *
4073     * This listener will be called whenever this view is attached or detached
4074     * from a window. Remove the listener using
4075     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4076     *
4077     * @param listener Listener to attach
4078     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4079     */
4080    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4081        ListenerInfo li = getListenerInfo();
4082        if (li.mOnAttachStateChangeListeners == null) {
4083            li.mOnAttachStateChangeListeners
4084                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4085        }
4086        li.mOnAttachStateChangeListeners.add(listener);
4087    }
4088
4089    /**
4090     * Remove a listener for attach state changes. The listener will receive no further
4091     * notification of window attach/detach events.
4092     *
4093     * @param listener Listener to remove
4094     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4095     */
4096    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4097        ListenerInfo li = mListenerInfo;
4098        if (li == null || li.mOnAttachStateChangeListeners == null) {
4099            return;
4100        }
4101        li.mOnAttachStateChangeListeners.remove(listener);
4102    }
4103
4104    /**
4105     * Returns the focus-change callback registered for this view.
4106     *
4107     * @return The callback, or null if one is not registered.
4108     */
4109    public OnFocusChangeListener getOnFocusChangeListener() {
4110        ListenerInfo li = mListenerInfo;
4111        return li != null ? li.mOnFocusChangeListener : null;
4112    }
4113
4114    /**
4115     * Register a callback to be invoked when this view is clicked. If this view is not
4116     * clickable, it becomes clickable.
4117     *
4118     * @param l The callback that will run
4119     *
4120     * @see #setClickable(boolean)
4121     */
4122    public void setOnClickListener(OnClickListener l) {
4123        if (!isClickable()) {
4124            setClickable(true);
4125        }
4126        getListenerInfo().mOnClickListener = l;
4127    }
4128
4129    /**
4130     * Return whether this view has an attached OnClickListener.  Returns
4131     * true if there is a listener, false if there is none.
4132     */
4133    public boolean hasOnClickListeners() {
4134        ListenerInfo li = mListenerInfo;
4135        return (li != null && li.mOnClickListener != null);
4136    }
4137
4138    /**
4139     * Register a callback to be invoked when this view is clicked and held. If this view is not
4140     * long clickable, it becomes long clickable.
4141     *
4142     * @param l The callback that will run
4143     *
4144     * @see #setLongClickable(boolean)
4145     */
4146    public void setOnLongClickListener(OnLongClickListener l) {
4147        if (!isLongClickable()) {
4148            setLongClickable(true);
4149        }
4150        getListenerInfo().mOnLongClickListener = l;
4151    }
4152
4153    /**
4154     * Register a callback to be invoked when the context menu for this view is
4155     * being built. If this view is not long clickable, it becomes long clickable.
4156     *
4157     * @param l The callback that will run
4158     *
4159     */
4160    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4161        if (!isLongClickable()) {
4162            setLongClickable(true);
4163        }
4164        getListenerInfo().mOnCreateContextMenuListener = l;
4165    }
4166
4167    /**
4168     * Call this view's OnClickListener, if it is defined.  Performs all normal
4169     * actions associated with clicking: reporting accessibility event, playing
4170     * a sound, etc.
4171     *
4172     * @return True there was an assigned OnClickListener that was called, false
4173     *         otherwise is returned.
4174     */
4175    public boolean performClick() {
4176        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4177
4178        ListenerInfo li = mListenerInfo;
4179        if (li != null && li.mOnClickListener != null) {
4180            playSoundEffect(SoundEffectConstants.CLICK);
4181            li.mOnClickListener.onClick(this);
4182            return true;
4183        }
4184
4185        return false;
4186    }
4187
4188    /**
4189     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4190     * this only calls the listener, and does not do any associated clicking
4191     * actions like reporting an accessibility event.
4192     *
4193     * @return True there was an assigned OnClickListener that was called, false
4194     *         otherwise is returned.
4195     */
4196    public boolean callOnClick() {
4197        ListenerInfo li = mListenerInfo;
4198        if (li != null && li.mOnClickListener != null) {
4199            li.mOnClickListener.onClick(this);
4200            return true;
4201        }
4202        return false;
4203    }
4204
4205    /**
4206     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4207     * OnLongClickListener did not consume the event.
4208     *
4209     * @return True if one of the above receivers consumed the event, false otherwise.
4210     */
4211    public boolean performLongClick() {
4212        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4213
4214        boolean handled = false;
4215        ListenerInfo li = mListenerInfo;
4216        if (li != null && li.mOnLongClickListener != null) {
4217            handled = li.mOnLongClickListener.onLongClick(View.this);
4218        }
4219        if (!handled) {
4220            handled = showContextMenu();
4221        }
4222        if (handled) {
4223            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4224        }
4225        return handled;
4226    }
4227
4228    /**
4229     * Performs button-related actions during a touch down event.
4230     *
4231     * @param event The event.
4232     * @return True if the down was consumed.
4233     *
4234     * @hide
4235     */
4236    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4237        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4238            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4239                return true;
4240            }
4241        }
4242        return false;
4243    }
4244
4245    /**
4246     * Bring up the context menu for this view.
4247     *
4248     * @return Whether a context menu was displayed.
4249     */
4250    public boolean showContextMenu() {
4251        return getParent().showContextMenuForChild(this);
4252    }
4253
4254    /**
4255     * Bring up the context menu for this view, referring to the item under the specified point.
4256     *
4257     * @param x The referenced x coordinate.
4258     * @param y The referenced y coordinate.
4259     * @param metaState The keyboard modifiers that were pressed.
4260     * @return Whether a context menu was displayed.
4261     *
4262     * @hide
4263     */
4264    public boolean showContextMenu(float x, float y, int metaState) {
4265        return showContextMenu();
4266    }
4267
4268    /**
4269     * Start an action mode.
4270     *
4271     * @param callback Callback that will control the lifecycle of the action mode
4272     * @return The new action mode if it is started, null otherwise
4273     *
4274     * @see ActionMode
4275     */
4276    public ActionMode startActionMode(ActionMode.Callback callback) {
4277        ViewParent parent = getParent();
4278        if (parent == null) return null;
4279        return parent.startActionModeForChild(this, callback);
4280    }
4281
4282    /**
4283     * Register a callback to be invoked when a hardware key is pressed in this view.
4284     * Key presses in software input methods will generally not trigger the methods of
4285     * this listener.
4286     * @param l the key listener to attach to this view
4287     */
4288    public void setOnKeyListener(OnKeyListener l) {
4289        getListenerInfo().mOnKeyListener = l;
4290    }
4291
4292    /**
4293     * Register a callback to be invoked when a touch event is sent to this view.
4294     * @param l the touch listener to attach to this view
4295     */
4296    public void setOnTouchListener(OnTouchListener l) {
4297        getListenerInfo().mOnTouchListener = l;
4298    }
4299
4300    /**
4301     * Register a callback to be invoked when a generic motion event is sent to this view.
4302     * @param l the generic motion listener to attach to this view
4303     */
4304    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4305        getListenerInfo().mOnGenericMotionListener = l;
4306    }
4307
4308    /**
4309     * Register a callback to be invoked when a hover event is sent to this view.
4310     * @param l the hover listener to attach to this view
4311     */
4312    public void setOnHoverListener(OnHoverListener l) {
4313        getListenerInfo().mOnHoverListener = l;
4314    }
4315
4316    /**
4317     * Register a drag event listener callback object for this View. The parameter is
4318     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4319     * View, the system calls the
4320     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4321     * @param l An implementation of {@link android.view.View.OnDragListener}.
4322     */
4323    public void setOnDragListener(OnDragListener l) {
4324        getListenerInfo().mOnDragListener = l;
4325    }
4326
4327    /**
4328     * Give this view focus. This will cause
4329     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4330     *
4331     * Note: this does not check whether this {@link View} should get focus, it just
4332     * gives it focus no matter what.  It should only be called internally by framework
4333     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4334     *
4335     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4336     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4337     *        focus moved when requestFocus() is called. It may not always
4338     *        apply, in which case use the default View.FOCUS_DOWN.
4339     * @param previouslyFocusedRect The rectangle of the view that had focus
4340     *        prior in this View's coordinate system.
4341     */
4342    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4343        if (DBG) {
4344            System.out.println(this + " requestFocus()");
4345        }
4346
4347        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4348            mPrivateFlags |= PFLAG_FOCUSED;
4349
4350            if (mParent != null) {
4351                mParent.requestChildFocus(this, this);
4352            }
4353
4354            onFocusChanged(true, direction, previouslyFocusedRect);
4355            refreshDrawableState();
4356
4357            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4358                notifyAccessibilityStateChanged();
4359            }
4360        }
4361    }
4362
4363    /**
4364     * Request that a rectangle of this view be visible on the screen,
4365     * scrolling if necessary just enough.
4366     *
4367     * <p>A View should call this if it maintains some notion of which part
4368     * of its content is interesting.  For example, a text editing view
4369     * should call this when its cursor moves.
4370     *
4371     * @param rectangle The rectangle.
4372     * @return Whether any parent scrolled.
4373     */
4374    public boolean requestRectangleOnScreen(Rect rectangle) {
4375        return requestRectangleOnScreen(rectangle, false);
4376    }
4377
4378    /**
4379     * Request that a rectangle of this view be visible on the screen,
4380     * scrolling if necessary just enough.
4381     *
4382     * <p>A View should call this if it maintains some notion of which part
4383     * of its content is interesting.  For example, a text editing view
4384     * should call this when its cursor moves.
4385     *
4386     * <p>When <code>immediate</code> is set to true, scrolling will not be
4387     * animated.
4388     *
4389     * @param rectangle The rectangle.
4390     * @param immediate True to forbid animated scrolling, false otherwise
4391     * @return Whether any parent scrolled.
4392     */
4393    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4394        if (mParent == null) {
4395            return false;
4396        }
4397
4398        View child = this;
4399
4400        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4401        position.set(rectangle);
4402
4403        ViewParent parent = mParent;
4404        boolean scrolled = false;
4405        while (parent != null) {
4406            rectangle.set((int) position.left, (int) position.top,
4407                    (int) position.right, (int) position.bottom);
4408
4409            scrolled |= parent.requestChildRectangleOnScreen(child,
4410                    rectangle, immediate);
4411
4412            if (!child.hasIdentityMatrix()) {
4413                child.getMatrix().mapRect(position);
4414            }
4415
4416            position.offset(child.mLeft, child.mTop);
4417
4418            if (!(parent instanceof View)) {
4419                break;
4420            }
4421
4422            View parentView = (View) parent;
4423
4424            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4425
4426            child = parentView;
4427            parent = child.getParent();
4428        }
4429
4430        return scrolled;
4431    }
4432
4433    /**
4434     * Called when this view wants to give up focus. If focus is cleared
4435     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4436     * <p>
4437     * <strong>Note:</strong> When a View clears focus the framework is trying
4438     * to give focus to the first focusable View from the top. Hence, if this
4439     * View is the first from the top that can take focus, then all callbacks
4440     * related to clearing focus will be invoked after wich the framework will
4441     * give focus to this view.
4442     * </p>
4443     */
4444    public void clearFocus() {
4445        if (DBG) {
4446            System.out.println(this + " clearFocus()");
4447        }
4448
4449        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4450            mPrivateFlags &= ~PFLAG_FOCUSED;
4451
4452            if (mParent != null) {
4453                mParent.clearChildFocus(this);
4454            }
4455
4456            onFocusChanged(false, 0, null);
4457
4458            refreshDrawableState();
4459
4460            ensureInputFocusOnFirstFocusable();
4461
4462            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4463                notifyAccessibilityStateChanged();
4464            }
4465        }
4466    }
4467
4468    void ensureInputFocusOnFirstFocusable() {
4469        View root = getRootView();
4470        if (root != null) {
4471            root.requestFocus();
4472        }
4473    }
4474
4475    /**
4476     * Called internally by the view system when a new view is getting focus.
4477     * This is what clears the old focus.
4478     */
4479    void unFocus() {
4480        if (DBG) {
4481            System.out.println(this + " unFocus()");
4482        }
4483
4484        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4485            mPrivateFlags &= ~PFLAG_FOCUSED;
4486
4487            onFocusChanged(false, 0, null);
4488            refreshDrawableState();
4489
4490            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4491                notifyAccessibilityStateChanged();
4492            }
4493        }
4494    }
4495
4496    /**
4497     * Returns true if this view has focus iteself, or is the ancestor of the
4498     * view that has focus.
4499     *
4500     * @return True if this view has or contains focus, false otherwise.
4501     */
4502    @ViewDebug.ExportedProperty(category = "focus")
4503    public boolean hasFocus() {
4504        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4505    }
4506
4507    /**
4508     * Returns true if this view is focusable or if it contains a reachable View
4509     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4510     * is a View whose parents do not block descendants focus.
4511     *
4512     * Only {@link #VISIBLE} views are considered focusable.
4513     *
4514     * @return True if the view is focusable or if the view contains a focusable
4515     *         View, false otherwise.
4516     *
4517     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4518     */
4519    public boolean hasFocusable() {
4520        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4521    }
4522
4523    /**
4524     * Called by the view system when the focus state of this view changes.
4525     * When the focus change event is caused by directional navigation, direction
4526     * and previouslyFocusedRect provide insight into where the focus is coming from.
4527     * When overriding, be sure to call up through to the super class so that
4528     * the standard focus handling will occur.
4529     *
4530     * @param gainFocus True if the View has focus; false otherwise.
4531     * @param direction The direction focus has moved when requestFocus()
4532     *                  is called to give this view focus. Values are
4533     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4534     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4535     *                  It may not always apply, in which case use the default.
4536     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4537     *        system, of the previously focused view.  If applicable, this will be
4538     *        passed in as finer grained information about where the focus is coming
4539     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4540     */
4541    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4542        if (gainFocus) {
4543            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4544                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4545            }
4546        }
4547
4548        InputMethodManager imm = InputMethodManager.peekInstance();
4549        if (!gainFocus) {
4550            if (isPressed()) {
4551                setPressed(false);
4552            }
4553            if (imm != null && mAttachInfo != null
4554                    && mAttachInfo.mHasWindowFocus) {
4555                imm.focusOut(this);
4556            }
4557            onFocusLost();
4558        } else if (imm != null && mAttachInfo != null
4559                && mAttachInfo.mHasWindowFocus) {
4560            imm.focusIn(this);
4561        }
4562
4563        invalidate(true);
4564        ListenerInfo li = mListenerInfo;
4565        if (li != null && li.mOnFocusChangeListener != null) {
4566            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4567        }
4568
4569        if (mAttachInfo != null) {
4570            mAttachInfo.mKeyDispatchState.reset(this);
4571        }
4572    }
4573
4574    /**
4575     * Sends an accessibility event of the given type. If accessibility is
4576     * not enabled this method has no effect. The default implementation calls
4577     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4578     * to populate information about the event source (this View), then calls
4579     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4580     * populate the text content of the event source including its descendants,
4581     * and last calls
4582     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4583     * on its parent to resuest sending of the event to interested parties.
4584     * <p>
4585     * If an {@link AccessibilityDelegate} has been specified via calling
4586     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4587     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4588     * responsible for handling this call.
4589     * </p>
4590     *
4591     * @param eventType The type of the event to send, as defined by several types from
4592     * {@link android.view.accessibility.AccessibilityEvent}, such as
4593     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4594     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4595     *
4596     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4597     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4598     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4599     * @see AccessibilityDelegate
4600     */
4601    public void sendAccessibilityEvent(int eventType) {
4602        if (mAccessibilityDelegate != null) {
4603            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4604        } else {
4605            sendAccessibilityEventInternal(eventType);
4606        }
4607    }
4608
4609    /**
4610     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4611     * {@link AccessibilityEvent} to make an announcement which is related to some
4612     * sort of a context change for which none of the events representing UI transitions
4613     * is a good fit. For example, announcing a new page in a book. If accessibility
4614     * is not enabled this method does nothing.
4615     *
4616     * @param text The announcement text.
4617     */
4618    public void announceForAccessibility(CharSequence text) {
4619        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4620            AccessibilityEvent event = AccessibilityEvent.obtain(
4621                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4622            onInitializeAccessibilityEvent(event);
4623            event.getText().add(text);
4624            event.setContentDescription(null);
4625            mParent.requestSendAccessibilityEvent(this, event);
4626        }
4627    }
4628
4629    /**
4630     * @see #sendAccessibilityEvent(int)
4631     *
4632     * Note: Called from the default {@link AccessibilityDelegate}.
4633     */
4634    void sendAccessibilityEventInternal(int eventType) {
4635        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4636            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4637        }
4638    }
4639
4640    /**
4641     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4642     * takes as an argument an empty {@link AccessibilityEvent} and does not
4643     * perform a check whether accessibility is enabled.
4644     * <p>
4645     * If an {@link AccessibilityDelegate} has been specified via calling
4646     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4647     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4648     * is responsible for handling this call.
4649     * </p>
4650     *
4651     * @param event The event to send.
4652     *
4653     * @see #sendAccessibilityEvent(int)
4654     */
4655    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4656        if (mAccessibilityDelegate != null) {
4657            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4658        } else {
4659            sendAccessibilityEventUncheckedInternal(event);
4660        }
4661    }
4662
4663    /**
4664     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4665     *
4666     * Note: Called from the default {@link AccessibilityDelegate}.
4667     */
4668    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4669        if (!isShown()) {
4670            return;
4671        }
4672        onInitializeAccessibilityEvent(event);
4673        // Only a subset of accessibility events populates text content.
4674        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4675            dispatchPopulateAccessibilityEvent(event);
4676        }
4677        // In the beginning we called #isShown(), so we know that getParent() is not null.
4678        getParent().requestSendAccessibilityEvent(this, event);
4679    }
4680
4681    /**
4682     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4683     * to its children for adding their text content to the event. Note that the
4684     * event text is populated in a separate dispatch path since we add to the
4685     * event not only the text of the source but also the text of all its descendants.
4686     * A typical implementation will call
4687     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4688     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4689     * on each child. Override this method if custom population of the event text
4690     * content is required.
4691     * <p>
4692     * If an {@link AccessibilityDelegate} has been specified via calling
4693     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4694     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4695     * is responsible for handling this call.
4696     * </p>
4697     * <p>
4698     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4699     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4700     * </p>
4701     *
4702     * @param event The event.
4703     *
4704     * @return True if the event population was completed.
4705     */
4706    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4707        if (mAccessibilityDelegate != null) {
4708            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4709        } else {
4710            return dispatchPopulateAccessibilityEventInternal(event);
4711        }
4712    }
4713
4714    /**
4715     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4716     *
4717     * Note: Called from the default {@link AccessibilityDelegate}.
4718     */
4719    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4720        onPopulateAccessibilityEvent(event);
4721        return false;
4722    }
4723
4724    /**
4725     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4726     * giving a chance to this View to populate the accessibility event with its
4727     * text content. While this method is free to modify event
4728     * attributes other than text content, doing so should normally be performed in
4729     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4730     * <p>
4731     * Example: Adding formatted date string to an accessibility event in addition
4732     *          to the text added by the super implementation:
4733     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4734     *     super.onPopulateAccessibilityEvent(event);
4735     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4736     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4737     *         mCurrentDate.getTimeInMillis(), flags);
4738     *     event.getText().add(selectedDateUtterance);
4739     * }</pre>
4740     * <p>
4741     * If an {@link AccessibilityDelegate} has been specified via calling
4742     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4743     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4744     * is responsible for handling this call.
4745     * </p>
4746     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4747     * information to the event, in case the default implementation has basic information to add.
4748     * </p>
4749     *
4750     * @param event The accessibility event which to populate.
4751     *
4752     * @see #sendAccessibilityEvent(int)
4753     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4754     */
4755    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4756        if (mAccessibilityDelegate != null) {
4757            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4758        } else {
4759            onPopulateAccessibilityEventInternal(event);
4760        }
4761    }
4762
4763    /**
4764     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4765     *
4766     * Note: Called from the default {@link AccessibilityDelegate}.
4767     */
4768    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4769
4770    }
4771
4772    /**
4773     * Initializes an {@link AccessibilityEvent} with information about
4774     * this View which is the event source. In other words, the source of
4775     * an accessibility event is the view whose state change triggered firing
4776     * the event.
4777     * <p>
4778     * Example: Setting the password property of an event in addition
4779     *          to properties set by the super implementation:
4780     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4781     *     super.onInitializeAccessibilityEvent(event);
4782     *     event.setPassword(true);
4783     * }</pre>
4784     * <p>
4785     * If an {@link AccessibilityDelegate} has been specified via calling
4786     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4787     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4788     * is responsible for handling this call.
4789     * </p>
4790     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4791     * information to the event, in case the default implementation has basic information to add.
4792     * </p>
4793     * @param event The event to initialize.
4794     *
4795     * @see #sendAccessibilityEvent(int)
4796     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4797     */
4798    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4799        if (mAccessibilityDelegate != null) {
4800            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4801        } else {
4802            onInitializeAccessibilityEventInternal(event);
4803        }
4804    }
4805
4806    /**
4807     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4808     *
4809     * Note: Called from the default {@link AccessibilityDelegate}.
4810     */
4811    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4812        event.setSource(this);
4813        event.setClassName(View.class.getName());
4814        event.setPackageName(getContext().getPackageName());
4815        event.setEnabled(isEnabled());
4816        event.setContentDescription(mContentDescription);
4817
4818        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4819            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4820            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4821                    FOCUSABLES_ALL);
4822            event.setItemCount(focusablesTempList.size());
4823            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4824            focusablesTempList.clear();
4825        }
4826    }
4827
4828    /**
4829     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4830     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4831     * This method is responsible for obtaining an accessibility node info from a
4832     * pool of reusable instances and calling
4833     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4834     * initialize the former.
4835     * <p>
4836     * Note: The client is responsible for recycling the obtained instance by calling
4837     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4838     * </p>
4839     *
4840     * @return A populated {@link AccessibilityNodeInfo}.
4841     *
4842     * @see AccessibilityNodeInfo
4843     */
4844    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4845        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4846        if (provider != null) {
4847            return provider.createAccessibilityNodeInfo(View.NO_ID);
4848        } else {
4849            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4850            onInitializeAccessibilityNodeInfo(info);
4851            return info;
4852        }
4853    }
4854
4855    /**
4856     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4857     * The base implementation sets:
4858     * <ul>
4859     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4860     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4861     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4862     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4863     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4864     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4865     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4866     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4867     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4868     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4869     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4870     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4871     * </ul>
4872     * <p>
4873     * Subclasses should override this method, call the super implementation,
4874     * and set additional attributes.
4875     * </p>
4876     * <p>
4877     * If an {@link AccessibilityDelegate} has been specified via calling
4878     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4879     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4880     * is responsible for handling this call.
4881     * </p>
4882     *
4883     * @param info The instance to initialize.
4884     */
4885    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4886        if (mAccessibilityDelegate != null) {
4887            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4888        } else {
4889            onInitializeAccessibilityNodeInfoInternal(info);
4890        }
4891    }
4892
4893    /**
4894     * Gets the location of this view in screen coordintates.
4895     *
4896     * @param outRect The output location
4897     */
4898    private void getBoundsOnScreen(Rect outRect) {
4899        if (mAttachInfo == null) {
4900            return;
4901        }
4902
4903        RectF position = mAttachInfo.mTmpTransformRect;
4904        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4905
4906        if (!hasIdentityMatrix()) {
4907            getMatrix().mapRect(position);
4908        }
4909
4910        position.offset(mLeft, mTop);
4911
4912        ViewParent parent = mParent;
4913        while (parent instanceof View) {
4914            View parentView = (View) parent;
4915
4916            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4917
4918            if (!parentView.hasIdentityMatrix()) {
4919                parentView.getMatrix().mapRect(position);
4920            }
4921
4922            position.offset(parentView.mLeft, parentView.mTop);
4923
4924            parent = parentView.mParent;
4925        }
4926
4927        if (parent instanceof ViewRootImpl) {
4928            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4929            position.offset(0, -viewRootImpl.mCurScrollY);
4930        }
4931
4932        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4933
4934        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4935                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4936    }
4937
4938    /**
4939     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4940     *
4941     * Note: Called from the default {@link AccessibilityDelegate}.
4942     */
4943    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4944        Rect bounds = mAttachInfo.mTmpInvalRect;
4945
4946        getDrawingRect(bounds);
4947        info.setBoundsInParent(bounds);
4948
4949        getBoundsOnScreen(bounds);
4950        info.setBoundsInScreen(bounds);
4951
4952        ViewParent parent = getParentForAccessibility();
4953        if (parent instanceof View) {
4954            info.setParent((View) parent);
4955        }
4956
4957        if (mID != View.NO_ID) {
4958            View rootView = getRootView();
4959            if (rootView == null) {
4960                rootView = this;
4961            }
4962            View label = rootView.findLabelForView(this, mID);
4963            if (label != null) {
4964                info.setLabeledBy(label);
4965            }
4966        }
4967
4968        if (mLabelForId != View.NO_ID) {
4969            View rootView = getRootView();
4970            if (rootView == null) {
4971                rootView = this;
4972            }
4973            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
4974            if (labeled != null) {
4975                info.setLabelFor(labeled);
4976            }
4977        }
4978
4979        info.setVisibleToUser(isVisibleToUser());
4980
4981        info.setPackageName(mContext.getPackageName());
4982        info.setClassName(View.class.getName());
4983        info.setContentDescription(getContentDescription());
4984
4985        info.setEnabled(isEnabled());
4986        info.setClickable(isClickable());
4987        info.setFocusable(isFocusable());
4988        info.setFocused(isFocused());
4989        info.setAccessibilityFocused(isAccessibilityFocused());
4990        info.setSelected(isSelected());
4991        info.setLongClickable(isLongClickable());
4992
4993        // TODO: These make sense only if we are in an AdapterView but all
4994        // views can be selected. Maybe from accessibility perspective
4995        // we should report as selectable view in an AdapterView.
4996        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4997        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4998
4999        if (isFocusable()) {
5000            if (isFocused()) {
5001                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5002            } else {
5003                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5004            }
5005        }
5006
5007        if (!isAccessibilityFocused()) {
5008            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5009        } else {
5010            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5011        }
5012
5013        if (isClickable() && isEnabled()) {
5014            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5015        }
5016
5017        if (isLongClickable() && isEnabled()) {
5018            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5019        }
5020
5021        if (mContentDescription != null && mContentDescription.length() > 0) {
5022            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5023            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5024            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5025                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5026                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5027        }
5028    }
5029
5030    private View findLabelForView(View view, int labeledId) {
5031        if (mMatchLabelForPredicate == null) {
5032            mMatchLabelForPredicate = new MatchLabelForPredicate();
5033        }
5034        mMatchLabelForPredicate.mLabeledId = labeledId;
5035        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5036    }
5037
5038    /**
5039     * Computes whether this view is visible to the user. Such a view is
5040     * attached, visible, all its predecessors are visible, it is not clipped
5041     * entirely by its predecessors, and has an alpha greater than zero.
5042     *
5043     * @return Whether the view is visible on the screen.
5044     *
5045     * @hide
5046     */
5047    protected boolean isVisibleToUser() {
5048        return isVisibleToUser(null);
5049    }
5050
5051    /**
5052     * Computes whether the given portion of this view is visible to the user.
5053     * Such a view is attached, visible, all its predecessors are visible,
5054     * has an alpha greater than zero, and the specified portion is not
5055     * clipped entirely by its predecessors.
5056     *
5057     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5058     *                    <code>null</code>, and the entire view will be tested in this case.
5059     *                    When <code>true</code> is returned by the function, the actual visible
5060     *                    region will be stored in this parameter; that is, if boundInView is fully
5061     *                    contained within the view, no modification will be made, otherwise regions
5062     *                    outside of the visible area of the view will be clipped.
5063     *
5064     * @return Whether the specified portion of the view is visible on the screen.
5065     *
5066     * @hide
5067     */
5068    protected boolean isVisibleToUser(Rect boundInView) {
5069        if (mAttachInfo != null) {
5070            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5071            Point offset = mAttachInfo.mPoint;
5072            // The first two checks are made also made by isShown() which
5073            // however traverses the tree up to the parent to catch that.
5074            // Therefore, we do some fail fast check to minimize the up
5075            // tree traversal.
5076            boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE
5077                && getAlpha() > 0
5078                && isShown()
5079                && getGlobalVisibleRect(visibleRect, offset);
5080            if (isVisible && boundInView != null) {
5081                visibleRect.offset(-offset.x, -offset.y);
5082                // isVisible is always true here, use a simple assignment
5083                isVisible = boundInView.intersect(visibleRect);
5084            }
5085            return isVisible;
5086        }
5087
5088        return false;
5089    }
5090
5091    /**
5092     * Returns the delegate for implementing accessibility support via
5093     * composition. For more details see {@link AccessibilityDelegate}.
5094     *
5095     * @return The delegate, or null if none set.
5096     *
5097     * @hide
5098     */
5099    public AccessibilityDelegate getAccessibilityDelegate() {
5100        return mAccessibilityDelegate;
5101    }
5102
5103    /**
5104     * Sets a delegate for implementing accessibility support via composition as
5105     * opposed to inheritance. The delegate's primary use is for implementing
5106     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5107     *
5108     * @param delegate The delegate instance.
5109     *
5110     * @see AccessibilityDelegate
5111     */
5112    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5113        mAccessibilityDelegate = delegate;
5114    }
5115
5116    /**
5117     * Gets the provider for managing a virtual view hierarchy rooted at this View
5118     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5119     * that explore the window content.
5120     * <p>
5121     * If this method returns an instance, this instance is responsible for managing
5122     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5123     * View including the one representing the View itself. Similarly the returned
5124     * instance is responsible for performing accessibility actions on any virtual
5125     * view or the root view itself.
5126     * </p>
5127     * <p>
5128     * If an {@link AccessibilityDelegate} has been specified via calling
5129     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5130     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5131     * is responsible for handling this call.
5132     * </p>
5133     *
5134     * @return The provider.
5135     *
5136     * @see AccessibilityNodeProvider
5137     */
5138    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5139        if (mAccessibilityDelegate != null) {
5140            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5141        } else {
5142            return null;
5143        }
5144    }
5145
5146    /**
5147     * Gets the unique identifier of this view on the screen for accessibility purposes.
5148     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5149     *
5150     * @return The view accessibility id.
5151     *
5152     * @hide
5153     */
5154    public int getAccessibilityViewId() {
5155        if (mAccessibilityViewId == NO_ID) {
5156            mAccessibilityViewId = sNextAccessibilityViewId++;
5157        }
5158        return mAccessibilityViewId;
5159    }
5160
5161    /**
5162     * Gets the unique identifier of the window in which this View reseides.
5163     *
5164     * @return The window accessibility id.
5165     *
5166     * @hide
5167     */
5168    public int getAccessibilityWindowId() {
5169        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5170    }
5171
5172    /**
5173     * Gets the {@link View} description. It briefly describes the view and is
5174     * primarily used for accessibility support. Set this property to enable
5175     * better accessibility support for your application. This is especially
5176     * true for views that do not have textual representation (For example,
5177     * ImageButton).
5178     *
5179     * @return The content description.
5180     *
5181     * @attr ref android.R.styleable#View_contentDescription
5182     */
5183    @ViewDebug.ExportedProperty(category = "accessibility")
5184    public CharSequence getContentDescription() {
5185        return mContentDescription;
5186    }
5187
5188    /**
5189     * Sets the {@link View} description. It briefly describes the view and is
5190     * primarily used for accessibility support. Set this property to enable
5191     * better accessibility support for your application. This is especially
5192     * true for views that do not have textual representation (For example,
5193     * ImageButton).
5194     *
5195     * @param contentDescription The content description.
5196     *
5197     * @attr ref android.R.styleable#View_contentDescription
5198     */
5199    @RemotableViewMethod
5200    public void setContentDescription(CharSequence contentDescription) {
5201        mContentDescription = contentDescription;
5202        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5203        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5204             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5205        }
5206    }
5207
5208    /**
5209     * Gets the id of a view for which this view serves as a label for
5210     * accessibility purposes.
5211     *
5212     * @return The labeled view id.
5213     */
5214    @ViewDebug.ExportedProperty(category = "accessibility")
5215    public int getLabelFor() {
5216        return mLabelForId;
5217    }
5218
5219    /**
5220     * Sets the id of a view for which this view serves as a label for
5221     * accessibility purposes.
5222     *
5223     * @param id The labeled view id.
5224     */
5225    @RemotableViewMethod
5226    public void setLabelFor(int id) {
5227        mLabelForId = id;
5228        if (mLabelForId != View.NO_ID
5229                && mID == View.NO_ID) {
5230            mID = generateViewId();
5231        }
5232    }
5233
5234    /**
5235     * Invoked whenever this view loses focus, either by losing window focus or by losing
5236     * focus within its window. This method can be used to clear any state tied to the
5237     * focus. For instance, if a button is held pressed with the trackball and the window
5238     * loses focus, this method can be used to cancel the press.
5239     *
5240     * Subclasses of View overriding this method should always call super.onFocusLost().
5241     *
5242     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5243     * @see #onWindowFocusChanged(boolean)
5244     *
5245     * @hide pending API council approval
5246     */
5247    protected void onFocusLost() {
5248        resetPressedState();
5249    }
5250
5251    private void resetPressedState() {
5252        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5253            return;
5254        }
5255
5256        if (isPressed()) {
5257            setPressed(false);
5258
5259            if (!mHasPerformedLongPress) {
5260                removeLongPressCallback();
5261            }
5262        }
5263    }
5264
5265    /**
5266     * Returns true if this view has focus
5267     *
5268     * @return True if this view has focus, false otherwise.
5269     */
5270    @ViewDebug.ExportedProperty(category = "focus")
5271    public boolean isFocused() {
5272        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5273    }
5274
5275    /**
5276     * Find the view in the hierarchy rooted at this view that currently has
5277     * focus.
5278     *
5279     * @return The view that currently has focus, or null if no focused view can
5280     *         be found.
5281     */
5282    public View findFocus() {
5283        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5284    }
5285
5286    /**
5287     * Indicates whether this view is one of the set of scrollable containers in
5288     * its window.
5289     *
5290     * @return whether this view is one of the set of scrollable containers in
5291     * its window
5292     *
5293     * @attr ref android.R.styleable#View_isScrollContainer
5294     */
5295    public boolean isScrollContainer() {
5296        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5297    }
5298
5299    /**
5300     * Change whether this view is one of the set of scrollable containers in
5301     * its window.  This will be used to determine whether the window can
5302     * resize or must pan when a soft input area is open -- scrollable
5303     * containers allow the window to use resize mode since the container
5304     * will appropriately shrink.
5305     *
5306     * @attr ref android.R.styleable#View_isScrollContainer
5307     */
5308    public void setScrollContainer(boolean isScrollContainer) {
5309        if (isScrollContainer) {
5310            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5311                mAttachInfo.mScrollContainers.add(this);
5312                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5313            }
5314            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5315        } else {
5316            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5317                mAttachInfo.mScrollContainers.remove(this);
5318            }
5319            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5320        }
5321    }
5322
5323    /**
5324     * Returns the quality of the drawing cache.
5325     *
5326     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5327     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5328     *
5329     * @see #setDrawingCacheQuality(int)
5330     * @see #setDrawingCacheEnabled(boolean)
5331     * @see #isDrawingCacheEnabled()
5332     *
5333     * @attr ref android.R.styleable#View_drawingCacheQuality
5334     */
5335    public int getDrawingCacheQuality() {
5336        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5337    }
5338
5339    /**
5340     * Set the drawing cache quality of this view. This value is used only when the
5341     * drawing cache is enabled
5342     *
5343     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5344     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5345     *
5346     * @see #getDrawingCacheQuality()
5347     * @see #setDrawingCacheEnabled(boolean)
5348     * @see #isDrawingCacheEnabled()
5349     *
5350     * @attr ref android.R.styleable#View_drawingCacheQuality
5351     */
5352    public void setDrawingCacheQuality(int quality) {
5353        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5354    }
5355
5356    /**
5357     * Returns whether the screen should remain on, corresponding to the current
5358     * value of {@link #KEEP_SCREEN_ON}.
5359     *
5360     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5361     *
5362     * @see #setKeepScreenOn(boolean)
5363     *
5364     * @attr ref android.R.styleable#View_keepScreenOn
5365     */
5366    public boolean getKeepScreenOn() {
5367        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5368    }
5369
5370    /**
5371     * Controls whether the screen should remain on, modifying the
5372     * value of {@link #KEEP_SCREEN_ON}.
5373     *
5374     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5375     *
5376     * @see #getKeepScreenOn()
5377     *
5378     * @attr ref android.R.styleable#View_keepScreenOn
5379     */
5380    public void setKeepScreenOn(boolean keepScreenOn) {
5381        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5382    }
5383
5384    /**
5385     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5386     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5387     *
5388     * @attr ref android.R.styleable#View_nextFocusLeft
5389     */
5390    public int getNextFocusLeftId() {
5391        return mNextFocusLeftId;
5392    }
5393
5394    /**
5395     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5396     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5397     * decide automatically.
5398     *
5399     * @attr ref android.R.styleable#View_nextFocusLeft
5400     */
5401    public void setNextFocusLeftId(int nextFocusLeftId) {
5402        mNextFocusLeftId = nextFocusLeftId;
5403    }
5404
5405    /**
5406     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5407     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5408     *
5409     * @attr ref android.R.styleable#View_nextFocusRight
5410     */
5411    public int getNextFocusRightId() {
5412        return mNextFocusRightId;
5413    }
5414
5415    /**
5416     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5417     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5418     * decide automatically.
5419     *
5420     * @attr ref android.R.styleable#View_nextFocusRight
5421     */
5422    public void setNextFocusRightId(int nextFocusRightId) {
5423        mNextFocusRightId = nextFocusRightId;
5424    }
5425
5426    /**
5427     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5428     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5429     *
5430     * @attr ref android.R.styleable#View_nextFocusUp
5431     */
5432    public int getNextFocusUpId() {
5433        return mNextFocusUpId;
5434    }
5435
5436    /**
5437     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5438     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5439     * decide automatically.
5440     *
5441     * @attr ref android.R.styleable#View_nextFocusUp
5442     */
5443    public void setNextFocusUpId(int nextFocusUpId) {
5444        mNextFocusUpId = nextFocusUpId;
5445    }
5446
5447    /**
5448     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5449     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5450     *
5451     * @attr ref android.R.styleable#View_nextFocusDown
5452     */
5453    public int getNextFocusDownId() {
5454        return mNextFocusDownId;
5455    }
5456
5457    /**
5458     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5459     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5460     * decide automatically.
5461     *
5462     * @attr ref android.R.styleable#View_nextFocusDown
5463     */
5464    public void setNextFocusDownId(int nextFocusDownId) {
5465        mNextFocusDownId = nextFocusDownId;
5466    }
5467
5468    /**
5469     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5470     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5471     *
5472     * @attr ref android.R.styleable#View_nextFocusForward
5473     */
5474    public int getNextFocusForwardId() {
5475        return mNextFocusForwardId;
5476    }
5477
5478    /**
5479     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5480     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5481     * decide automatically.
5482     *
5483     * @attr ref android.R.styleable#View_nextFocusForward
5484     */
5485    public void setNextFocusForwardId(int nextFocusForwardId) {
5486        mNextFocusForwardId = nextFocusForwardId;
5487    }
5488
5489    /**
5490     * Returns the visibility of this view and all of its ancestors
5491     *
5492     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5493     */
5494    public boolean isShown() {
5495        View current = this;
5496        //noinspection ConstantConditions
5497        do {
5498            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5499                return false;
5500            }
5501            ViewParent parent = current.mParent;
5502            if (parent == null) {
5503                return false; // We are not attached to the view root
5504            }
5505            if (!(parent instanceof View)) {
5506                return true;
5507            }
5508            current = (View) parent;
5509        } while (current != null);
5510
5511        return false;
5512    }
5513
5514    /**
5515     * Called by the view hierarchy when the content insets for a window have
5516     * changed, to allow it to adjust its content to fit within those windows.
5517     * The content insets tell you the space that the status bar, input method,
5518     * and other system windows infringe on the application's window.
5519     *
5520     * <p>You do not normally need to deal with this function, since the default
5521     * window decoration given to applications takes care of applying it to the
5522     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5523     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5524     * and your content can be placed under those system elements.  You can then
5525     * use this method within your view hierarchy if you have parts of your UI
5526     * which you would like to ensure are not being covered.
5527     *
5528     * <p>The default implementation of this method simply applies the content
5529     * inset's to the view's padding, consuming that content (modifying the
5530     * insets to be 0), and returning true.  This behavior is off by default, but can
5531     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5532     *
5533     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5534     * insets object is propagated down the hierarchy, so any changes made to it will
5535     * be seen by all following views (including potentially ones above in
5536     * the hierarchy since this is a depth-first traversal).  The first view
5537     * that returns true will abort the entire traversal.
5538     *
5539     * <p>The default implementation works well for a situation where it is
5540     * used with a container that covers the entire window, allowing it to
5541     * apply the appropriate insets to its content on all edges.  If you need
5542     * a more complicated layout (such as two different views fitting system
5543     * windows, one on the top of the window, and one on the bottom),
5544     * you can override the method and handle the insets however you would like.
5545     * Note that the insets provided by the framework are always relative to the
5546     * far edges of the window, not accounting for the location of the called view
5547     * within that window.  (In fact when this method is called you do not yet know
5548     * where the layout will place the view, as it is done before layout happens.)
5549     *
5550     * <p>Note: unlike many View methods, there is no dispatch phase to this
5551     * call.  If you are overriding it in a ViewGroup and want to allow the
5552     * call to continue to your children, you must be sure to call the super
5553     * implementation.
5554     *
5555     * <p>Here is a sample layout that makes use of fitting system windows
5556     * to have controls for a video view placed inside of the window decorations
5557     * that it hides and shows.  This can be used with code like the second
5558     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5559     *
5560     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5561     *
5562     * @param insets Current content insets of the window.  Prior to
5563     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5564     * the insets or else you and Android will be unhappy.
5565     *
5566     * @return Return true if this view applied the insets and it should not
5567     * continue propagating further down the hierarchy, false otherwise.
5568     * @see #getFitsSystemWindows()
5569     * @see #setFitsSystemWindows(boolean)
5570     * @see #setSystemUiVisibility(int)
5571     */
5572    protected boolean fitSystemWindows(Rect insets) {
5573        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5574            mUserPaddingStart = UNDEFINED_PADDING;
5575            mUserPaddingEnd = UNDEFINED_PADDING;
5576            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5577                    || mAttachInfo == null
5578                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5579                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5580                return true;
5581            } else {
5582                internalSetPadding(0, 0, 0, 0);
5583                return false;
5584            }
5585        }
5586        return false;
5587    }
5588
5589    /**
5590     * Sets whether or not this view should account for system screen decorations
5591     * such as the status bar and inset its content; that is, controlling whether
5592     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5593     * executed.  See that method for more details.
5594     *
5595     * <p>Note that if you are providing your own implementation of
5596     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5597     * flag to true -- your implementation will be overriding the default
5598     * implementation that checks this flag.
5599     *
5600     * @param fitSystemWindows If true, then the default implementation of
5601     * {@link #fitSystemWindows(Rect)} will be executed.
5602     *
5603     * @attr ref android.R.styleable#View_fitsSystemWindows
5604     * @see #getFitsSystemWindows()
5605     * @see #fitSystemWindows(Rect)
5606     * @see #setSystemUiVisibility(int)
5607     */
5608    public void setFitsSystemWindows(boolean fitSystemWindows) {
5609        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5610    }
5611
5612    /**
5613     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5614     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5615     * will be executed.
5616     *
5617     * @return Returns true if the default implementation of
5618     * {@link #fitSystemWindows(Rect)} will be executed.
5619     *
5620     * @attr ref android.R.styleable#View_fitsSystemWindows
5621     * @see #setFitsSystemWindows()
5622     * @see #fitSystemWindows(Rect)
5623     * @see #setSystemUiVisibility(int)
5624     */
5625    public boolean getFitsSystemWindows() {
5626        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5627    }
5628
5629    /** @hide */
5630    public boolean fitsSystemWindows() {
5631        return getFitsSystemWindows();
5632    }
5633
5634    /**
5635     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5636     */
5637    public void requestFitSystemWindows() {
5638        if (mParent != null) {
5639            mParent.requestFitSystemWindows();
5640        }
5641    }
5642
5643    /**
5644     * For use by PhoneWindow to make its own system window fitting optional.
5645     * @hide
5646     */
5647    public void makeOptionalFitsSystemWindows() {
5648        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5649    }
5650
5651    /**
5652     * Returns the visibility status for this view.
5653     *
5654     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5655     * @attr ref android.R.styleable#View_visibility
5656     */
5657    @ViewDebug.ExportedProperty(mapping = {
5658        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5659        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5660        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5661    })
5662    public int getVisibility() {
5663        return mViewFlags & VISIBILITY_MASK;
5664    }
5665
5666    /**
5667     * Set the enabled state of this view.
5668     *
5669     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5670     * @attr ref android.R.styleable#View_visibility
5671     */
5672    @RemotableViewMethod
5673    public void setVisibility(int visibility) {
5674        setFlags(visibility, VISIBILITY_MASK);
5675        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5676    }
5677
5678    /**
5679     * Returns the enabled status for this view. The interpretation of the
5680     * enabled state varies by subclass.
5681     *
5682     * @return True if this view is enabled, false otherwise.
5683     */
5684    @ViewDebug.ExportedProperty
5685    public boolean isEnabled() {
5686        return (mViewFlags & ENABLED_MASK) == ENABLED;
5687    }
5688
5689    /**
5690     * Set the enabled state of this view. The interpretation of the enabled
5691     * state varies by subclass.
5692     *
5693     * @param enabled True if this view is enabled, false otherwise.
5694     */
5695    @RemotableViewMethod
5696    public void setEnabled(boolean enabled) {
5697        if (enabled == isEnabled()) return;
5698
5699        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5700
5701        /*
5702         * The View most likely has to change its appearance, so refresh
5703         * the drawable state.
5704         */
5705        refreshDrawableState();
5706
5707        // Invalidate too, since the default behavior for views is to be
5708        // be drawn at 50% alpha rather than to change the drawable.
5709        invalidate(true);
5710    }
5711
5712    /**
5713     * Set whether this view can receive the focus.
5714     *
5715     * Setting this to false will also ensure that this view is not focusable
5716     * in touch mode.
5717     *
5718     * @param focusable If true, this view can receive the focus.
5719     *
5720     * @see #setFocusableInTouchMode(boolean)
5721     * @attr ref android.R.styleable#View_focusable
5722     */
5723    public void setFocusable(boolean focusable) {
5724        if (!focusable) {
5725            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5726        }
5727        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5728    }
5729
5730    /**
5731     * Set whether this view can receive focus while in touch mode.
5732     *
5733     * Setting this to true will also ensure that this view is focusable.
5734     *
5735     * @param focusableInTouchMode If true, this view can receive the focus while
5736     *   in touch mode.
5737     *
5738     * @see #setFocusable(boolean)
5739     * @attr ref android.R.styleable#View_focusableInTouchMode
5740     */
5741    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5742        // Focusable in touch mode should always be set before the focusable flag
5743        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5744        // which, in touch mode, will not successfully request focus on this view
5745        // because the focusable in touch mode flag is not set
5746        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5747        if (focusableInTouchMode) {
5748            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5749        }
5750    }
5751
5752    /**
5753     * Set whether this view should have sound effects enabled for events such as
5754     * clicking and touching.
5755     *
5756     * <p>You may wish to disable sound effects for a view if you already play sounds,
5757     * for instance, a dial key that plays dtmf tones.
5758     *
5759     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5760     * @see #isSoundEffectsEnabled()
5761     * @see #playSoundEffect(int)
5762     * @attr ref android.R.styleable#View_soundEffectsEnabled
5763     */
5764    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5765        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5766    }
5767
5768    /**
5769     * @return whether this view should have sound effects enabled for events such as
5770     *     clicking and touching.
5771     *
5772     * @see #setSoundEffectsEnabled(boolean)
5773     * @see #playSoundEffect(int)
5774     * @attr ref android.R.styleable#View_soundEffectsEnabled
5775     */
5776    @ViewDebug.ExportedProperty
5777    public boolean isSoundEffectsEnabled() {
5778        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5779    }
5780
5781    /**
5782     * Set whether this view should have haptic feedback for events such as
5783     * long presses.
5784     *
5785     * <p>You may wish to disable haptic feedback if your view already controls
5786     * its own haptic feedback.
5787     *
5788     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5789     * @see #isHapticFeedbackEnabled()
5790     * @see #performHapticFeedback(int)
5791     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5792     */
5793    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5794        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5795    }
5796
5797    /**
5798     * @return whether this view should have haptic feedback enabled for events
5799     * long presses.
5800     *
5801     * @see #setHapticFeedbackEnabled(boolean)
5802     * @see #performHapticFeedback(int)
5803     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5804     */
5805    @ViewDebug.ExportedProperty
5806    public boolean isHapticFeedbackEnabled() {
5807        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5808    }
5809
5810    /**
5811     * Returns the layout direction for this view.
5812     *
5813     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5814     *   {@link #LAYOUT_DIRECTION_RTL},
5815     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5816     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5817     * @attr ref android.R.styleable#View_layoutDirection
5818     *
5819     * @hide
5820     */
5821    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5822        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5823        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5824        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5825        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5826    })
5827    public int getRawLayoutDirection() {
5828        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5829    }
5830
5831    /**
5832     * Set the layout direction for this view. This will propagate a reset of layout direction
5833     * resolution to the view's children and resolve layout direction for this view.
5834     *
5835     * @param layoutDirection the layout direction to set. Should be one of:
5836     *
5837     * {@link #LAYOUT_DIRECTION_LTR},
5838     * {@link #LAYOUT_DIRECTION_RTL},
5839     * {@link #LAYOUT_DIRECTION_INHERIT},
5840     * {@link #LAYOUT_DIRECTION_LOCALE}.
5841     *
5842     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5843     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5844     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5845     *
5846     * @attr ref android.R.styleable#View_layoutDirection
5847     */
5848    @RemotableViewMethod
5849    public void setLayoutDirection(int layoutDirection) {
5850        if (getRawLayoutDirection() != layoutDirection) {
5851            // Reset the current layout direction and the resolved one
5852            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5853            resetRtlProperties();
5854            // Set the new layout direction (filtered)
5855            mPrivateFlags2 |=
5856                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
5857            // We need to resolve all RTL properties as they all depend on layout direction
5858            resolveRtlPropertiesIfNeeded();
5859        }
5860    }
5861
5862    /**
5863     * Returns the resolved layout direction for this view.
5864     *
5865     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5866     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5867     *
5868     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
5869     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
5870     */
5871    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5872        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5873        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5874    })
5875    public int getLayoutDirection() {
5876        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
5877        if (targetSdkVersion < JELLY_BEAN_MR1) {
5878            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
5879            return LAYOUT_DIRECTION_LTR;
5880        }
5881        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
5882                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5883    }
5884
5885    /**
5886     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5887     * layout attribute and/or the inherited value from the parent
5888     *
5889     * @return true if the layout is right-to-left.
5890     *
5891     * @hide
5892     */
5893    @ViewDebug.ExportedProperty(category = "layout")
5894    public boolean isLayoutRtl() {
5895        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
5896    }
5897
5898    /**
5899     * Indicates whether the view is currently tracking transient state that the
5900     * app should not need to concern itself with saving and restoring, but that
5901     * the framework should take special note to preserve when possible.
5902     *
5903     * <p>A view with transient state cannot be trivially rebound from an external
5904     * data source, such as an adapter binding item views in a list. This may be
5905     * because the view is performing an animation, tracking user selection
5906     * of content, or similar.</p>
5907     *
5908     * @return true if the view has transient state
5909     */
5910    @ViewDebug.ExportedProperty(category = "layout")
5911    public boolean hasTransientState() {
5912        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
5913    }
5914
5915    /**
5916     * Set whether this view is currently tracking transient state that the
5917     * framework should attempt to preserve when possible. This flag is reference counted,
5918     * so every call to setHasTransientState(true) should be paired with a later call
5919     * to setHasTransientState(false).
5920     *
5921     * <p>A view with transient state cannot be trivially rebound from an external
5922     * data source, such as an adapter binding item views in a list. This may be
5923     * because the view is performing an animation, tracking user selection
5924     * of content, or similar.</p>
5925     *
5926     * @param hasTransientState true if this view has transient state
5927     */
5928    public void setHasTransientState(boolean hasTransientState) {
5929        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5930                mTransientStateCount - 1;
5931        if (mTransientStateCount < 0) {
5932            mTransientStateCount = 0;
5933            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5934                    "unmatched pair of setHasTransientState calls");
5935        }
5936        if ((hasTransientState && mTransientStateCount == 1) ||
5937                (!hasTransientState && mTransientStateCount == 0)) {
5938            // update flag if we've just incremented up from 0 or decremented down to 0
5939            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
5940                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
5941            if (mParent != null) {
5942                try {
5943                    mParent.childHasTransientStateChanged(this, hasTransientState);
5944                } catch (AbstractMethodError e) {
5945                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5946                            " does not fully implement ViewParent", e);
5947                }
5948            }
5949        }
5950    }
5951
5952    /**
5953     * If this view doesn't do any drawing on its own, set this flag to
5954     * allow further optimizations. By default, this flag is not set on
5955     * View, but could be set on some View subclasses such as ViewGroup.
5956     *
5957     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5958     * you should clear this flag.
5959     *
5960     * @param willNotDraw whether or not this View draw on its own
5961     */
5962    public void setWillNotDraw(boolean willNotDraw) {
5963        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5964    }
5965
5966    /**
5967     * Returns whether or not this View draws on its own.
5968     *
5969     * @return true if this view has nothing to draw, false otherwise
5970     */
5971    @ViewDebug.ExportedProperty(category = "drawing")
5972    public boolean willNotDraw() {
5973        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5974    }
5975
5976    /**
5977     * When a View's drawing cache is enabled, drawing is redirected to an
5978     * offscreen bitmap. Some views, like an ImageView, must be able to
5979     * bypass this mechanism if they already draw a single bitmap, to avoid
5980     * unnecessary usage of the memory.
5981     *
5982     * @param willNotCacheDrawing true if this view does not cache its
5983     *        drawing, false otherwise
5984     */
5985    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5986        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5987    }
5988
5989    /**
5990     * Returns whether or not this View can cache its drawing or not.
5991     *
5992     * @return true if this view does not cache its drawing, false otherwise
5993     */
5994    @ViewDebug.ExportedProperty(category = "drawing")
5995    public boolean willNotCacheDrawing() {
5996        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5997    }
5998
5999    /**
6000     * Indicates whether this view reacts to click events or not.
6001     *
6002     * @return true if the view is clickable, false otherwise
6003     *
6004     * @see #setClickable(boolean)
6005     * @attr ref android.R.styleable#View_clickable
6006     */
6007    @ViewDebug.ExportedProperty
6008    public boolean isClickable() {
6009        return (mViewFlags & CLICKABLE) == CLICKABLE;
6010    }
6011
6012    /**
6013     * Enables or disables click events for this view. When a view
6014     * is clickable it will change its state to "pressed" on every click.
6015     * Subclasses should set the view clickable to visually react to
6016     * user's clicks.
6017     *
6018     * @param clickable true to make the view clickable, false otherwise
6019     *
6020     * @see #isClickable()
6021     * @attr ref android.R.styleable#View_clickable
6022     */
6023    public void setClickable(boolean clickable) {
6024        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6025    }
6026
6027    /**
6028     * Indicates whether this view reacts to long click events or not.
6029     *
6030     * @return true if the view is long clickable, false otherwise
6031     *
6032     * @see #setLongClickable(boolean)
6033     * @attr ref android.R.styleable#View_longClickable
6034     */
6035    public boolean isLongClickable() {
6036        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6037    }
6038
6039    /**
6040     * Enables or disables long click events for this view. When a view is long
6041     * clickable it reacts to the user holding down the button for a longer
6042     * duration than a tap. This event can either launch the listener or a
6043     * context menu.
6044     *
6045     * @param longClickable true to make the view long clickable, false otherwise
6046     * @see #isLongClickable()
6047     * @attr ref android.R.styleable#View_longClickable
6048     */
6049    public void setLongClickable(boolean longClickable) {
6050        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6051    }
6052
6053    /**
6054     * Sets the pressed state for this view.
6055     *
6056     * @see #isClickable()
6057     * @see #setClickable(boolean)
6058     *
6059     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6060     *        the View's internal state from a previously set "pressed" state.
6061     */
6062    public void setPressed(boolean pressed) {
6063        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6064
6065        if (pressed) {
6066            mPrivateFlags |= PFLAG_PRESSED;
6067        } else {
6068            mPrivateFlags &= ~PFLAG_PRESSED;
6069        }
6070
6071        if (needsRefresh) {
6072            refreshDrawableState();
6073        }
6074        dispatchSetPressed(pressed);
6075    }
6076
6077    /**
6078     * Dispatch setPressed to all of this View's children.
6079     *
6080     * @see #setPressed(boolean)
6081     *
6082     * @param pressed The new pressed state
6083     */
6084    protected void dispatchSetPressed(boolean pressed) {
6085    }
6086
6087    /**
6088     * Indicates whether the view is currently in pressed state. Unless
6089     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6090     * the pressed state.
6091     *
6092     * @see #setPressed(boolean)
6093     * @see #isClickable()
6094     * @see #setClickable(boolean)
6095     *
6096     * @return true if the view is currently pressed, false otherwise
6097     */
6098    public boolean isPressed() {
6099        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6100    }
6101
6102    /**
6103     * Indicates whether this view will save its state (that is,
6104     * whether its {@link #onSaveInstanceState} method will be called).
6105     *
6106     * @return Returns true if the view state saving is enabled, else false.
6107     *
6108     * @see #setSaveEnabled(boolean)
6109     * @attr ref android.R.styleable#View_saveEnabled
6110     */
6111    public boolean isSaveEnabled() {
6112        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6113    }
6114
6115    /**
6116     * Controls whether the saving of this view's state is
6117     * enabled (that is, whether its {@link #onSaveInstanceState} method
6118     * will be called).  Note that even if freezing is enabled, the
6119     * view still must have an id assigned to it (via {@link #setId(int)})
6120     * for its state to be saved.  This flag can only disable the
6121     * saving of this view; any child views may still have their state saved.
6122     *
6123     * @param enabled Set to false to <em>disable</em> state saving, or true
6124     * (the default) to allow it.
6125     *
6126     * @see #isSaveEnabled()
6127     * @see #setId(int)
6128     * @see #onSaveInstanceState()
6129     * @attr ref android.R.styleable#View_saveEnabled
6130     */
6131    public void setSaveEnabled(boolean enabled) {
6132        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6133    }
6134
6135    /**
6136     * Gets whether the framework should discard touches when the view's
6137     * window is obscured by another visible window.
6138     * Refer to the {@link View} security documentation for more details.
6139     *
6140     * @return True if touch filtering is enabled.
6141     *
6142     * @see #setFilterTouchesWhenObscured(boolean)
6143     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6144     */
6145    @ViewDebug.ExportedProperty
6146    public boolean getFilterTouchesWhenObscured() {
6147        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6148    }
6149
6150    /**
6151     * Sets whether the framework should discard touches when the view's
6152     * window is obscured by another visible window.
6153     * Refer to the {@link View} security documentation for more details.
6154     *
6155     * @param enabled True if touch filtering should be enabled.
6156     *
6157     * @see #getFilterTouchesWhenObscured
6158     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6159     */
6160    public void setFilterTouchesWhenObscured(boolean enabled) {
6161        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6162                FILTER_TOUCHES_WHEN_OBSCURED);
6163    }
6164
6165    /**
6166     * Indicates whether the entire hierarchy under this view will save its
6167     * state when a state saving traversal occurs from its parent.  The default
6168     * is true; if false, these views will not be saved unless
6169     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6170     *
6171     * @return Returns true if the view state saving from parent is enabled, else false.
6172     *
6173     * @see #setSaveFromParentEnabled(boolean)
6174     */
6175    public boolean isSaveFromParentEnabled() {
6176        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6177    }
6178
6179    /**
6180     * Controls whether the entire hierarchy under this view will save its
6181     * state when a state saving traversal occurs from its parent.  The default
6182     * is true; if false, these views will not be saved unless
6183     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6184     *
6185     * @param enabled Set to false to <em>disable</em> state saving, or true
6186     * (the default) to allow it.
6187     *
6188     * @see #isSaveFromParentEnabled()
6189     * @see #setId(int)
6190     * @see #onSaveInstanceState()
6191     */
6192    public void setSaveFromParentEnabled(boolean enabled) {
6193        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6194    }
6195
6196
6197    /**
6198     * Returns whether this View is able to take focus.
6199     *
6200     * @return True if this view can take focus, or false otherwise.
6201     * @attr ref android.R.styleable#View_focusable
6202     */
6203    @ViewDebug.ExportedProperty(category = "focus")
6204    public final boolean isFocusable() {
6205        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6206    }
6207
6208    /**
6209     * When a view is focusable, it may not want to take focus when in touch mode.
6210     * For example, a button would like focus when the user is navigating via a D-pad
6211     * so that the user can click on it, but once the user starts touching the screen,
6212     * the button shouldn't take focus
6213     * @return Whether the view is focusable in touch mode.
6214     * @attr ref android.R.styleable#View_focusableInTouchMode
6215     */
6216    @ViewDebug.ExportedProperty
6217    public final boolean isFocusableInTouchMode() {
6218        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6219    }
6220
6221    /**
6222     * Find the nearest view in the specified direction that can take focus.
6223     * This does not actually give focus to that view.
6224     *
6225     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6226     *
6227     * @return The nearest focusable in the specified direction, or null if none
6228     *         can be found.
6229     */
6230    public View focusSearch(int direction) {
6231        if (mParent != null) {
6232            return mParent.focusSearch(this, direction);
6233        } else {
6234            return null;
6235        }
6236    }
6237
6238    /**
6239     * This method is the last chance for the focused view and its ancestors to
6240     * respond to an arrow key. This is called when the focused view did not
6241     * consume the key internally, nor could the view system find a new view in
6242     * the requested direction to give focus to.
6243     *
6244     * @param focused The currently focused view.
6245     * @param direction The direction focus wants to move. One of FOCUS_UP,
6246     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6247     * @return True if the this view consumed this unhandled move.
6248     */
6249    public boolean dispatchUnhandledMove(View focused, int direction) {
6250        return false;
6251    }
6252
6253    /**
6254     * If a user manually specified the next view id for a particular direction,
6255     * use the root to look up the view.
6256     * @param root The root view of the hierarchy containing this view.
6257     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6258     * or FOCUS_BACKWARD.
6259     * @return The user specified next view, or null if there is none.
6260     */
6261    View findUserSetNextFocus(View root, int direction) {
6262        switch (direction) {
6263            case FOCUS_LEFT:
6264                if (mNextFocusLeftId == View.NO_ID) return null;
6265                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6266            case FOCUS_RIGHT:
6267                if (mNextFocusRightId == View.NO_ID) return null;
6268                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6269            case FOCUS_UP:
6270                if (mNextFocusUpId == View.NO_ID) return null;
6271                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6272            case FOCUS_DOWN:
6273                if (mNextFocusDownId == View.NO_ID) return null;
6274                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6275            case FOCUS_FORWARD:
6276                if (mNextFocusForwardId == View.NO_ID) return null;
6277                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6278            case FOCUS_BACKWARD: {
6279                if (mID == View.NO_ID) return null;
6280                final int id = mID;
6281                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6282                    @Override
6283                    public boolean apply(View t) {
6284                        return t.mNextFocusForwardId == id;
6285                    }
6286                });
6287            }
6288        }
6289        return null;
6290    }
6291
6292    private View findViewInsideOutShouldExist(View root, int id) {
6293        if (mMatchIdPredicate == null) {
6294            mMatchIdPredicate = new MatchIdPredicate();
6295        }
6296        mMatchIdPredicate.mId = id;
6297        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6298        if (result == null) {
6299            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6300        }
6301        return result;
6302    }
6303
6304    /**
6305     * Find and return all focusable views that are descendants of this view,
6306     * possibly including this view if it is focusable itself.
6307     *
6308     * @param direction The direction of the focus
6309     * @return A list of focusable views
6310     */
6311    public ArrayList<View> getFocusables(int direction) {
6312        ArrayList<View> result = new ArrayList<View>(24);
6313        addFocusables(result, direction);
6314        return result;
6315    }
6316
6317    /**
6318     * Add any focusable views that are descendants of this view (possibly
6319     * including this view if it is focusable itself) to views.  If we are in touch mode,
6320     * only add views that are also focusable in touch mode.
6321     *
6322     * @param views Focusable views found so far
6323     * @param direction The direction of the focus
6324     */
6325    public void addFocusables(ArrayList<View> views, int direction) {
6326        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6327    }
6328
6329    /**
6330     * Adds any focusable views that are descendants of this view (possibly
6331     * including this view if it is focusable itself) to views. This method
6332     * adds all focusable views regardless if we are in touch mode or
6333     * only views focusable in touch mode if we are in touch mode or
6334     * only views that can take accessibility focus if accessibility is enabeld
6335     * depending on the focusable mode paramater.
6336     *
6337     * @param views Focusable views found so far or null if all we are interested is
6338     *        the number of focusables.
6339     * @param direction The direction of the focus.
6340     * @param focusableMode The type of focusables to be added.
6341     *
6342     * @see #FOCUSABLES_ALL
6343     * @see #FOCUSABLES_TOUCH_MODE
6344     */
6345    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6346        if (views == null) {
6347            return;
6348        }
6349        if (!isFocusable()) {
6350            return;
6351        }
6352        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6353                && isInTouchMode() && !isFocusableInTouchMode()) {
6354            return;
6355        }
6356        views.add(this);
6357    }
6358
6359    /**
6360     * Finds the Views that contain given text. The containment is case insensitive.
6361     * The search is performed by either the text that the View renders or the content
6362     * description that describes the view for accessibility purposes and the view does
6363     * not render or both. Clients can specify how the search is to be performed via
6364     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6365     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6366     *
6367     * @param outViews The output list of matching Views.
6368     * @param searched The text to match against.
6369     *
6370     * @see #FIND_VIEWS_WITH_TEXT
6371     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6372     * @see #setContentDescription(CharSequence)
6373     */
6374    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6375        if (getAccessibilityNodeProvider() != null) {
6376            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6377                outViews.add(this);
6378            }
6379        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6380                && (searched != null && searched.length() > 0)
6381                && (mContentDescription != null && mContentDescription.length() > 0)) {
6382            String searchedLowerCase = searched.toString().toLowerCase();
6383            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6384            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6385                outViews.add(this);
6386            }
6387        }
6388    }
6389
6390    /**
6391     * Find and return all touchable views that are descendants of this view,
6392     * possibly including this view if it is touchable itself.
6393     *
6394     * @return A list of touchable views
6395     */
6396    public ArrayList<View> getTouchables() {
6397        ArrayList<View> result = new ArrayList<View>();
6398        addTouchables(result);
6399        return result;
6400    }
6401
6402    /**
6403     * Add any touchable views that are descendants of this view (possibly
6404     * including this view if it is touchable itself) to views.
6405     *
6406     * @param views Touchable views found so far
6407     */
6408    public void addTouchables(ArrayList<View> views) {
6409        final int viewFlags = mViewFlags;
6410
6411        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6412                && (viewFlags & ENABLED_MASK) == ENABLED) {
6413            views.add(this);
6414        }
6415    }
6416
6417    /**
6418     * Returns whether this View is accessibility focused.
6419     *
6420     * @return True if this View is accessibility focused.
6421     */
6422    boolean isAccessibilityFocused() {
6423        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6424    }
6425
6426    /**
6427     * Call this to try to give accessibility focus to this view.
6428     *
6429     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6430     * returns false or the view is no visible or the view already has accessibility
6431     * focus.
6432     *
6433     * See also {@link #focusSearch(int)}, which is what you call to say that you
6434     * have focus, and you want your parent to look for the next one.
6435     *
6436     * @return Whether this view actually took accessibility focus.
6437     *
6438     * @hide
6439     */
6440    public boolean requestAccessibilityFocus() {
6441        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6442        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6443            return false;
6444        }
6445        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6446            return false;
6447        }
6448        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6449            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6450            ViewRootImpl viewRootImpl = getViewRootImpl();
6451            if (viewRootImpl != null) {
6452                viewRootImpl.setAccessibilityFocus(this, null);
6453            }
6454            if (mAttachInfo != null) {
6455                Rect rectangle = mAttachInfo.mTmpInvalRect;
6456                getDrawingRect(rectangle);
6457                requestRectangleOnScreen(rectangle);
6458            }
6459            invalidate();
6460            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6461            notifyAccessibilityStateChanged();
6462            return true;
6463        }
6464        return false;
6465    }
6466
6467    /**
6468     * Call this to try to clear accessibility focus of this view.
6469     *
6470     * See also {@link #focusSearch(int)}, which is what you call to say that you
6471     * have focus, and you want your parent to look for the next one.
6472     *
6473     * @hide
6474     */
6475    public void clearAccessibilityFocus() {
6476        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6477            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6478            invalidate();
6479            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6480            notifyAccessibilityStateChanged();
6481        }
6482        // Clear the global reference of accessibility focus if this
6483        // view or any of its descendants had accessibility focus.
6484        ViewRootImpl viewRootImpl = getViewRootImpl();
6485        if (viewRootImpl != null) {
6486            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6487            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6488                viewRootImpl.setAccessibilityFocus(null, null);
6489            }
6490        }
6491    }
6492
6493    private void sendAccessibilityHoverEvent(int eventType) {
6494        // Since we are not delivering to a client accessibility events from not
6495        // important views (unless the clinet request that) we need to fire the
6496        // event from the deepest view exposed to the client. As a consequence if
6497        // the user crosses a not exposed view the client will see enter and exit
6498        // of the exposed predecessor followed by and enter and exit of that same
6499        // predecessor when entering and exiting the not exposed descendant. This
6500        // is fine since the client has a clear idea which view is hovered at the
6501        // price of a couple more events being sent. This is a simple and
6502        // working solution.
6503        View source = this;
6504        while (true) {
6505            if (source.includeForAccessibility()) {
6506                source.sendAccessibilityEvent(eventType);
6507                return;
6508            }
6509            ViewParent parent = source.getParent();
6510            if (parent instanceof View) {
6511                source = (View) parent;
6512            } else {
6513                return;
6514            }
6515        }
6516    }
6517
6518    /**
6519     * Clears accessibility focus without calling any callback methods
6520     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6521     * is used for clearing accessibility focus when giving this focus to
6522     * another view.
6523     */
6524    void clearAccessibilityFocusNoCallbacks() {
6525        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6526            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6527            invalidate();
6528        }
6529    }
6530
6531    /**
6532     * Call this to try to give focus to a specific view or to one of its
6533     * descendants.
6534     *
6535     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6536     * false), or if it is focusable and it is not focusable in touch mode
6537     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6538     *
6539     * See also {@link #focusSearch(int)}, which is what you call to say that you
6540     * have focus, and you want your parent to look for the next one.
6541     *
6542     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6543     * {@link #FOCUS_DOWN} and <code>null</code>.
6544     *
6545     * @return Whether this view or one of its descendants actually took focus.
6546     */
6547    public final boolean requestFocus() {
6548        return requestFocus(View.FOCUS_DOWN);
6549    }
6550
6551    /**
6552     * Call this to try to give focus to a specific view or to one of its
6553     * descendants and give it a hint about what direction focus is heading.
6554     *
6555     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6556     * false), or if it is focusable and it is not focusable in touch mode
6557     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6558     *
6559     * See also {@link #focusSearch(int)}, which is what you call to say that you
6560     * have focus, and you want your parent to look for the next one.
6561     *
6562     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6563     * <code>null</code> set for the previously focused rectangle.
6564     *
6565     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6566     * @return Whether this view or one of its descendants actually took focus.
6567     */
6568    public final boolean requestFocus(int direction) {
6569        return requestFocus(direction, null);
6570    }
6571
6572    /**
6573     * Call this to try to give focus to a specific view or to one of its descendants
6574     * and give it hints about the direction and a specific rectangle that the focus
6575     * is coming from.  The rectangle can help give larger views a finer grained hint
6576     * about where focus is coming from, and therefore, where to show selection, or
6577     * forward focus change internally.
6578     *
6579     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6580     * false), or if it is focusable and it is not focusable in touch mode
6581     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6582     *
6583     * A View will not take focus if it is not visible.
6584     *
6585     * A View will not take focus if one of its parents has
6586     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6587     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6588     *
6589     * See also {@link #focusSearch(int)}, which is what you call to say that you
6590     * have focus, and you want your parent to look for the next one.
6591     *
6592     * You may wish to override this method if your custom {@link View} has an internal
6593     * {@link View} that it wishes to forward the request to.
6594     *
6595     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6596     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6597     *        to give a finer grained hint about where focus is coming from.  May be null
6598     *        if there is no hint.
6599     * @return Whether this view or one of its descendants actually took focus.
6600     */
6601    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6602        return requestFocusNoSearch(direction, previouslyFocusedRect);
6603    }
6604
6605    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6606        // need to be focusable
6607        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6608                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6609            return false;
6610        }
6611
6612        // need to be focusable in touch mode if in touch mode
6613        if (isInTouchMode() &&
6614            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6615               return false;
6616        }
6617
6618        // need to not have any parents blocking us
6619        if (hasAncestorThatBlocksDescendantFocus()) {
6620            return false;
6621        }
6622
6623        handleFocusGainInternal(direction, previouslyFocusedRect);
6624        return true;
6625    }
6626
6627    /**
6628     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6629     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6630     * touch mode to request focus when they are touched.
6631     *
6632     * @return Whether this view or one of its descendants actually took focus.
6633     *
6634     * @see #isInTouchMode()
6635     *
6636     */
6637    public final boolean requestFocusFromTouch() {
6638        // Leave touch mode if we need to
6639        if (isInTouchMode()) {
6640            ViewRootImpl viewRoot = getViewRootImpl();
6641            if (viewRoot != null) {
6642                viewRoot.ensureTouchMode(false);
6643            }
6644        }
6645        return requestFocus(View.FOCUS_DOWN);
6646    }
6647
6648    /**
6649     * @return Whether any ancestor of this view blocks descendant focus.
6650     */
6651    private boolean hasAncestorThatBlocksDescendantFocus() {
6652        ViewParent ancestor = mParent;
6653        while (ancestor instanceof ViewGroup) {
6654            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6655            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6656                return true;
6657            } else {
6658                ancestor = vgAncestor.getParent();
6659            }
6660        }
6661        return false;
6662    }
6663
6664    /**
6665     * Gets the mode for determining whether this View is important for accessibility
6666     * which is if it fires accessibility events and if it is reported to
6667     * accessibility services that query the screen.
6668     *
6669     * @return The mode for determining whether a View is important for accessibility.
6670     *
6671     * @attr ref android.R.styleable#View_importantForAccessibility
6672     *
6673     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6674     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6675     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6676     */
6677    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6678            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6679            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6680            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6681        })
6682    public int getImportantForAccessibility() {
6683        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6684                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6685    }
6686
6687    /**
6688     * Sets how to determine whether this view is important for accessibility
6689     * which is if it fires accessibility events and if it is reported to
6690     * accessibility services that query the screen.
6691     *
6692     * @param mode How to determine whether this view is important for accessibility.
6693     *
6694     * @attr ref android.R.styleable#View_importantForAccessibility
6695     *
6696     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6697     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6698     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6699     */
6700    public void setImportantForAccessibility(int mode) {
6701        if (mode != getImportantForAccessibility()) {
6702            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6703            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6704                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6705            notifyAccessibilityStateChanged();
6706        }
6707    }
6708
6709    /**
6710     * Gets whether this view should be exposed for accessibility.
6711     *
6712     * @return Whether the view is exposed for accessibility.
6713     *
6714     * @hide
6715     */
6716    public boolean isImportantForAccessibility() {
6717        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6718                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6719        switch (mode) {
6720            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6721                return true;
6722            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6723                return false;
6724            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6725                return isActionableForAccessibility() || hasListenersForAccessibility()
6726                        || getAccessibilityNodeProvider() != null;
6727            default:
6728                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6729                        + mode);
6730        }
6731    }
6732
6733    /**
6734     * Gets the parent for accessibility purposes. Note that the parent for
6735     * accessibility is not necessary the immediate parent. It is the first
6736     * predecessor that is important for accessibility.
6737     *
6738     * @return The parent for accessibility purposes.
6739     */
6740    public ViewParent getParentForAccessibility() {
6741        if (mParent instanceof View) {
6742            View parentView = (View) mParent;
6743            if (parentView.includeForAccessibility()) {
6744                return mParent;
6745            } else {
6746                return mParent.getParentForAccessibility();
6747            }
6748        }
6749        return null;
6750    }
6751
6752    /**
6753     * Adds the children of a given View for accessibility. Since some Views are
6754     * not important for accessibility the children for accessibility are not
6755     * necessarily direct children of the riew, rather they are the first level of
6756     * descendants important for accessibility.
6757     *
6758     * @param children The list of children for accessibility.
6759     */
6760    public void addChildrenForAccessibility(ArrayList<View> children) {
6761        if (includeForAccessibility()) {
6762            children.add(this);
6763        }
6764    }
6765
6766    /**
6767     * Whether to regard this view for accessibility. A view is regarded for
6768     * accessibility if it is important for accessibility or the querying
6769     * accessibility service has explicitly requested that view not
6770     * important for accessibility are regarded.
6771     *
6772     * @return Whether to regard the view for accessibility.
6773     *
6774     * @hide
6775     */
6776    public boolean includeForAccessibility() {
6777        if (mAttachInfo != null) {
6778            return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility();
6779        }
6780        return false;
6781    }
6782
6783    /**
6784     * Returns whether the View is considered actionable from
6785     * accessibility perspective. Such view are important for
6786     * accessibility.
6787     *
6788     * @return True if the view is actionable for accessibility.
6789     *
6790     * @hide
6791     */
6792    public boolean isActionableForAccessibility() {
6793        return (isClickable() || isLongClickable() || isFocusable());
6794    }
6795
6796    /**
6797     * Returns whether the View has registered callbacks wich makes it
6798     * important for accessibility.
6799     *
6800     * @return True if the view is actionable for accessibility.
6801     */
6802    private boolean hasListenersForAccessibility() {
6803        ListenerInfo info = getListenerInfo();
6804        return mTouchDelegate != null || info.mOnKeyListener != null
6805                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6806                || info.mOnHoverListener != null || info.mOnDragListener != null;
6807    }
6808
6809    /**
6810     * Notifies accessibility services that some view's important for
6811     * accessibility state has changed. Note that such notifications
6812     * are made at most once every
6813     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6814     * to avoid unnecessary load to the system. Also once a view has
6815     * made a notifucation this method is a NOP until the notification has
6816     * been sent to clients.
6817     *
6818     * @hide
6819     *
6820     * TODO: Makse sure this method is called for any view state change
6821     *       that is interesting for accessilility purposes.
6822     */
6823    public void notifyAccessibilityStateChanged() {
6824        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6825            return;
6826        }
6827        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6828            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6829            if (mParent != null) {
6830                mParent.childAccessibilityStateChanged(this);
6831            }
6832        }
6833    }
6834
6835    /**
6836     * Reset the state indicating the this view has requested clients
6837     * interested in its accessibility state to be notified.
6838     *
6839     * @hide
6840     */
6841    public void resetAccessibilityStateChanged() {
6842        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6843    }
6844
6845    /**
6846     * Performs the specified accessibility action on the view. For
6847     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6848    * <p>
6849    * If an {@link AccessibilityDelegate} has been specified via calling
6850    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6851    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6852    * is responsible for handling this call.
6853    * </p>
6854     *
6855     * @param action The action to perform.
6856     * @param arguments Optional action arguments.
6857     * @return Whether the action was performed.
6858     */
6859    public boolean performAccessibilityAction(int action, Bundle arguments) {
6860      if (mAccessibilityDelegate != null) {
6861          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6862      } else {
6863          return performAccessibilityActionInternal(action, arguments);
6864      }
6865    }
6866
6867   /**
6868    * @see #performAccessibilityAction(int, Bundle)
6869    *
6870    * Note: Called from the default {@link AccessibilityDelegate}.
6871    */
6872    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6873        switch (action) {
6874            case AccessibilityNodeInfo.ACTION_CLICK: {
6875                if (isClickable()) {
6876                    return performClick();
6877                }
6878            } break;
6879            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6880                if (isLongClickable()) {
6881                    return performLongClick();
6882                }
6883            } break;
6884            case AccessibilityNodeInfo.ACTION_FOCUS: {
6885                if (!hasFocus()) {
6886                    // Get out of touch mode since accessibility
6887                    // wants to move focus around.
6888                    getViewRootImpl().ensureTouchMode(false);
6889                    return requestFocus();
6890                }
6891            } break;
6892            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6893                if (hasFocus()) {
6894                    clearFocus();
6895                    return !isFocused();
6896                }
6897            } break;
6898            case AccessibilityNodeInfo.ACTION_SELECT: {
6899                if (!isSelected()) {
6900                    setSelected(true);
6901                    return isSelected();
6902                }
6903            } break;
6904            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6905                if (isSelected()) {
6906                    setSelected(false);
6907                    return !isSelected();
6908                }
6909            } break;
6910            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6911                if (!isAccessibilityFocused()) {
6912                    return requestAccessibilityFocus();
6913                }
6914            } break;
6915            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6916                if (isAccessibilityFocused()) {
6917                    clearAccessibilityFocus();
6918                    return true;
6919                }
6920            } break;
6921            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6922                if (arguments != null) {
6923                    final int granularity = arguments.getInt(
6924                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6925                    return nextAtGranularity(granularity);
6926                }
6927            } break;
6928            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6929                if (arguments != null) {
6930                    final int granularity = arguments.getInt(
6931                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6932                    return previousAtGranularity(granularity);
6933                }
6934            } break;
6935        }
6936        return false;
6937    }
6938
6939    private boolean nextAtGranularity(int granularity) {
6940        CharSequence text = getIterableTextForAccessibility();
6941        if (text == null || text.length() == 0) {
6942            return false;
6943        }
6944        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6945        if (iterator == null) {
6946            return false;
6947        }
6948        final int current = getAccessibilityCursorPosition();
6949        final int[] range = iterator.following(current);
6950        if (range == null) {
6951            return false;
6952        }
6953        final int start = range[0];
6954        final int end = range[1];
6955        setAccessibilityCursorPosition(end);
6956        sendViewTextTraversedAtGranularityEvent(
6957                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6958                granularity, start, end);
6959        return true;
6960    }
6961
6962    private boolean previousAtGranularity(int granularity) {
6963        CharSequence text = getIterableTextForAccessibility();
6964        if (text == null || text.length() == 0) {
6965            return false;
6966        }
6967        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6968        if (iterator == null) {
6969            return false;
6970        }
6971        int current = getAccessibilityCursorPosition();
6972        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6973            current = text.length();
6974        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6975            // When traversing by character we always put the cursor after the character
6976            // to ease edit and have to compensate before asking the for previous segment.
6977            current--;
6978        }
6979        final int[] range = iterator.preceding(current);
6980        if (range == null) {
6981            return false;
6982        }
6983        final int start = range[0];
6984        final int end = range[1];
6985        // Always put the cursor after the character to ease edit.
6986        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6987            setAccessibilityCursorPosition(end);
6988        } else {
6989            setAccessibilityCursorPosition(start);
6990        }
6991        sendViewTextTraversedAtGranularityEvent(
6992                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6993                granularity, start, end);
6994        return true;
6995    }
6996
6997    /**
6998     * Gets the text reported for accessibility purposes.
6999     *
7000     * @return The accessibility text.
7001     *
7002     * @hide
7003     */
7004    public CharSequence getIterableTextForAccessibility() {
7005        return getContentDescription();
7006    }
7007
7008    /**
7009     * @hide
7010     */
7011    public int getAccessibilityCursorPosition() {
7012        return mAccessibilityCursorPosition;
7013    }
7014
7015    /**
7016     * @hide
7017     */
7018    public void setAccessibilityCursorPosition(int position) {
7019        mAccessibilityCursorPosition = position;
7020    }
7021
7022    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7023            int fromIndex, int toIndex) {
7024        if (mParent == null) {
7025            return;
7026        }
7027        AccessibilityEvent event = AccessibilityEvent.obtain(
7028                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7029        onInitializeAccessibilityEvent(event);
7030        onPopulateAccessibilityEvent(event);
7031        event.setFromIndex(fromIndex);
7032        event.setToIndex(toIndex);
7033        event.setAction(action);
7034        event.setMovementGranularity(granularity);
7035        mParent.requestSendAccessibilityEvent(this, event);
7036    }
7037
7038    /**
7039     * @hide
7040     */
7041    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7042        switch (granularity) {
7043            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7044                CharSequence text = getIterableTextForAccessibility();
7045                if (text != null && text.length() > 0) {
7046                    CharacterTextSegmentIterator iterator =
7047                        CharacterTextSegmentIterator.getInstance(
7048                                mContext.getResources().getConfiguration().locale);
7049                    iterator.initialize(text.toString());
7050                    return iterator;
7051                }
7052            } break;
7053            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7054                CharSequence text = getIterableTextForAccessibility();
7055                if (text != null && text.length() > 0) {
7056                    WordTextSegmentIterator iterator =
7057                        WordTextSegmentIterator.getInstance(
7058                                mContext.getResources().getConfiguration().locale);
7059                    iterator.initialize(text.toString());
7060                    return iterator;
7061                }
7062            } break;
7063            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7064                CharSequence text = getIterableTextForAccessibility();
7065                if (text != null && text.length() > 0) {
7066                    ParagraphTextSegmentIterator iterator =
7067                        ParagraphTextSegmentIterator.getInstance();
7068                    iterator.initialize(text.toString());
7069                    return iterator;
7070                }
7071            } break;
7072        }
7073        return null;
7074    }
7075
7076    /**
7077     * @hide
7078     */
7079    public void dispatchStartTemporaryDetach() {
7080        clearAccessibilityFocus();
7081        clearDisplayList();
7082
7083        onStartTemporaryDetach();
7084    }
7085
7086    /**
7087     * This is called when a container is going to temporarily detach a child, with
7088     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7089     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7090     * {@link #onDetachedFromWindow()} when the container is done.
7091     */
7092    public void onStartTemporaryDetach() {
7093        removeUnsetPressCallback();
7094        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7095    }
7096
7097    /**
7098     * @hide
7099     */
7100    public void dispatchFinishTemporaryDetach() {
7101        onFinishTemporaryDetach();
7102    }
7103
7104    /**
7105     * Called after {@link #onStartTemporaryDetach} when the container is done
7106     * changing the view.
7107     */
7108    public void onFinishTemporaryDetach() {
7109    }
7110
7111    /**
7112     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7113     * for this view's window.  Returns null if the view is not currently attached
7114     * to the window.  Normally you will not need to use this directly, but
7115     * just use the standard high-level event callbacks like
7116     * {@link #onKeyDown(int, KeyEvent)}.
7117     */
7118    public KeyEvent.DispatcherState getKeyDispatcherState() {
7119        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7120    }
7121
7122    /**
7123     * Dispatch a key event before it is processed by any input method
7124     * associated with the view hierarchy.  This can be used to intercept
7125     * key events in special situations before the IME consumes them; a
7126     * typical example would be handling the BACK key to update the application's
7127     * UI instead of allowing the IME to see it and close itself.
7128     *
7129     * @param event The key event to be dispatched.
7130     * @return True if the event was handled, false otherwise.
7131     */
7132    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7133        return onKeyPreIme(event.getKeyCode(), event);
7134    }
7135
7136    /**
7137     * Dispatch a key event to the next view on the focus path. This path runs
7138     * from the top of the view tree down to the currently focused view. If this
7139     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7140     * the next node down the focus path. This method also fires any key
7141     * listeners.
7142     *
7143     * @param event The key event to be dispatched.
7144     * @return True if the event was handled, false otherwise.
7145     */
7146    public boolean dispatchKeyEvent(KeyEvent event) {
7147        if (mInputEventConsistencyVerifier != null) {
7148            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7149        }
7150
7151        // Give any attached key listener a first crack at the event.
7152        //noinspection SimplifiableIfStatement
7153        ListenerInfo li = mListenerInfo;
7154        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7155                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7156            return true;
7157        }
7158
7159        if (event.dispatch(this, mAttachInfo != null
7160                ? mAttachInfo.mKeyDispatchState : null, this)) {
7161            return true;
7162        }
7163
7164        if (mInputEventConsistencyVerifier != null) {
7165            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7166        }
7167        return false;
7168    }
7169
7170    /**
7171     * Dispatches a key shortcut event.
7172     *
7173     * @param event The key event to be dispatched.
7174     * @return True if the event was handled by the view, false otherwise.
7175     */
7176    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7177        return onKeyShortcut(event.getKeyCode(), event);
7178    }
7179
7180    /**
7181     * Pass the touch screen motion event down to the target view, or this
7182     * view if it is the target.
7183     *
7184     * @param event The motion event to be dispatched.
7185     * @return True if the event was handled by the view, false otherwise.
7186     */
7187    public boolean dispatchTouchEvent(MotionEvent event) {
7188        if (mInputEventConsistencyVerifier != null) {
7189            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7190        }
7191
7192        if (onFilterTouchEventForSecurity(event)) {
7193            //noinspection SimplifiableIfStatement
7194            ListenerInfo li = mListenerInfo;
7195            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7196                    && li.mOnTouchListener.onTouch(this, event)) {
7197                return true;
7198            }
7199
7200            if (onTouchEvent(event)) {
7201                return true;
7202            }
7203        }
7204
7205        if (mInputEventConsistencyVerifier != null) {
7206            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7207        }
7208        return false;
7209    }
7210
7211    /**
7212     * Filter the touch event to apply security policies.
7213     *
7214     * @param event The motion event to be filtered.
7215     * @return True if the event should be dispatched, false if the event should be dropped.
7216     *
7217     * @see #getFilterTouchesWhenObscured
7218     */
7219    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7220        //noinspection RedundantIfStatement
7221        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7222                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7223            // Window is obscured, drop this touch.
7224            return false;
7225        }
7226        return true;
7227    }
7228
7229    /**
7230     * Pass a trackball motion event down to the focused view.
7231     *
7232     * @param event The motion event to be dispatched.
7233     * @return True if the event was handled by the view, false otherwise.
7234     */
7235    public boolean dispatchTrackballEvent(MotionEvent event) {
7236        if (mInputEventConsistencyVerifier != null) {
7237            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7238        }
7239
7240        return onTrackballEvent(event);
7241    }
7242
7243    /**
7244     * Dispatch a generic motion event.
7245     * <p>
7246     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7247     * are delivered to the view under the pointer.  All other generic motion events are
7248     * delivered to the focused view.  Hover events are handled specially and are delivered
7249     * to {@link #onHoverEvent(MotionEvent)}.
7250     * </p>
7251     *
7252     * @param event The motion event to be dispatched.
7253     * @return True if the event was handled by the view, false otherwise.
7254     */
7255    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7256        if (mInputEventConsistencyVerifier != null) {
7257            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7258        }
7259
7260        final int source = event.getSource();
7261        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7262            final int action = event.getAction();
7263            if (action == MotionEvent.ACTION_HOVER_ENTER
7264                    || action == MotionEvent.ACTION_HOVER_MOVE
7265                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7266                if (dispatchHoverEvent(event)) {
7267                    return true;
7268                }
7269            } else if (dispatchGenericPointerEvent(event)) {
7270                return true;
7271            }
7272        } else if (dispatchGenericFocusedEvent(event)) {
7273            return true;
7274        }
7275
7276        if (dispatchGenericMotionEventInternal(event)) {
7277            return true;
7278        }
7279
7280        if (mInputEventConsistencyVerifier != null) {
7281            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7282        }
7283        return false;
7284    }
7285
7286    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7287        //noinspection SimplifiableIfStatement
7288        ListenerInfo li = mListenerInfo;
7289        if (li != null && li.mOnGenericMotionListener != null
7290                && (mViewFlags & ENABLED_MASK) == ENABLED
7291                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7292            return true;
7293        }
7294
7295        if (onGenericMotionEvent(event)) {
7296            return true;
7297        }
7298
7299        if (mInputEventConsistencyVerifier != null) {
7300            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7301        }
7302        return false;
7303    }
7304
7305    /**
7306     * Dispatch a hover event.
7307     * <p>
7308     * Do not call this method directly.
7309     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7310     * </p>
7311     *
7312     * @param event The motion event to be dispatched.
7313     * @return True if the event was handled by the view, false otherwise.
7314     */
7315    protected boolean dispatchHoverEvent(MotionEvent event) {
7316        //noinspection SimplifiableIfStatement
7317        ListenerInfo li = mListenerInfo;
7318        if (li != null && li.mOnHoverListener != null
7319                && (mViewFlags & ENABLED_MASK) == ENABLED
7320                && li.mOnHoverListener.onHover(this, event)) {
7321            return true;
7322        }
7323
7324        return onHoverEvent(event);
7325    }
7326
7327    /**
7328     * Returns true if the view has a child to which it has recently sent
7329     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7330     * it does not have a hovered child, then it must be the innermost hovered view.
7331     * @hide
7332     */
7333    protected boolean hasHoveredChild() {
7334        return false;
7335    }
7336
7337    /**
7338     * Dispatch a generic motion event to the view under the first pointer.
7339     * <p>
7340     * Do not call this method directly.
7341     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7342     * </p>
7343     *
7344     * @param event The motion event to be dispatched.
7345     * @return True if the event was handled by the view, false otherwise.
7346     */
7347    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7348        return false;
7349    }
7350
7351    /**
7352     * Dispatch a generic motion event to the currently focused view.
7353     * <p>
7354     * Do not call this method directly.
7355     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7356     * </p>
7357     *
7358     * @param event The motion event to be dispatched.
7359     * @return True if the event was handled by the view, false otherwise.
7360     */
7361    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7362        return false;
7363    }
7364
7365    /**
7366     * Dispatch a pointer event.
7367     * <p>
7368     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7369     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7370     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7371     * and should not be expected to handle other pointing device features.
7372     * </p>
7373     *
7374     * @param event The motion event to be dispatched.
7375     * @return True if the event was handled by the view, false otherwise.
7376     * @hide
7377     */
7378    public final boolean dispatchPointerEvent(MotionEvent event) {
7379        if (event.isTouchEvent()) {
7380            return dispatchTouchEvent(event);
7381        } else {
7382            return dispatchGenericMotionEvent(event);
7383        }
7384    }
7385
7386    /**
7387     * Called when the window containing this view gains or loses window focus.
7388     * ViewGroups should override to route to their children.
7389     *
7390     * @param hasFocus True if the window containing this view now has focus,
7391     *        false otherwise.
7392     */
7393    public void dispatchWindowFocusChanged(boolean hasFocus) {
7394        onWindowFocusChanged(hasFocus);
7395    }
7396
7397    /**
7398     * Called when the window containing this view gains or loses focus.  Note
7399     * that this is separate from view focus: to receive key events, both
7400     * your view and its window must have focus.  If a window is displayed
7401     * on top of yours that takes input focus, then your own window will lose
7402     * focus but the view focus will remain unchanged.
7403     *
7404     * @param hasWindowFocus True if the window containing this view now has
7405     *        focus, false otherwise.
7406     */
7407    public void onWindowFocusChanged(boolean hasWindowFocus) {
7408        InputMethodManager imm = InputMethodManager.peekInstance();
7409        if (!hasWindowFocus) {
7410            if (isPressed()) {
7411                setPressed(false);
7412            }
7413            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7414                imm.focusOut(this);
7415            }
7416            removeLongPressCallback();
7417            removeTapCallback();
7418            onFocusLost();
7419        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7420            imm.focusIn(this);
7421        }
7422        refreshDrawableState();
7423    }
7424
7425    /**
7426     * Returns true if this view is in a window that currently has window focus.
7427     * Note that this is not the same as the view itself having focus.
7428     *
7429     * @return True if this view is in a window that currently has window focus.
7430     */
7431    public boolean hasWindowFocus() {
7432        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7433    }
7434
7435    /**
7436     * Dispatch a view visibility change down the view hierarchy.
7437     * ViewGroups should override to route to their children.
7438     * @param changedView The view whose visibility changed. Could be 'this' or
7439     * an ancestor view.
7440     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7441     * {@link #INVISIBLE} or {@link #GONE}.
7442     */
7443    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7444        onVisibilityChanged(changedView, visibility);
7445    }
7446
7447    /**
7448     * Called when the visibility of the view or an ancestor of the view is changed.
7449     * @param changedView The view whose visibility changed. Could be 'this' or
7450     * an ancestor view.
7451     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7452     * {@link #INVISIBLE} or {@link #GONE}.
7453     */
7454    protected void onVisibilityChanged(View changedView, int visibility) {
7455        if (visibility == VISIBLE) {
7456            if (mAttachInfo != null) {
7457                initialAwakenScrollBars();
7458            } else {
7459                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7460            }
7461        }
7462    }
7463
7464    /**
7465     * Dispatch a hint about whether this view is displayed. For instance, when
7466     * a View moves out of the screen, it might receives a display hint indicating
7467     * the view is not displayed. Applications should not <em>rely</em> on this hint
7468     * as there is no guarantee that they will receive one.
7469     *
7470     * @param hint A hint about whether or not this view is displayed:
7471     * {@link #VISIBLE} or {@link #INVISIBLE}.
7472     */
7473    public void dispatchDisplayHint(int hint) {
7474        onDisplayHint(hint);
7475    }
7476
7477    /**
7478     * Gives this view a hint about whether is displayed or not. For instance, when
7479     * a View moves out of the screen, it might receives a display hint indicating
7480     * the view is not displayed. Applications should not <em>rely</em> on this hint
7481     * as there is no guarantee that they will receive one.
7482     *
7483     * @param hint A hint about whether or not this view is displayed:
7484     * {@link #VISIBLE} or {@link #INVISIBLE}.
7485     */
7486    protected void onDisplayHint(int hint) {
7487    }
7488
7489    /**
7490     * Dispatch a window visibility change down the view hierarchy.
7491     * ViewGroups should override to route to their children.
7492     *
7493     * @param visibility The new visibility of the window.
7494     *
7495     * @see #onWindowVisibilityChanged(int)
7496     */
7497    public void dispatchWindowVisibilityChanged(int visibility) {
7498        onWindowVisibilityChanged(visibility);
7499    }
7500
7501    /**
7502     * Called when the window containing has change its visibility
7503     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7504     * that this tells you whether or not your window is being made visible
7505     * to the window manager; this does <em>not</em> tell you whether or not
7506     * your window is obscured by other windows on the screen, even if it
7507     * is itself visible.
7508     *
7509     * @param visibility The new visibility of the window.
7510     */
7511    protected void onWindowVisibilityChanged(int visibility) {
7512        if (visibility == VISIBLE) {
7513            initialAwakenScrollBars();
7514        }
7515    }
7516
7517    /**
7518     * Returns the current visibility of the window this view is attached to
7519     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7520     *
7521     * @return Returns the current visibility of the view's window.
7522     */
7523    public int getWindowVisibility() {
7524        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7525    }
7526
7527    /**
7528     * Retrieve the overall visible display size in which the window this view is
7529     * attached to has been positioned in.  This takes into account screen
7530     * decorations above the window, for both cases where the window itself
7531     * is being position inside of them or the window is being placed under
7532     * then and covered insets are used for the window to position its content
7533     * inside.  In effect, this tells you the available area where content can
7534     * be placed and remain visible to users.
7535     *
7536     * <p>This function requires an IPC back to the window manager to retrieve
7537     * the requested information, so should not be used in performance critical
7538     * code like drawing.
7539     *
7540     * @param outRect Filled in with the visible display frame.  If the view
7541     * is not attached to a window, this is simply the raw display size.
7542     */
7543    public void getWindowVisibleDisplayFrame(Rect outRect) {
7544        if (mAttachInfo != null) {
7545            try {
7546                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7547            } catch (RemoteException e) {
7548                return;
7549            }
7550            // XXX This is really broken, and probably all needs to be done
7551            // in the window manager, and we need to know more about whether
7552            // we want the area behind or in front of the IME.
7553            final Rect insets = mAttachInfo.mVisibleInsets;
7554            outRect.left += insets.left;
7555            outRect.top += insets.top;
7556            outRect.right -= insets.right;
7557            outRect.bottom -= insets.bottom;
7558            return;
7559        }
7560        // The view is not attached to a display so we don't have a context.
7561        // Make a best guess about the display size.
7562        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7563        d.getRectSize(outRect);
7564    }
7565
7566    /**
7567     * Dispatch a notification about a resource configuration change down
7568     * the view hierarchy.
7569     * ViewGroups should override to route to their children.
7570     *
7571     * @param newConfig The new resource configuration.
7572     *
7573     * @see #onConfigurationChanged(android.content.res.Configuration)
7574     */
7575    public void dispatchConfigurationChanged(Configuration newConfig) {
7576        onConfigurationChanged(newConfig);
7577    }
7578
7579    /**
7580     * Called when the current configuration of the resources being used
7581     * by the application have changed.  You can use this to decide when
7582     * to reload resources that can changed based on orientation and other
7583     * configuration characterstics.  You only need to use this if you are
7584     * not relying on the normal {@link android.app.Activity} mechanism of
7585     * recreating the activity instance upon a configuration change.
7586     *
7587     * @param newConfig The new resource configuration.
7588     */
7589    protected void onConfigurationChanged(Configuration newConfig) {
7590    }
7591
7592    /**
7593     * Private function to aggregate all per-view attributes in to the view
7594     * root.
7595     */
7596    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7597        performCollectViewAttributes(attachInfo, visibility);
7598    }
7599
7600    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7601        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7602            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7603                attachInfo.mKeepScreenOn = true;
7604            }
7605            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7606            ListenerInfo li = mListenerInfo;
7607            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7608                attachInfo.mHasSystemUiListeners = true;
7609            }
7610        }
7611    }
7612
7613    void needGlobalAttributesUpdate(boolean force) {
7614        final AttachInfo ai = mAttachInfo;
7615        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7616            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7617                    || ai.mHasSystemUiListeners) {
7618                ai.mRecomputeGlobalAttributes = true;
7619            }
7620        }
7621    }
7622
7623    /**
7624     * Returns whether the device is currently in touch mode.  Touch mode is entered
7625     * once the user begins interacting with the device by touch, and affects various
7626     * things like whether focus is always visible to the user.
7627     *
7628     * @return Whether the device is in touch mode.
7629     */
7630    @ViewDebug.ExportedProperty
7631    public boolean isInTouchMode() {
7632        if (mAttachInfo != null) {
7633            return mAttachInfo.mInTouchMode;
7634        } else {
7635            return ViewRootImpl.isInTouchMode();
7636        }
7637    }
7638
7639    /**
7640     * Returns the context the view is running in, through which it can
7641     * access the current theme, resources, etc.
7642     *
7643     * @return The view's Context.
7644     */
7645    @ViewDebug.CapturedViewProperty
7646    public final Context getContext() {
7647        return mContext;
7648    }
7649
7650    /**
7651     * Handle a key event before it is processed by any input method
7652     * associated with the view hierarchy.  This can be used to intercept
7653     * key events in special situations before the IME consumes them; a
7654     * typical example would be handling the BACK key to update the application's
7655     * UI instead of allowing the IME to see it and close itself.
7656     *
7657     * @param keyCode The value in event.getKeyCode().
7658     * @param event Description of the key event.
7659     * @return If you handled the event, return true. If you want to allow the
7660     *         event to be handled by the next receiver, return false.
7661     */
7662    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7663        return false;
7664    }
7665
7666    /**
7667     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7668     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7669     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7670     * is released, if the view is enabled and clickable.
7671     *
7672     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7673     * although some may elect to do so in some situations. Do not rely on this to
7674     * catch software key presses.
7675     *
7676     * @param keyCode A key code that represents the button pressed, from
7677     *                {@link android.view.KeyEvent}.
7678     * @param event   The KeyEvent object that defines the button action.
7679     */
7680    public boolean onKeyDown(int keyCode, KeyEvent event) {
7681        boolean result = false;
7682
7683        switch (keyCode) {
7684            case KeyEvent.KEYCODE_DPAD_CENTER:
7685            case KeyEvent.KEYCODE_ENTER: {
7686                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7687                    return true;
7688                }
7689                // Long clickable items don't necessarily have to be clickable
7690                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7691                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7692                        (event.getRepeatCount() == 0)) {
7693                    setPressed(true);
7694                    checkForLongClick(0);
7695                    return true;
7696                }
7697                break;
7698            }
7699        }
7700        return result;
7701    }
7702
7703    /**
7704     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7705     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7706     * the event).
7707     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7708     * although some may elect to do so in some situations. Do not rely on this to
7709     * catch software key presses.
7710     */
7711    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7712        return false;
7713    }
7714
7715    /**
7716     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7717     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7718     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7719     * {@link KeyEvent#KEYCODE_ENTER} is released.
7720     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7721     * although some may elect to do so in some situations. Do not rely on this to
7722     * catch software key presses.
7723     *
7724     * @param keyCode A key code that represents the button pressed, from
7725     *                {@link android.view.KeyEvent}.
7726     * @param event   The KeyEvent object that defines the button action.
7727     */
7728    public boolean onKeyUp(int keyCode, KeyEvent event) {
7729        boolean result = false;
7730
7731        switch (keyCode) {
7732            case KeyEvent.KEYCODE_DPAD_CENTER:
7733            case KeyEvent.KEYCODE_ENTER: {
7734                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7735                    return true;
7736                }
7737                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7738                    setPressed(false);
7739
7740                    if (!mHasPerformedLongPress) {
7741                        // This is a tap, so remove the longpress check
7742                        removeLongPressCallback();
7743
7744                        result = performClick();
7745                    }
7746                }
7747                break;
7748            }
7749        }
7750        return result;
7751    }
7752
7753    /**
7754     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7755     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7756     * the event).
7757     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7758     * although some may elect to do so in some situations. Do not rely on this to
7759     * catch software key presses.
7760     *
7761     * @param keyCode     A key code that represents the button pressed, from
7762     *                    {@link android.view.KeyEvent}.
7763     * @param repeatCount The number of times the action was made.
7764     * @param event       The KeyEvent object that defines the button action.
7765     */
7766    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7767        return false;
7768    }
7769
7770    /**
7771     * Called on the focused view when a key shortcut event is not handled.
7772     * Override this method to implement local key shortcuts for the View.
7773     * Key shortcuts can also be implemented by setting the
7774     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7775     *
7776     * @param keyCode The value in event.getKeyCode().
7777     * @param event Description of the key event.
7778     * @return If you handled the event, return true. If you want to allow the
7779     *         event to be handled by the next receiver, return false.
7780     */
7781    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7782        return false;
7783    }
7784
7785    /**
7786     * Check whether the called view is a text editor, in which case it
7787     * would make sense to automatically display a soft input window for
7788     * it.  Subclasses should override this if they implement
7789     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7790     * a call on that method would return a non-null InputConnection, and
7791     * they are really a first-class editor that the user would normally
7792     * start typing on when the go into a window containing your view.
7793     *
7794     * <p>The default implementation always returns false.  This does
7795     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7796     * will not be called or the user can not otherwise perform edits on your
7797     * view; it is just a hint to the system that this is not the primary
7798     * purpose of this view.
7799     *
7800     * @return Returns true if this view is a text editor, else false.
7801     */
7802    public boolean onCheckIsTextEditor() {
7803        return false;
7804    }
7805
7806    /**
7807     * Create a new InputConnection for an InputMethod to interact
7808     * with the view.  The default implementation returns null, since it doesn't
7809     * support input methods.  You can override this to implement such support.
7810     * This is only needed for views that take focus and text input.
7811     *
7812     * <p>When implementing this, you probably also want to implement
7813     * {@link #onCheckIsTextEditor()} to indicate you will return a
7814     * non-null InputConnection.
7815     *
7816     * @param outAttrs Fill in with attribute information about the connection.
7817     */
7818    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7819        return null;
7820    }
7821
7822    /**
7823     * Called by the {@link android.view.inputmethod.InputMethodManager}
7824     * when a view who is not the current
7825     * input connection target is trying to make a call on the manager.  The
7826     * default implementation returns false; you can override this to return
7827     * true for certain views if you are performing InputConnection proxying
7828     * to them.
7829     * @param view The View that is making the InputMethodManager call.
7830     * @return Return true to allow the call, false to reject.
7831     */
7832    public boolean checkInputConnectionProxy(View view) {
7833        return false;
7834    }
7835
7836    /**
7837     * Show the context menu for this view. It is not safe to hold on to the
7838     * menu after returning from this method.
7839     *
7840     * You should normally not overload this method. Overload
7841     * {@link #onCreateContextMenu(ContextMenu)} or define an
7842     * {@link OnCreateContextMenuListener} to add items to the context menu.
7843     *
7844     * @param menu The context menu to populate
7845     */
7846    public void createContextMenu(ContextMenu menu) {
7847        ContextMenuInfo menuInfo = getContextMenuInfo();
7848
7849        // Sets the current menu info so all items added to menu will have
7850        // my extra info set.
7851        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7852
7853        onCreateContextMenu(menu);
7854        ListenerInfo li = mListenerInfo;
7855        if (li != null && li.mOnCreateContextMenuListener != null) {
7856            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7857        }
7858
7859        // Clear the extra information so subsequent items that aren't mine don't
7860        // have my extra info.
7861        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7862
7863        if (mParent != null) {
7864            mParent.createContextMenu(menu);
7865        }
7866    }
7867
7868    /**
7869     * Views should implement this if they have extra information to associate
7870     * with the context menu. The return result is supplied as a parameter to
7871     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7872     * callback.
7873     *
7874     * @return Extra information about the item for which the context menu
7875     *         should be shown. This information will vary across different
7876     *         subclasses of View.
7877     */
7878    protected ContextMenuInfo getContextMenuInfo() {
7879        return null;
7880    }
7881
7882    /**
7883     * Views should implement this if the view itself is going to add items to
7884     * the context menu.
7885     *
7886     * @param menu the context menu to populate
7887     */
7888    protected void onCreateContextMenu(ContextMenu menu) {
7889    }
7890
7891    /**
7892     * Implement this method to handle trackball motion events.  The
7893     * <em>relative</em> movement of the trackball since the last event
7894     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7895     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7896     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7897     * they will often be fractional values, representing the more fine-grained
7898     * movement information available from a trackball).
7899     *
7900     * @param event The motion event.
7901     * @return True if the event was handled, false otherwise.
7902     */
7903    public boolean onTrackballEvent(MotionEvent event) {
7904        return false;
7905    }
7906
7907    /**
7908     * Implement this method to handle generic motion events.
7909     * <p>
7910     * Generic motion events describe joystick movements, mouse hovers, track pad
7911     * touches, scroll wheel movements and other input events.  The
7912     * {@link MotionEvent#getSource() source} of the motion event specifies
7913     * the class of input that was received.  Implementations of this method
7914     * must examine the bits in the source before processing the event.
7915     * The following code example shows how this is done.
7916     * </p><p>
7917     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7918     * are delivered to the view under the pointer.  All other generic motion events are
7919     * delivered to the focused view.
7920     * </p>
7921     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7922     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7923     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7924     *             // process the joystick movement...
7925     *             return true;
7926     *         }
7927     *     }
7928     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7929     *         switch (event.getAction()) {
7930     *             case MotionEvent.ACTION_HOVER_MOVE:
7931     *                 // process the mouse hover movement...
7932     *                 return true;
7933     *             case MotionEvent.ACTION_SCROLL:
7934     *                 // process the scroll wheel movement...
7935     *                 return true;
7936     *         }
7937     *     }
7938     *     return super.onGenericMotionEvent(event);
7939     * }</pre>
7940     *
7941     * @param event The generic motion event being processed.
7942     * @return True if the event was handled, false otherwise.
7943     */
7944    public boolean onGenericMotionEvent(MotionEvent event) {
7945        return false;
7946    }
7947
7948    /**
7949     * Implement this method to handle hover events.
7950     * <p>
7951     * This method is called whenever a pointer is hovering into, over, or out of the
7952     * bounds of a view and the view is not currently being touched.
7953     * Hover events are represented as pointer events with action
7954     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7955     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7956     * </p>
7957     * <ul>
7958     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7959     * when the pointer enters the bounds of the view.</li>
7960     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7961     * when the pointer has already entered the bounds of the view and has moved.</li>
7962     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7963     * when the pointer has exited the bounds of the view or when the pointer is
7964     * about to go down due to a button click, tap, or similar user action that
7965     * causes the view to be touched.</li>
7966     * </ul>
7967     * <p>
7968     * The view should implement this method to return true to indicate that it is
7969     * handling the hover event, such as by changing its drawable state.
7970     * </p><p>
7971     * The default implementation calls {@link #setHovered} to update the hovered state
7972     * of the view when a hover enter or hover exit event is received, if the view
7973     * is enabled and is clickable.  The default implementation also sends hover
7974     * accessibility events.
7975     * </p>
7976     *
7977     * @param event The motion event that describes the hover.
7978     * @return True if the view handled the hover event.
7979     *
7980     * @see #isHovered
7981     * @see #setHovered
7982     * @see #onHoverChanged
7983     */
7984    public boolean onHoverEvent(MotionEvent event) {
7985        // The root view may receive hover (or touch) events that are outside the bounds of
7986        // the window.  This code ensures that we only send accessibility events for
7987        // hovers that are actually within the bounds of the root view.
7988        final int action = event.getActionMasked();
7989        if (!mSendingHoverAccessibilityEvents) {
7990            if ((action == MotionEvent.ACTION_HOVER_ENTER
7991                    || action == MotionEvent.ACTION_HOVER_MOVE)
7992                    && !hasHoveredChild()
7993                    && pointInView(event.getX(), event.getY())) {
7994                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7995                mSendingHoverAccessibilityEvents = true;
7996            }
7997        } else {
7998            if (action == MotionEvent.ACTION_HOVER_EXIT
7999                    || (action == MotionEvent.ACTION_MOVE
8000                            && !pointInView(event.getX(), event.getY()))) {
8001                mSendingHoverAccessibilityEvents = false;
8002                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8003                // If the window does not have input focus we take away accessibility
8004                // focus as soon as the user stop hovering over the view.
8005                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8006                    getViewRootImpl().setAccessibilityFocus(null, null);
8007                }
8008            }
8009        }
8010
8011        if (isHoverable()) {
8012            switch (action) {
8013                case MotionEvent.ACTION_HOVER_ENTER:
8014                    setHovered(true);
8015                    break;
8016                case MotionEvent.ACTION_HOVER_EXIT:
8017                    setHovered(false);
8018                    break;
8019            }
8020
8021            // Dispatch the event to onGenericMotionEvent before returning true.
8022            // This is to provide compatibility with existing applications that
8023            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8024            // break because of the new default handling for hoverable views
8025            // in onHoverEvent.
8026            // Note that onGenericMotionEvent will be called by default when
8027            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8028            dispatchGenericMotionEventInternal(event);
8029            return true;
8030        }
8031
8032        return false;
8033    }
8034
8035    /**
8036     * Returns true if the view should handle {@link #onHoverEvent}
8037     * by calling {@link #setHovered} to change its hovered state.
8038     *
8039     * @return True if the view is hoverable.
8040     */
8041    private boolean isHoverable() {
8042        final int viewFlags = mViewFlags;
8043        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8044            return false;
8045        }
8046
8047        return (viewFlags & CLICKABLE) == CLICKABLE
8048                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8049    }
8050
8051    /**
8052     * Returns true if the view is currently hovered.
8053     *
8054     * @return True if the view is currently hovered.
8055     *
8056     * @see #setHovered
8057     * @see #onHoverChanged
8058     */
8059    @ViewDebug.ExportedProperty
8060    public boolean isHovered() {
8061        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8062    }
8063
8064    /**
8065     * Sets whether the view is currently hovered.
8066     * <p>
8067     * Calling this method also changes the drawable state of the view.  This
8068     * enables the view to react to hover by using different drawable resources
8069     * to change its appearance.
8070     * </p><p>
8071     * The {@link #onHoverChanged} method is called when the hovered state changes.
8072     * </p>
8073     *
8074     * @param hovered True if the view is hovered.
8075     *
8076     * @see #isHovered
8077     * @see #onHoverChanged
8078     */
8079    public void setHovered(boolean hovered) {
8080        if (hovered) {
8081            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8082                mPrivateFlags |= PFLAG_HOVERED;
8083                refreshDrawableState();
8084                onHoverChanged(true);
8085            }
8086        } else {
8087            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8088                mPrivateFlags &= ~PFLAG_HOVERED;
8089                refreshDrawableState();
8090                onHoverChanged(false);
8091            }
8092        }
8093    }
8094
8095    /**
8096     * Implement this method to handle hover state changes.
8097     * <p>
8098     * This method is called whenever the hover state changes as a result of a
8099     * call to {@link #setHovered}.
8100     * </p>
8101     *
8102     * @param hovered The current hover state, as returned by {@link #isHovered}.
8103     *
8104     * @see #isHovered
8105     * @see #setHovered
8106     */
8107    public void onHoverChanged(boolean hovered) {
8108    }
8109
8110    /**
8111     * Implement this method to handle touch screen motion events.
8112     *
8113     * @param event The motion event.
8114     * @return True if the event was handled, false otherwise.
8115     */
8116    public boolean onTouchEvent(MotionEvent event) {
8117        final int viewFlags = mViewFlags;
8118
8119        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8120            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8121                setPressed(false);
8122            }
8123            // A disabled view that is clickable still consumes the touch
8124            // events, it just doesn't respond to them.
8125            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8126                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8127        }
8128
8129        if (mTouchDelegate != null) {
8130            if (mTouchDelegate.onTouchEvent(event)) {
8131                return true;
8132            }
8133        }
8134
8135        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8136                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8137            switch (event.getAction()) {
8138                case MotionEvent.ACTION_UP:
8139                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8140                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8141                        // take focus if we don't have it already and we should in
8142                        // touch mode.
8143                        boolean focusTaken = false;
8144                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8145                            focusTaken = requestFocus();
8146                        }
8147
8148                        if (prepressed) {
8149                            // The button is being released before we actually
8150                            // showed it as pressed.  Make it show the pressed
8151                            // state now (before scheduling the click) to ensure
8152                            // the user sees it.
8153                            setPressed(true);
8154                       }
8155
8156                        if (!mHasPerformedLongPress) {
8157                            // This is a tap, so remove the longpress check
8158                            removeLongPressCallback();
8159
8160                            // Only perform take click actions if we were in the pressed state
8161                            if (!focusTaken) {
8162                                // Use a Runnable and post this rather than calling
8163                                // performClick directly. This lets other visual state
8164                                // of the view update before click actions start.
8165                                if (mPerformClick == null) {
8166                                    mPerformClick = new PerformClick();
8167                                }
8168                                if (!post(mPerformClick)) {
8169                                    performClick();
8170                                }
8171                            }
8172                        }
8173
8174                        if (mUnsetPressedState == null) {
8175                            mUnsetPressedState = new UnsetPressedState();
8176                        }
8177
8178                        if (prepressed) {
8179                            postDelayed(mUnsetPressedState,
8180                                    ViewConfiguration.getPressedStateDuration());
8181                        } else if (!post(mUnsetPressedState)) {
8182                            // If the post failed, unpress right now
8183                            mUnsetPressedState.run();
8184                        }
8185                        removeTapCallback();
8186                    }
8187                    break;
8188
8189                case MotionEvent.ACTION_DOWN:
8190                    mHasPerformedLongPress = false;
8191
8192                    if (performButtonActionOnTouchDown(event)) {
8193                        break;
8194                    }
8195
8196                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8197                    boolean isInScrollingContainer = isInScrollingContainer();
8198
8199                    // For views inside a scrolling container, delay the pressed feedback for
8200                    // a short period in case this is a scroll.
8201                    if (isInScrollingContainer) {
8202                        mPrivateFlags |= PFLAG_PREPRESSED;
8203                        if (mPendingCheckForTap == null) {
8204                            mPendingCheckForTap = new CheckForTap();
8205                        }
8206                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8207                    } else {
8208                        // Not inside a scrolling container, so show the feedback right away
8209                        setPressed(true);
8210                        checkForLongClick(0);
8211                    }
8212                    break;
8213
8214                case MotionEvent.ACTION_CANCEL:
8215                    setPressed(false);
8216                    removeTapCallback();
8217                    break;
8218
8219                case MotionEvent.ACTION_MOVE:
8220                    final int x = (int) event.getX();
8221                    final int y = (int) event.getY();
8222
8223                    // Be lenient about moving outside of buttons
8224                    if (!pointInView(x, y, mTouchSlop)) {
8225                        // Outside button
8226                        removeTapCallback();
8227                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8228                            // Remove any future long press/tap checks
8229                            removeLongPressCallback();
8230
8231                            setPressed(false);
8232                        }
8233                    }
8234                    break;
8235            }
8236            return true;
8237        }
8238
8239        return false;
8240    }
8241
8242    /**
8243     * @hide
8244     */
8245    public boolean isInScrollingContainer() {
8246        ViewParent p = getParent();
8247        while (p != null && p instanceof ViewGroup) {
8248            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8249                return true;
8250            }
8251            p = p.getParent();
8252        }
8253        return false;
8254    }
8255
8256    /**
8257     * Remove the longpress detection timer.
8258     */
8259    private void removeLongPressCallback() {
8260        if (mPendingCheckForLongPress != null) {
8261          removeCallbacks(mPendingCheckForLongPress);
8262        }
8263    }
8264
8265    /**
8266     * Remove the pending click action
8267     */
8268    private void removePerformClickCallback() {
8269        if (mPerformClick != null) {
8270            removeCallbacks(mPerformClick);
8271        }
8272    }
8273
8274    /**
8275     * Remove the prepress detection timer.
8276     */
8277    private void removeUnsetPressCallback() {
8278        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8279            setPressed(false);
8280            removeCallbacks(mUnsetPressedState);
8281        }
8282    }
8283
8284    /**
8285     * Remove the tap detection timer.
8286     */
8287    private void removeTapCallback() {
8288        if (mPendingCheckForTap != null) {
8289            mPrivateFlags &= ~PFLAG_PREPRESSED;
8290            removeCallbacks(mPendingCheckForTap);
8291        }
8292    }
8293
8294    /**
8295     * Cancels a pending long press.  Your subclass can use this if you
8296     * want the context menu to come up if the user presses and holds
8297     * at the same place, but you don't want it to come up if they press
8298     * and then move around enough to cause scrolling.
8299     */
8300    public void cancelLongPress() {
8301        removeLongPressCallback();
8302
8303        /*
8304         * The prepressed state handled by the tap callback is a display
8305         * construct, but the tap callback will post a long press callback
8306         * less its own timeout. Remove it here.
8307         */
8308        removeTapCallback();
8309    }
8310
8311    /**
8312     * Remove the pending callback for sending a
8313     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8314     */
8315    private void removeSendViewScrolledAccessibilityEventCallback() {
8316        if (mSendViewScrolledAccessibilityEvent != null) {
8317            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8318            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8319        }
8320    }
8321
8322    /**
8323     * Sets the TouchDelegate for this View.
8324     */
8325    public void setTouchDelegate(TouchDelegate delegate) {
8326        mTouchDelegate = delegate;
8327    }
8328
8329    /**
8330     * Gets the TouchDelegate for this View.
8331     */
8332    public TouchDelegate getTouchDelegate() {
8333        return mTouchDelegate;
8334    }
8335
8336    /**
8337     * Set flags controlling behavior of this view.
8338     *
8339     * @param flags Constant indicating the value which should be set
8340     * @param mask Constant indicating the bit range that should be changed
8341     */
8342    void setFlags(int flags, int mask) {
8343        int old = mViewFlags;
8344        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8345
8346        int changed = mViewFlags ^ old;
8347        if (changed == 0) {
8348            return;
8349        }
8350        int privateFlags = mPrivateFlags;
8351
8352        /* Check if the FOCUSABLE bit has changed */
8353        if (((changed & FOCUSABLE_MASK) != 0) &&
8354                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8355            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8356                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8357                /* Give up focus if we are no longer focusable */
8358                clearFocus();
8359            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8360                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8361                /*
8362                 * Tell the view system that we are now available to take focus
8363                 * if no one else already has it.
8364                 */
8365                if (mParent != null) mParent.focusableViewAvailable(this);
8366            }
8367            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8368                notifyAccessibilityStateChanged();
8369            }
8370        }
8371
8372        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8373            if ((changed & VISIBILITY_MASK) != 0) {
8374                /*
8375                 * If this view is becoming visible, invalidate it in case it changed while
8376                 * it was not visible. Marking it drawn ensures that the invalidation will
8377                 * go through.
8378                 */
8379                mPrivateFlags |= PFLAG_DRAWN;
8380                invalidate(true);
8381
8382                needGlobalAttributesUpdate(true);
8383
8384                // a view becoming visible is worth notifying the parent
8385                // about in case nothing has focus.  even if this specific view
8386                // isn't focusable, it may contain something that is, so let
8387                // the root view try to give this focus if nothing else does.
8388                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8389                    mParent.focusableViewAvailable(this);
8390                }
8391            }
8392        }
8393
8394        /* Check if the GONE bit has changed */
8395        if ((changed & GONE) != 0) {
8396            needGlobalAttributesUpdate(false);
8397            requestLayout();
8398
8399            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8400                if (hasFocus()) clearFocus();
8401                clearAccessibilityFocus();
8402                destroyDrawingCache();
8403                if (mParent instanceof View) {
8404                    // GONE views noop invalidation, so invalidate the parent
8405                    ((View) mParent).invalidate(true);
8406                }
8407                // Mark the view drawn to ensure that it gets invalidated properly the next
8408                // time it is visible and gets invalidated
8409                mPrivateFlags |= PFLAG_DRAWN;
8410            }
8411            if (mAttachInfo != null) {
8412                mAttachInfo.mViewVisibilityChanged = true;
8413            }
8414        }
8415
8416        /* Check if the VISIBLE bit has changed */
8417        if ((changed & INVISIBLE) != 0) {
8418            needGlobalAttributesUpdate(false);
8419            /*
8420             * If this view is becoming invisible, set the DRAWN flag so that
8421             * the next invalidate() will not be skipped.
8422             */
8423            mPrivateFlags |= PFLAG_DRAWN;
8424
8425            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8426                // root view becoming invisible shouldn't clear focus and accessibility focus
8427                if (getRootView() != this) {
8428                    clearFocus();
8429                    clearAccessibilityFocus();
8430                }
8431            }
8432            if (mAttachInfo != null) {
8433                mAttachInfo.mViewVisibilityChanged = true;
8434            }
8435        }
8436
8437        if ((changed & VISIBILITY_MASK) != 0) {
8438            if (mParent instanceof ViewGroup) {
8439                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8440                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8441                ((View) mParent).invalidate(true);
8442            } else if (mParent != null) {
8443                mParent.invalidateChild(this, null);
8444            }
8445            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8446        }
8447
8448        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8449            destroyDrawingCache();
8450        }
8451
8452        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8453            destroyDrawingCache();
8454            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8455            invalidateParentCaches();
8456        }
8457
8458        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8459            destroyDrawingCache();
8460            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8461        }
8462
8463        if ((changed & DRAW_MASK) != 0) {
8464            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8465                if (mBackground != null) {
8466                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8467                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8468                } else {
8469                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8470                }
8471            } else {
8472                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8473            }
8474            requestLayout();
8475            invalidate(true);
8476        }
8477
8478        if ((changed & KEEP_SCREEN_ON) != 0) {
8479            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8480                mParent.recomputeViewAttributes(this);
8481            }
8482        }
8483
8484        if (AccessibilityManager.getInstance(mContext).isEnabled()
8485                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8486                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8487            notifyAccessibilityStateChanged();
8488        }
8489    }
8490
8491    /**
8492     * Change the view's z order in the tree, so it's on top of other sibling
8493     * views
8494     */
8495    public void bringToFront() {
8496        if (mParent != null) {
8497            mParent.bringChildToFront(this);
8498        }
8499    }
8500
8501    /**
8502     * This is called in response to an internal scroll in this view (i.e., the
8503     * view scrolled its own contents). This is typically as a result of
8504     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8505     * called.
8506     *
8507     * @param l Current horizontal scroll origin.
8508     * @param t Current vertical scroll origin.
8509     * @param oldl Previous horizontal scroll origin.
8510     * @param oldt Previous vertical scroll origin.
8511     */
8512    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8513        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8514            postSendViewScrolledAccessibilityEventCallback();
8515        }
8516
8517        mBackgroundSizeChanged = true;
8518
8519        final AttachInfo ai = mAttachInfo;
8520        if (ai != null) {
8521            ai.mViewScrollChanged = true;
8522        }
8523    }
8524
8525    /**
8526     * Interface definition for a callback to be invoked when the layout bounds of a view
8527     * changes due to layout processing.
8528     */
8529    public interface OnLayoutChangeListener {
8530        /**
8531         * Called when the focus state of a view has changed.
8532         *
8533         * @param v The view whose state has changed.
8534         * @param left The new value of the view's left property.
8535         * @param top The new value of the view's top property.
8536         * @param right The new value of the view's right property.
8537         * @param bottom The new value of the view's bottom property.
8538         * @param oldLeft The previous value of the view's left property.
8539         * @param oldTop The previous value of the view's top property.
8540         * @param oldRight The previous value of the view's right property.
8541         * @param oldBottom The previous value of the view's bottom property.
8542         */
8543        void onLayoutChange(View v, int left, int top, int right, int bottom,
8544            int oldLeft, int oldTop, int oldRight, int oldBottom);
8545    }
8546
8547    /**
8548     * This is called during layout when the size of this view has changed. If
8549     * you were just added to the view hierarchy, you're called with the old
8550     * values of 0.
8551     *
8552     * @param w Current width of this view.
8553     * @param h Current height of this view.
8554     * @param oldw Old width of this view.
8555     * @param oldh Old height of this view.
8556     */
8557    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8558    }
8559
8560    /**
8561     * Called by draw to draw the child views. This may be overridden
8562     * by derived classes to gain control just before its children are drawn
8563     * (but after its own view has been drawn).
8564     * @param canvas the canvas on which to draw the view
8565     */
8566    protected void dispatchDraw(Canvas canvas) {
8567
8568    }
8569
8570    /**
8571     * Gets the parent of this view. Note that the parent is a
8572     * ViewParent and not necessarily a View.
8573     *
8574     * @return Parent of this view.
8575     */
8576    public final ViewParent getParent() {
8577        return mParent;
8578    }
8579
8580    /**
8581     * Set the horizontal scrolled position of your view. This will cause a call to
8582     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8583     * invalidated.
8584     * @param value the x position to scroll to
8585     */
8586    public void setScrollX(int value) {
8587        scrollTo(value, mScrollY);
8588    }
8589
8590    /**
8591     * Set the vertical scrolled position of your view. This will cause a call to
8592     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8593     * invalidated.
8594     * @param value the y position to scroll to
8595     */
8596    public void setScrollY(int value) {
8597        scrollTo(mScrollX, value);
8598    }
8599
8600    /**
8601     * Return the scrolled left position of this view. This is the left edge of
8602     * the displayed part of your view. You do not need to draw any pixels
8603     * farther left, since those are outside of the frame of your view on
8604     * screen.
8605     *
8606     * @return The left edge of the displayed part of your view, in pixels.
8607     */
8608    public final int getScrollX() {
8609        return mScrollX;
8610    }
8611
8612    /**
8613     * Return the scrolled top position of this view. This is the top edge of
8614     * the displayed part of your view. You do not need to draw any pixels above
8615     * it, since those are outside of the frame of your view on screen.
8616     *
8617     * @return The top edge of the displayed part of your view, in pixels.
8618     */
8619    public final int getScrollY() {
8620        return mScrollY;
8621    }
8622
8623    /**
8624     * Return the width of the your view.
8625     *
8626     * @return The width of your view, in pixels.
8627     */
8628    @ViewDebug.ExportedProperty(category = "layout")
8629    public final int getWidth() {
8630        return mRight - mLeft;
8631    }
8632
8633    /**
8634     * Return the height of your view.
8635     *
8636     * @return The height of your view, in pixels.
8637     */
8638    @ViewDebug.ExportedProperty(category = "layout")
8639    public final int getHeight() {
8640        return mBottom - mTop;
8641    }
8642
8643    /**
8644     * Return the visible drawing bounds of your view. Fills in the output
8645     * rectangle with the values from getScrollX(), getScrollY(),
8646     * getWidth(), and getHeight().
8647     *
8648     * @param outRect The (scrolled) drawing bounds of the view.
8649     */
8650    public void getDrawingRect(Rect outRect) {
8651        outRect.left = mScrollX;
8652        outRect.top = mScrollY;
8653        outRect.right = mScrollX + (mRight - mLeft);
8654        outRect.bottom = mScrollY + (mBottom - mTop);
8655    }
8656
8657    /**
8658     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8659     * raw width component (that is the result is masked by
8660     * {@link #MEASURED_SIZE_MASK}).
8661     *
8662     * @return The raw measured width of this view.
8663     */
8664    public final int getMeasuredWidth() {
8665        return mMeasuredWidth & MEASURED_SIZE_MASK;
8666    }
8667
8668    /**
8669     * Return the full width measurement information for this view as computed
8670     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8671     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8672     * This should be used during measurement and layout calculations only. Use
8673     * {@link #getWidth()} to see how wide a view is after layout.
8674     *
8675     * @return The measured width of this view as a bit mask.
8676     */
8677    public final int getMeasuredWidthAndState() {
8678        return mMeasuredWidth;
8679    }
8680
8681    /**
8682     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8683     * raw width component (that is the result is masked by
8684     * {@link #MEASURED_SIZE_MASK}).
8685     *
8686     * @return The raw measured height of this view.
8687     */
8688    public final int getMeasuredHeight() {
8689        return mMeasuredHeight & MEASURED_SIZE_MASK;
8690    }
8691
8692    /**
8693     * Return the full height measurement information for this view as computed
8694     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8695     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8696     * This should be used during measurement and layout calculations only. Use
8697     * {@link #getHeight()} to see how wide a view is after layout.
8698     *
8699     * @return The measured width of this view as a bit mask.
8700     */
8701    public final int getMeasuredHeightAndState() {
8702        return mMeasuredHeight;
8703    }
8704
8705    /**
8706     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8707     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8708     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8709     * and the height component is at the shifted bits
8710     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8711     */
8712    public final int getMeasuredState() {
8713        return (mMeasuredWidth&MEASURED_STATE_MASK)
8714                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8715                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8716    }
8717
8718    /**
8719     * The transform matrix of this view, which is calculated based on the current
8720     * roation, scale, and pivot properties.
8721     *
8722     * @see #getRotation()
8723     * @see #getScaleX()
8724     * @see #getScaleY()
8725     * @see #getPivotX()
8726     * @see #getPivotY()
8727     * @return The current transform matrix for the view
8728     */
8729    public Matrix getMatrix() {
8730        if (mTransformationInfo != null) {
8731            updateMatrix();
8732            return mTransformationInfo.mMatrix;
8733        }
8734        return Matrix.IDENTITY_MATRIX;
8735    }
8736
8737    /**
8738     * Utility function to determine if the value is far enough away from zero to be
8739     * considered non-zero.
8740     * @param value A floating point value to check for zero-ness
8741     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8742     */
8743    private static boolean nonzero(float value) {
8744        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8745    }
8746
8747    /**
8748     * Returns true if the transform matrix is the identity matrix.
8749     * Recomputes the matrix if necessary.
8750     *
8751     * @return True if the transform matrix is the identity matrix, false otherwise.
8752     */
8753    final boolean hasIdentityMatrix() {
8754        if (mTransformationInfo != null) {
8755            updateMatrix();
8756            return mTransformationInfo.mMatrixIsIdentity;
8757        }
8758        return true;
8759    }
8760
8761    void ensureTransformationInfo() {
8762        if (mTransformationInfo == null) {
8763            mTransformationInfo = new TransformationInfo();
8764        }
8765    }
8766
8767    /**
8768     * Recomputes the transform matrix if necessary.
8769     */
8770    private void updateMatrix() {
8771        final TransformationInfo info = mTransformationInfo;
8772        if (info == null) {
8773            return;
8774        }
8775        if (info.mMatrixDirty) {
8776            // transform-related properties have changed since the last time someone
8777            // asked for the matrix; recalculate it with the current values
8778
8779            // Figure out if we need to update the pivot point
8780            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8781                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8782                    info.mPrevWidth = mRight - mLeft;
8783                    info.mPrevHeight = mBottom - mTop;
8784                    info.mPivotX = info.mPrevWidth / 2f;
8785                    info.mPivotY = info.mPrevHeight / 2f;
8786                }
8787            }
8788            info.mMatrix.reset();
8789            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8790                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8791                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8792                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8793            } else {
8794                if (info.mCamera == null) {
8795                    info.mCamera = new Camera();
8796                    info.matrix3D = new Matrix();
8797                }
8798                info.mCamera.save();
8799                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8800                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8801                info.mCamera.getMatrix(info.matrix3D);
8802                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8803                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8804                        info.mPivotY + info.mTranslationY);
8805                info.mMatrix.postConcat(info.matrix3D);
8806                info.mCamera.restore();
8807            }
8808            info.mMatrixDirty = false;
8809            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8810            info.mInverseMatrixDirty = true;
8811        }
8812    }
8813
8814   /**
8815     * Utility method to retrieve the inverse of the current mMatrix property.
8816     * We cache the matrix to avoid recalculating it when transform properties
8817     * have not changed.
8818     *
8819     * @return The inverse of the current matrix of this view.
8820     */
8821    final Matrix getInverseMatrix() {
8822        final TransformationInfo info = mTransformationInfo;
8823        if (info != null) {
8824            updateMatrix();
8825            if (info.mInverseMatrixDirty) {
8826                if (info.mInverseMatrix == null) {
8827                    info.mInverseMatrix = new Matrix();
8828                }
8829                info.mMatrix.invert(info.mInverseMatrix);
8830                info.mInverseMatrixDirty = false;
8831            }
8832            return info.mInverseMatrix;
8833        }
8834        return Matrix.IDENTITY_MATRIX;
8835    }
8836
8837    /**
8838     * Gets the distance along the Z axis from the camera to this view.
8839     *
8840     * @see #setCameraDistance(float)
8841     *
8842     * @return The distance along the Z axis.
8843     */
8844    public float getCameraDistance() {
8845        ensureTransformationInfo();
8846        final float dpi = mResources.getDisplayMetrics().densityDpi;
8847        final TransformationInfo info = mTransformationInfo;
8848        if (info.mCamera == null) {
8849            info.mCamera = new Camera();
8850            info.matrix3D = new Matrix();
8851        }
8852        return -(info.mCamera.getLocationZ() * dpi);
8853    }
8854
8855    /**
8856     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8857     * views are drawn) from the camera to this view. The camera's distance
8858     * affects 3D transformations, for instance rotations around the X and Y
8859     * axis. If the rotationX or rotationY properties are changed and this view is
8860     * large (more than half the size of the screen), it is recommended to always
8861     * use a camera distance that's greater than the height (X axis rotation) or
8862     * the width (Y axis rotation) of this view.</p>
8863     *
8864     * <p>The distance of the camera from the view plane can have an affect on the
8865     * perspective distortion of the view when it is rotated around the x or y axis.
8866     * For example, a large distance will result in a large viewing angle, and there
8867     * will not be much perspective distortion of the view as it rotates. A short
8868     * distance may cause much more perspective distortion upon rotation, and can
8869     * also result in some drawing artifacts if the rotated view ends up partially
8870     * behind the camera (which is why the recommendation is to use a distance at
8871     * least as far as the size of the view, if the view is to be rotated.)</p>
8872     *
8873     * <p>The distance is expressed in "depth pixels." The default distance depends
8874     * on the screen density. For instance, on a medium density display, the
8875     * default distance is 1280. On a high density display, the default distance
8876     * is 1920.</p>
8877     *
8878     * <p>If you want to specify a distance that leads to visually consistent
8879     * results across various densities, use the following formula:</p>
8880     * <pre>
8881     * float scale = context.getResources().getDisplayMetrics().density;
8882     * view.setCameraDistance(distance * scale);
8883     * </pre>
8884     *
8885     * <p>The density scale factor of a high density display is 1.5,
8886     * and 1920 = 1280 * 1.5.</p>
8887     *
8888     * @param distance The distance in "depth pixels", if negative the opposite
8889     *        value is used
8890     *
8891     * @see #setRotationX(float)
8892     * @see #setRotationY(float)
8893     */
8894    public void setCameraDistance(float distance) {
8895        invalidateViewProperty(true, false);
8896
8897        ensureTransformationInfo();
8898        final float dpi = mResources.getDisplayMetrics().densityDpi;
8899        final TransformationInfo info = mTransformationInfo;
8900        if (info.mCamera == null) {
8901            info.mCamera = new Camera();
8902            info.matrix3D = new Matrix();
8903        }
8904
8905        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8906        info.mMatrixDirty = true;
8907
8908        invalidateViewProperty(false, false);
8909        if (mDisplayList != null) {
8910            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8911        }
8912        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8913            // View was rejected last time it was drawn by its parent; this may have changed
8914            invalidateParentIfNeeded();
8915        }
8916    }
8917
8918    /**
8919     * The degrees that the view is rotated around the pivot point.
8920     *
8921     * @see #setRotation(float)
8922     * @see #getPivotX()
8923     * @see #getPivotY()
8924     *
8925     * @return The degrees of rotation.
8926     */
8927    @ViewDebug.ExportedProperty(category = "drawing")
8928    public float getRotation() {
8929        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8930    }
8931
8932    /**
8933     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8934     * result in clockwise rotation.
8935     *
8936     * @param rotation The degrees of rotation.
8937     *
8938     * @see #getRotation()
8939     * @see #getPivotX()
8940     * @see #getPivotY()
8941     * @see #setRotationX(float)
8942     * @see #setRotationY(float)
8943     *
8944     * @attr ref android.R.styleable#View_rotation
8945     */
8946    public void setRotation(float rotation) {
8947        ensureTransformationInfo();
8948        final TransformationInfo info = mTransformationInfo;
8949        if (info.mRotation != rotation) {
8950            // Double-invalidation is necessary to capture view's old and new areas
8951            invalidateViewProperty(true, false);
8952            info.mRotation = rotation;
8953            info.mMatrixDirty = true;
8954            invalidateViewProperty(false, true);
8955            if (mDisplayList != null) {
8956                mDisplayList.setRotation(rotation);
8957            }
8958            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8959                // View was rejected last time it was drawn by its parent; this may have changed
8960                invalidateParentIfNeeded();
8961            }
8962        }
8963    }
8964
8965    /**
8966     * The degrees that the view is rotated around the vertical axis through the pivot point.
8967     *
8968     * @see #getPivotX()
8969     * @see #getPivotY()
8970     * @see #setRotationY(float)
8971     *
8972     * @return The degrees of Y rotation.
8973     */
8974    @ViewDebug.ExportedProperty(category = "drawing")
8975    public float getRotationY() {
8976        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8977    }
8978
8979    /**
8980     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8981     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8982     * down the y axis.
8983     *
8984     * When rotating large views, it is recommended to adjust the camera distance
8985     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8986     *
8987     * @param rotationY The degrees of Y rotation.
8988     *
8989     * @see #getRotationY()
8990     * @see #getPivotX()
8991     * @see #getPivotY()
8992     * @see #setRotation(float)
8993     * @see #setRotationX(float)
8994     * @see #setCameraDistance(float)
8995     *
8996     * @attr ref android.R.styleable#View_rotationY
8997     */
8998    public void setRotationY(float rotationY) {
8999        ensureTransformationInfo();
9000        final TransformationInfo info = mTransformationInfo;
9001        if (info.mRotationY != rotationY) {
9002            invalidateViewProperty(true, false);
9003            info.mRotationY = rotationY;
9004            info.mMatrixDirty = true;
9005            invalidateViewProperty(false, true);
9006            if (mDisplayList != null) {
9007                mDisplayList.setRotationY(rotationY);
9008            }
9009            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9010                // View was rejected last time it was drawn by its parent; this may have changed
9011                invalidateParentIfNeeded();
9012            }
9013        }
9014    }
9015
9016    /**
9017     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9018     *
9019     * @see #getPivotX()
9020     * @see #getPivotY()
9021     * @see #setRotationX(float)
9022     *
9023     * @return The degrees of X rotation.
9024     */
9025    @ViewDebug.ExportedProperty(category = "drawing")
9026    public float getRotationX() {
9027        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9028    }
9029
9030    /**
9031     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9032     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9033     * x axis.
9034     *
9035     * When rotating large views, it is recommended to adjust the camera distance
9036     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9037     *
9038     * @param rotationX The degrees of X rotation.
9039     *
9040     * @see #getRotationX()
9041     * @see #getPivotX()
9042     * @see #getPivotY()
9043     * @see #setRotation(float)
9044     * @see #setRotationY(float)
9045     * @see #setCameraDistance(float)
9046     *
9047     * @attr ref android.R.styleable#View_rotationX
9048     */
9049    public void setRotationX(float rotationX) {
9050        ensureTransformationInfo();
9051        final TransformationInfo info = mTransformationInfo;
9052        if (info.mRotationX != rotationX) {
9053            invalidateViewProperty(true, false);
9054            info.mRotationX = rotationX;
9055            info.mMatrixDirty = true;
9056            invalidateViewProperty(false, true);
9057            if (mDisplayList != null) {
9058                mDisplayList.setRotationX(rotationX);
9059            }
9060            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9061                // View was rejected last time it was drawn by its parent; this may have changed
9062                invalidateParentIfNeeded();
9063            }
9064        }
9065    }
9066
9067    /**
9068     * The amount that the view is scaled in x around the pivot point, as a proportion of
9069     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9070     *
9071     * <p>By default, this is 1.0f.
9072     *
9073     * @see #getPivotX()
9074     * @see #getPivotY()
9075     * @return The scaling factor.
9076     */
9077    @ViewDebug.ExportedProperty(category = "drawing")
9078    public float getScaleX() {
9079        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9080    }
9081
9082    /**
9083     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9084     * the view's unscaled width. A value of 1 means that no scaling is applied.
9085     *
9086     * @param scaleX The scaling factor.
9087     * @see #getPivotX()
9088     * @see #getPivotY()
9089     *
9090     * @attr ref android.R.styleable#View_scaleX
9091     */
9092    public void setScaleX(float scaleX) {
9093        ensureTransformationInfo();
9094        final TransformationInfo info = mTransformationInfo;
9095        if (info.mScaleX != scaleX) {
9096            invalidateViewProperty(true, false);
9097            info.mScaleX = scaleX;
9098            info.mMatrixDirty = true;
9099            invalidateViewProperty(false, true);
9100            if (mDisplayList != null) {
9101                mDisplayList.setScaleX(scaleX);
9102            }
9103            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9104                // View was rejected last time it was drawn by its parent; this may have changed
9105                invalidateParentIfNeeded();
9106            }
9107        }
9108    }
9109
9110    /**
9111     * The amount that the view is scaled in y around the pivot point, as a proportion of
9112     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9113     *
9114     * <p>By default, this is 1.0f.
9115     *
9116     * @see #getPivotX()
9117     * @see #getPivotY()
9118     * @return The scaling factor.
9119     */
9120    @ViewDebug.ExportedProperty(category = "drawing")
9121    public float getScaleY() {
9122        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9123    }
9124
9125    /**
9126     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9127     * the view's unscaled width. A value of 1 means that no scaling is applied.
9128     *
9129     * @param scaleY The scaling factor.
9130     * @see #getPivotX()
9131     * @see #getPivotY()
9132     *
9133     * @attr ref android.R.styleable#View_scaleY
9134     */
9135    public void setScaleY(float scaleY) {
9136        ensureTransformationInfo();
9137        final TransformationInfo info = mTransformationInfo;
9138        if (info.mScaleY != scaleY) {
9139            invalidateViewProperty(true, false);
9140            info.mScaleY = scaleY;
9141            info.mMatrixDirty = true;
9142            invalidateViewProperty(false, true);
9143            if (mDisplayList != null) {
9144                mDisplayList.setScaleY(scaleY);
9145            }
9146            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9147                // View was rejected last time it was drawn by its parent; this may have changed
9148                invalidateParentIfNeeded();
9149            }
9150        }
9151    }
9152
9153    /**
9154     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9155     * and {@link #setScaleX(float) scaled}.
9156     *
9157     * @see #getRotation()
9158     * @see #getScaleX()
9159     * @see #getScaleY()
9160     * @see #getPivotY()
9161     * @return The x location of the pivot point.
9162     *
9163     * @attr ref android.R.styleable#View_transformPivotX
9164     */
9165    @ViewDebug.ExportedProperty(category = "drawing")
9166    public float getPivotX() {
9167        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9168    }
9169
9170    /**
9171     * Sets the x location of the point around which the view is
9172     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9173     * By default, the pivot point is centered on the object.
9174     * Setting this property disables this behavior and causes the view to use only the
9175     * explicitly set pivotX and pivotY values.
9176     *
9177     * @param pivotX The x location of the pivot point.
9178     * @see #getRotation()
9179     * @see #getScaleX()
9180     * @see #getScaleY()
9181     * @see #getPivotY()
9182     *
9183     * @attr ref android.R.styleable#View_transformPivotX
9184     */
9185    public void setPivotX(float pivotX) {
9186        ensureTransformationInfo();
9187        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9188        final TransformationInfo info = mTransformationInfo;
9189        if (info.mPivotX != pivotX) {
9190            invalidateViewProperty(true, false);
9191            info.mPivotX = pivotX;
9192            info.mMatrixDirty = true;
9193            invalidateViewProperty(false, true);
9194            if (mDisplayList != null) {
9195                mDisplayList.setPivotX(pivotX);
9196            }
9197            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9198                // View was rejected last time it was drawn by its parent; this may have changed
9199                invalidateParentIfNeeded();
9200            }
9201        }
9202    }
9203
9204    /**
9205     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9206     * and {@link #setScaleY(float) scaled}.
9207     *
9208     * @see #getRotation()
9209     * @see #getScaleX()
9210     * @see #getScaleY()
9211     * @see #getPivotY()
9212     * @return The y location of the pivot point.
9213     *
9214     * @attr ref android.R.styleable#View_transformPivotY
9215     */
9216    @ViewDebug.ExportedProperty(category = "drawing")
9217    public float getPivotY() {
9218        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9219    }
9220
9221    /**
9222     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9223     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9224     * Setting this property disables this behavior and causes the view to use only the
9225     * explicitly set pivotX and pivotY values.
9226     *
9227     * @param pivotY The y location of the pivot point.
9228     * @see #getRotation()
9229     * @see #getScaleX()
9230     * @see #getScaleY()
9231     * @see #getPivotY()
9232     *
9233     * @attr ref android.R.styleable#View_transformPivotY
9234     */
9235    public void setPivotY(float pivotY) {
9236        ensureTransformationInfo();
9237        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9238        final TransformationInfo info = mTransformationInfo;
9239        if (info.mPivotY != pivotY) {
9240            invalidateViewProperty(true, false);
9241            info.mPivotY = pivotY;
9242            info.mMatrixDirty = true;
9243            invalidateViewProperty(false, true);
9244            if (mDisplayList != null) {
9245                mDisplayList.setPivotY(pivotY);
9246            }
9247            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9248                // View was rejected last time it was drawn by its parent; this may have changed
9249                invalidateParentIfNeeded();
9250            }
9251        }
9252    }
9253
9254    /**
9255     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9256     * completely transparent and 1 means the view is completely opaque.
9257     *
9258     * <p>By default this is 1.0f.
9259     * @return The opacity of the view.
9260     */
9261    @ViewDebug.ExportedProperty(category = "drawing")
9262    public float getAlpha() {
9263        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9264    }
9265
9266    /**
9267     * Returns whether this View has content which overlaps. This function, intended to be
9268     * overridden by specific View types, is an optimization when alpha is set on a view. If
9269     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9270     * and then composited it into place, which can be expensive. If the view has no overlapping
9271     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9272     * An example of overlapping rendering is a TextView with a background image, such as a
9273     * Button. An example of non-overlapping rendering is a TextView with no background, or
9274     * an ImageView with only the foreground image. The default implementation returns true;
9275     * subclasses should override if they have cases which can be optimized.
9276     *
9277     * @return true if the content in this view might overlap, false otherwise.
9278     */
9279    public boolean hasOverlappingRendering() {
9280        return true;
9281    }
9282
9283    /**
9284     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9285     * completely transparent and 1 means the view is completely opaque.</p>
9286     *
9287     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9288     * responsible for applying the opacity itself. Otherwise, calling this method is
9289     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9290     * setting a hardware layer.</p>
9291     *
9292     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9293     * performance implications. It is generally best to use the alpha property sparingly and
9294     * transiently, as in the case of fading animations.</p>
9295     *
9296     * @param alpha The opacity of the view.
9297     *
9298     * @see #setLayerType(int, android.graphics.Paint)
9299     *
9300     * @attr ref android.R.styleable#View_alpha
9301     */
9302    public void setAlpha(float alpha) {
9303        ensureTransformationInfo();
9304        if (mTransformationInfo.mAlpha != alpha) {
9305            mTransformationInfo.mAlpha = alpha;
9306            if (onSetAlpha((int) (alpha * 255))) {
9307                mPrivateFlags |= PFLAG_ALPHA_SET;
9308                // subclass is handling alpha - don't optimize rendering cache invalidation
9309                invalidateParentCaches();
9310                invalidate(true);
9311            } else {
9312                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9313                invalidateViewProperty(true, false);
9314                if (mDisplayList != null) {
9315                    mDisplayList.setAlpha(alpha);
9316                }
9317            }
9318        }
9319    }
9320
9321    /**
9322     * Faster version of setAlpha() which performs the same steps except there are
9323     * no calls to invalidate(). The caller of this function should perform proper invalidation
9324     * on the parent and this object. The return value indicates whether the subclass handles
9325     * alpha (the return value for onSetAlpha()).
9326     *
9327     * @param alpha The new value for the alpha property
9328     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9329     *         the new value for the alpha property is different from the old value
9330     */
9331    boolean setAlphaNoInvalidation(float alpha) {
9332        ensureTransformationInfo();
9333        if (mTransformationInfo.mAlpha != alpha) {
9334            mTransformationInfo.mAlpha = alpha;
9335            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9336            if (subclassHandlesAlpha) {
9337                mPrivateFlags |= PFLAG_ALPHA_SET;
9338                return true;
9339            } else {
9340                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9341                if (mDisplayList != null) {
9342                    mDisplayList.setAlpha(alpha);
9343                }
9344            }
9345        }
9346        return false;
9347    }
9348
9349    /**
9350     * Top position of this view relative to its parent.
9351     *
9352     * @return The top of this view, in pixels.
9353     */
9354    @ViewDebug.CapturedViewProperty
9355    public final int getTop() {
9356        return mTop;
9357    }
9358
9359    /**
9360     * Sets the top position of this view relative to its parent. This method is meant to be called
9361     * by the layout system and should not generally be called otherwise, because the property
9362     * may be changed at any time by the layout.
9363     *
9364     * @param top The top of this view, in pixels.
9365     */
9366    public final void setTop(int top) {
9367        if (top != mTop) {
9368            updateMatrix();
9369            final boolean matrixIsIdentity = mTransformationInfo == null
9370                    || mTransformationInfo.mMatrixIsIdentity;
9371            if (matrixIsIdentity) {
9372                if (mAttachInfo != null) {
9373                    int minTop;
9374                    int yLoc;
9375                    if (top < mTop) {
9376                        minTop = top;
9377                        yLoc = top - mTop;
9378                    } else {
9379                        minTop = mTop;
9380                        yLoc = 0;
9381                    }
9382                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9383                }
9384            } else {
9385                // Double-invalidation is necessary to capture view's old and new areas
9386                invalidate(true);
9387            }
9388
9389            int width = mRight - mLeft;
9390            int oldHeight = mBottom - mTop;
9391
9392            mTop = top;
9393            if (mDisplayList != null) {
9394                mDisplayList.setTop(mTop);
9395            }
9396
9397            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9398
9399            if (!matrixIsIdentity) {
9400                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9401                    // A change in dimension means an auto-centered pivot point changes, too
9402                    mTransformationInfo.mMatrixDirty = true;
9403                }
9404                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9405                invalidate(true);
9406            }
9407            mBackgroundSizeChanged = true;
9408            invalidateParentIfNeeded();
9409            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9410                // View was rejected last time it was drawn by its parent; this may have changed
9411                invalidateParentIfNeeded();
9412            }
9413        }
9414    }
9415
9416    /**
9417     * Bottom position of this view relative to its parent.
9418     *
9419     * @return The bottom of this view, in pixels.
9420     */
9421    @ViewDebug.CapturedViewProperty
9422    public final int getBottom() {
9423        return mBottom;
9424    }
9425
9426    /**
9427     * True if this view has changed since the last time being drawn.
9428     *
9429     * @return The dirty state of this view.
9430     */
9431    public boolean isDirty() {
9432        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9433    }
9434
9435    /**
9436     * Sets the bottom position of this view relative to its parent. This method is meant to be
9437     * called by the layout system and should not generally be called otherwise, because the
9438     * property may be changed at any time by the layout.
9439     *
9440     * @param bottom The bottom of this view, in pixels.
9441     */
9442    public final void setBottom(int bottom) {
9443        if (bottom != mBottom) {
9444            updateMatrix();
9445            final boolean matrixIsIdentity = mTransformationInfo == null
9446                    || mTransformationInfo.mMatrixIsIdentity;
9447            if (matrixIsIdentity) {
9448                if (mAttachInfo != null) {
9449                    int maxBottom;
9450                    if (bottom < mBottom) {
9451                        maxBottom = mBottom;
9452                    } else {
9453                        maxBottom = bottom;
9454                    }
9455                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9456                }
9457            } else {
9458                // Double-invalidation is necessary to capture view's old and new areas
9459                invalidate(true);
9460            }
9461
9462            int width = mRight - mLeft;
9463            int oldHeight = mBottom - mTop;
9464
9465            mBottom = bottom;
9466            if (mDisplayList != null) {
9467                mDisplayList.setBottom(mBottom);
9468            }
9469
9470            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9471
9472            if (!matrixIsIdentity) {
9473                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9474                    // A change in dimension means an auto-centered pivot point changes, too
9475                    mTransformationInfo.mMatrixDirty = true;
9476                }
9477                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9478                invalidate(true);
9479            }
9480            mBackgroundSizeChanged = true;
9481            invalidateParentIfNeeded();
9482            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9483                // View was rejected last time it was drawn by its parent; this may have changed
9484                invalidateParentIfNeeded();
9485            }
9486        }
9487    }
9488
9489    /**
9490     * Left position of this view relative to its parent.
9491     *
9492     * @return The left edge of this view, in pixels.
9493     */
9494    @ViewDebug.CapturedViewProperty
9495    public final int getLeft() {
9496        return mLeft;
9497    }
9498
9499    /**
9500     * Sets the left position of this view relative to its parent. This method is meant to be called
9501     * by the layout system and should not generally be called otherwise, because the property
9502     * may be changed at any time by the layout.
9503     *
9504     * @param left The bottom of this view, in pixels.
9505     */
9506    public final void setLeft(int left) {
9507        if (left != mLeft) {
9508            updateMatrix();
9509            final boolean matrixIsIdentity = mTransformationInfo == null
9510                    || mTransformationInfo.mMatrixIsIdentity;
9511            if (matrixIsIdentity) {
9512                if (mAttachInfo != null) {
9513                    int minLeft;
9514                    int xLoc;
9515                    if (left < mLeft) {
9516                        minLeft = left;
9517                        xLoc = left - mLeft;
9518                    } else {
9519                        minLeft = mLeft;
9520                        xLoc = 0;
9521                    }
9522                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9523                }
9524            } else {
9525                // Double-invalidation is necessary to capture view's old and new areas
9526                invalidate(true);
9527            }
9528
9529            int oldWidth = mRight - mLeft;
9530            int height = mBottom - mTop;
9531
9532            mLeft = left;
9533            if (mDisplayList != null) {
9534                mDisplayList.setLeft(left);
9535            }
9536
9537            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9538
9539            if (!matrixIsIdentity) {
9540                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9541                    // A change in dimension means an auto-centered pivot point changes, too
9542                    mTransformationInfo.mMatrixDirty = true;
9543                }
9544                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9545                invalidate(true);
9546            }
9547            mBackgroundSizeChanged = true;
9548            invalidateParentIfNeeded();
9549            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9550                // View was rejected last time it was drawn by its parent; this may have changed
9551                invalidateParentIfNeeded();
9552            }
9553        }
9554    }
9555
9556    /**
9557     * Right position of this view relative to its parent.
9558     *
9559     * @return The right edge of this view, in pixels.
9560     */
9561    @ViewDebug.CapturedViewProperty
9562    public final int getRight() {
9563        return mRight;
9564    }
9565
9566    /**
9567     * Sets the right position of this view relative to its parent. This method is meant to be called
9568     * by the layout system and should not generally be called otherwise, because the property
9569     * may be changed at any time by the layout.
9570     *
9571     * @param right The bottom of this view, in pixels.
9572     */
9573    public final void setRight(int right) {
9574        if (right != mRight) {
9575            updateMatrix();
9576            final boolean matrixIsIdentity = mTransformationInfo == null
9577                    || mTransformationInfo.mMatrixIsIdentity;
9578            if (matrixIsIdentity) {
9579                if (mAttachInfo != null) {
9580                    int maxRight;
9581                    if (right < mRight) {
9582                        maxRight = mRight;
9583                    } else {
9584                        maxRight = right;
9585                    }
9586                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9587                }
9588            } else {
9589                // Double-invalidation is necessary to capture view's old and new areas
9590                invalidate(true);
9591            }
9592
9593            int oldWidth = mRight - mLeft;
9594            int height = mBottom - mTop;
9595
9596            mRight = right;
9597            if (mDisplayList != null) {
9598                mDisplayList.setRight(mRight);
9599            }
9600
9601            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9602
9603            if (!matrixIsIdentity) {
9604                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9605                    // A change in dimension means an auto-centered pivot point changes, too
9606                    mTransformationInfo.mMatrixDirty = true;
9607                }
9608                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9609                invalidate(true);
9610            }
9611            mBackgroundSizeChanged = true;
9612            invalidateParentIfNeeded();
9613            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9614                // View was rejected last time it was drawn by its parent; this may have changed
9615                invalidateParentIfNeeded();
9616            }
9617        }
9618    }
9619
9620    /**
9621     * The visual x position of this view, in pixels. This is equivalent to the
9622     * {@link #setTranslationX(float) translationX} property plus the current
9623     * {@link #getLeft() left} property.
9624     *
9625     * @return The visual x position of this view, in pixels.
9626     */
9627    @ViewDebug.ExportedProperty(category = "drawing")
9628    public float getX() {
9629        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9630    }
9631
9632    /**
9633     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9634     * {@link #setTranslationX(float) translationX} property to be the difference between
9635     * the x value passed in and the current {@link #getLeft() left} property.
9636     *
9637     * @param x The visual x position of this view, in pixels.
9638     */
9639    public void setX(float x) {
9640        setTranslationX(x - mLeft);
9641    }
9642
9643    /**
9644     * The visual y position of this view, in pixels. This is equivalent to the
9645     * {@link #setTranslationY(float) translationY} property plus the current
9646     * {@link #getTop() top} property.
9647     *
9648     * @return The visual y position of this view, in pixels.
9649     */
9650    @ViewDebug.ExportedProperty(category = "drawing")
9651    public float getY() {
9652        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9653    }
9654
9655    /**
9656     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9657     * {@link #setTranslationY(float) translationY} property to be the difference between
9658     * the y value passed in and the current {@link #getTop() top} property.
9659     *
9660     * @param y The visual y position of this view, in pixels.
9661     */
9662    public void setY(float y) {
9663        setTranslationY(y - mTop);
9664    }
9665
9666
9667    /**
9668     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9669     * This position is post-layout, in addition to wherever the object's
9670     * layout placed it.
9671     *
9672     * @return The horizontal position of this view relative to its left position, in pixels.
9673     */
9674    @ViewDebug.ExportedProperty(category = "drawing")
9675    public float getTranslationX() {
9676        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9677    }
9678
9679    /**
9680     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9681     * This effectively positions the object post-layout, in addition to wherever the object's
9682     * layout placed it.
9683     *
9684     * @param translationX The horizontal position of this view relative to its left position,
9685     * in pixels.
9686     *
9687     * @attr ref android.R.styleable#View_translationX
9688     */
9689    public void setTranslationX(float translationX) {
9690        ensureTransformationInfo();
9691        final TransformationInfo info = mTransformationInfo;
9692        if (info.mTranslationX != translationX) {
9693            // Double-invalidation is necessary to capture view's old and new areas
9694            invalidateViewProperty(true, false);
9695            info.mTranslationX = translationX;
9696            info.mMatrixDirty = true;
9697            invalidateViewProperty(false, true);
9698            if (mDisplayList != null) {
9699                mDisplayList.setTranslationX(translationX);
9700            }
9701            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9702                // View was rejected last time it was drawn by its parent; this may have changed
9703                invalidateParentIfNeeded();
9704            }
9705        }
9706    }
9707
9708    /**
9709     * The horizontal location of this view relative to its {@link #getTop() top} position.
9710     * This position is post-layout, in addition to wherever the object's
9711     * layout placed it.
9712     *
9713     * @return The vertical position of this view relative to its top position,
9714     * in pixels.
9715     */
9716    @ViewDebug.ExportedProperty(category = "drawing")
9717    public float getTranslationY() {
9718        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9719    }
9720
9721    /**
9722     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9723     * This effectively positions the object post-layout, in addition to wherever the object's
9724     * layout placed it.
9725     *
9726     * @param translationY The vertical position of this view relative to its top position,
9727     * in pixels.
9728     *
9729     * @attr ref android.R.styleable#View_translationY
9730     */
9731    public void setTranslationY(float translationY) {
9732        ensureTransformationInfo();
9733        final TransformationInfo info = mTransformationInfo;
9734        if (info.mTranslationY != translationY) {
9735            invalidateViewProperty(true, false);
9736            info.mTranslationY = translationY;
9737            info.mMatrixDirty = true;
9738            invalidateViewProperty(false, true);
9739            if (mDisplayList != null) {
9740                mDisplayList.setTranslationY(translationY);
9741            }
9742            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9743                // View was rejected last time it was drawn by its parent; this may have changed
9744                invalidateParentIfNeeded();
9745            }
9746        }
9747    }
9748
9749    /**
9750     * Hit rectangle in parent's coordinates
9751     *
9752     * @param outRect The hit rectangle of the view.
9753     */
9754    public void getHitRect(Rect outRect) {
9755        updateMatrix();
9756        final TransformationInfo info = mTransformationInfo;
9757        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9758            outRect.set(mLeft, mTop, mRight, mBottom);
9759        } else {
9760            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9761            tmpRect.set(-info.mPivotX, -info.mPivotY,
9762                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9763            info.mMatrix.mapRect(tmpRect);
9764            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9765                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9766        }
9767    }
9768
9769    /**
9770     * Determines whether the given point, in local coordinates is inside the view.
9771     */
9772    /*package*/ final boolean pointInView(float localX, float localY) {
9773        return localX >= 0 && localX < (mRight - mLeft)
9774                && localY >= 0 && localY < (mBottom - mTop);
9775    }
9776
9777    /**
9778     * Utility method to determine whether the given point, in local coordinates,
9779     * is inside the view, where the area of the view is expanded by the slop factor.
9780     * This method is called while processing touch-move events to determine if the event
9781     * is still within the view.
9782     */
9783    private boolean pointInView(float localX, float localY, float slop) {
9784        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9785                localY < ((mBottom - mTop) + slop);
9786    }
9787
9788    /**
9789     * When a view has focus and the user navigates away from it, the next view is searched for
9790     * starting from the rectangle filled in by this method.
9791     *
9792     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
9793     * of the view.  However, if your view maintains some idea of internal selection,
9794     * such as a cursor, or a selected row or column, you should override this method and
9795     * fill in a more specific rectangle.
9796     *
9797     * @param r The rectangle to fill in, in this view's coordinates.
9798     */
9799    public void getFocusedRect(Rect r) {
9800        getDrawingRect(r);
9801    }
9802
9803    /**
9804     * If some part of this view is not clipped by any of its parents, then
9805     * return that area in r in global (root) coordinates. To convert r to local
9806     * coordinates (without taking possible View rotations into account), offset
9807     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9808     * If the view is completely clipped or translated out, return false.
9809     *
9810     * @param r If true is returned, r holds the global coordinates of the
9811     *        visible portion of this view.
9812     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9813     *        between this view and its root. globalOffet may be null.
9814     * @return true if r is non-empty (i.e. part of the view is visible at the
9815     *         root level.
9816     */
9817    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9818        int width = mRight - mLeft;
9819        int height = mBottom - mTop;
9820        if (width > 0 && height > 0) {
9821            r.set(0, 0, width, height);
9822            if (globalOffset != null) {
9823                globalOffset.set(-mScrollX, -mScrollY);
9824            }
9825            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9826        }
9827        return false;
9828    }
9829
9830    public final boolean getGlobalVisibleRect(Rect r) {
9831        return getGlobalVisibleRect(r, null);
9832    }
9833
9834    public final boolean getLocalVisibleRect(Rect r) {
9835        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9836        if (getGlobalVisibleRect(r, offset)) {
9837            r.offset(-offset.x, -offset.y); // make r local
9838            return true;
9839        }
9840        return false;
9841    }
9842
9843    /**
9844     * Offset this view's vertical location by the specified number of pixels.
9845     *
9846     * @param offset the number of pixels to offset the view by
9847     */
9848    public void offsetTopAndBottom(int offset) {
9849        if (offset != 0) {
9850            updateMatrix();
9851            final boolean matrixIsIdentity = mTransformationInfo == null
9852                    || mTransformationInfo.mMatrixIsIdentity;
9853            if (matrixIsIdentity) {
9854                if (mDisplayList != null) {
9855                    invalidateViewProperty(false, false);
9856                } else {
9857                    final ViewParent p = mParent;
9858                    if (p != null && mAttachInfo != null) {
9859                        final Rect r = mAttachInfo.mTmpInvalRect;
9860                        int minTop;
9861                        int maxBottom;
9862                        int yLoc;
9863                        if (offset < 0) {
9864                            minTop = mTop + offset;
9865                            maxBottom = mBottom;
9866                            yLoc = offset;
9867                        } else {
9868                            minTop = mTop;
9869                            maxBottom = mBottom + offset;
9870                            yLoc = 0;
9871                        }
9872                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9873                        p.invalidateChild(this, r);
9874                    }
9875                }
9876            } else {
9877                invalidateViewProperty(false, false);
9878            }
9879
9880            mTop += offset;
9881            mBottom += offset;
9882            if (mDisplayList != null) {
9883                mDisplayList.offsetTopBottom(offset);
9884                invalidateViewProperty(false, false);
9885            } else {
9886                if (!matrixIsIdentity) {
9887                    invalidateViewProperty(false, true);
9888                }
9889                invalidateParentIfNeeded();
9890            }
9891        }
9892    }
9893
9894    /**
9895     * Offset this view's horizontal location by the specified amount of pixels.
9896     *
9897     * @param offset the numer of pixels to offset the view by
9898     */
9899    public void offsetLeftAndRight(int offset) {
9900        if (offset != 0) {
9901            updateMatrix();
9902            final boolean matrixIsIdentity = mTransformationInfo == null
9903                    || mTransformationInfo.mMatrixIsIdentity;
9904            if (matrixIsIdentity) {
9905                if (mDisplayList != null) {
9906                    invalidateViewProperty(false, false);
9907                } else {
9908                    final ViewParent p = mParent;
9909                    if (p != null && mAttachInfo != null) {
9910                        final Rect r = mAttachInfo.mTmpInvalRect;
9911                        int minLeft;
9912                        int maxRight;
9913                        if (offset < 0) {
9914                            minLeft = mLeft + offset;
9915                            maxRight = mRight;
9916                        } else {
9917                            minLeft = mLeft;
9918                            maxRight = mRight + offset;
9919                        }
9920                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9921                        p.invalidateChild(this, r);
9922                    }
9923                }
9924            } else {
9925                invalidateViewProperty(false, false);
9926            }
9927
9928            mLeft += offset;
9929            mRight += offset;
9930            if (mDisplayList != null) {
9931                mDisplayList.offsetLeftRight(offset);
9932                invalidateViewProperty(false, false);
9933            } else {
9934                if (!matrixIsIdentity) {
9935                    invalidateViewProperty(false, true);
9936                }
9937                invalidateParentIfNeeded();
9938            }
9939        }
9940    }
9941
9942    /**
9943     * Get the LayoutParams associated with this view. All views should have
9944     * layout parameters. These supply parameters to the <i>parent</i> of this
9945     * view specifying how it should be arranged. There are many subclasses of
9946     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9947     * of ViewGroup that are responsible for arranging their children.
9948     *
9949     * This method may return null if this View is not attached to a parent
9950     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9951     * was not invoked successfully. When a View is attached to a parent
9952     * ViewGroup, this method must not return null.
9953     *
9954     * @return The LayoutParams associated with this view, or null if no
9955     *         parameters have been set yet
9956     */
9957    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9958    public ViewGroup.LayoutParams getLayoutParams() {
9959        return mLayoutParams;
9960    }
9961
9962    /**
9963     * Set the layout parameters associated with this view. These supply
9964     * parameters to the <i>parent</i> of this view specifying how it should be
9965     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9966     * correspond to the different subclasses of ViewGroup that are responsible
9967     * for arranging their children.
9968     *
9969     * @param params The layout parameters for this view, cannot be null
9970     */
9971    public void setLayoutParams(ViewGroup.LayoutParams params) {
9972        if (params == null) {
9973            throw new NullPointerException("Layout parameters cannot be null");
9974        }
9975        mLayoutParams = params;
9976        resolveLayoutParams();
9977        if (mParent instanceof ViewGroup) {
9978            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9979        }
9980        requestLayout();
9981    }
9982
9983    /**
9984     * Resolve the layout parameters depending on the resolved layout direction
9985     */
9986    private void resolveLayoutParams() {
9987        if (mLayoutParams != null) {
9988            mLayoutParams.onResolveLayoutDirection(getLayoutDirection());
9989        }
9990    }
9991
9992    /**
9993     * Set the scrolled position of your view. This will cause a call to
9994     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9995     * invalidated.
9996     * @param x the x position to scroll to
9997     * @param y the y position to scroll to
9998     */
9999    public void scrollTo(int x, int y) {
10000        if (mScrollX != x || mScrollY != y) {
10001            int oldX = mScrollX;
10002            int oldY = mScrollY;
10003            mScrollX = x;
10004            mScrollY = y;
10005            invalidateParentCaches();
10006            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10007            if (!awakenScrollBars()) {
10008                postInvalidateOnAnimation();
10009            }
10010        }
10011    }
10012
10013    /**
10014     * Move the scrolled position of your view. This will cause a call to
10015     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10016     * invalidated.
10017     * @param x the amount of pixels to scroll by horizontally
10018     * @param y the amount of pixels to scroll by vertically
10019     */
10020    public void scrollBy(int x, int y) {
10021        scrollTo(mScrollX + x, mScrollY + y);
10022    }
10023
10024    /**
10025     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10026     * animation to fade the scrollbars out after a default delay. If a subclass
10027     * provides animated scrolling, the start delay should equal the duration
10028     * of the scrolling animation.</p>
10029     *
10030     * <p>The animation starts only if at least one of the scrollbars is
10031     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10032     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10033     * this method returns true, and false otherwise. If the animation is
10034     * started, this method calls {@link #invalidate()}; in that case the
10035     * caller should not call {@link #invalidate()}.</p>
10036     *
10037     * <p>This method should be invoked every time a subclass directly updates
10038     * the scroll parameters.</p>
10039     *
10040     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10041     * and {@link #scrollTo(int, int)}.</p>
10042     *
10043     * @return true if the animation is played, false otherwise
10044     *
10045     * @see #awakenScrollBars(int)
10046     * @see #scrollBy(int, int)
10047     * @see #scrollTo(int, int)
10048     * @see #isHorizontalScrollBarEnabled()
10049     * @see #isVerticalScrollBarEnabled()
10050     * @see #setHorizontalScrollBarEnabled(boolean)
10051     * @see #setVerticalScrollBarEnabled(boolean)
10052     */
10053    protected boolean awakenScrollBars() {
10054        return mScrollCache != null &&
10055                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10056    }
10057
10058    /**
10059     * Trigger the scrollbars to draw.
10060     * This method differs from awakenScrollBars() only in its default duration.
10061     * initialAwakenScrollBars() will show the scroll bars for longer than
10062     * usual to give the user more of a chance to notice them.
10063     *
10064     * @return true if the animation is played, false otherwise.
10065     */
10066    private boolean initialAwakenScrollBars() {
10067        return mScrollCache != null &&
10068                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10069    }
10070
10071    /**
10072     * <p>
10073     * Trigger the scrollbars to draw. When invoked this method starts an
10074     * animation to fade the scrollbars out after a fixed delay. If a subclass
10075     * provides animated scrolling, the start delay should equal the duration of
10076     * the scrolling animation.
10077     * </p>
10078     *
10079     * <p>
10080     * The animation starts only if at least one of the scrollbars is enabled,
10081     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10082     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10083     * this method returns true, and false otherwise. If the animation is
10084     * started, this method calls {@link #invalidate()}; in that case the caller
10085     * should not call {@link #invalidate()}.
10086     * </p>
10087     *
10088     * <p>
10089     * This method should be invoked everytime a subclass directly updates the
10090     * scroll parameters.
10091     * </p>
10092     *
10093     * @param startDelay the delay, in milliseconds, after which the animation
10094     *        should start; when the delay is 0, the animation starts
10095     *        immediately
10096     * @return true if the animation is played, false otherwise
10097     *
10098     * @see #scrollBy(int, int)
10099     * @see #scrollTo(int, int)
10100     * @see #isHorizontalScrollBarEnabled()
10101     * @see #isVerticalScrollBarEnabled()
10102     * @see #setHorizontalScrollBarEnabled(boolean)
10103     * @see #setVerticalScrollBarEnabled(boolean)
10104     */
10105    protected boolean awakenScrollBars(int startDelay) {
10106        return awakenScrollBars(startDelay, true);
10107    }
10108
10109    /**
10110     * <p>
10111     * Trigger the scrollbars to draw. When invoked this method starts an
10112     * animation to fade the scrollbars out after a fixed delay. If a subclass
10113     * provides animated scrolling, the start delay should equal the duration of
10114     * the scrolling animation.
10115     * </p>
10116     *
10117     * <p>
10118     * The animation starts only if at least one of the scrollbars is enabled,
10119     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10120     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10121     * this method returns true, and false otherwise. If the animation is
10122     * started, this method calls {@link #invalidate()} if the invalidate parameter
10123     * is set to true; in that case the caller
10124     * should not call {@link #invalidate()}.
10125     * </p>
10126     *
10127     * <p>
10128     * This method should be invoked everytime a subclass directly updates the
10129     * scroll parameters.
10130     * </p>
10131     *
10132     * @param startDelay the delay, in milliseconds, after which the animation
10133     *        should start; when the delay is 0, the animation starts
10134     *        immediately
10135     *
10136     * @param invalidate Wheter this method should call invalidate
10137     *
10138     * @return true if the animation is played, false otherwise
10139     *
10140     * @see #scrollBy(int, int)
10141     * @see #scrollTo(int, int)
10142     * @see #isHorizontalScrollBarEnabled()
10143     * @see #isVerticalScrollBarEnabled()
10144     * @see #setHorizontalScrollBarEnabled(boolean)
10145     * @see #setVerticalScrollBarEnabled(boolean)
10146     */
10147    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10148        final ScrollabilityCache scrollCache = mScrollCache;
10149
10150        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10151            return false;
10152        }
10153
10154        if (scrollCache.scrollBar == null) {
10155            scrollCache.scrollBar = new ScrollBarDrawable();
10156        }
10157
10158        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10159
10160            if (invalidate) {
10161                // Invalidate to show the scrollbars
10162                postInvalidateOnAnimation();
10163            }
10164
10165            if (scrollCache.state == ScrollabilityCache.OFF) {
10166                // FIXME: this is copied from WindowManagerService.
10167                // We should get this value from the system when it
10168                // is possible to do so.
10169                final int KEY_REPEAT_FIRST_DELAY = 750;
10170                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10171            }
10172
10173            // Tell mScrollCache when we should start fading. This may
10174            // extend the fade start time if one was already scheduled
10175            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10176            scrollCache.fadeStartTime = fadeStartTime;
10177            scrollCache.state = ScrollabilityCache.ON;
10178
10179            // Schedule our fader to run, unscheduling any old ones first
10180            if (mAttachInfo != null) {
10181                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10182                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10183            }
10184
10185            return true;
10186        }
10187
10188        return false;
10189    }
10190
10191    /**
10192     * Do not invalidate views which are not visible and which are not running an animation. They
10193     * will not get drawn and they should not set dirty flags as if they will be drawn
10194     */
10195    private boolean skipInvalidate() {
10196        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10197                (!(mParent instanceof ViewGroup) ||
10198                        !((ViewGroup) mParent).isViewTransitioning(this));
10199    }
10200    /**
10201     * Mark the area defined by dirty as needing to be drawn. If the view is
10202     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10203     * in the future. This must be called from a UI thread. To call from a non-UI
10204     * thread, call {@link #postInvalidate()}.
10205     *
10206     * WARNING: This method is destructive to dirty.
10207     * @param dirty the rectangle representing the bounds of the dirty region
10208     */
10209    public void invalidate(Rect dirty) {
10210        if (skipInvalidate()) {
10211            return;
10212        }
10213        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10214                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10215                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10216            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10217            mPrivateFlags |= PFLAG_INVALIDATED;
10218            mPrivateFlags |= PFLAG_DIRTY;
10219            final ViewParent p = mParent;
10220            final AttachInfo ai = mAttachInfo;
10221            //noinspection PointlessBooleanExpression,ConstantConditions
10222            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10223                if (p != null && ai != null && ai.mHardwareAccelerated) {
10224                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10225                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10226                    p.invalidateChild(this, null);
10227                    return;
10228                }
10229            }
10230            if (p != null && ai != null) {
10231                final int scrollX = mScrollX;
10232                final int scrollY = mScrollY;
10233                final Rect r = ai.mTmpInvalRect;
10234                r.set(dirty.left - scrollX, dirty.top - scrollY,
10235                        dirty.right - scrollX, dirty.bottom - scrollY);
10236                mParent.invalidateChild(this, r);
10237            }
10238        }
10239    }
10240
10241    /**
10242     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10243     * The coordinates of the dirty rect are relative to the view.
10244     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10245     * will be called at some point in the future. This must be called from
10246     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10247     * @param l the left position of the dirty region
10248     * @param t the top position of the dirty region
10249     * @param r the right position of the dirty region
10250     * @param b the bottom position of the dirty region
10251     */
10252    public void invalidate(int l, int t, int r, int b) {
10253        if (skipInvalidate()) {
10254            return;
10255        }
10256        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10257                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10258                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10259            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10260            mPrivateFlags |= PFLAG_INVALIDATED;
10261            mPrivateFlags |= PFLAG_DIRTY;
10262            final ViewParent p = mParent;
10263            final AttachInfo ai = mAttachInfo;
10264            //noinspection PointlessBooleanExpression,ConstantConditions
10265            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10266                if (p != null && ai != null && ai.mHardwareAccelerated) {
10267                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10268                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10269                    p.invalidateChild(this, null);
10270                    return;
10271                }
10272            }
10273            if (p != null && ai != null && l < r && t < b) {
10274                final int scrollX = mScrollX;
10275                final int scrollY = mScrollY;
10276                final Rect tmpr = ai.mTmpInvalRect;
10277                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10278                p.invalidateChild(this, tmpr);
10279            }
10280        }
10281    }
10282
10283    /**
10284     * Invalidate the whole view. If the view is visible,
10285     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10286     * the future. This must be called from a UI thread. To call from a non-UI thread,
10287     * call {@link #postInvalidate()}.
10288     */
10289    public void invalidate() {
10290        invalidate(true);
10291    }
10292
10293    /**
10294     * This is where the invalidate() work actually happens. A full invalidate()
10295     * causes the drawing cache to be invalidated, but this function can be called with
10296     * invalidateCache set to false to skip that invalidation step for cases that do not
10297     * need it (for example, a component that remains at the same dimensions with the same
10298     * content).
10299     *
10300     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10301     * well. This is usually true for a full invalidate, but may be set to false if the
10302     * View's contents or dimensions have not changed.
10303     */
10304    void invalidate(boolean invalidateCache) {
10305        if (skipInvalidate()) {
10306            return;
10307        }
10308        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10309                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10310                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10311            mLastIsOpaque = isOpaque();
10312            mPrivateFlags &= ~PFLAG_DRAWN;
10313            mPrivateFlags |= PFLAG_DIRTY;
10314            if (invalidateCache) {
10315                mPrivateFlags |= PFLAG_INVALIDATED;
10316                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10317            }
10318            final AttachInfo ai = mAttachInfo;
10319            final ViewParent p = mParent;
10320            //noinspection PointlessBooleanExpression,ConstantConditions
10321            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10322                if (p != null && ai != null && ai.mHardwareAccelerated) {
10323                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10324                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10325                    p.invalidateChild(this, null);
10326                    return;
10327                }
10328            }
10329
10330            if (p != null && ai != null) {
10331                final Rect r = ai.mTmpInvalRect;
10332                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10333                // Don't call invalidate -- we don't want to internally scroll
10334                // our own bounds
10335                p.invalidateChild(this, r);
10336            }
10337        }
10338    }
10339
10340    /**
10341     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10342     * set any flags or handle all of the cases handled by the default invalidation methods.
10343     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10344     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10345     * walk up the hierarchy, transforming the dirty rect as necessary.
10346     *
10347     * The method also handles normal invalidation logic if display list properties are not
10348     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10349     * backup approach, to handle these cases used in the various property-setting methods.
10350     *
10351     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10352     * are not being used in this view
10353     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10354     * list properties are not being used in this view
10355     */
10356    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10357        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10358            if (invalidateParent) {
10359                invalidateParentCaches();
10360            }
10361            if (forceRedraw) {
10362                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10363            }
10364            invalidate(false);
10365        } else {
10366            final AttachInfo ai = mAttachInfo;
10367            final ViewParent p = mParent;
10368            if (p != null && ai != null) {
10369                final Rect r = ai.mTmpInvalRect;
10370                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10371                if (mParent instanceof ViewGroup) {
10372                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10373                } else {
10374                    mParent.invalidateChild(this, r);
10375                }
10376            }
10377        }
10378    }
10379
10380    /**
10381     * Utility method to transform a given Rect by the current matrix of this view.
10382     */
10383    void transformRect(final Rect rect) {
10384        if (!getMatrix().isIdentity()) {
10385            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10386            boundingRect.set(rect);
10387            getMatrix().mapRect(boundingRect);
10388            rect.set((int) (boundingRect.left - 0.5f),
10389                    (int) (boundingRect.top - 0.5f),
10390                    (int) (boundingRect.right + 0.5f),
10391                    (int) (boundingRect.bottom + 0.5f));
10392        }
10393    }
10394
10395    /**
10396     * Used to indicate that the parent of this view should clear its caches. This functionality
10397     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10398     * which is necessary when various parent-managed properties of the view change, such as
10399     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10400     * clears the parent caches and does not causes an invalidate event.
10401     *
10402     * @hide
10403     */
10404    protected void invalidateParentCaches() {
10405        if (mParent instanceof View) {
10406            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10407        }
10408    }
10409
10410    /**
10411     * Used to indicate that the parent of this view should be invalidated. This functionality
10412     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10413     * which is necessary when various parent-managed properties of the view change, such as
10414     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10415     * an invalidation event to the parent.
10416     *
10417     * @hide
10418     */
10419    protected void invalidateParentIfNeeded() {
10420        if (isHardwareAccelerated() && mParent instanceof View) {
10421            ((View) mParent).invalidate(true);
10422        }
10423    }
10424
10425    /**
10426     * Indicates whether this View is opaque. An opaque View guarantees that it will
10427     * draw all the pixels overlapping its bounds using a fully opaque color.
10428     *
10429     * Subclasses of View should override this method whenever possible to indicate
10430     * whether an instance is opaque. Opaque Views are treated in a special way by
10431     * the View hierarchy, possibly allowing it to perform optimizations during
10432     * invalidate/draw passes.
10433     *
10434     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10435     */
10436    @ViewDebug.ExportedProperty(category = "drawing")
10437    public boolean isOpaque() {
10438        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10439                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10440    }
10441
10442    /**
10443     * @hide
10444     */
10445    protected void computeOpaqueFlags() {
10446        // Opaque if:
10447        //   - Has a background
10448        //   - Background is opaque
10449        //   - Doesn't have scrollbars or scrollbars are inside overlay
10450
10451        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10452            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10453        } else {
10454            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10455        }
10456
10457        final int flags = mViewFlags;
10458        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10459                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10460            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10461        } else {
10462            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10463        }
10464    }
10465
10466    /**
10467     * @hide
10468     */
10469    protected boolean hasOpaqueScrollbars() {
10470        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10471    }
10472
10473    /**
10474     * @return A handler associated with the thread running the View. This
10475     * handler can be used to pump events in the UI events queue.
10476     */
10477    public Handler getHandler() {
10478        if (mAttachInfo != null) {
10479            return mAttachInfo.mHandler;
10480        }
10481        return null;
10482    }
10483
10484    /**
10485     * Gets the view root associated with the View.
10486     * @return The view root, or null if none.
10487     * @hide
10488     */
10489    public ViewRootImpl getViewRootImpl() {
10490        if (mAttachInfo != null) {
10491            return mAttachInfo.mViewRootImpl;
10492        }
10493        return null;
10494    }
10495
10496    /**
10497     * <p>Causes the Runnable to be added to the message queue.
10498     * The runnable will be run on the user interface thread.</p>
10499     *
10500     * <p>This method can be invoked from outside of the UI thread
10501     * only when this View is attached to a window.</p>
10502     *
10503     * @param action The Runnable that will be executed.
10504     *
10505     * @return Returns true if the Runnable was successfully placed in to the
10506     *         message queue.  Returns false on failure, usually because the
10507     *         looper processing the message queue is exiting.
10508     *
10509     * @see #postDelayed
10510     * @see #removeCallbacks
10511     */
10512    public boolean post(Runnable action) {
10513        final AttachInfo attachInfo = mAttachInfo;
10514        if (attachInfo != null) {
10515            return attachInfo.mHandler.post(action);
10516        }
10517        // Assume that post will succeed later
10518        ViewRootImpl.getRunQueue().post(action);
10519        return true;
10520    }
10521
10522    /**
10523     * <p>Causes the Runnable to be added to the message queue, to be run
10524     * after the specified amount of time elapses.
10525     * The runnable will be run on the user interface thread.</p>
10526     *
10527     * <p>This method can be invoked from outside of the UI thread
10528     * only when this View is attached to a window.</p>
10529     *
10530     * @param action The Runnable that will be executed.
10531     * @param delayMillis The delay (in milliseconds) until the Runnable
10532     *        will be executed.
10533     *
10534     * @return true if the Runnable was successfully placed in to the
10535     *         message queue.  Returns false on failure, usually because the
10536     *         looper processing the message queue is exiting.  Note that a
10537     *         result of true does not mean the Runnable will be processed --
10538     *         if the looper is quit before the delivery time of the message
10539     *         occurs then the message will be dropped.
10540     *
10541     * @see #post
10542     * @see #removeCallbacks
10543     */
10544    public boolean postDelayed(Runnable action, long delayMillis) {
10545        final AttachInfo attachInfo = mAttachInfo;
10546        if (attachInfo != null) {
10547            return attachInfo.mHandler.postDelayed(action, delayMillis);
10548        }
10549        // Assume that post will succeed later
10550        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10551        return true;
10552    }
10553
10554    /**
10555     * <p>Causes the Runnable to execute on the next animation time step.
10556     * The runnable will be run on the user interface thread.</p>
10557     *
10558     * <p>This method can be invoked from outside of the UI thread
10559     * only when this View is attached to a window.</p>
10560     *
10561     * @param action The Runnable that will be executed.
10562     *
10563     * @see #postOnAnimationDelayed
10564     * @see #removeCallbacks
10565     */
10566    public void postOnAnimation(Runnable action) {
10567        final AttachInfo attachInfo = mAttachInfo;
10568        if (attachInfo != null) {
10569            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10570                    Choreographer.CALLBACK_ANIMATION, action, null);
10571        } else {
10572            // Assume that post will succeed later
10573            ViewRootImpl.getRunQueue().post(action);
10574        }
10575    }
10576
10577    /**
10578     * <p>Causes the Runnable to execute on the next animation time step,
10579     * after the specified amount of time elapses.
10580     * The runnable will be run on the user interface thread.</p>
10581     *
10582     * <p>This method can be invoked from outside of the UI thread
10583     * only when this View is attached to a window.</p>
10584     *
10585     * @param action The Runnable that will be executed.
10586     * @param delayMillis The delay (in milliseconds) until the Runnable
10587     *        will be executed.
10588     *
10589     * @see #postOnAnimation
10590     * @see #removeCallbacks
10591     */
10592    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10593        final AttachInfo attachInfo = mAttachInfo;
10594        if (attachInfo != null) {
10595            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10596                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10597        } else {
10598            // Assume that post will succeed later
10599            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10600        }
10601    }
10602
10603    /**
10604     * <p>Removes the specified Runnable from the message queue.</p>
10605     *
10606     * <p>This method can be invoked from outside of the UI thread
10607     * only when this View is attached to a window.</p>
10608     *
10609     * @param action The Runnable to remove from the message handling queue
10610     *
10611     * @return true if this view could ask the Handler to remove the Runnable,
10612     *         false otherwise. When the returned value is true, the Runnable
10613     *         may or may not have been actually removed from the message queue
10614     *         (for instance, if the Runnable was not in the queue already.)
10615     *
10616     * @see #post
10617     * @see #postDelayed
10618     * @see #postOnAnimation
10619     * @see #postOnAnimationDelayed
10620     */
10621    public boolean removeCallbacks(Runnable action) {
10622        if (action != null) {
10623            final AttachInfo attachInfo = mAttachInfo;
10624            if (attachInfo != null) {
10625                attachInfo.mHandler.removeCallbacks(action);
10626                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10627                        Choreographer.CALLBACK_ANIMATION, action, null);
10628            } else {
10629                // Assume that post will succeed later
10630                ViewRootImpl.getRunQueue().removeCallbacks(action);
10631            }
10632        }
10633        return true;
10634    }
10635
10636    /**
10637     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10638     * Use this to invalidate the View from a non-UI thread.</p>
10639     *
10640     * <p>This method can be invoked from outside of the UI thread
10641     * only when this View is attached to a window.</p>
10642     *
10643     * @see #invalidate()
10644     * @see #postInvalidateDelayed(long)
10645     */
10646    public void postInvalidate() {
10647        postInvalidateDelayed(0);
10648    }
10649
10650    /**
10651     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10652     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10653     *
10654     * <p>This method can be invoked from outside of the UI thread
10655     * only when this View is attached to a window.</p>
10656     *
10657     * @param left The left coordinate of the rectangle to invalidate.
10658     * @param top The top coordinate of the rectangle to invalidate.
10659     * @param right The right coordinate of the rectangle to invalidate.
10660     * @param bottom The bottom coordinate of the rectangle to invalidate.
10661     *
10662     * @see #invalidate(int, int, int, int)
10663     * @see #invalidate(Rect)
10664     * @see #postInvalidateDelayed(long, int, int, int, int)
10665     */
10666    public void postInvalidate(int left, int top, int right, int bottom) {
10667        postInvalidateDelayed(0, left, top, right, bottom);
10668    }
10669
10670    /**
10671     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10672     * loop. Waits for the specified amount of time.</p>
10673     *
10674     * <p>This method can be invoked from outside of the UI thread
10675     * only when this View is attached to a window.</p>
10676     *
10677     * @param delayMilliseconds the duration in milliseconds to delay the
10678     *         invalidation by
10679     *
10680     * @see #invalidate()
10681     * @see #postInvalidate()
10682     */
10683    public void postInvalidateDelayed(long delayMilliseconds) {
10684        // We try only with the AttachInfo because there's no point in invalidating
10685        // if we are not attached to our window
10686        final AttachInfo attachInfo = mAttachInfo;
10687        if (attachInfo != null) {
10688            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10689        }
10690    }
10691
10692    /**
10693     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10694     * through the event loop. Waits for the specified amount of time.</p>
10695     *
10696     * <p>This method can be invoked from outside of the UI thread
10697     * only when this View is attached to a window.</p>
10698     *
10699     * @param delayMilliseconds the duration in milliseconds to delay the
10700     *         invalidation by
10701     * @param left The left coordinate of the rectangle to invalidate.
10702     * @param top The top coordinate of the rectangle to invalidate.
10703     * @param right The right coordinate of the rectangle to invalidate.
10704     * @param bottom The bottom coordinate of the rectangle to invalidate.
10705     *
10706     * @see #invalidate(int, int, int, int)
10707     * @see #invalidate(Rect)
10708     * @see #postInvalidate(int, int, int, int)
10709     */
10710    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10711            int right, int bottom) {
10712
10713        // We try only with the AttachInfo because there's no point in invalidating
10714        // if we are not attached to our window
10715        final AttachInfo attachInfo = mAttachInfo;
10716        if (attachInfo != null) {
10717            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10718            info.target = this;
10719            info.left = left;
10720            info.top = top;
10721            info.right = right;
10722            info.bottom = bottom;
10723
10724            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10725        }
10726    }
10727
10728    /**
10729     * <p>Cause an invalidate to happen on the next animation time step, typically the
10730     * next display frame.</p>
10731     *
10732     * <p>This method can be invoked from outside of the UI thread
10733     * only when this View is attached to a window.</p>
10734     *
10735     * @see #invalidate()
10736     */
10737    public void postInvalidateOnAnimation() {
10738        // We try only with the AttachInfo because there's no point in invalidating
10739        // if we are not attached to our window
10740        final AttachInfo attachInfo = mAttachInfo;
10741        if (attachInfo != null) {
10742            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10743        }
10744    }
10745
10746    /**
10747     * <p>Cause an invalidate of the specified area to happen on the next animation
10748     * time step, typically the next display frame.</p>
10749     *
10750     * <p>This method can be invoked from outside of the UI thread
10751     * only when this View is attached to a window.</p>
10752     *
10753     * @param left The left coordinate of the rectangle to invalidate.
10754     * @param top The top coordinate of the rectangle to invalidate.
10755     * @param right The right coordinate of the rectangle to invalidate.
10756     * @param bottom The bottom coordinate of the rectangle to invalidate.
10757     *
10758     * @see #invalidate(int, int, int, int)
10759     * @see #invalidate(Rect)
10760     */
10761    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10762        // We try only with the AttachInfo because there's no point in invalidating
10763        // if we are not attached to our window
10764        final AttachInfo attachInfo = mAttachInfo;
10765        if (attachInfo != null) {
10766            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10767            info.target = this;
10768            info.left = left;
10769            info.top = top;
10770            info.right = right;
10771            info.bottom = bottom;
10772
10773            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10774        }
10775    }
10776
10777    /**
10778     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10779     * This event is sent at most once every
10780     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10781     */
10782    private void postSendViewScrolledAccessibilityEventCallback() {
10783        if (mSendViewScrolledAccessibilityEvent == null) {
10784            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10785        }
10786        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10787            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10788            postDelayed(mSendViewScrolledAccessibilityEvent,
10789                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10790        }
10791    }
10792
10793    /**
10794     * Called by a parent to request that a child update its values for mScrollX
10795     * and mScrollY if necessary. This will typically be done if the child is
10796     * animating a scroll using a {@link android.widget.Scroller Scroller}
10797     * object.
10798     */
10799    public void computeScroll() {
10800    }
10801
10802    /**
10803     * <p>Indicate whether the horizontal edges are faded when the view is
10804     * scrolled horizontally.</p>
10805     *
10806     * @return true if the horizontal edges should are faded on scroll, false
10807     *         otherwise
10808     *
10809     * @see #setHorizontalFadingEdgeEnabled(boolean)
10810     *
10811     * @attr ref android.R.styleable#View_requiresFadingEdge
10812     */
10813    public boolean isHorizontalFadingEdgeEnabled() {
10814        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10815    }
10816
10817    /**
10818     * <p>Define whether the horizontal edges should be faded when this view
10819     * is scrolled horizontally.</p>
10820     *
10821     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10822     *                                    be faded when the view is scrolled
10823     *                                    horizontally
10824     *
10825     * @see #isHorizontalFadingEdgeEnabled()
10826     *
10827     * @attr ref android.R.styleable#View_requiresFadingEdge
10828     */
10829    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10830        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10831            if (horizontalFadingEdgeEnabled) {
10832                initScrollCache();
10833            }
10834
10835            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10836        }
10837    }
10838
10839    /**
10840     * <p>Indicate whether the vertical edges are faded when the view is
10841     * scrolled horizontally.</p>
10842     *
10843     * @return true if the vertical edges should are faded on scroll, false
10844     *         otherwise
10845     *
10846     * @see #setVerticalFadingEdgeEnabled(boolean)
10847     *
10848     * @attr ref android.R.styleable#View_requiresFadingEdge
10849     */
10850    public boolean isVerticalFadingEdgeEnabled() {
10851        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10852    }
10853
10854    /**
10855     * <p>Define whether the vertical edges should be faded when this view
10856     * is scrolled vertically.</p>
10857     *
10858     * @param verticalFadingEdgeEnabled true if the vertical edges should
10859     *                                  be faded when the view is scrolled
10860     *                                  vertically
10861     *
10862     * @see #isVerticalFadingEdgeEnabled()
10863     *
10864     * @attr ref android.R.styleable#View_requiresFadingEdge
10865     */
10866    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10867        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10868            if (verticalFadingEdgeEnabled) {
10869                initScrollCache();
10870            }
10871
10872            mViewFlags ^= FADING_EDGE_VERTICAL;
10873        }
10874    }
10875
10876    /**
10877     * Returns the strength, or intensity, of the top faded edge. The strength is
10878     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10879     * returns 0.0 or 1.0 but no value in between.
10880     *
10881     * Subclasses should override this method to provide a smoother fade transition
10882     * when scrolling occurs.
10883     *
10884     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10885     */
10886    protected float getTopFadingEdgeStrength() {
10887        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10888    }
10889
10890    /**
10891     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10892     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10893     * returns 0.0 or 1.0 but no value in between.
10894     *
10895     * Subclasses should override this method to provide a smoother fade transition
10896     * when scrolling occurs.
10897     *
10898     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10899     */
10900    protected float getBottomFadingEdgeStrength() {
10901        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10902                computeVerticalScrollRange() ? 1.0f : 0.0f;
10903    }
10904
10905    /**
10906     * Returns the strength, or intensity, of the left faded edge. The strength is
10907     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10908     * returns 0.0 or 1.0 but no value in between.
10909     *
10910     * Subclasses should override this method to provide a smoother fade transition
10911     * when scrolling occurs.
10912     *
10913     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10914     */
10915    protected float getLeftFadingEdgeStrength() {
10916        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10917    }
10918
10919    /**
10920     * Returns the strength, or intensity, of the right faded edge. The strength is
10921     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10922     * returns 0.0 or 1.0 but no value in between.
10923     *
10924     * Subclasses should override this method to provide a smoother fade transition
10925     * when scrolling occurs.
10926     *
10927     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10928     */
10929    protected float getRightFadingEdgeStrength() {
10930        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10931                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10932    }
10933
10934    /**
10935     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10936     * scrollbar is not drawn by default.</p>
10937     *
10938     * @return true if the horizontal scrollbar should be painted, false
10939     *         otherwise
10940     *
10941     * @see #setHorizontalScrollBarEnabled(boolean)
10942     */
10943    public boolean isHorizontalScrollBarEnabled() {
10944        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10945    }
10946
10947    /**
10948     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10949     * scrollbar is not drawn by default.</p>
10950     *
10951     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10952     *                                   be painted
10953     *
10954     * @see #isHorizontalScrollBarEnabled()
10955     */
10956    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10957        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10958            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10959            computeOpaqueFlags();
10960            resolvePadding();
10961        }
10962    }
10963
10964    /**
10965     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10966     * scrollbar is not drawn by default.</p>
10967     *
10968     * @return true if the vertical scrollbar should be painted, false
10969     *         otherwise
10970     *
10971     * @see #setVerticalScrollBarEnabled(boolean)
10972     */
10973    public boolean isVerticalScrollBarEnabled() {
10974        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10975    }
10976
10977    /**
10978     * <p>Define whether the vertical scrollbar should be drawn or not. The
10979     * scrollbar is not drawn by default.</p>
10980     *
10981     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10982     *                                 be painted
10983     *
10984     * @see #isVerticalScrollBarEnabled()
10985     */
10986    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10987        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10988            mViewFlags ^= SCROLLBARS_VERTICAL;
10989            computeOpaqueFlags();
10990            resolvePadding();
10991        }
10992    }
10993
10994    /**
10995     * @hide
10996     */
10997    protected void recomputePadding() {
10998        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10999    }
11000
11001    /**
11002     * Define whether scrollbars will fade when the view is not scrolling.
11003     *
11004     * @param fadeScrollbars wheter to enable fading
11005     *
11006     * @attr ref android.R.styleable#View_fadeScrollbars
11007     */
11008    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11009        initScrollCache();
11010        final ScrollabilityCache scrollabilityCache = mScrollCache;
11011        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11012        if (fadeScrollbars) {
11013            scrollabilityCache.state = ScrollabilityCache.OFF;
11014        } else {
11015            scrollabilityCache.state = ScrollabilityCache.ON;
11016        }
11017    }
11018
11019    /**
11020     *
11021     * Returns true if scrollbars will fade when this view is not scrolling
11022     *
11023     * @return true if scrollbar fading is enabled
11024     *
11025     * @attr ref android.R.styleable#View_fadeScrollbars
11026     */
11027    public boolean isScrollbarFadingEnabled() {
11028        return mScrollCache != null && mScrollCache.fadeScrollBars;
11029    }
11030
11031    /**
11032     *
11033     * Returns the delay before scrollbars fade.
11034     *
11035     * @return the delay before scrollbars fade
11036     *
11037     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11038     */
11039    public int getScrollBarDefaultDelayBeforeFade() {
11040        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11041                mScrollCache.scrollBarDefaultDelayBeforeFade;
11042    }
11043
11044    /**
11045     * Define the delay before scrollbars fade.
11046     *
11047     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11048     *
11049     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11050     */
11051    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11052        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11053    }
11054
11055    /**
11056     *
11057     * Returns the scrollbar fade duration.
11058     *
11059     * @return the scrollbar fade duration
11060     *
11061     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11062     */
11063    public int getScrollBarFadeDuration() {
11064        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11065                mScrollCache.scrollBarFadeDuration;
11066    }
11067
11068    /**
11069     * Define the scrollbar fade duration.
11070     *
11071     * @param scrollBarFadeDuration - the scrollbar fade duration
11072     *
11073     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11074     */
11075    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11076        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11077    }
11078
11079    /**
11080     *
11081     * Returns the scrollbar size.
11082     *
11083     * @return the scrollbar size
11084     *
11085     * @attr ref android.R.styleable#View_scrollbarSize
11086     */
11087    public int getScrollBarSize() {
11088        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11089                mScrollCache.scrollBarSize;
11090    }
11091
11092    /**
11093     * Define the scrollbar size.
11094     *
11095     * @param scrollBarSize - the scrollbar size
11096     *
11097     * @attr ref android.R.styleable#View_scrollbarSize
11098     */
11099    public void setScrollBarSize(int scrollBarSize) {
11100        getScrollCache().scrollBarSize = scrollBarSize;
11101    }
11102
11103    /**
11104     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11105     * inset. When inset, they add to the padding of the view. And the scrollbars
11106     * can be drawn inside the padding area or on the edge of the view. For example,
11107     * if a view has a background drawable and you want to draw the scrollbars
11108     * inside the padding specified by the drawable, you can use
11109     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11110     * appear at the edge of the view, ignoring the padding, then you can use
11111     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11112     * @param style the style of the scrollbars. Should be one of
11113     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11114     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11115     * @see #SCROLLBARS_INSIDE_OVERLAY
11116     * @see #SCROLLBARS_INSIDE_INSET
11117     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11118     * @see #SCROLLBARS_OUTSIDE_INSET
11119     *
11120     * @attr ref android.R.styleable#View_scrollbarStyle
11121     */
11122    public void setScrollBarStyle(int style) {
11123        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11124            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11125            computeOpaqueFlags();
11126            resolvePadding();
11127        }
11128    }
11129
11130    /**
11131     * <p>Returns the current scrollbar style.</p>
11132     * @return the current scrollbar style
11133     * @see #SCROLLBARS_INSIDE_OVERLAY
11134     * @see #SCROLLBARS_INSIDE_INSET
11135     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11136     * @see #SCROLLBARS_OUTSIDE_INSET
11137     *
11138     * @attr ref android.R.styleable#View_scrollbarStyle
11139     */
11140    @ViewDebug.ExportedProperty(mapping = {
11141            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11142            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11143            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11144            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11145    })
11146    public int getScrollBarStyle() {
11147        return mViewFlags & SCROLLBARS_STYLE_MASK;
11148    }
11149
11150    /**
11151     * <p>Compute the horizontal range that the horizontal scrollbar
11152     * represents.</p>
11153     *
11154     * <p>The range is expressed in arbitrary units that must be the same as the
11155     * units used by {@link #computeHorizontalScrollExtent()} and
11156     * {@link #computeHorizontalScrollOffset()}.</p>
11157     *
11158     * <p>The default range is the drawing width of this view.</p>
11159     *
11160     * @return the total horizontal range represented by the horizontal
11161     *         scrollbar
11162     *
11163     * @see #computeHorizontalScrollExtent()
11164     * @see #computeHorizontalScrollOffset()
11165     * @see android.widget.ScrollBarDrawable
11166     */
11167    protected int computeHorizontalScrollRange() {
11168        return getWidth();
11169    }
11170
11171    /**
11172     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11173     * within the horizontal range. This value is used to compute the position
11174     * of the thumb within the scrollbar's track.</p>
11175     *
11176     * <p>The range is expressed in arbitrary units that must be the same as the
11177     * units used by {@link #computeHorizontalScrollRange()} and
11178     * {@link #computeHorizontalScrollExtent()}.</p>
11179     *
11180     * <p>The default offset is the scroll offset of this view.</p>
11181     *
11182     * @return the horizontal offset of the scrollbar's thumb
11183     *
11184     * @see #computeHorizontalScrollRange()
11185     * @see #computeHorizontalScrollExtent()
11186     * @see android.widget.ScrollBarDrawable
11187     */
11188    protected int computeHorizontalScrollOffset() {
11189        return mScrollX;
11190    }
11191
11192    /**
11193     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11194     * within the horizontal range. This value is used to compute the length
11195     * of the thumb within the scrollbar's track.</p>
11196     *
11197     * <p>The range is expressed in arbitrary units that must be the same as the
11198     * units used by {@link #computeHorizontalScrollRange()} and
11199     * {@link #computeHorizontalScrollOffset()}.</p>
11200     *
11201     * <p>The default extent is the drawing width of this view.</p>
11202     *
11203     * @return the horizontal extent of the scrollbar's thumb
11204     *
11205     * @see #computeHorizontalScrollRange()
11206     * @see #computeHorizontalScrollOffset()
11207     * @see android.widget.ScrollBarDrawable
11208     */
11209    protected int computeHorizontalScrollExtent() {
11210        return getWidth();
11211    }
11212
11213    /**
11214     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11215     *
11216     * <p>The range is expressed in arbitrary units that must be the same as the
11217     * units used by {@link #computeVerticalScrollExtent()} and
11218     * {@link #computeVerticalScrollOffset()}.</p>
11219     *
11220     * @return the total vertical range represented by the vertical scrollbar
11221     *
11222     * <p>The default range is the drawing height of this view.</p>
11223     *
11224     * @see #computeVerticalScrollExtent()
11225     * @see #computeVerticalScrollOffset()
11226     * @see android.widget.ScrollBarDrawable
11227     */
11228    protected int computeVerticalScrollRange() {
11229        return getHeight();
11230    }
11231
11232    /**
11233     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11234     * within the horizontal range. This value is used to compute the position
11235     * of the thumb within the scrollbar's track.</p>
11236     *
11237     * <p>The range is expressed in arbitrary units that must be the same as the
11238     * units used by {@link #computeVerticalScrollRange()} and
11239     * {@link #computeVerticalScrollExtent()}.</p>
11240     *
11241     * <p>The default offset is the scroll offset of this view.</p>
11242     *
11243     * @return the vertical offset of the scrollbar's thumb
11244     *
11245     * @see #computeVerticalScrollRange()
11246     * @see #computeVerticalScrollExtent()
11247     * @see android.widget.ScrollBarDrawable
11248     */
11249    protected int computeVerticalScrollOffset() {
11250        return mScrollY;
11251    }
11252
11253    /**
11254     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11255     * within the vertical range. This value is used to compute the length
11256     * of the thumb within the scrollbar's track.</p>
11257     *
11258     * <p>The range is expressed in arbitrary units that must be the same as the
11259     * units used by {@link #computeVerticalScrollRange()} and
11260     * {@link #computeVerticalScrollOffset()}.</p>
11261     *
11262     * <p>The default extent is the drawing height of this view.</p>
11263     *
11264     * @return the vertical extent of the scrollbar's thumb
11265     *
11266     * @see #computeVerticalScrollRange()
11267     * @see #computeVerticalScrollOffset()
11268     * @see android.widget.ScrollBarDrawable
11269     */
11270    protected int computeVerticalScrollExtent() {
11271        return getHeight();
11272    }
11273
11274    /**
11275     * Check if this view can be scrolled horizontally in a certain direction.
11276     *
11277     * @param direction Negative to check scrolling left, positive to check scrolling right.
11278     * @return true if this view can be scrolled in the specified direction, false otherwise.
11279     */
11280    public boolean canScrollHorizontally(int direction) {
11281        final int offset = computeHorizontalScrollOffset();
11282        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11283        if (range == 0) return false;
11284        if (direction < 0) {
11285            return offset > 0;
11286        } else {
11287            return offset < range - 1;
11288        }
11289    }
11290
11291    /**
11292     * Check if this view can be scrolled vertically in a certain direction.
11293     *
11294     * @param direction Negative to check scrolling up, positive to check scrolling down.
11295     * @return true if this view can be scrolled in the specified direction, false otherwise.
11296     */
11297    public boolean canScrollVertically(int direction) {
11298        final int offset = computeVerticalScrollOffset();
11299        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11300        if (range == 0) return false;
11301        if (direction < 0) {
11302            return offset > 0;
11303        } else {
11304            return offset < range - 1;
11305        }
11306    }
11307
11308    /**
11309     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11310     * scrollbars are painted only if they have been awakened first.</p>
11311     *
11312     * @param canvas the canvas on which to draw the scrollbars
11313     *
11314     * @see #awakenScrollBars(int)
11315     */
11316    protected final void onDrawScrollBars(Canvas canvas) {
11317        // scrollbars are drawn only when the animation is running
11318        final ScrollabilityCache cache = mScrollCache;
11319        if (cache != null) {
11320
11321            int state = cache.state;
11322
11323            if (state == ScrollabilityCache.OFF) {
11324                return;
11325            }
11326
11327            boolean invalidate = false;
11328
11329            if (state == ScrollabilityCache.FADING) {
11330                // We're fading -- get our fade interpolation
11331                if (cache.interpolatorValues == null) {
11332                    cache.interpolatorValues = new float[1];
11333                }
11334
11335                float[] values = cache.interpolatorValues;
11336
11337                // Stops the animation if we're done
11338                if (cache.scrollBarInterpolator.timeToValues(values) ==
11339                        Interpolator.Result.FREEZE_END) {
11340                    cache.state = ScrollabilityCache.OFF;
11341                } else {
11342                    cache.scrollBar.setAlpha(Math.round(values[0]));
11343                }
11344
11345                // This will make the scroll bars inval themselves after
11346                // drawing. We only want this when we're fading so that
11347                // we prevent excessive redraws
11348                invalidate = true;
11349            } else {
11350                // We're just on -- but we may have been fading before so
11351                // reset alpha
11352                cache.scrollBar.setAlpha(255);
11353            }
11354
11355
11356            final int viewFlags = mViewFlags;
11357
11358            final boolean drawHorizontalScrollBar =
11359                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11360            final boolean drawVerticalScrollBar =
11361                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11362                && !isVerticalScrollBarHidden();
11363
11364            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11365                final int width = mRight - mLeft;
11366                final int height = mBottom - mTop;
11367
11368                final ScrollBarDrawable scrollBar = cache.scrollBar;
11369
11370                final int scrollX = mScrollX;
11371                final int scrollY = mScrollY;
11372                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11373
11374                int left, top, right, bottom;
11375
11376                if (drawHorizontalScrollBar) {
11377                    int size = scrollBar.getSize(false);
11378                    if (size <= 0) {
11379                        size = cache.scrollBarSize;
11380                    }
11381
11382                    scrollBar.setParameters(computeHorizontalScrollRange(),
11383                                            computeHorizontalScrollOffset(),
11384                                            computeHorizontalScrollExtent(), false);
11385                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11386                            getVerticalScrollbarWidth() : 0;
11387                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11388                    left = scrollX + (mPaddingLeft & inside);
11389                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11390                    bottom = top + size;
11391                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11392                    if (invalidate) {
11393                        invalidate(left, top, right, bottom);
11394                    }
11395                }
11396
11397                if (drawVerticalScrollBar) {
11398                    int size = scrollBar.getSize(true);
11399                    if (size <= 0) {
11400                        size = cache.scrollBarSize;
11401                    }
11402
11403                    scrollBar.setParameters(computeVerticalScrollRange(),
11404                                            computeVerticalScrollOffset(),
11405                                            computeVerticalScrollExtent(), true);
11406                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11407                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11408                        verticalScrollbarPosition = isLayoutRtl() ?
11409                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11410                    }
11411                    switch (verticalScrollbarPosition) {
11412                        default:
11413                        case SCROLLBAR_POSITION_RIGHT:
11414                            left = scrollX + width - size - (mUserPaddingRight & inside);
11415                            break;
11416                        case SCROLLBAR_POSITION_LEFT:
11417                            left = scrollX + (mUserPaddingLeft & inside);
11418                            break;
11419                    }
11420                    top = scrollY + (mPaddingTop & inside);
11421                    right = left + size;
11422                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11423                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11424                    if (invalidate) {
11425                        invalidate(left, top, right, bottom);
11426                    }
11427                }
11428            }
11429        }
11430    }
11431
11432    /**
11433     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11434     * FastScroller is visible.
11435     * @return whether to temporarily hide the vertical scrollbar
11436     * @hide
11437     */
11438    protected boolean isVerticalScrollBarHidden() {
11439        return false;
11440    }
11441
11442    /**
11443     * <p>Draw the horizontal scrollbar if
11444     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11445     *
11446     * @param canvas the canvas on which to draw the scrollbar
11447     * @param scrollBar the scrollbar's drawable
11448     *
11449     * @see #isHorizontalScrollBarEnabled()
11450     * @see #computeHorizontalScrollRange()
11451     * @see #computeHorizontalScrollExtent()
11452     * @see #computeHorizontalScrollOffset()
11453     * @see android.widget.ScrollBarDrawable
11454     * @hide
11455     */
11456    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11457            int l, int t, int r, int b) {
11458        scrollBar.setBounds(l, t, r, b);
11459        scrollBar.draw(canvas);
11460    }
11461
11462    /**
11463     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11464     * returns true.</p>
11465     *
11466     * @param canvas the canvas on which to draw the scrollbar
11467     * @param scrollBar the scrollbar's drawable
11468     *
11469     * @see #isVerticalScrollBarEnabled()
11470     * @see #computeVerticalScrollRange()
11471     * @see #computeVerticalScrollExtent()
11472     * @see #computeVerticalScrollOffset()
11473     * @see android.widget.ScrollBarDrawable
11474     * @hide
11475     */
11476    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11477            int l, int t, int r, int b) {
11478        scrollBar.setBounds(l, t, r, b);
11479        scrollBar.draw(canvas);
11480    }
11481
11482    /**
11483     * Implement this to do your drawing.
11484     *
11485     * @param canvas the canvas on which the background will be drawn
11486     */
11487    protected void onDraw(Canvas canvas) {
11488    }
11489
11490    /*
11491     * Caller is responsible for calling requestLayout if necessary.
11492     * (This allows addViewInLayout to not request a new layout.)
11493     */
11494    void assignParent(ViewParent parent) {
11495        if (mParent == null) {
11496            mParent = parent;
11497        } else if (parent == null) {
11498            mParent = null;
11499        } else {
11500            throw new RuntimeException("view " + this + " being added, but"
11501                    + " it already has a parent");
11502        }
11503    }
11504
11505    /**
11506     * This is called when the view is attached to a window.  At this point it
11507     * has a Surface and will start drawing.  Note that this function is
11508     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11509     * however it may be called any time before the first onDraw -- including
11510     * before or after {@link #onMeasure(int, int)}.
11511     *
11512     * @see #onDetachedFromWindow()
11513     */
11514    protected void onAttachedToWindow() {
11515        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11516            mParent.requestTransparentRegion(this);
11517        }
11518
11519        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11520            initialAwakenScrollBars();
11521            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11522        }
11523
11524        jumpDrawablesToCurrentState();
11525
11526        clearAccessibilityFocus();
11527        if (isFocused()) {
11528            InputMethodManager imm = InputMethodManager.peekInstance();
11529            imm.focusIn(this);
11530        }
11531
11532        if (mAttachInfo != null && mDisplayList != null) {
11533            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11534        }
11535    }
11536
11537    /**
11538     * Resolve all RTL related properties.
11539     */
11540    void resolveRtlPropertiesIfNeeded() {
11541        if (!needRtlPropertiesResolution()) return;
11542
11543        // Order is important here: LayoutDirection MUST be resolved first
11544        if (!isLayoutDirectionResolved()) {
11545            resolveLayoutDirection();
11546            resolveLayoutParams();
11547        }
11548        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11549        if (!isTextDirectionResolved()) {
11550            resolveTextDirection();
11551        }
11552        if (!isTextAlignmentResolved()) {
11553            resolveTextAlignment();
11554        }
11555        if (!isPaddingResolved()) {
11556            resolvePadding();
11557        }
11558        if (!isDrawablesResolved()) {
11559            resolveDrawables();
11560        }
11561        requestLayout();
11562        invalidate(true);
11563        onRtlPropertiesChanged(getLayoutDirection());
11564    }
11565
11566    // Reset resolution of all RTL related properties.
11567    void resetRtlProperties() {
11568        resetResolvedLayoutDirection();
11569        resetResolvedTextDirection();
11570        resetResolvedTextAlignment();
11571        resetResolvedPadding();
11572        resetResolvedDrawables();
11573    }
11574
11575    /**
11576     * @see #onScreenStateChanged(int)
11577     */
11578    void dispatchScreenStateChanged(int screenState) {
11579        onScreenStateChanged(screenState);
11580    }
11581
11582    /**
11583     * This method is called whenever the state of the screen this view is
11584     * attached to changes. A state change will usually occurs when the screen
11585     * turns on or off (whether it happens automatically or the user does it
11586     * manually.)
11587     *
11588     * @param screenState The new state of the screen. Can be either
11589     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11590     */
11591    public void onScreenStateChanged(int screenState) {
11592    }
11593
11594    /**
11595     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11596     */
11597    private boolean hasRtlSupport() {
11598        return mContext.getApplicationInfo().hasRtlSupport();
11599    }
11600
11601    /**
11602     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11603     * RTL not supported)
11604     */
11605    private boolean isRtlCompatibilityMode() {
11606        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11607        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11608    }
11609
11610    /**
11611     * @return true if RTL properties need resolution.
11612     */
11613    private boolean needRtlPropertiesResolution() {
11614        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11615    }
11616
11617    /**
11618     * Called when any RTL property (layout direction or text direction or text alignment) has
11619     * been changed.
11620     *
11621     * Subclasses need to override this method to take care of cached information that depends on the
11622     * resolved layout direction, or to inform child views that inherit their layout direction.
11623     *
11624     * The default implementation does nothing.
11625     *
11626     * @param layoutDirection the direction of the layout
11627     *
11628     * @see #LAYOUT_DIRECTION_LTR
11629     * @see #LAYOUT_DIRECTION_RTL
11630     */
11631    public void onRtlPropertiesChanged(int layoutDirection) {
11632    }
11633
11634    /**
11635     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11636     * that the parent directionality can and will be resolved before its children.
11637     *
11638     * @return true if resolution has been done, false otherwise.
11639     *
11640     * @hide
11641     */
11642    public boolean resolveLayoutDirection() {
11643        // Clear any previous layout direction resolution
11644        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11645
11646        if (hasRtlSupport()) {
11647            // Set resolved depending on layout direction
11648            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11649                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11650                case LAYOUT_DIRECTION_INHERIT:
11651                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11652                    // later to get the correct resolved value
11653                    if (!canResolveLayoutDirection()) return false;
11654
11655                    View parent = ((View) mParent);
11656                    // Parent has not yet resolved, LTR is still the default
11657                    if (!parent.isLayoutDirectionResolved()) return false;
11658
11659                    if (parent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11660                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11661                    }
11662                    break;
11663                case LAYOUT_DIRECTION_RTL:
11664                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11665                    break;
11666                case LAYOUT_DIRECTION_LOCALE:
11667                    if((LAYOUT_DIRECTION_RTL ==
11668                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11669                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11670                    }
11671                    break;
11672                default:
11673                    // Nothing to do, LTR by default
11674            }
11675        }
11676
11677        // Set to resolved
11678        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11679        return true;
11680    }
11681
11682    /**
11683     * Check if layout direction resolution can be done.
11684     *
11685     * @return true if layout direction resolution can be done otherwise return false.
11686     *
11687     * @hide
11688     */
11689    public boolean canResolveLayoutDirection() {
11690        switch (getRawLayoutDirection()) {
11691            case LAYOUT_DIRECTION_INHERIT:
11692                return (mParent != null) && (mParent instanceof ViewGroup) &&
11693                       ((ViewGroup) mParent).canResolveLayoutDirection();
11694            default:
11695                return true;
11696        }
11697    }
11698
11699    /**
11700     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11701     * {@link #onMeasure(int, int)}.
11702     *
11703     * @hide
11704     */
11705    public void resetResolvedLayoutDirection() {
11706        // Reset the current resolved bits
11707        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11708    }
11709
11710    /**
11711     * @return true if the layout direction is inherited.
11712     *
11713     * @hide
11714     */
11715    public boolean isLayoutDirectionInherited() {
11716        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11717    }
11718
11719    /**
11720     * @return true if layout direction has been resolved.
11721     */
11722    private boolean isLayoutDirectionResolved() {
11723        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11724    }
11725
11726    /**
11727     * Return if padding has been resolved
11728     *
11729     * @hide
11730     */
11731    boolean isPaddingResolved() {
11732        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11733    }
11734
11735    /**
11736     * Resolve padding depending on layout direction.
11737     *
11738     * @hide
11739     */
11740    public void resolvePadding() {
11741        if (!isRtlCompatibilityMode()) {
11742            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11743            // If start / end padding are defined, they will be resolved (hence overriding) to
11744            // left / right or right / left depending on the resolved layout direction.
11745            // If start / end padding are not defined, use the left / right ones.
11746            int resolvedLayoutDirection = getLayoutDirection();
11747            // Set user padding to initial values ...
11748            mUserPaddingLeft = (mUserPaddingLeftInitial == UNDEFINED_PADDING) ?
11749                    0 : mUserPaddingLeftInitial;
11750            mUserPaddingRight = (mUserPaddingRightInitial == UNDEFINED_PADDING) ?
11751                    0 : mUserPaddingRightInitial;
11752            // ... then resolve it.
11753            switch (resolvedLayoutDirection) {
11754                case LAYOUT_DIRECTION_RTL:
11755                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11756                        mUserPaddingRight = mUserPaddingStart;
11757                    }
11758                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11759                        mUserPaddingLeft = mUserPaddingEnd;
11760                    }
11761                    break;
11762                case LAYOUT_DIRECTION_LTR:
11763                default:
11764                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11765                        mUserPaddingLeft = mUserPaddingStart;
11766                    }
11767                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11768                        mUserPaddingRight = mUserPaddingEnd;
11769                    }
11770            }
11771
11772            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11773
11774            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11775                    mUserPaddingBottom);
11776            onRtlPropertiesChanged(resolvedLayoutDirection);
11777        }
11778
11779        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11780    }
11781
11782    /**
11783     * Reset the resolved layout direction.
11784     *
11785     * @hide
11786     */
11787    public void resetResolvedPadding() {
11788        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11789    }
11790
11791    /**
11792     * This is called when the view is detached from a window.  At this point it
11793     * no longer has a surface for drawing.
11794     *
11795     * @see #onAttachedToWindow()
11796     */
11797    protected void onDetachedFromWindow() {
11798        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
11799
11800        removeUnsetPressCallback();
11801        removeLongPressCallback();
11802        removePerformClickCallback();
11803        removeSendViewScrolledAccessibilityEventCallback();
11804
11805        destroyDrawingCache();
11806
11807        destroyLayer(false);
11808
11809        if (mAttachInfo != null) {
11810            if (mDisplayList != null) {
11811                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11812            }
11813            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11814        } else {
11815            // Should never happen
11816            clearDisplayList();
11817        }
11818
11819        mCurrentAnimation = null;
11820
11821        resetRtlProperties();
11822        onRtlPropertiesChanged(LAYOUT_DIRECTION_DEFAULT);
11823        resetAccessibilityStateChanged();
11824    }
11825
11826    /**
11827     * @return The number of times this view has been attached to a window
11828     */
11829    protected int getWindowAttachCount() {
11830        return mWindowAttachCount;
11831    }
11832
11833    /**
11834     * Retrieve a unique token identifying the window this view is attached to.
11835     * @return Return the window's token for use in
11836     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11837     */
11838    public IBinder getWindowToken() {
11839        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11840    }
11841
11842    /**
11843     * Retrieve a unique token identifying the top-level "real" window of
11844     * the window that this view is attached to.  That is, this is like
11845     * {@link #getWindowToken}, except if the window this view in is a panel
11846     * window (attached to another containing window), then the token of
11847     * the containing window is returned instead.
11848     *
11849     * @return Returns the associated window token, either
11850     * {@link #getWindowToken()} or the containing window's token.
11851     */
11852    public IBinder getApplicationWindowToken() {
11853        AttachInfo ai = mAttachInfo;
11854        if (ai != null) {
11855            IBinder appWindowToken = ai.mPanelParentWindowToken;
11856            if (appWindowToken == null) {
11857                appWindowToken = ai.mWindowToken;
11858            }
11859            return appWindowToken;
11860        }
11861        return null;
11862    }
11863
11864    /**
11865     * Gets the logical display to which the view's window has been attached.
11866     *
11867     * @return The logical display, or null if the view is not currently attached to a window.
11868     */
11869    public Display getDisplay() {
11870        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
11871    }
11872
11873    /**
11874     * Retrieve private session object this view hierarchy is using to
11875     * communicate with the window manager.
11876     * @return the session object to communicate with the window manager
11877     */
11878    /*package*/ IWindowSession getWindowSession() {
11879        return mAttachInfo != null ? mAttachInfo.mSession : null;
11880    }
11881
11882    /**
11883     * @param info the {@link android.view.View.AttachInfo} to associated with
11884     *        this view
11885     */
11886    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11887        //System.out.println("Attached! " + this);
11888        mAttachInfo = info;
11889        mWindowAttachCount++;
11890        // We will need to evaluate the drawable state at least once.
11891        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
11892        if (mFloatingTreeObserver != null) {
11893            info.mTreeObserver.merge(mFloatingTreeObserver);
11894            mFloatingTreeObserver = null;
11895        }
11896        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
11897            mAttachInfo.mScrollContainers.add(this);
11898            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
11899        }
11900        performCollectViewAttributes(mAttachInfo, visibility);
11901        onAttachedToWindow();
11902
11903        ListenerInfo li = mListenerInfo;
11904        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11905                li != null ? li.mOnAttachStateChangeListeners : null;
11906        if (listeners != null && listeners.size() > 0) {
11907            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11908            // perform the dispatching. The iterator is a safe guard against listeners that
11909            // could mutate the list by calling the various add/remove methods. This prevents
11910            // the array from being modified while we iterate it.
11911            for (OnAttachStateChangeListener listener : listeners) {
11912                listener.onViewAttachedToWindow(this);
11913            }
11914        }
11915
11916        int vis = info.mWindowVisibility;
11917        if (vis != GONE) {
11918            onWindowVisibilityChanged(vis);
11919        }
11920        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
11921            // If nobody has evaluated the drawable state yet, then do it now.
11922            refreshDrawableState();
11923        }
11924        needGlobalAttributesUpdate(false);
11925    }
11926
11927    void dispatchDetachedFromWindow() {
11928        AttachInfo info = mAttachInfo;
11929        if (info != null) {
11930            int vis = info.mWindowVisibility;
11931            if (vis != GONE) {
11932                onWindowVisibilityChanged(GONE);
11933            }
11934        }
11935
11936        onDetachedFromWindow();
11937
11938        ListenerInfo li = mListenerInfo;
11939        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11940                li != null ? li.mOnAttachStateChangeListeners : null;
11941        if (listeners != null && listeners.size() > 0) {
11942            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11943            // perform the dispatching. The iterator is a safe guard against listeners that
11944            // could mutate the list by calling the various add/remove methods. This prevents
11945            // the array from being modified while we iterate it.
11946            for (OnAttachStateChangeListener listener : listeners) {
11947                listener.onViewDetachedFromWindow(this);
11948            }
11949        }
11950
11951        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
11952            mAttachInfo.mScrollContainers.remove(this);
11953            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
11954        }
11955
11956        mAttachInfo = null;
11957    }
11958
11959    /**
11960     * Store this view hierarchy's frozen state into the given container.
11961     *
11962     * @param container The SparseArray in which to save the view's state.
11963     *
11964     * @see #restoreHierarchyState(android.util.SparseArray)
11965     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11966     * @see #onSaveInstanceState()
11967     */
11968    public void saveHierarchyState(SparseArray<Parcelable> container) {
11969        dispatchSaveInstanceState(container);
11970    }
11971
11972    /**
11973     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11974     * this view and its children. May be overridden to modify how freezing happens to a
11975     * view's children; for example, some views may want to not store state for their children.
11976     *
11977     * @param container The SparseArray in which to save the view's state.
11978     *
11979     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11980     * @see #saveHierarchyState(android.util.SparseArray)
11981     * @see #onSaveInstanceState()
11982     */
11983    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11984        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11985            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
11986            Parcelable state = onSaveInstanceState();
11987            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
11988                throw new IllegalStateException(
11989                        "Derived class did not call super.onSaveInstanceState()");
11990            }
11991            if (state != null) {
11992                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11993                // + ": " + state);
11994                container.put(mID, state);
11995            }
11996        }
11997    }
11998
11999    /**
12000     * Hook allowing a view to generate a representation of its internal state
12001     * that can later be used to create a new instance with that same state.
12002     * This state should only contain information that is not persistent or can
12003     * not be reconstructed later. For example, you will never store your
12004     * current position on screen because that will be computed again when a
12005     * new instance of the view is placed in its view hierarchy.
12006     * <p>
12007     * Some examples of things you may store here: the current cursor position
12008     * in a text view (but usually not the text itself since that is stored in a
12009     * content provider or other persistent storage), the currently selected
12010     * item in a list view.
12011     *
12012     * @return Returns a Parcelable object containing the view's current dynamic
12013     *         state, or null if there is nothing interesting to save. The
12014     *         default implementation returns null.
12015     * @see #onRestoreInstanceState(android.os.Parcelable)
12016     * @see #saveHierarchyState(android.util.SparseArray)
12017     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12018     * @see #setSaveEnabled(boolean)
12019     */
12020    protected Parcelable onSaveInstanceState() {
12021        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12022        return BaseSavedState.EMPTY_STATE;
12023    }
12024
12025    /**
12026     * Restore this view hierarchy's frozen state from the given container.
12027     *
12028     * @param container The SparseArray which holds previously frozen states.
12029     *
12030     * @see #saveHierarchyState(android.util.SparseArray)
12031     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12032     * @see #onRestoreInstanceState(android.os.Parcelable)
12033     */
12034    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12035        dispatchRestoreInstanceState(container);
12036    }
12037
12038    /**
12039     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12040     * state for this view and its children. May be overridden to modify how restoring
12041     * happens to a view's children; for example, some views may want to not store state
12042     * for their children.
12043     *
12044     * @param container The SparseArray which holds previously saved state.
12045     *
12046     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12047     * @see #restoreHierarchyState(android.util.SparseArray)
12048     * @see #onRestoreInstanceState(android.os.Parcelable)
12049     */
12050    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12051        if (mID != NO_ID) {
12052            Parcelable state = container.get(mID);
12053            if (state != null) {
12054                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12055                // + ": " + state);
12056                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12057                onRestoreInstanceState(state);
12058                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12059                    throw new IllegalStateException(
12060                            "Derived class did not call super.onRestoreInstanceState()");
12061                }
12062            }
12063        }
12064    }
12065
12066    /**
12067     * Hook allowing a view to re-apply a representation of its internal state that had previously
12068     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12069     * null state.
12070     *
12071     * @param state The frozen state that had previously been returned by
12072     *        {@link #onSaveInstanceState}.
12073     *
12074     * @see #onSaveInstanceState()
12075     * @see #restoreHierarchyState(android.util.SparseArray)
12076     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12077     */
12078    protected void onRestoreInstanceState(Parcelable state) {
12079        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12080        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12081            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12082                    + "received " + state.getClass().toString() + " instead. This usually happens "
12083                    + "when two views of different type have the same id in the same hierarchy. "
12084                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12085                    + "other views do not use the same id.");
12086        }
12087    }
12088
12089    /**
12090     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12091     *
12092     * @return the drawing start time in milliseconds
12093     */
12094    public long getDrawingTime() {
12095        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12096    }
12097
12098    /**
12099     * <p>Enables or disables the duplication of the parent's state into this view. When
12100     * duplication is enabled, this view gets its drawable state from its parent rather
12101     * than from its own internal properties.</p>
12102     *
12103     * <p>Note: in the current implementation, setting this property to true after the
12104     * view was added to a ViewGroup might have no effect at all. This property should
12105     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12106     *
12107     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12108     * property is enabled, an exception will be thrown.</p>
12109     *
12110     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12111     * parent, these states should not be affected by this method.</p>
12112     *
12113     * @param enabled True to enable duplication of the parent's drawable state, false
12114     *                to disable it.
12115     *
12116     * @see #getDrawableState()
12117     * @see #isDuplicateParentStateEnabled()
12118     */
12119    public void setDuplicateParentStateEnabled(boolean enabled) {
12120        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12121    }
12122
12123    /**
12124     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12125     *
12126     * @return True if this view's drawable state is duplicated from the parent,
12127     *         false otherwise
12128     *
12129     * @see #getDrawableState()
12130     * @see #setDuplicateParentStateEnabled(boolean)
12131     */
12132    public boolean isDuplicateParentStateEnabled() {
12133        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12134    }
12135
12136    /**
12137     * <p>Specifies the type of layer backing this view. The layer can be
12138     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12139     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12140     *
12141     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12142     * instance that controls how the layer is composed on screen. The following
12143     * properties of the paint are taken into account when composing the layer:</p>
12144     * <ul>
12145     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12146     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12147     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12148     * </ul>
12149     *
12150     * <p>If this view has an alpha value set to < 1.0 by calling
12151     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12152     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12153     * equivalent to setting a hardware layer on this view and providing a paint with
12154     * the desired alpha value.</p>
12155     *
12156     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
12157     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
12158     * for more information on when and how to use layers.</p>
12159     *
12160     * @param layerType The type of layer to use with this view, must be one of
12161     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12162     *        {@link #LAYER_TYPE_HARDWARE}
12163     * @param paint The paint used to compose the layer. This argument is optional
12164     *        and can be null. It is ignored when the layer type is
12165     *        {@link #LAYER_TYPE_NONE}
12166     *
12167     * @see #getLayerType()
12168     * @see #LAYER_TYPE_NONE
12169     * @see #LAYER_TYPE_SOFTWARE
12170     * @see #LAYER_TYPE_HARDWARE
12171     * @see #setAlpha(float)
12172     *
12173     * @attr ref android.R.styleable#View_layerType
12174     */
12175    public void setLayerType(int layerType, Paint paint) {
12176        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12177            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12178                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12179        }
12180
12181        if (layerType == mLayerType) {
12182            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12183                mLayerPaint = paint == null ? new Paint() : paint;
12184                invalidateParentCaches();
12185                invalidate(true);
12186            }
12187            return;
12188        }
12189
12190        // Destroy any previous software drawing cache if needed
12191        switch (mLayerType) {
12192            case LAYER_TYPE_HARDWARE:
12193                destroyLayer(false);
12194                // fall through - non-accelerated views may use software layer mechanism instead
12195            case LAYER_TYPE_SOFTWARE:
12196                destroyDrawingCache();
12197                break;
12198            default:
12199                break;
12200        }
12201
12202        mLayerType = layerType;
12203        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12204        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12205        mLocalDirtyRect = layerDisabled ? null : new Rect();
12206
12207        invalidateParentCaches();
12208        invalidate(true);
12209    }
12210
12211    /**
12212     * Updates the {@link Paint} object used with the current layer (used only if the current
12213     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12214     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12215     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12216     * ensure that the view gets redrawn immediately.
12217     *
12218     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12219     * instance that controls how the layer is composed on screen. The following
12220     * properties of the paint are taken into account when composing the layer:</p>
12221     * <ul>
12222     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12223     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12224     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12225     * </ul>
12226     *
12227     * <p>If this view has an alpha value set to < 1.0 by calling
12228     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12229     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12230     * equivalent to setting a hardware layer on this view and providing a paint with
12231     * the desired alpha value.</p>
12232     *
12233     * @param paint The paint used to compose the layer. This argument is optional
12234     *        and can be null. It is ignored when the layer type is
12235     *        {@link #LAYER_TYPE_NONE}
12236     *
12237     * @see #setLayerType(int, android.graphics.Paint)
12238     */
12239    public void setLayerPaint(Paint paint) {
12240        int layerType = getLayerType();
12241        if (layerType != LAYER_TYPE_NONE) {
12242            mLayerPaint = paint == null ? new Paint() : paint;
12243            if (layerType == LAYER_TYPE_HARDWARE) {
12244                HardwareLayer layer = getHardwareLayer();
12245                if (layer != null) {
12246                    layer.setLayerPaint(paint);
12247                }
12248                invalidateViewProperty(false, false);
12249            } else {
12250                invalidate();
12251            }
12252        }
12253    }
12254
12255    /**
12256     * Indicates whether this view has a static layer. A view with layer type
12257     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12258     * dynamic.
12259     */
12260    boolean hasStaticLayer() {
12261        return true;
12262    }
12263
12264    /**
12265     * Indicates what type of layer is currently associated with this view. By default
12266     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12267     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12268     * for more information on the different types of layers.
12269     *
12270     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12271     *         {@link #LAYER_TYPE_HARDWARE}
12272     *
12273     * @see #setLayerType(int, android.graphics.Paint)
12274     * @see #buildLayer()
12275     * @see #LAYER_TYPE_NONE
12276     * @see #LAYER_TYPE_SOFTWARE
12277     * @see #LAYER_TYPE_HARDWARE
12278     */
12279    public int getLayerType() {
12280        return mLayerType;
12281    }
12282
12283    /**
12284     * Forces this view's layer to be created and this view to be rendered
12285     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12286     * invoking this method will have no effect.
12287     *
12288     * This method can for instance be used to render a view into its layer before
12289     * starting an animation. If this view is complex, rendering into the layer
12290     * before starting the animation will avoid skipping frames.
12291     *
12292     * @throws IllegalStateException If this view is not attached to a window
12293     *
12294     * @see #setLayerType(int, android.graphics.Paint)
12295     */
12296    public void buildLayer() {
12297        if (mLayerType == LAYER_TYPE_NONE) return;
12298
12299        if (mAttachInfo == null) {
12300            throw new IllegalStateException("This view must be attached to a window first");
12301        }
12302
12303        switch (mLayerType) {
12304            case LAYER_TYPE_HARDWARE:
12305                if (mAttachInfo.mHardwareRenderer != null &&
12306                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12307                        mAttachInfo.mHardwareRenderer.validate()) {
12308                    getHardwareLayer();
12309                }
12310                break;
12311            case LAYER_TYPE_SOFTWARE:
12312                buildDrawingCache(true);
12313                break;
12314        }
12315    }
12316
12317    /**
12318     * <p>Returns a hardware layer that can be used to draw this view again
12319     * without executing its draw method.</p>
12320     *
12321     * @return A HardwareLayer ready to render, or null if an error occurred.
12322     */
12323    HardwareLayer getHardwareLayer() {
12324        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12325                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12326            return null;
12327        }
12328
12329        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12330
12331        final int width = mRight - mLeft;
12332        final int height = mBottom - mTop;
12333
12334        if (width == 0 || height == 0) {
12335            return null;
12336        }
12337
12338        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12339            if (mHardwareLayer == null) {
12340                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12341                        width, height, isOpaque());
12342                mLocalDirtyRect.set(0, 0, width, height);
12343            } else {
12344                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12345                    if (mHardwareLayer.resize(width, height)) {
12346                        mLocalDirtyRect.set(0, 0, width, height);
12347                    }
12348                }
12349
12350                // This should not be necessary but applications that change
12351                // the parameters of their background drawable without calling
12352                // this.setBackground(Drawable) can leave the view in a bad state
12353                // (for instance isOpaque() returns true, but the background is
12354                // not opaque.)
12355                computeOpaqueFlags();
12356
12357                final boolean opaque = isOpaque();
12358                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12359                    mHardwareLayer.setOpaque(opaque);
12360                    mLocalDirtyRect.set(0, 0, width, height);
12361                }
12362            }
12363
12364            // The layer is not valid if the underlying GPU resources cannot be allocated
12365            if (!mHardwareLayer.isValid()) {
12366                return null;
12367            }
12368
12369            mHardwareLayer.setLayerPaint(mLayerPaint);
12370            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12371            ViewRootImpl viewRoot = getViewRootImpl();
12372            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12373
12374            mLocalDirtyRect.setEmpty();
12375        }
12376
12377        return mHardwareLayer;
12378    }
12379
12380    /**
12381     * Destroys this View's hardware layer if possible.
12382     *
12383     * @return True if the layer was destroyed, false otherwise.
12384     *
12385     * @see #setLayerType(int, android.graphics.Paint)
12386     * @see #LAYER_TYPE_HARDWARE
12387     */
12388    boolean destroyLayer(boolean valid) {
12389        if (mHardwareLayer != null) {
12390            AttachInfo info = mAttachInfo;
12391            if (info != null && info.mHardwareRenderer != null &&
12392                    info.mHardwareRenderer.isEnabled() &&
12393                    (valid || info.mHardwareRenderer.validate())) {
12394                mHardwareLayer.destroy();
12395                mHardwareLayer = null;
12396
12397                invalidate(true);
12398                invalidateParentCaches();
12399            }
12400            return true;
12401        }
12402        return false;
12403    }
12404
12405    /**
12406     * Destroys all hardware rendering resources. This method is invoked
12407     * when the system needs to reclaim resources. Upon execution of this
12408     * method, you should free any OpenGL resources created by the view.
12409     *
12410     * Note: you <strong>must</strong> call
12411     * <code>super.destroyHardwareResources()</code> when overriding
12412     * this method.
12413     *
12414     * @hide
12415     */
12416    protected void destroyHardwareResources() {
12417        destroyLayer(true);
12418    }
12419
12420    /**
12421     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12422     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12423     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12424     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12425     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12426     * null.</p>
12427     *
12428     * <p>Enabling the drawing cache is similar to
12429     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12430     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12431     * drawing cache has no effect on rendering because the system uses a different mechanism
12432     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12433     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12434     * for information on how to enable software and hardware layers.</p>
12435     *
12436     * <p>This API can be used to manually generate
12437     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12438     * {@link #getDrawingCache()}.</p>
12439     *
12440     * @param enabled true to enable the drawing cache, false otherwise
12441     *
12442     * @see #isDrawingCacheEnabled()
12443     * @see #getDrawingCache()
12444     * @see #buildDrawingCache()
12445     * @see #setLayerType(int, android.graphics.Paint)
12446     */
12447    public void setDrawingCacheEnabled(boolean enabled) {
12448        mCachingFailed = false;
12449        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12450    }
12451
12452    /**
12453     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12454     *
12455     * @return true if the drawing cache is enabled
12456     *
12457     * @see #setDrawingCacheEnabled(boolean)
12458     * @see #getDrawingCache()
12459     */
12460    @ViewDebug.ExportedProperty(category = "drawing")
12461    public boolean isDrawingCacheEnabled() {
12462        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12463    }
12464
12465    /**
12466     * Debugging utility which recursively outputs the dirty state of a view and its
12467     * descendants.
12468     *
12469     * @hide
12470     */
12471    @SuppressWarnings({"UnusedDeclaration"})
12472    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12473        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12474                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12475                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12476                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12477        if (clear) {
12478            mPrivateFlags &= clearMask;
12479        }
12480        if (this instanceof ViewGroup) {
12481            ViewGroup parent = (ViewGroup) this;
12482            final int count = parent.getChildCount();
12483            for (int i = 0; i < count; i++) {
12484                final View child = parent.getChildAt(i);
12485                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12486            }
12487        }
12488    }
12489
12490    /**
12491     * This method is used by ViewGroup to cause its children to restore or recreate their
12492     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12493     * to recreate its own display list, which would happen if it went through the normal
12494     * draw/dispatchDraw mechanisms.
12495     *
12496     * @hide
12497     */
12498    protected void dispatchGetDisplayList() {}
12499
12500    /**
12501     * A view that is not attached or hardware accelerated cannot create a display list.
12502     * This method checks these conditions and returns the appropriate result.
12503     *
12504     * @return true if view has the ability to create a display list, false otherwise.
12505     *
12506     * @hide
12507     */
12508    public boolean canHaveDisplayList() {
12509        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12510    }
12511
12512    /**
12513     * @return The HardwareRenderer associated with that view or null if hardware rendering
12514     * is not supported or this this has not been attached to a window.
12515     *
12516     * @hide
12517     */
12518    public HardwareRenderer getHardwareRenderer() {
12519        if (mAttachInfo != null) {
12520            return mAttachInfo.mHardwareRenderer;
12521        }
12522        return null;
12523    }
12524
12525    /**
12526     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12527     * Otherwise, the same display list will be returned (after having been rendered into
12528     * along the way, depending on the invalidation state of the view).
12529     *
12530     * @param displayList The previous version of this displayList, could be null.
12531     * @param isLayer Whether the requester of the display list is a layer. If so,
12532     * the view will avoid creating a layer inside the resulting display list.
12533     * @return A new or reused DisplayList object.
12534     */
12535    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12536        if (!canHaveDisplayList()) {
12537            return null;
12538        }
12539
12540        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12541                displayList == null || !displayList.isValid() ||
12542                (!isLayer && mRecreateDisplayList))) {
12543            // Don't need to recreate the display list, just need to tell our
12544            // children to restore/recreate theirs
12545            if (displayList != null && displayList.isValid() &&
12546                    !isLayer && !mRecreateDisplayList) {
12547                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12548                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12549                dispatchGetDisplayList();
12550
12551                return displayList;
12552            }
12553
12554            if (!isLayer) {
12555                // If we got here, we're recreating it. Mark it as such to ensure that
12556                // we copy in child display lists into ours in drawChild()
12557                mRecreateDisplayList = true;
12558            }
12559            if (displayList == null) {
12560                final String name = getClass().getSimpleName();
12561                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12562                // If we're creating a new display list, make sure our parent gets invalidated
12563                // since they will need to recreate their display list to account for this
12564                // new child display list.
12565                invalidateParentCaches();
12566            }
12567
12568            boolean caching = false;
12569            final HardwareCanvas canvas = displayList.start();
12570            int width = mRight - mLeft;
12571            int height = mBottom - mTop;
12572
12573            try {
12574                canvas.setViewport(width, height);
12575                // The dirty rect should always be null for a display list
12576                canvas.onPreDraw(null);
12577                int layerType = getLayerType();
12578                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12579                    if (layerType == LAYER_TYPE_HARDWARE) {
12580                        final HardwareLayer layer = getHardwareLayer();
12581                        if (layer != null && layer.isValid()) {
12582                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12583                        } else {
12584                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12585                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12586                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12587                        }
12588                        caching = true;
12589                    } else {
12590                        buildDrawingCache(true);
12591                        Bitmap cache = getDrawingCache(true);
12592                        if (cache != null) {
12593                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12594                            caching = true;
12595                        }
12596                    }
12597                } else {
12598
12599                    computeScroll();
12600
12601                    canvas.translate(-mScrollX, -mScrollY);
12602                    if (!isLayer) {
12603                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12604                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12605                    }
12606
12607                    // Fast path for layouts with no backgrounds
12608                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12609                        dispatchDraw(canvas);
12610                    } else {
12611                        draw(canvas);
12612                    }
12613                }
12614            } finally {
12615                canvas.onPostDraw();
12616
12617                displayList.end();
12618                displayList.setCaching(caching);
12619                if (isLayer) {
12620                    displayList.setLeftTopRightBottom(0, 0, width, height);
12621                } else {
12622                    setDisplayListProperties(displayList);
12623                }
12624            }
12625        } else if (!isLayer) {
12626            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12627            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12628        }
12629
12630        return displayList;
12631    }
12632
12633    /**
12634     * Get the DisplayList for the HardwareLayer
12635     *
12636     * @param layer The HardwareLayer whose DisplayList we want
12637     * @return A DisplayList fopr the specified HardwareLayer
12638     */
12639    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12640        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12641        layer.setDisplayList(displayList);
12642        return displayList;
12643    }
12644
12645
12646    /**
12647     * <p>Returns a display list that can be used to draw this view again
12648     * without executing its draw method.</p>
12649     *
12650     * @return A DisplayList ready to replay, or null if caching is not enabled.
12651     *
12652     * @hide
12653     */
12654    public DisplayList getDisplayList() {
12655        mDisplayList = getDisplayList(mDisplayList, false);
12656        return mDisplayList;
12657    }
12658
12659    private void clearDisplayList() {
12660        if (mDisplayList != null) {
12661            mDisplayList.invalidate();
12662            mDisplayList.clear();
12663        }
12664    }
12665
12666    /**
12667     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12668     *
12669     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12670     *
12671     * @see #getDrawingCache(boolean)
12672     */
12673    public Bitmap getDrawingCache() {
12674        return getDrawingCache(false);
12675    }
12676
12677    /**
12678     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12679     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12680     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12681     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12682     * request the drawing cache by calling this method and draw it on screen if the
12683     * returned bitmap is not null.</p>
12684     *
12685     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12686     * this method will create a bitmap of the same size as this view. Because this bitmap
12687     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12688     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12689     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12690     * size than the view. This implies that your application must be able to handle this
12691     * size.</p>
12692     *
12693     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12694     *        the current density of the screen when the application is in compatibility
12695     *        mode.
12696     *
12697     * @return A bitmap representing this view or null if cache is disabled.
12698     *
12699     * @see #setDrawingCacheEnabled(boolean)
12700     * @see #isDrawingCacheEnabled()
12701     * @see #buildDrawingCache(boolean)
12702     * @see #destroyDrawingCache()
12703     */
12704    public Bitmap getDrawingCache(boolean autoScale) {
12705        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12706            return null;
12707        }
12708        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12709            buildDrawingCache(autoScale);
12710        }
12711        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12712    }
12713
12714    /**
12715     * <p>Frees the resources used by the drawing cache. If you call
12716     * {@link #buildDrawingCache()} manually without calling
12717     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12718     * should cleanup the cache with this method afterwards.</p>
12719     *
12720     * @see #setDrawingCacheEnabled(boolean)
12721     * @see #buildDrawingCache()
12722     * @see #getDrawingCache()
12723     */
12724    public void destroyDrawingCache() {
12725        if (mDrawingCache != null) {
12726            mDrawingCache.recycle();
12727            mDrawingCache = null;
12728        }
12729        if (mUnscaledDrawingCache != null) {
12730            mUnscaledDrawingCache.recycle();
12731            mUnscaledDrawingCache = null;
12732        }
12733    }
12734
12735    /**
12736     * Setting a solid background color for the drawing cache's bitmaps will improve
12737     * performance and memory usage. Note, though that this should only be used if this
12738     * view will always be drawn on top of a solid color.
12739     *
12740     * @param color The background color to use for the drawing cache's bitmap
12741     *
12742     * @see #setDrawingCacheEnabled(boolean)
12743     * @see #buildDrawingCache()
12744     * @see #getDrawingCache()
12745     */
12746    public void setDrawingCacheBackgroundColor(int color) {
12747        if (color != mDrawingCacheBackgroundColor) {
12748            mDrawingCacheBackgroundColor = color;
12749            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12750        }
12751    }
12752
12753    /**
12754     * @see #setDrawingCacheBackgroundColor(int)
12755     *
12756     * @return The background color to used for the drawing cache's bitmap
12757     */
12758    public int getDrawingCacheBackgroundColor() {
12759        return mDrawingCacheBackgroundColor;
12760    }
12761
12762    /**
12763     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12764     *
12765     * @see #buildDrawingCache(boolean)
12766     */
12767    public void buildDrawingCache() {
12768        buildDrawingCache(false);
12769    }
12770
12771    /**
12772     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12773     *
12774     * <p>If you call {@link #buildDrawingCache()} manually without calling
12775     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12776     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12777     *
12778     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12779     * this method will create a bitmap of the same size as this view. Because this bitmap
12780     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12781     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12782     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12783     * size than the view. This implies that your application must be able to handle this
12784     * size.</p>
12785     *
12786     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12787     * you do not need the drawing cache bitmap, calling this method will increase memory
12788     * usage and cause the view to be rendered in software once, thus negatively impacting
12789     * performance.</p>
12790     *
12791     * @see #getDrawingCache()
12792     * @see #destroyDrawingCache()
12793     */
12794    public void buildDrawingCache(boolean autoScale) {
12795        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
12796                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12797            mCachingFailed = false;
12798
12799            int width = mRight - mLeft;
12800            int height = mBottom - mTop;
12801
12802            final AttachInfo attachInfo = mAttachInfo;
12803            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12804
12805            if (autoScale && scalingRequired) {
12806                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12807                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12808            }
12809
12810            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12811            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12812            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12813
12814            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
12815            final long drawingCacheSize =
12816                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
12817            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
12818                if (width > 0 && height > 0) {
12819                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
12820                            + projectedBitmapSize + " bytes, only "
12821                            + drawingCacheSize + " available");
12822                }
12823                destroyDrawingCache();
12824                mCachingFailed = true;
12825                return;
12826            }
12827
12828            boolean clear = true;
12829            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12830
12831            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12832                Bitmap.Config quality;
12833                if (!opaque) {
12834                    // Never pick ARGB_4444 because it looks awful
12835                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12836                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12837                        case DRAWING_CACHE_QUALITY_AUTO:
12838                            quality = Bitmap.Config.ARGB_8888;
12839                            break;
12840                        case DRAWING_CACHE_QUALITY_LOW:
12841                            quality = Bitmap.Config.ARGB_8888;
12842                            break;
12843                        case DRAWING_CACHE_QUALITY_HIGH:
12844                            quality = Bitmap.Config.ARGB_8888;
12845                            break;
12846                        default:
12847                            quality = Bitmap.Config.ARGB_8888;
12848                            break;
12849                    }
12850                } else {
12851                    // Optimization for translucent windows
12852                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12853                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12854                }
12855
12856                // Try to cleanup memory
12857                if (bitmap != null) bitmap.recycle();
12858
12859                try {
12860                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12861                            width, height, quality);
12862                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12863                    if (autoScale) {
12864                        mDrawingCache = bitmap;
12865                    } else {
12866                        mUnscaledDrawingCache = bitmap;
12867                    }
12868                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12869                } catch (OutOfMemoryError e) {
12870                    // If there is not enough memory to create the bitmap cache, just
12871                    // ignore the issue as bitmap caches are not required to draw the
12872                    // view hierarchy
12873                    if (autoScale) {
12874                        mDrawingCache = null;
12875                    } else {
12876                        mUnscaledDrawingCache = null;
12877                    }
12878                    mCachingFailed = true;
12879                    return;
12880                }
12881
12882                clear = drawingCacheBackgroundColor != 0;
12883            }
12884
12885            Canvas canvas;
12886            if (attachInfo != null) {
12887                canvas = attachInfo.mCanvas;
12888                if (canvas == null) {
12889                    canvas = new Canvas();
12890                }
12891                canvas.setBitmap(bitmap);
12892                // Temporarily clobber the cached Canvas in case one of our children
12893                // is also using a drawing cache. Without this, the children would
12894                // steal the canvas by attaching their own bitmap to it and bad, bad
12895                // thing would happen (invisible views, corrupted drawings, etc.)
12896                attachInfo.mCanvas = null;
12897            } else {
12898                // This case should hopefully never or seldom happen
12899                canvas = new Canvas(bitmap);
12900            }
12901
12902            if (clear) {
12903                bitmap.eraseColor(drawingCacheBackgroundColor);
12904            }
12905
12906            computeScroll();
12907            final int restoreCount = canvas.save();
12908
12909            if (autoScale && scalingRequired) {
12910                final float scale = attachInfo.mApplicationScale;
12911                canvas.scale(scale, scale);
12912            }
12913
12914            canvas.translate(-mScrollX, -mScrollY);
12915
12916            mPrivateFlags |= PFLAG_DRAWN;
12917            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12918                    mLayerType != LAYER_TYPE_NONE) {
12919                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
12920            }
12921
12922            // Fast path for layouts with no backgrounds
12923            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12924                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12925                dispatchDraw(canvas);
12926            } else {
12927                draw(canvas);
12928            }
12929
12930            canvas.restoreToCount(restoreCount);
12931            canvas.setBitmap(null);
12932
12933            if (attachInfo != null) {
12934                // Restore the cached Canvas for our siblings
12935                attachInfo.mCanvas = canvas;
12936            }
12937        }
12938    }
12939
12940    /**
12941     * Create a snapshot of the view into a bitmap.  We should probably make
12942     * some form of this public, but should think about the API.
12943     */
12944    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12945        int width = mRight - mLeft;
12946        int height = mBottom - mTop;
12947
12948        final AttachInfo attachInfo = mAttachInfo;
12949        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12950        width = (int) ((width * scale) + 0.5f);
12951        height = (int) ((height * scale) + 0.5f);
12952
12953        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12954                width > 0 ? width : 1, height > 0 ? height : 1, quality);
12955        if (bitmap == null) {
12956            throw new OutOfMemoryError();
12957        }
12958
12959        Resources resources = getResources();
12960        if (resources != null) {
12961            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12962        }
12963
12964        Canvas canvas;
12965        if (attachInfo != null) {
12966            canvas = attachInfo.mCanvas;
12967            if (canvas == null) {
12968                canvas = new Canvas();
12969            }
12970            canvas.setBitmap(bitmap);
12971            // Temporarily clobber the cached Canvas in case one of our children
12972            // is also using a drawing cache. Without this, the children would
12973            // steal the canvas by attaching their own bitmap to it and bad, bad
12974            // things would happen (invisible views, corrupted drawings, etc.)
12975            attachInfo.mCanvas = null;
12976        } else {
12977            // This case should hopefully never or seldom happen
12978            canvas = new Canvas(bitmap);
12979        }
12980
12981        if ((backgroundColor & 0xff000000) != 0) {
12982            bitmap.eraseColor(backgroundColor);
12983        }
12984
12985        computeScroll();
12986        final int restoreCount = canvas.save();
12987        canvas.scale(scale, scale);
12988        canvas.translate(-mScrollX, -mScrollY);
12989
12990        // Temporarily remove the dirty mask
12991        int flags = mPrivateFlags;
12992        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12993
12994        // Fast path for layouts with no backgrounds
12995        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12996            dispatchDraw(canvas);
12997        } else {
12998            draw(canvas);
12999        }
13000
13001        mPrivateFlags = flags;
13002
13003        canvas.restoreToCount(restoreCount);
13004        canvas.setBitmap(null);
13005
13006        if (attachInfo != null) {
13007            // Restore the cached Canvas for our siblings
13008            attachInfo.mCanvas = canvas;
13009        }
13010
13011        return bitmap;
13012    }
13013
13014    /**
13015     * Indicates whether this View is currently in edit mode. A View is usually
13016     * in edit mode when displayed within a developer tool. For instance, if
13017     * this View is being drawn by a visual user interface builder, this method
13018     * should return true.
13019     *
13020     * Subclasses should check the return value of this method to provide
13021     * different behaviors if their normal behavior might interfere with the
13022     * host environment. For instance: the class spawns a thread in its
13023     * constructor, the drawing code relies on device-specific features, etc.
13024     *
13025     * This method is usually checked in the drawing code of custom widgets.
13026     *
13027     * @return True if this View is in edit mode, false otherwise.
13028     */
13029    public boolean isInEditMode() {
13030        return false;
13031    }
13032
13033    /**
13034     * If the View draws content inside its padding and enables fading edges,
13035     * it needs to support padding offsets. Padding offsets are added to the
13036     * fading edges to extend the length of the fade so that it covers pixels
13037     * drawn inside the padding.
13038     *
13039     * Subclasses of this class should override this method if they need
13040     * to draw content inside the padding.
13041     *
13042     * @return True if padding offset must be applied, false otherwise.
13043     *
13044     * @see #getLeftPaddingOffset()
13045     * @see #getRightPaddingOffset()
13046     * @see #getTopPaddingOffset()
13047     * @see #getBottomPaddingOffset()
13048     *
13049     * @since CURRENT
13050     */
13051    protected boolean isPaddingOffsetRequired() {
13052        return false;
13053    }
13054
13055    /**
13056     * Amount by which to extend the left fading region. Called only when
13057     * {@link #isPaddingOffsetRequired()} returns true.
13058     *
13059     * @return The left padding offset in pixels.
13060     *
13061     * @see #isPaddingOffsetRequired()
13062     *
13063     * @since CURRENT
13064     */
13065    protected int getLeftPaddingOffset() {
13066        return 0;
13067    }
13068
13069    /**
13070     * Amount by which to extend the right fading region. Called only when
13071     * {@link #isPaddingOffsetRequired()} returns true.
13072     *
13073     * @return The right padding offset in pixels.
13074     *
13075     * @see #isPaddingOffsetRequired()
13076     *
13077     * @since CURRENT
13078     */
13079    protected int getRightPaddingOffset() {
13080        return 0;
13081    }
13082
13083    /**
13084     * Amount by which to extend the top fading region. Called only when
13085     * {@link #isPaddingOffsetRequired()} returns true.
13086     *
13087     * @return The top padding offset in pixels.
13088     *
13089     * @see #isPaddingOffsetRequired()
13090     *
13091     * @since CURRENT
13092     */
13093    protected int getTopPaddingOffset() {
13094        return 0;
13095    }
13096
13097    /**
13098     * Amount by which to extend the bottom fading region. Called only when
13099     * {@link #isPaddingOffsetRequired()} returns true.
13100     *
13101     * @return The bottom padding offset in pixels.
13102     *
13103     * @see #isPaddingOffsetRequired()
13104     *
13105     * @since CURRENT
13106     */
13107    protected int getBottomPaddingOffset() {
13108        return 0;
13109    }
13110
13111    /**
13112     * @hide
13113     * @param offsetRequired
13114     */
13115    protected int getFadeTop(boolean offsetRequired) {
13116        int top = mPaddingTop;
13117        if (offsetRequired) top += getTopPaddingOffset();
13118        return top;
13119    }
13120
13121    /**
13122     * @hide
13123     * @param offsetRequired
13124     */
13125    protected int getFadeHeight(boolean offsetRequired) {
13126        int padding = mPaddingTop;
13127        if (offsetRequired) padding += getTopPaddingOffset();
13128        return mBottom - mTop - mPaddingBottom - padding;
13129    }
13130
13131    /**
13132     * <p>Indicates whether this view is attached to a hardware accelerated
13133     * window or not.</p>
13134     *
13135     * <p>Even if this method returns true, it does not mean that every call
13136     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13137     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13138     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13139     * window is hardware accelerated,
13140     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13141     * return false, and this method will return true.</p>
13142     *
13143     * @return True if the view is attached to a window and the window is
13144     *         hardware accelerated; false in any other case.
13145     */
13146    public boolean isHardwareAccelerated() {
13147        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13148    }
13149
13150    /**
13151     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13152     * case of an active Animation being run on the view.
13153     */
13154    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13155            Animation a, boolean scalingRequired) {
13156        Transformation invalidationTransform;
13157        final int flags = parent.mGroupFlags;
13158        final boolean initialized = a.isInitialized();
13159        if (!initialized) {
13160            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13161            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13162            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13163            onAnimationStart();
13164        }
13165
13166        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13167        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13168            if (parent.mInvalidationTransformation == null) {
13169                parent.mInvalidationTransformation = new Transformation();
13170            }
13171            invalidationTransform = parent.mInvalidationTransformation;
13172            a.getTransformation(drawingTime, invalidationTransform, 1f);
13173        } else {
13174            invalidationTransform = parent.mChildTransformation;
13175        }
13176
13177        if (more) {
13178            if (!a.willChangeBounds()) {
13179                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13180                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13181                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13182                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13183                    // The child need to draw an animation, potentially offscreen, so
13184                    // make sure we do not cancel invalidate requests
13185                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13186                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13187                }
13188            } else {
13189                if (parent.mInvalidateRegion == null) {
13190                    parent.mInvalidateRegion = new RectF();
13191                }
13192                final RectF region = parent.mInvalidateRegion;
13193                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13194                        invalidationTransform);
13195
13196                // The child need to draw an animation, potentially offscreen, so
13197                // make sure we do not cancel invalidate requests
13198                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13199
13200                final int left = mLeft + (int) region.left;
13201                final int top = mTop + (int) region.top;
13202                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13203                        top + (int) (region.height() + .5f));
13204            }
13205        }
13206        return more;
13207    }
13208
13209    /**
13210     * This method is called by getDisplayList() when a display list is created or re-rendered.
13211     * It sets or resets the current value of all properties on that display list (resetting is
13212     * necessary when a display list is being re-created, because we need to make sure that
13213     * previously-set transform values
13214     */
13215    void setDisplayListProperties(DisplayList displayList) {
13216        if (displayList != null) {
13217            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13218            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13219            if (mParent instanceof ViewGroup) {
13220                displayList.setClipChildren(
13221                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13222            }
13223            float alpha = 1;
13224            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13225                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13226                ViewGroup parentVG = (ViewGroup) mParent;
13227                final boolean hasTransform =
13228                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13229                if (hasTransform) {
13230                    Transformation transform = parentVG.mChildTransformation;
13231                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13232                    if (transformType != Transformation.TYPE_IDENTITY) {
13233                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13234                            alpha = transform.getAlpha();
13235                        }
13236                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13237                            displayList.setStaticMatrix(transform.getMatrix());
13238                        }
13239                    }
13240                }
13241            }
13242            if (mTransformationInfo != null) {
13243                alpha *= mTransformationInfo.mAlpha;
13244                if (alpha < 1) {
13245                    final int multipliedAlpha = (int) (255 * alpha);
13246                    if (onSetAlpha(multipliedAlpha)) {
13247                        alpha = 1;
13248                    }
13249                }
13250                displayList.setTransformationInfo(alpha,
13251                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13252                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13253                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13254                        mTransformationInfo.mScaleY);
13255                if (mTransformationInfo.mCamera == null) {
13256                    mTransformationInfo.mCamera = new Camera();
13257                    mTransformationInfo.matrix3D = new Matrix();
13258                }
13259                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13260                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13261                    displayList.setPivotX(getPivotX());
13262                    displayList.setPivotY(getPivotY());
13263                }
13264            } else if (alpha < 1) {
13265                displayList.setAlpha(alpha);
13266            }
13267        }
13268    }
13269
13270    /**
13271     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13272     * This draw() method is an implementation detail and is not intended to be overridden or
13273     * to be called from anywhere else other than ViewGroup.drawChild().
13274     */
13275    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13276        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13277        boolean more = false;
13278        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13279        final int flags = parent.mGroupFlags;
13280
13281        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13282            parent.mChildTransformation.clear();
13283            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13284        }
13285
13286        Transformation transformToApply = null;
13287        boolean concatMatrix = false;
13288
13289        boolean scalingRequired = false;
13290        boolean caching;
13291        int layerType = getLayerType();
13292
13293        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13294        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13295                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13296            caching = true;
13297            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13298            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13299        } else {
13300            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13301        }
13302
13303        final Animation a = getAnimation();
13304        if (a != null) {
13305            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13306            concatMatrix = a.willChangeTransformationMatrix();
13307            if (concatMatrix) {
13308                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13309            }
13310            transformToApply = parent.mChildTransformation;
13311        } else {
13312            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM &&
13313                    mDisplayList != null) {
13314                // No longer animating: clear out old animation matrix
13315                mDisplayList.setAnimationMatrix(null);
13316                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13317            }
13318            if (!useDisplayListProperties &&
13319                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13320                final boolean hasTransform =
13321                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13322                if (hasTransform) {
13323                    final int transformType = parent.mChildTransformation.getTransformationType();
13324                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13325                            parent.mChildTransformation : null;
13326                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13327                }
13328            }
13329        }
13330
13331        concatMatrix |= !childHasIdentityMatrix;
13332
13333        // Sets the flag as early as possible to allow draw() implementations
13334        // to call invalidate() successfully when doing animations
13335        mPrivateFlags |= PFLAG_DRAWN;
13336
13337        if (!concatMatrix &&
13338                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13339                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13340                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13341                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13342            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13343            return more;
13344        }
13345        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13346
13347        if (hardwareAccelerated) {
13348            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13349            // retain the flag's value temporarily in the mRecreateDisplayList flag
13350            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13351            mPrivateFlags &= ~PFLAG_INVALIDATED;
13352        }
13353
13354        DisplayList displayList = null;
13355        Bitmap cache = null;
13356        boolean hasDisplayList = false;
13357        if (caching) {
13358            if (!hardwareAccelerated) {
13359                if (layerType != LAYER_TYPE_NONE) {
13360                    layerType = LAYER_TYPE_SOFTWARE;
13361                    buildDrawingCache(true);
13362                }
13363                cache = getDrawingCache(true);
13364            } else {
13365                switch (layerType) {
13366                    case LAYER_TYPE_SOFTWARE:
13367                        if (useDisplayListProperties) {
13368                            hasDisplayList = canHaveDisplayList();
13369                        } else {
13370                            buildDrawingCache(true);
13371                            cache = getDrawingCache(true);
13372                        }
13373                        break;
13374                    case LAYER_TYPE_HARDWARE:
13375                        if (useDisplayListProperties) {
13376                            hasDisplayList = canHaveDisplayList();
13377                        }
13378                        break;
13379                    case LAYER_TYPE_NONE:
13380                        // Delay getting the display list until animation-driven alpha values are
13381                        // set up and possibly passed on to the view
13382                        hasDisplayList = canHaveDisplayList();
13383                        break;
13384                }
13385            }
13386        }
13387        useDisplayListProperties &= hasDisplayList;
13388        if (useDisplayListProperties) {
13389            displayList = getDisplayList();
13390            if (!displayList.isValid()) {
13391                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13392                // to getDisplayList(), the display list will be marked invalid and we should not
13393                // try to use it again.
13394                displayList = null;
13395                hasDisplayList = false;
13396                useDisplayListProperties = false;
13397            }
13398        }
13399
13400        int sx = 0;
13401        int sy = 0;
13402        if (!hasDisplayList) {
13403            computeScroll();
13404            sx = mScrollX;
13405            sy = mScrollY;
13406        }
13407
13408        final boolean hasNoCache = cache == null || hasDisplayList;
13409        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13410                layerType != LAYER_TYPE_HARDWARE;
13411
13412        int restoreTo = -1;
13413        if (!useDisplayListProperties || transformToApply != null) {
13414            restoreTo = canvas.save();
13415        }
13416        if (offsetForScroll) {
13417            canvas.translate(mLeft - sx, mTop - sy);
13418        } else {
13419            if (!useDisplayListProperties) {
13420                canvas.translate(mLeft, mTop);
13421            }
13422            if (scalingRequired) {
13423                if (useDisplayListProperties) {
13424                    // TODO: Might not need this if we put everything inside the DL
13425                    restoreTo = canvas.save();
13426                }
13427                // mAttachInfo cannot be null, otherwise scalingRequired == false
13428                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13429                canvas.scale(scale, scale);
13430            }
13431        }
13432
13433        float alpha = useDisplayListProperties ? 1 : getAlpha();
13434        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13435                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13436            if (transformToApply != null || !childHasIdentityMatrix) {
13437                int transX = 0;
13438                int transY = 0;
13439
13440                if (offsetForScroll) {
13441                    transX = -sx;
13442                    transY = -sy;
13443                }
13444
13445                if (transformToApply != null) {
13446                    if (concatMatrix) {
13447                        if (useDisplayListProperties) {
13448                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13449                        } else {
13450                            // Undo the scroll translation, apply the transformation matrix,
13451                            // then redo the scroll translate to get the correct result.
13452                            canvas.translate(-transX, -transY);
13453                            canvas.concat(transformToApply.getMatrix());
13454                            canvas.translate(transX, transY);
13455                        }
13456                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13457                    }
13458
13459                    float transformAlpha = transformToApply.getAlpha();
13460                    if (transformAlpha < 1) {
13461                        alpha *= transformAlpha;
13462                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13463                    }
13464                }
13465
13466                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13467                    canvas.translate(-transX, -transY);
13468                    canvas.concat(getMatrix());
13469                    canvas.translate(transX, transY);
13470                }
13471            }
13472
13473            // Deal with alpha if it is or used to be <1
13474            if (alpha < 1 ||
13475                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13476                if (alpha < 1) {
13477                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13478                } else {
13479                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13480                }
13481                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13482                if (hasNoCache) {
13483                    final int multipliedAlpha = (int) (255 * alpha);
13484                    if (!onSetAlpha(multipliedAlpha)) {
13485                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13486                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13487                                layerType != LAYER_TYPE_NONE) {
13488                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13489                        }
13490                        if (useDisplayListProperties) {
13491                            displayList.setAlpha(alpha * getAlpha());
13492                        } else  if (layerType == LAYER_TYPE_NONE) {
13493                            final int scrollX = hasDisplayList ? 0 : sx;
13494                            final int scrollY = hasDisplayList ? 0 : sy;
13495                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13496                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13497                        }
13498                    } else {
13499                        // Alpha is handled by the child directly, clobber the layer's alpha
13500                        mPrivateFlags |= PFLAG_ALPHA_SET;
13501                    }
13502                }
13503            }
13504        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13505            onSetAlpha(255);
13506            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13507        }
13508
13509        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13510                !useDisplayListProperties) {
13511            if (offsetForScroll) {
13512                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13513            } else {
13514                if (!scalingRequired || cache == null) {
13515                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13516                } else {
13517                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13518                }
13519            }
13520        }
13521
13522        if (!useDisplayListProperties && hasDisplayList) {
13523            displayList = getDisplayList();
13524            if (!displayList.isValid()) {
13525                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13526                // to getDisplayList(), the display list will be marked invalid and we should not
13527                // try to use it again.
13528                displayList = null;
13529                hasDisplayList = false;
13530            }
13531        }
13532
13533        if (hasNoCache) {
13534            boolean layerRendered = false;
13535            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13536                final HardwareLayer layer = getHardwareLayer();
13537                if (layer != null && layer.isValid()) {
13538                    mLayerPaint.setAlpha((int) (alpha * 255));
13539                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13540                    layerRendered = true;
13541                } else {
13542                    final int scrollX = hasDisplayList ? 0 : sx;
13543                    final int scrollY = hasDisplayList ? 0 : sy;
13544                    canvas.saveLayer(scrollX, scrollY,
13545                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13546                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13547                }
13548            }
13549
13550            if (!layerRendered) {
13551                if (!hasDisplayList) {
13552                    // Fast path for layouts with no backgrounds
13553                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13554                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13555                        dispatchDraw(canvas);
13556                    } else {
13557                        draw(canvas);
13558                    }
13559                } else {
13560                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13561                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13562                }
13563            }
13564        } else if (cache != null) {
13565            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13566            Paint cachePaint;
13567
13568            if (layerType == LAYER_TYPE_NONE) {
13569                cachePaint = parent.mCachePaint;
13570                if (cachePaint == null) {
13571                    cachePaint = new Paint();
13572                    cachePaint.setDither(false);
13573                    parent.mCachePaint = cachePaint;
13574                }
13575                if (alpha < 1) {
13576                    cachePaint.setAlpha((int) (alpha * 255));
13577                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13578                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13579                    cachePaint.setAlpha(255);
13580                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13581                }
13582            } else {
13583                cachePaint = mLayerPaint;
13584                cachePaint.setAlpha((int) (alpha * 255));
13585            }
13586            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13587        }
13588
13589        if (restoreTo >= 0) {
13590            canvas.restoreToCount(restoreTo);
13591        }
13592
13593        if (a != null && !more) {
13594            if (!hardwareAccelerated && !a.getFillAfter()) {
13595                onSetAlpha(255);
13596            }
13597            parent.finishAnimatingView(this, a);
13598        }
13599
13600        if (more && hardwareAccelerated) {
13601            // invalidation is the trigger to recreate display lists, so if we're using
13602            // display lists to render, force an invalidate to allow the animation to
13603            // continue drawing another frame
13604            parent.invalidate(true);
13605            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13606                // alpha animations should cause the child to recreate its display list
13607                invalidate(true);
13608            }
13609        }
13610
13611        mRecreateDisplayList = false;
13612
13613        return more;
13614    }
13615
13616    /**
13617     * Manually render this view (and all of its children) to the given Canvas.
13618     * The view must have already done a full layout before this function is
13619     * called.  When implementing a view, implement
13620     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13621     * If you do need to override this method, call the superclass version.
13622     *
13623     * @param canvas The Canvas to which the View is rendered.
13624     */
13625    public void draw(Canvas canvas) {
13626        final int privateFlags = mPrivateFlags;
13627        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13628                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13629        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13630
13631        /*
13632         * Draw traversal performs several drawing steps which must be executed
13633         * in the appropriate order:
13634         *
13635         *      1. Draw the background
13636         *      2. If necessary, save the canvas' layers to prepare for fading
13637         *      3. Draw view's content
13638         *      4. Draw children
13639         *      5. If necessary, draw the fading edges and restore layers
13640         *      6. Draw decorations (scrollbars for instance)
13641         */
13642
13643        // Step 1, draw the background, if needed
13644        int saveCount;
13645
13646        if (!dirtyOpaque) {
13647            final Drawable background = mBackground;
13648            if (background != null) {
13649                final int scrollX = mScrollX;
13650                final int scrollY = mScrollY;
13651
13652                if (mBackgroundSizeChanged) {
13653                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13654                    mBackgroundSizeChanged = false;
13655                }
13656
13657                if ((scrollX | scrollY) == 0) {
13658                    background.draw(canvas);
13659                } else {
13660                    canvas.translate(scrollX, scrollY);
13661                    background.draw(canvas);
13662                    canvas.translate(-scrollX, -scrollY);
13663                }
13664            }
13665        }
13666
13667        // skip step 2 & 5 if possible (common case)
13668        final int viewFlags = mViewFlags;
13669        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13670        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13671        if (!verticalEdges && !horizontalEdges) {
13672            // Step 3, draw the content
13673            if (!dirtyOpaque) onDraw(canvas);
13674
13675            // Step 4, draw the children
13676            dispatchDraw(canvas);
13677
13678            // Step 6, draw decorations (scrollbars)
13679            onDrawScrollBars(canvas);
13680
13681            // we're done...
13682            return;
13683        }
13684
13685        /*
13686         * Here we do the full fledged routine...
13687         * (this is an uncommon case where speed matters less,
13688         * this is why we repeat some of the tests that have been
13689         * done above)
13690         */
13691
13692        boolean drawTop = false;
13693        boolean drawBottom = false;
13694        boolean drawLeft = false;
13695        boolean drawRight = false;
13696
13697        float topFadeStrength = 0.0f;
13698        float bottomFadeStrength = 0.0f;
13699        float leftFadeStrength = 0.0f;
13700        float rightFadeStrength = 0.0f;
13701
13702        // Step 2, save the canvas' layers
13703        int paddingLeft = mPaddingLeft;
13704
13705        final boolean offsetRequired = isPaddingOffsetRequired();
13706        if (offsetRequired) {
13707            paddingLeft += getLeftPaddingOffset();
13708        }
13709
13710        int left = mScrollX + paddingLeft;
13711        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13712        int top = mScrollY + getFadeTop(offsetRequired);
13713        int bottom = top + getFadeHeight(offsetRequired);
13714
13715        if (offsetRequired) {
13716            right += getRightPaddingOffset();
13717            bottom += getBottomPaddingOffset();
13718        }
13719
13720        final ScrollabilityCache scrollabilityCache = mScrollCache;
13721        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13722        int length = (int) fadeHeight;
13723
13724        // clip the fade length if top and bottom fades overlap
13725        // overlapping fades produce odd-looking artifacts
13726        if (verticalEdges && (top + length > bottom - length)) {
13727            length = (bottom - top) / 2;
13728        }
13729
13730        // also clip horizontal fades if necessary
13731        if (horizontalEdges && (left + length > right - length)) {
13732            length = (right - left) / 2;
13733        }
13734
13735        if (verticalEdges) {
13736            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13737            drawTop = topFadeStrength * fadeHeight > 1.0f;
13738            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13739            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13740        }
13741
13742        if (horizontalEdges) {
13743            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13744            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13745            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13746            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13747        }
13748
13749        saveCount = canvas.getSaveCount();
13750
13751        int solidColor = getSolidColor();
13752        if (solidColor == 0) {
13753            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13754
13755            if (drawTop) {
13756                canvas.saveLayer(left, top, right, top + length, null, flags);
13757            }
13758
13759            if (drawBottom) {
13760                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13761            }
13762
13763            if (drawLeft) {
13764                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13765            }
13766
13767            if (drawRight) {
13768                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13769            }
13770        } else {
13771            scrollabilityCache.setFadeColor(solidColor);
13772        }
13773
13774        // Step 3, draw the content
13775        if (!dirtyOpaque) onDraw(canvas);
13776
13777        // Step 4, draw the children
13778        dispatchDraw(canvas);
13779
13780        // Step 5, draw the fade effect and restore layers
13781        final Paint p = scrollabilityCache.paint;
13782        final Matrix matrix = scrollabilityCache.matrix;
13783        final Shader fade = scrollabilityCache.shader;
13784
13785        if (drawTop) {
13786            matrix.setScale(1, fadeHeight * topFadeStrength);
13787            matrix.postTranslate(left, top);
13788            fade.setLocalMatrix(matrix);
13789            canvas.drawRect(left, top, right, top + length, p);
13790        }
13791
13792        if (drawBottom) {
13793            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13794            matrix.postRotate(180);
13795            matrix.postTranslate(left, bottom);
13796            fade.setLocalMatrix(matrix);
13797            canvas.drawRect(left, bottom - length, right, bottom, p);
13798        }
13799
13800        if (drawLeft) {
13801            matrix.setScale(1, fadeHeight * leftFadeStrength);
13802            matrix.postRotate(-90);
13803            matrix.postTranslate(left, top);
13804            fade.setLocalMatrix(matrix);
13805            canvas.drawRect(left, top, left + length, bottom, p);
13806        }
13807
13808        if (drawRight) {
13809            matrix.setScale(1, fadeHeight * rightFadeStrength);
13810            matrix.postRotate(90);
13811            matrix.postTranslate(right, top);
13812            fade.setLocalMatrix(matrix);
13813            canvas.drawRect(right - length, top, right, bottom, p);
13814        }
13815
13816        canvas.restoreToCount(saveCount);
13817
13818        // Step 6, draw decorations (scrollbars)
13819        onDrawScrollBars(canvas);
13820    }
13821
13822    /**
13823     * Override this if your view is known to always be drawn on top of a solid color background,
13824     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13825     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13826     * should be set to 0xFF.
13827     *
13828     * @see #setVerticalFadingEdgeEnabled(boolean)
13829     * @see #setHorizontalFadingEdgeEnabled(boolean)
13830     *
13831     * @return The known solid color background for this view, or 0 if the color may vary
13832     */
13833    @ViewDebug.ExportedProperty(category = "drawing")
13834    public int getSolidColor() {
13835        return 0;
13836    }
13837
13838    /**
13839     * Build a human readable string representation of the specified view flags.
13840     *
13841     * @param flags the view flags to convert to a string
13842     * @return a String representing the supplied flags
13843     */
13844    private static String printFlags(int flags) {
13845        String output = "";
13846        int numFlags = 0;
13847        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13848            output += "TAKES_FOCUS";
13849            numFlags++;
13850        }
13851
13852        switch (flags & VISIBILITY_MASK) {
13853        case INVISIBLE:
13854            if (numFlags > 0) {
13855                output += " ";
13856            }
13857            output += "INVISIBLE";
13858            // USELESS HERE numFlags++;
13859            break;
13860        case GONE:
13861            if (numFlags > 0) {
13862                output += " ";
13863            }
13864            output += "GONE";
13865            // USELESS HERE numFlags++;
13866            break;
13867        default:
13868            break;
13869        }
13870        return output;
13871    }
13872
13873    /**
13874     * Build a human readable string representation of the specified private
13875     * view flags.
13876     *
13877     * @param privateFlags the private view flags to convert to a string
13878     * @return a String representing the supplied flags
13879     */
13880    private static String printPrivateFlags(int privateFlags) {
13881        String output = "";
13882        int numFlags = 0;
13883
13884        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
13885            output += "WANTS_FOCUS";
13886            numFlags++;
13887        }
13888
13889        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
13890            if (numFlags > 0) {
13891                output += " ";
13892            }
13893            output += "FOCUSED";
13894            numFlags++;
13895        }
13896
13897        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
13898            if (numFlags > 0) {
13899                output += " ";
13900            }
13901            output += "SELECTED";
13902            numFlags++;
13903        }
13904
13905        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
13906            if (numFlags > 0) {
13907                output += " ";
13908            }
13909            output += "IS_ROOT_NAMESPACE";
13910            numFlags++;
13911        }
13912
13913        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
13914            if (numFlags > 0) {
13915                output += " ";
13916            }
13917            output += "HAS_BOUNDS";
13918            numFlags++;
13919        }
13920
13921        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
13922            if (numFlags > 0) {
13923                output += " ";
13924            }
13925            output += "DRAWN";
13926            // USELESS HERE numFlags++;
13927        }
13928        return output;
13929    }
13930
13931    /**
13932     * <p>Indicates whether or not this view's layout will be requested during
13933     * the next hierarchy layout pass.</p>
13934     *
13935     * @return true if the layout will be forced during next layout pass
13936     */
13937    public boolean isLayoutRequested() {
13938        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
13939    }
13940
13941    /**
13942     * Return true if o is a ViewGroup that is laying out using optical bounds.
13943     * @hide
13944     */
13945    public static boolean isLayoutModeOptical(Object o) {
13946        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
13947    }
13948
13949    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
13950        Insets parentInsets = mParent instanceof View ?
13951                ((View) mParent).getOpticalInsets() : Insets.NONE;
13952        Insets childInsets = getOpticalInsets();
13953        return setFrame(
13954                left   + parentInsets.left - childInsets.left,
13955                top    + parentInsets.top  - childInsets.top,
13956                right  + parentInsets.left + childInsets.right,
13957                bottom + parentInsets.top  + childInsets.bottom);
13958    }
13959
13960    /**
13961     * Assign a size and position to a view and all of its
13962     * descendants
13963     *
13964     * <p>This is the second phase of the layout mechanism.
13965     * (The first is measuring). In this phase, each parent calls
13966     * layout on all of its children to position them.
13967     * This is typically done using the child measurements
13968     * that were stored in the measure pass().</p>
13969     *
13970     * <p>Derived classes should not override this method.
13971     * Derived classes with children should override
13972     * onLayout. In that method, they should
13973     * call layout on each of their children.</p>
13974     *
13975     * @param l Left position, relative to parent
13976     * @param t Top position, relative to parent
13977     * @param r Right position, relative to parent
13978     * @param b Bottom position, relative to parent
13979     */
13980    @SuppressWarnings({"unchecked"})
13981    public void layout(int l, int t, int r, int b) {
13982        int oldL = mLeft;
13983        int oldT = mTop;
13984        int oldB = mBottom;
13985        int oldR = mRight;
13986        boolean changed = isLayoutModeOptical(mParent) ?
13987                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
13988        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
13989            onLayout(changed, l, t, r, b);
13990            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
13991
13992            ListenerInfo li = mListenerInfo;
13993            if (li != null && li.mOnLayoutChangeListeners != null) {
13994                ArrayList<OnLayoutChangeListener> listenersCopy =
13995                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13996                int numListeners = listenersCopy.size();
13997                for (int i = 0; i < numListeners; ++i) {
13998                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13999                }
14000            }
14001        }
14002        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14003    }
14004
14005    /**
14006     * Called from layout when this view should
14007     * assign a size and position to each of its children.
14008     *
14009     * Derived classes with children should override
14010     * this method and call layout on each of
14011     * their children.
14012     * @param changed This is a new size or position for this view
14013     * @param left Left position, relative to parent
14014     * @param top Top position, relative to parent
14015     * @param right Right position, relative to parent
14016     * @param bottom Bottom position, relative to parent
14017     */
14018    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14019    }
14020
14021    /**
14022     * Assign a size and position to this view.
14023     *
14024     * This is called from layout.
14025     *
14026     * @param left Left position, relative to parent
14027     * @param top Top position, relative to parent
14028     * @param right Right position, relative to parent
14029     * @param bottom Bottom position, relative to parent
14030     * @return true if the new size and position are different than the
14031     *         previous ones
14032     * {@hide}
14033     */
14034    protected boolean setFrame(int left, int top, int right, int bottom) {
14035        boolean changed = false;
14036
14037        if (DBG) {
14038            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14039                    + right + "," + bottom + ")");
14040        }
14041
14042        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14043            changed = true;
14044
14045            // Remember our drawn bit
14046            int drawn = mPrivateFlags & PFLAG_DRAWN;
14047
14048            int oldWidth = mRight - mLeft;
14049            int oldHeight = mBottom - mTop;
14050            int newWidth = right - left;
14051            int newHeight = bottom - top;
14052            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14053
14054            // Invalidate our old position
14055            invalidate(sizeChanged);
14056
14057            mLeft = left;
14058            mTop = top;
14059            mRight = right;
14060            mBottom = bottom;
14061            if (mDisplayList != null) {
14062                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14063            }
14064
14065            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14066
14067
14068            if (sizeChanged) {
14069                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14070                    // A change in dimension means an auto-centered pivot point changes, too
14071                    if (mTransformationInfo != null) {
14072                        mTransformationInfo.mMatrixDirty = true;
14073                    }
14074                }
14075                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14076            }
14077
14078            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14079                // If we are visible, force the DRAWN bit to on so that
14080                // this invalidate will go through (at least to our parent).
14081                // This is because someone may have invalidated this view
14082                // before this call to setFrame came in, thereby clearing
14083                // the DRAWN bit.
14084                mPrivateFlags |= PFLAG_DRAWN;
14085                invalidate(sizeChanged);
14086                // parent display list may need to be recreated based on a change in the bounds
14087                // of any child
14088                invalidateParentCaches();
14089            }
14090
14091            // Reset drawn bit to original value (invalidate turns it off)
14092            mPrivateFlags |= drawn;
14093
14094            mBackgroundSizeChanged = true;
14095        }
14096        return changed;
14097    }
14098
14099    /**
14100     * Finalize inflating a view from XML.  This is called as the last phase
14101     * of inflation, after all child views have been added.
14102     *
14103     * <p>Even if the subclass overrides onFinishInflate, they should always be
14104     * sure to call the super method, so that we get called.
14105     */
14106    protected void onFinishInflate() {
14107    }
14108
14109    /**
14110     * Returns the resources associated with this view.
14111     *
14112     * @return Resources object.
14113     */
14114    public Resources getResources() {
14115        return mResources;
14116    }
14117
14118    /**
14119     * Invalidates the specified Drawable.
14120     *
14121     * @param drawable the drawable to invalidate
14122     */
14123    public void invalidateDrawable(Drawable drawable) {
14124        if (verifyDrawable(drawable)) {
14125            final Rect dirty = drawable.getBounds();
14126            final int scrollX = mScrollX;
14127            final int scrollY = mScrollY;
14128
14129            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14130                    dirty.right + scrollX, dirty.bottom + scrollY);
14131        }
14132    }
14133
14134    /**
14135     * Schedules an action on a drawable to occur at a specified time.
14136     *
14137     * @param who the recipient of the action
14138     * @param what the action to run on the drawable
14139     * @param when the time at which the action must occur. Uses the
14140     *        {@link SystemClock#uptimeMillis} timebase.
14141     */
14142    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14143        if (verifyDrawable(who) && what != null) {
14144            final long delay = when - SystemClock.uptimeMillis();
14145            if (mAttachInfo != null) {
14146                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14147                        Choreographer.CALLBACK_ANIMATION, what, who,
14148                        Choreographer.subtractFrameDelay(delay));
14149            } else {
14150                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14151            }
14152        }
14153    }
14154
14155    /**
14156     * Cancels a scheduled action on a drawable.
14157     *
14158     * @param who the recipient of the action
14159     * @param what the action to cancel
14160     */
14161    public void unscheduleDrawable(Drawable who, Runnable what) {
14162        if (verifyDrawable(who) && what != null) {
14163            if (mAttachInfo != null) {
14164                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14165                        Choreographer.CALLBACK_ANIMATION, what, who);
14166            } else {
14167                ViewRootImpl.getRunQueue().removeCallbacks(what);
14168            }
14169        }
14170    }
14171
14172    /**
14173     * Unschedule any events associated with the given Drawable.  This can be
14174     * used when selecting a new Drawable into a view, so that the previous
14175     * one is completely unscheduled.
14176     *
14177     * @param who The Drawable to unschedule.
14178     *
14179     * @see #drawableStateChanged
14180     */
14181    public void unscheduleDrawable(Drawable who) {
14182        if (mAttachInfo != null && who != null) {
14183            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14184                    Choreographer.CALLBACK_ANIMATION, null, who);
14185        }
14186    }
14187
14188    /**
14189     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14190     * that the View directionality can and will be resolved before its Drawables.
14191     *
14192     * Will call {@link View#onResolveDrawables} when resolution is done.
14193     *
14194     * @hide
14195     */
14196    public void resolveDrawables() {
14197        if (mBackground != null) {
14198            mBackground.setLayoutDirection(getLayoutDirection());
14199        }
14200        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14201        onResolveDrawables(getLayoutDirection());
14202    }
14203
14204    /**
14205     * Called when layout direction has been resolved.
14206     *
14207     * The default implementation does nothing.
14208     *
14209     * @param layoutDirection The resolved layout direction.
14210     *
14211     * @see #LAYOUT_DIRECTION_LTR
14212     * @see #LAYOUT_DIRECTION_RTL
14213     *
14214     * @hide
14215     */
14216    public void onResolveDrawables(int layoutDirection) {
14217    }
14218
14219    private void resetResolvedDrawables() {
14220        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14221    }
14222
14223    private boolean isDrawablesResolved() {
14224        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14225    }
14226
14227    /**
14228     * If your view subclass is displaying its own Drawable objects, it should
14229     * override this function and return true for any Drawable it is
14230     * displaying.  This allows animations for those drawables to be
14231     * scheduled.
14232     *
14233     * <p>Be sure to call through to the super class when overriding this
14234     * function.
14235     *
14236     * @param who The Drawable to verify.  Return true if it is one you are
14237     *            displaying, else return the result of calling through to the
14238     *            super class.
14239     *
14240     * @return boolean If true than the Drawable is being displayed in the
14241     *         view; else false and it is not allowed to animate.
14242     *
14243     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14244     * @see #drawableStateChanged()
14245     */
14246    protected boolean verifyDrawable(Drawable who) {
14247        return who == mBackground;
14248    }
14249
14250    /**
14251     * This function is called whenever the state of the view changes in such
14252     * a way that it impacts the state of drawables being shown.
14253     *
14254     * <p>Be sure to call through to the superclass when overriding this
14255     * function.
14256     *
14257     * @see Drawable#setState(int[])
14258     */
14259    protected void drawableStateChanged() {
14260        Drawable d = mBackground;
14261        if (d != null && d.isStateful()) {
14262            d.setState(getDrawableState());
14263        }
14264    }
14265
14266    /**
14267     * Call this to force a view to update its drawable state. This will cause
14268     * drawableStateChanged to be called on this view. Views that are interested
14269     * in the new state should call getDrawableState.
14270     *
14271     * @see #drawableStateChanged
14272     * @see #getDrawableState
14273     */
14274    public void refreshDrawableState() {
14275        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14276        drawableStateChanged();
14277
14278        ViewParent parent = mParent;
14279        if (parent != null) {
14280            parent.childDrawableStateChanged(this);
14281        }
14282    }
14283
14284    /**
14285     * Return an array of resource IDs of the drawable states representing the
14286     * current state of the view.
14287     *
14288     * @return The current drawable state
14289     *
14290     * @see Drawable#setState(int[])
14291     * @see #drawableStateChanged()
14292     * @see #onCreateDrawableState(int)
14293     */
14294    public final int[] getDrawableState() {
14295        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14296            return mDrawableState;
14297        } else {
14298            mDrawableState = onCreateDrawableState(0);
14299            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14300            return mDrawableState;
14301        }
14302    }
14303
14304    /**
14305     * Generate the new {@link android.graphics.drawable.Drawable} state for
14306     * this view. This is called by the view
14307     * system when the cached Drawable state is determined to be invalid.  To
14308     * retrieve the current state, you should use {@link #getDrawableState}.
14309     *
14310     * @param extraSpace if non-zero, this is the number of extra entries you
14311     * would like in the returned array in which you can place your own
14312     * states.
14313     *
14314     * @return Returns an array holding the current {@link Drawable} state of
14315     * the view.
14316     *
14317     * @see #mergeDrawableStates(int[], int[])
14318     */
14319    protected int[] onCreateDrawableState(int extraSpace) {
14320        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14321                mParent instanceof View) {
14322            return ((View) mParent).onCreateDrawableState(extraSpace);
14323        }
14324
14325        int[] drawableState;
14326
14327        int privateFlags = mPrivateFlags;
14328
14329        int viewStateIndex = 0;
14330        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14331        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14332        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14333        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14334        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14335        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14336        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14337                HardwareRenderer.isAvailable()) {
14338            // This is set if HW acceleration is requested, even if the current
14339            // process doesn't allow it.  This is just to allow app preview
14340            // windows to better match their app.
14341            viewStateIndex |= VIEW_STATE_ACCELERATED;
14342        }
14343        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14344
14345        final int privateFlags2 = mPrivateFlags2;
14346        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14347        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14348
14349        drawableState = VIEW_STATE_SETS[viewStateIndex];
14350
14351        //noinspection ConstantIfStatement
14352        if (false) {
14353            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14354            Log.i("View", toString()
14355                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14356                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14357                    + " fo=" + hasFocus()
14358                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14359                    + " wf=" + hasWindowFocus()
14360                    + ": " + Arrays.toString(drawableState));
14361        }
14362
14363        if (extraSpace == 0) {
14364            return drawableState;
14365        }
14366
14367        final int[] fullState;
14368        if (drawableState != null) {
14369            fullState = new int[drawableState.length + extraSpace];
14370            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14371        } else {
14372            fullState = new int[extraSpace];
14373        }
14374
14375        return fullState;
14376    }
14377
14378    /**
14379     * Merge your own state values in <var>additionalState</var> into the base
14380     * state values <var>baseState</var> that were returned by
14381     * {@link #onCreateDrawableState(int)}.
14382     *
14383     * @param baseState The base state values returned by
14384     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14385     * own additional state values.
14386     *
14387     * @param additionalState The additional state values you would like
14388     * added to <var>baseState</var>; this array is not modified.
14389     *
14390     * @return As a convenience, the <var>baseState</var> array you originally
14391     * passed into the function is returned.
14392     *
14393     * @see #onCreateDrawableState(int)
14394     */
14395    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14396        final int N = baseState.length;
14397        int i = N - 1;
14398        while (i >= 0 && baseState[i] == 0) {
14399            i--;
14400        }
14401        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14402        return baseState;
14403    }
14404
14405    /**
14406     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14407     * on all Drawable objects associated with this view.
14408     */
14409    public void jumpDrawablesToCurrentState() {
14410        if (mBackground != null) {
14411            mBackground.jumpToCurrentState();
14412        }
14413    }
14414
14415    /**
14416     * Sets the background color for this view.
14417     * @param color the color of the background
14418     */
14419    @RemotableViewMethod
14420    public void setBackgroundColor(int color) {
14421        if (mBackground instanceof ColorDrawable) {
14422            ((ColorDrawable) mBackground.mutate()).setColor(color);
14423            computeOpaqueFlags();
14424        } else {
14425            setBackground(new ColorDrawable(color));
14426        }
14427    }
14428
14429    /**
14430     * Set the background to a given resource. The resource should refer to
14431     * a Drawable object or 0 to remove the background.
14432     * @param resid The identifier of the resource.
14433     *
14434     * @attr ref android.R.styleable#View_background
14435     */
14436    @RemotableViewMethod
14437    public void setBackgroundResource(int resid) {
14438        if (resid != 0 && resid == mBackgroundResource) {
14439            return;
14440        }
14441
14442        Drawable d= null;
14443        if (resid != 0) {
14444            d = mResources.getDrawable(resid);
14445        }
14446        setBackground(d);
14447
14448        mBackgroundResource = resid;
14449    }
14450
14451    /**
14452     * Set the background to a given Drawable, or remove the background. If the
14453     * background has padding, this View's padding is set to the background's
14454     * padding. However, when a background is removed, this View's padding isn't
14455     * touched. If setting the padding is desired, please use
14456     * {@link #setPadding(int, int, int, int)}.
14457     *
14458     * @param background The Drawable to use as the background, or null to remove the
14459     *        background
14460     */
14461    public void setBackground(Drawable background) {
14462        //noinspection deprecation
14463        setBackgroundDrawable(background);
14464    }
14465
14466    /**
14467     * @deprecated use {@link #setBackground(Drawable)} instead
14468     */
14469    @Deprecated
14470    public void setBackgroundDrawable(Drawable background) {
14471        computeOpaqueFlags();
14472
14473        if (background == mBackground) {
14474            return;
14475        }
14476
14477        boolean requestLayout = false;
14478
14479        mBackgroundResource = 0;
14480
14481        /*
14482         * Regardless of whether we're setting a new background or not, we want
14483         * to clear the previous drawable.
14484         */
14485        if (mBackground != null) {
14486            mBackground.setCallback(null);
14487            unscheduleDrawable(mBackground);
14488        }
14489
14490        if (background != null) {
14491            Rect padding = sThreadLocal.get();
14492            if (padding == null) {
14493                padding = new Rect();
14494                sThreadLocal.set(padding);
14495            }
14496            resetResolvedDrawables();
14497            background.setLayoutDirection(getLayoutDirection());
14498            if (background.getPadding(padding)) {
14499                resetResolvedPadding();
14500                switch (background.getLayoutDirection()) {
14501                    case LAYOUT_DIRECTION_RTL:
14502                        mUserPaddingLeftInitial = padding.right;
14503                        mUserPaddingRightInitial = padding.left;
14504                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14505                        break;
14506                    case LAYOUT_DIRECTION_LTR:
14507                    default:
14508                        mUserPaddingLeftInitial = padding.left;
14509                        mUserPaddingRightInitial = padding.right;
14510                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14511                }
14512            }
14513
14514            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14515            // if it has a different minimum size, we should layout again
14516            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14517                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14518                requestLayout = true;
14519            }
14520
14521            background.setCallback(this);
14522            if (background.isStateful()) {
14523                background.setState(getDrawableState());
14524            }
14525            background.setVisible(getVisibility() == VISIBLE, false);
14526            mBackground = background;
14527
14528            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14529                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14530                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14531                requestLayout = true;
14532            }
14533        } else {
14534            /* Remove the background */
14535            mBackground = null;
14536
14537            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14538                /*
14539                 * This view ONLY drew the background before and we're removing
14540                 * the background, so now it won't draw anything
14541                 * (hence we SKIP_DRAW)
14542                 */
14543                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14544                mPrivateFlags |= PFLAG_SKIP_DRAW;
14545            }
14546
14547            /*
14548             * When the background is set, we try to apply its padding to this
14549             * View. When the background is removed, we don't touch this View's
14550             * padding. This is noted in the Javadocs. Hence, we don't need to
14551             * requestLayout(), the invalidate() below is sufficient.
14552             */
14553
14554            // The old background's minimum size could have affected this
14555            // View's layout, so let's requestLayout
14556            requestLayout = true;
14557        }
14558
14559        computeOpaqueFlags();
14560
14561        if (requestLayout) {
14562            requestLayout();
14563        }
14564
14565        mBackgroundSizeChanged = true;
14566        invalidate(true);
14567    }
14568
14569    /**
14570     * Gets the background drawable
14571     *
14572     * @return The drawable used as the background for this view, if any.
14573     *
14574     * @see #setBackground(Drawable)
14575     *
14576     * @attr ref android.R.styleable#View_background
14577     */
14578    public Drawable getBackground() {
14579        return mBackground;
14580    }
14581
14582    /**
14583     * Sets the padding. The view may add on the space required to display
14584     * the scrollbars, depending on the style and visibility of the scrollbars.
14585     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14586     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14587     * from the values set in this call.
14588     *
14589     * @attr ref android.R.styleable#View_padding
14590     * @attr ref android.R.styleable#View_paddingBottom
14591     * @attr ref android.R.styleable#View_paddingLeft
14592     * @attr ref android.R.styleable#View_paddingRight
14593     * @attr ref android.R.styleable#View_paddingTop
14594     * @param left the left padding in pixels
14595     * @param top the top padding in pixels
14596     * @param right the right padding in pixels
14597     * @param bottom the bottom padding in pixels
14598     */
14599    public void setPadding(int left, int top, int right, int bottom) {
14600        resetResolvedPadding();
14601
14602        mUserPaddingStart = UNDEFINED_PADDING;
14603        mUserPaddingEnd = UNDEFINED_PADDING;
14604
14605        mUserPaddingLeftInitial = left;
14606        mUserPaddingRightInitial = right;
14607
14608        internalSetPadding(left, top, right, bottom);
14609    }
14610
14611    /**
14612     * @hide
14613     */
14614    protected void internalSetPadding(int left, int top, int right, int bottom) {
14615        mUserPaddingLeft = left;
14616        mUserPaddingRight = right;
14617        mUserPaddingBottom = bottom;
14618
14619        final int viewFlags = mViewFlags;
14620        boolean changed = false;
14621
14622        // Common case is there are no scroll bars.
14623        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14624            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14625                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14626                        ? 0 : getVerticalScrollbarWidth();
14627                switch (mVerticalScrollbarPosition) {
14628                    case SCROLLBAR_POSITION_DEFAULT:
14629                        if (isLayoutRtl()) {
14630                            left += offset;
14631                        } else {
14632                            right += offset;
14633                        }
14634                        break;
14635                    case SCROLLBAR_POSITION_RIGHT:
14636                        right += offset;
14637                        break;
14638                    case SCROLLBAR_POSITION_LEFT:
14639                        left += offset;
14640                        break;
14641                }
14642            }
14643            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14644                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14645                        ? 0 : getHorizontalScrollbarHeight();
14646            }
14647        }
14648
14649        if (mPaddingLeft != left) {
14650            changed = true;
14651            mPaddingLeft = left;
14652        }
14653        if (mPaddingTop != top) {
14654            changed = true;
14655            mPaddingTop = top;
14656        }
14657        if (mPaddingRight != right) {
14658            changed = true;
14659            mPaddingRight = right;
14660        }
14661        if (mPaddingBottom != bottom) {
14662            changed = true;
14663            mPaddingBottom = bottom;
14664        }
14665
14666        if (changed) {
14667            requestLayout();
14668        }
14669    }
14670
14671    /**
14672     * Sets the relative padding. The view may add on the space required to display
14673     * the scrollbars, depending on the style and visibility of the scrollbars.
14674     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14675     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14676     * from the values set in this call.
14677     *
14678     * @attr ref android.R.styleable#View_padding
14679     * @attr ref android.R.styleable#View_paddingBottom
14680     * @attr ref android.R.styleable#View_paddingStart
14681     * @attr ref android.R.styleable#View_paddingEnd
14682     * @attr ref android.R.styleable#View_paddingTop
14683     * @param start the start padding in pixels
14684     * @param top the top padding in pixels
14685     * @param end the end padding in pixels
14686     * @param bottom the bottom padding in pixels
14687     */
14688    public void setPaddingRelative(int start, int top, int end, int bottom) {
14689        resetResolvedPadding();
14690
14691        mUserPaddingStart = start;
14692        mUserPaddingEnd = end;
14693
14694        switch(getLayoutDirection()) {
14695            case LAYOUT_DIRECTION_RTL:
14696                mUserPaddingLeftInitial = end;
14697                mUserPaddingRightInitial = start;
14698                internalSetPadding(end, top, start, bottom);
14699                break;
14700            case LAYOUT_DIRECTION_LTR:
14701            default:
14702                mUserPaddingLeftInitial = start;
14703                mUserPaddingRightInitial = end;
14704                internalSetPadding(start, top, end, bottom);
14705        }
14706    }
14707
14708    /**
14709     * Returns the top padding of this view.
14710     *
14711     * @return the top padding in pixels
14712     */
14713    public int getPaddingTop() {
14714        return mPaddingTop;
14715    }
14716
14717    /**
14718     * Returns the bottom padding of this view. If there are inset and enabled
14719     * scrollbars, this value may include the space required to display the
14720     * scrollbars as well.
14721     *
14722     * @return the bottom padding in pixels
14723     */
14724    public int getPaddingBottom() {
14725        return mPaddingBottom;
14726    }
14727
14728    /**
14729     * Returns the left padding of this view. If there are inset and enabled
14730     * scrollbars, this value may include the space required to display the
14731     * scrollbars as well.
14732     *
14733     * @return the left padding in pixels
14734     */
14735    public int getPaddingLeft() {
14736        if (!isPaddingResolved()) {
14737            resolvePadding();
14738        }
14739        return mPaddingLeft;
14740    }
14741
14742    /**
14743     * Returns the start padding of this view depending on its resolved layout direction.
14744     * If there are inset and enabled scrollbars, this value may include the space
14745     * required to display the scrollbars as well.
14746     *
14747     * @return the start padding in pixels
14748     */
14749    public int getPaddingStart() {
14750        if (!isPaddingResolved()) {
14751            resolvePadding();
14752        }
14753        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14754                mPaddingRight : mPaddingLeft;
14755    }
14756
14757    /**
14758     * Returns the right padding of this view. If there are inset and enabled
14759     * scrollbars, this value may include the space required to display the
14760     * scrollbars as well.
14761     *
14762     * @return the right padding in pixels
14763     */
14764    public int getPaddingRight() {
14765        if (!isPaddingResolved()) {
14766            resolvePadding();
14767        }
14768        return mPaddingRight;
14769    }
14770
14771    /**
14772     * Returns the end padding of this view depending on its resolved layout direction.
14773     * If there are inset and enabled scrollbars, this value may include the space
14774     * required to display the scrollbars as well.
14775     *
14776     * @return the end padding in pixels
14777     */
14778    public int getPaddingEnd() {
14779        if (!isPaddingResolved()) {
14780            resolvePadding();
14781        }
14782        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14783                mPaddingLeft : mPaddingRight;
14784    }
14785
14786    /**
14787     * Return if the padding as been set thru relative values
14788     * {@link #setPaddingRelative(int, int, int, int)} or thru
14789     * @attr ref android.R.styleable#View_paddingStart or
14790     * @attr ref android.R.styleable#View_paddingEnd
14791     *
14792     * @return true if the padding is relative or false if it is not.
14793     */
14794    public boolean isPaddingRelative() {
14795        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
14796    }
14797
14798    Insets computeOpticalInsets() {
14799        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
14800    }
14801
14802    /**
14803     * @hide
14804     */
14805    public Insets getOpticalInsets() {
14806        if (mLayoutInsets == null) {
14807            mLayoutInsets = computeOpticalInsets();
14808        }
14809        return mLayoutInsets;
14810    }
14811
14812    /**
14813     * Changes the selection state of this view. A view can be selected or not.
14814     * Note that selection is not the same as focus. Views are typically
14815     * selected in the context of an AdapterView like ListView or GridView;
14816     * the selected view is the view that is highlighted.
14817     *
14818     * @param selected true if the view must be selected, false otherwise
14819     */
14820    public void setSelected(boolean selected) {
14821        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
14822            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
14823            if (!selected) resetPressedState();
14824            invalidate(true);
14825            refreshDrawableState();
14826            dispatchSetSelected(selected);
14827            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14828                notifyAccessibilityStateChanged();
14829            }
14830        }
14831    }
14832
14833    /**
14834     * Dispatch setSelected to all of this View's children.
14835     *
14836     * @see #setSelected(boolean)
14837     *
14838     * @param selected The new selected state
14839     */
14840    protected void dispatchSetSelected(boolean selected) {
14841    }
14842
14843    /**
14844     * Indicates the selection state of this view.
14845     *
14846     * @return true if the view is selected, false otherwise
14847     */
14848    @ViewDebug.ExportedProperty
14849    public boolean isSelected() {
14850        return (mPrivateFlags & PFLAG_SELECTED) != 0;
14851    }
14852
14853    /**
14854     * Changes the activated state of this view. A view can be activated or not.
14855     * Note that activation is not the same as selection.  Selection is
14856     * a transient property, representing the view (hierarchy) the user is
14857     * currently interacting with.  Activation is a longer-term state that the
14858     * user can move views in and out of.  For example, in a list view with
14859     * single or multiple selection enabled, the views in the current selection
14860     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14861     * here.)  The activated state is propagated down to children of the view it
14862     * is set on.
14863     *
14864     * @param activated true if the view must be activated, false otherwise
14865     */
14866    public void setActivated(boolean activated) {
14867        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
14868            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
14869            invalidate(true);
14870            refreshDrawableState();
14871            dispatchSetActivated(activated);
14872        }
14873    }
14874
14875    /**
14876     * Dispatch setActivated to all of this View's children.
14877     *
14878     * @see #setActivated(boolean)
14879     *
14880     * @param activated The new activated state
14881     */
14882    protected void dispatchSetActivated(boolean activated) {
14883    }
14884
14885    /**
14886     * Indicates the activation state of this view.
14887     *
14888     * @return true if the view is activated, false otherwise
14889     */
14890    @ViewDebug.ExportedProperty
14891    public boolean isActivated() {
14892        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
14893    }
14894
14895    /**
14896     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14897     * observer can be used to get notifications when global events, like
14898     * layout, happen.
14899     *
14900     * The returned ViewTreeObserver observer is not guaranteed to remain
14901     * valid for the lifetime of this View. If the caller of this method keeps
14902     * a long-lived reference to ViewTreeObserver, it should always check for
14903     * the return value of {@link ViewTreeObserver#isAlive()}.
14904     *
14905     * @return The ViewTreeObserver for this view's hierarchy.
14906     */
14907    public ViewTreeObserver getViewTreeObserver() {
14908        if (mAttachInfo != null) {
14909            return mAttachInfo.mTreeObserver;
14910        }
14911        if (mFloatingTreeObserver == null) {
14912            mFloatingTreeObserver = new ViewTreeObserver();
14913        }
14914        return mFloatingTreeObserver;
14915    }
14916
14917    /**
14918     * <p>Finds the topmost view in the current view hierarchy.</p>
14919     *
14920     * @return the topmost view containing this view
14921     */
14922    public View getRootView() {
14923        if (mAttachInfo != null) {
14924            final View v = mAttachInfo.mRootView;
14925            if (v != null) {
14926                return v;
14927            }
14928        }
14929
14930        View parent = this;
14931
14932        while (parent.mParent != null && parent.mParent instanceof View) {
14933            parent = (View) parent.mParent;
14934        }
14935
14936        return parent;
14937    }
14938
14939    /**
14940     * <p>Computes the coordinates of this view on the screen. The argument
14941     * must be an array of two integers. After the method returns, the array
14942     * contains the x and y location in that order.</p>
14943     *
14944     * @param location an array of two integers in which to hold the coordinates
14945     */
14946    public void getLocationOnScreen(int[] location) {
14947        getLocationInWindow(location);
14948
14949        final AttachInfo info = mAttachInfo;
14950        if (info != null) {
14951            location[0] += info.mWindowLeft;
14952            location[1] += info.mWindowTop;
14953        }
14954    }
14955
14956    /**
14957     * <p>Computes the coordinates of this view in its window. The argument
14958     * must be an array of two integers. After the method returns, the array
14959     * contains the x and y location in that order.</p>
14960     *
14961     * @param location an array of two integers in which to hold the coordinates
14962     */
14963    public void getLocationInWindow(int[] location) {
14964        if (location == null || location.length < 2) {
14965            throw new IllegalArgumentException("location must be an array of two integers");
14966        }
14967
14968        if (mAttachInfo == null) {
14969            // When the view is not attached to a window, this method does not make sense
14970            location[0] = location[1] = 0;
14971            return;
14972        }
14973
14974        float[] position = mAttachInfo.mTmpTransformLocation;
14975        position[0] = position[1] = 0.0f;
14976
14977        if (!hasIdentityMatrix()) {
14978            getMatrix().mapPoints(position);
14979        }
14980
14981        position[0] += mLeft;
14982        position[1] += mTop;
14983
14984        ViewParent viewParent = mParent;
14985        while (viewParent instanceof View) {
14986            final View view = (View) viewParent;
14987
14988            position[0] -= view.mScrollX;
14989            position[1] -= view.mScrollY;
14990
14991            if (!view.hasIdentityMatrix()) {
14992                view.getMatrix().mapPoints(position);
14993            }
14994
14995            position[0] += view.mLeft;
14996            position[1] += view.mTop;
14997
14998            viewParent = view.mParent;
14999         }
15000
15001        if (viewParent instanceof ViewRootImpl) {
15002            // *cough*
15003            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15004            position[1] -= vr.mCurScrollY;
15005        }
15006
15007        location[0] = (int) (position[0] + 0.5f);
15008        location[1] = (int) (position[1] + 0.5f);
15009    }
15010
15011    /**
15012     * {@hide}
15013     * @param id the id of the view to be found
15014     * @return the view of the specified id, null if cannot be found
15015     */
15016    protected View findViewTraversal(int id) {
15017        if (id == mID) {
15018            return this;
15019        }
15020        return null;
15021    }
15022
15023    /**
15024     * {@hide}
15025     * @param tag the tag of the view to be found
15026     * @return the view of specified tag, null if cannot be found
15027     */
15028    protected View findViewWithTagTraversal(Object tag) {
15029        if (tag != null && tag.equals(mTag)) {
15030            return this;
15031        }
15032        return null;
15033    }
15034
15035    /**
15036     * {@hide}
15037     * @param predicate The predicate to evaluate.
15038     * @param childToSkip If not null, ignores this child during the recursive traversal.
15039     * @return The first view that matches the predicate or null.
15040     */
15041    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15042        if (predicate.apply(this)) {
15043            return this;
15044        }
15045        return null;
15046    }
15047
15048    /**
15049     * Look for a child view with the given id.  If this view has the given
15050     * id, return this view.
15051     *
15052     * @param id The id to search for.
15053     * @return The view that has the given id in the hierarchy or null
15054     */
15055    public final View findViewById(int id) {
15056        if (id < 0) {
15057            return null;
15058        }
15059        return findViewTraversal(id);
15060    }
15061
15062    /**
15063     * Finds a view by its unuque and stable accessibility id.
15064     *
15065     * @param accessibilityId The searched accessibility id.
15066     * @return The found view.
15067     */
15068    final View findViewByAccessibilityId(int accessibilityId) {
15069        if (accessibilityId < 0) {
15070            return null;
15071        }
15072        return findViewByAccessibilityIdTraversal(accessibilityId);
15073    }
15074
15075    /**
15076     * Performs the traversal to find a view by its unuque and stable accessibility id.
15077     *
15078     * <strong>Note:</strong>This method does not stop at the root namespace
15079     * boundary since the user can touch the screen at an arbitrary location
15080     * potentially crossing the root namespace bounday which will send an
15081     * accessibility event to accessibility services and they should be able
15082     * to obtain the event source. Also accessibility ids are guaranteed to be
15083     * unique in the window.
15084     *
15085     * @param accessibilityId The accessibility id.
15086     * @return The found view.
15087     */
15088    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15089        if (getAccessibilityViewId() == accessibilityId) {
15090            return this;
15091        }
15092        return null;
15093    }
15094
15095    /**
15096     * Look for a child view with the given tag.  If this view has the given
15097     * tag, return this view.
15098     *
15099     * @param tag The tag to search for, using "tag.equals(getTag())".
15100     * @return The View that has the given tag in the hierarchy or null
15101     */
15102    public final View findViewWithTag(Object tag) {
15103        if (tag == null) {
15104            return null;
15105        }
15106        return findViewWithTagTraversal(tag);
15107    }
15108
15109    /**
15110     * {@hide}
15111     * Look for a child view that matches the specified predicate.
15112     * If this view matches the predicate, return this view.
15113     *
15114     * @param predicate The predicate to evaluate.
15115     * @return The first view that matches the predicate or null.
15116     */
15117    public final View findViewByPredicate(Predicate<View> predicate) {
15118        return findViewByPredicateTraversal(predicate, null);
15119    }
15120
15121    /**
15122     * {@hide}
15123     * Look for a child view that matches the specified predicate,
15124     * starting with the specified view and its descendents and then
15125     * recusively searching the ancestors and siblings of that view
15126     * until this view is reached.
15127     *
15128     * This method is useful in cases where the predicate does not match
15129     * a single unique view (perhaps multiple views use the same id)
15130     * and we are trying to find the view that is "closest" in scope to the
15131     * starting view.
15132     *
15133     * @param start The view to start from.
15134     * @param predicate The predicate to evaluate.
15135     * @return The first view that matches the predicate or null.
15136     */
15137    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15138        View childToSkip = null;
15139        for (;;) {
15140            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15141            if (view != null || start == this) {
15142                return view;
15143            }
15144
15145            ViewParent parent = start.getParent();
15146            if (parent == null || !(parent instanceof View)) {
15147                return null;
15148            }
15149
15150            childToSkip = start;
15151            start = (View) parent;
15152        }
15153    }
15154
15155    /**
15156     * Sets the identifier for this view. The identifier does not have to be
15157     * unique in this view's hierarchy. The identifier should be a positive
15158     * number.
15159     *
15160     * @see #NO_ID
15161     * @see #getId()
15162     * @see #findViewById(int)
15163     *
15164     * @param id a number used to identify the view
15165     *
15166     * @attr ref android.R.styleable#View_id
15167     */
15168    public void setId(int id) {
15169        mID = id;
15170        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15171            mID = generateViewId();
15172        }
15173    }
15174
15175    /**
15176     * {@hide}
15177     *
15178     * @param isRoot true if the view belongs to the root namespace, false
15179     *        otherwise
15180     */
15181    public void setIsRootNamespace(boolean isRoot) {
15182        if (isRoot) {
15183            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15184        } else {
15185            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15186        }
15187    }
15188
15189    /**
15190     * {@hide}
15191     *
15192     * @return true if the view belongs to the root namespace, false otherwise
15193     */
15194    public boolean isRootNamespace() {
15195        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15196    }
15197
15198    /**
15199     * Returns this view's identifier.
15200     *
15201     * @return a positive integer used to identify the view or {@link #NO_ID}
15202     *         if the view has no ID
15203     *
15204     * @see #setId(int)
15205     * @see #findViewById(int)
15206     * @attr ref android.R.styleable#View_id
15207     */
15208    @ViewDebug.CapturedViewProperty
15209    public int getId() {
15210        return mID;
15211    }
15212
15213    /**
15214     * Returns this view's tag.
15215     *
15216     * @return the Object stored in this view as a tag
15217     *
15218     * @see #setTag(Object)
15219     * @see #getTag(int)
15220     */
15221    @ViewDebug.ExportedProperty
15222    public Object getTag() {
15223        return mTag;
15224    }
15225
15226    /**
15227     * Sets the tag associated with this view. A tag can be used to mark
15228     * a view in its hierarchy and does not have to be unique within the
15229     * hierarchy. Tags can also be used to store data within a view without
15230     * resorting to another data structure.
15231     *
15232     * @param tag an Object to tag the view with
15233     *
15234     * @see #getTag()
15235     * @see #setTag(int, Object)
15236     */
15237    public void setTag(final Object tag) {
15238        mTag = tag;
15239    }
15240
15241    /**
15242     * Returns the tag associated with this view and the specified key.
15243     *
15244     * @param key The key identifying the tag
15245     *
15246     * @return the Object stored in this view as a tag
15247     *
15248     * @see #setTag(int, Object)
15249     * @see #getTag()
15250     */
15251    public Object getTag(int key) {
15252        if (mKeyedTags != null) return mKeyedTags.get(key);
15253        return null;
15254    }
15255
15256    /**
15257     * Sets a tag associated with this view and a key. A tag can be used
15258     * to mark a view in its hierarchy and does not have to be unique within
15259     * the hierarchy. Tags can also be used to store data within a view
15260     * without resorting to another data structure.
15261     *
15262     * The specified key should be an id declared in the resources of the
15263     * application to ensure it is unique (see the <a
15264     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15265     * Keys identified as belonging to
15266     * the Android framework or not associated with any package will cause
15267     * an {@link IllegalArgumentException} to be thrown.
15268     *
15269     * @param key The key identifying the tag
15270     * @param tag An Object to tag the view with
15271     *
15272     * @throws IllegalArgumentException If they specified key is not valid
15273     *
15274     * @see #setTag(Object)
15275     * @see #getTag(int)
15276     */
15277    public void setTag(int key, final Object tag) {
15278        // If the package id is 0x00 or 0x01, it's either an undefined package
15279        // or a framework id
15280        if ((key >>> 24) < 2) {
15281            throw new IllegalArgumentException("The key must be an application-specific "
15282                    + "resource id.");
15283        }
15284
15285        setKeyedTag(key, tag);
15286    }
15287
15288    /**
15289     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15290     * framework id.
15291     *
15292     * @hide
15293     */
15294    public void setTagInternal(int key, Object tag) {
15295        if ((key >>> 24) != 0x1) {
15296            throw new IllegalArgumentException("The key must be a framework-specific "
15297                    + "resource id.");
15298        }
15299
15300        setKeyedTag(key, tag);
15301    }
15302
15303    private void setKeyedTag(int key, Object tag) {
15304        if (mKeyedTags == null) {
15305            mKeyedTags = new SparseArray<Object>();
15306        }
15307
15308        mKeyedTags.put(key, tag);
15309    }
15310
15311    /**
15312     * Prints information about this view in the log output, with the tag
15313     * {@link #VIEW_LOG_TAG}.
15314     *
15315     * @hide
15316     */
15317    public void debug() {
15318        debug(0);
15319    }
15320
15321    /**
15322     * Prints information about this view in the log output, with the tag
15323     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15324     * indentation defined by the <code>depth</code>.
15325     *
15326     * @param depth the indentation level
15327     *
15328     * @hide
15329     */
15330    protected void debug(int depth) {
15331        String output = debugIndent(depth - 1);
15332
15333        output += "+ " + this;
15334        int id = getId();
15335        if (id != -1) {
15336            output += " (id=" + id + ")";
15337        }
15338        Object tag = getTag();
15339        if (tag != null) {
15340            output += " (tag=" + tag + ")";
15341        }
15342        Log.d(VIEW_LOG_TAG, output);
15343
15344        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15345            output = debugIndent(depth) + " FOCUSED";
15346            Log.d(VIEW_LOG_TAG, output);
15347        }
15348
15349        output = debugIndent(depth);
15350        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15351                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15352                + "} ";
15353        Log.d(VIEW_LOG_TAG, output);
15354
15355        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15356                || mPaddingBottom != 0) {
15357            output = debugIndent(depth);
15358            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15359                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15360            Log.d(VIEW_LOG_TAG, output);
15361        }
15362
15363        output = debugIndent(depth);
15364        output += "mMeasureWidth=" + mMeasuredWidth +
15365                " mMeasureHeight=" + mMeasuredHeight;
15366        Log.d(VIEW_LOG_TAG, output);
15367
15368        output = debugIndent(depth);
15369        if (mLayoutParams == null) {
15370            output += "BAD! no layout params";
15371        } else {
15372            output = mLayoutParams.debug(output);
15373        }
15374        Log.d(VIEW_LOG_TAG, output);
15375
15376        output = debugIndent(depth);
15377        output += "flags={";
15378        output += View.printFlags(mViewFlags);
15379        output += "}";
15380        Log.d(VIEW_LOG_TAG, output);
15381
15382        output = debugIndent(depth);
15383        output += "privateFlags={";
15384        output += View.printPrivateFlags(mPrivateFlags);
15385        output += "}";
15386        Log.d(VIEW_LOG_TAG, output);
15387    }
15388
15389    /**
15390     * Creates a string of whitespaces used for indentation.
15391     *
15392     * @param depth the indentation level
15393     * @return a String containing (depth * 2 + 3) * 2 white spaces
15394     *
15395     * @hide
15396     */
15397    protected static String debugIndent(int depth) {
15398        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15399        for (int i = 0; i < (depth * 2) + 3; i++) {
15400            spaces.append(' ').append(' ');
15401        }
15402        return spaces.toString();
15403    }
15404
15405    /**
15406     * <p>Return the offset of the widget's text baseline from the widget's top
15407     * boundary. If this widget does not support baseline alignment, this
15408     * method returns -1. </p>
15409     *
15410     * @return the offset of the baseline within the widget's bounds or -1
15411     *         if baseline alignment is not supported
15412     */
15413    @ViewDebug.ExportedProperty(category = "layout")
15414    public int getBaseline() {
15415        return -1;
15416    }
15417
15418    /**
15419     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15420     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15421     * a layout pass.
15422     *
15423     * @return whether the view hierarchy is currently undergoing a layout pass
15424     */
15425    public boolean isInLayout() {
15426        ViewRootImpl viewRoot = getViewRootImpl();
15427        return (viewRoot != null && viewRoot.isInLayout());
15428    }
15429
15430    /**
15431     * Call this when something has changed which has invalidated the
15432     * layout of this view. This will schedule a layout pass of the view
15433     * tree. This should not be called while the view hierarchy is currently in a layout
15434     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15435     * end of the current layout pass (and then layout will run again) or after the current
15436     * frame is drawn and the next layout occurs.
15437     *
15438     * <p>Subclasses which override this method should call the superclass method to
15439     * handle possible request-during-layout errors correctly.</p>
15440     */
15441    public void requestLayout() {
15442        ViewRootImpl viewRoot = getViewRootImpl();
15443        if (viewRoot != null && viewRoot.isInLayout()) {
15444            viewRoot.requestLayoutDuringLayout(this);
15445            return;
15446        }
15447        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15448        mPrivateFlags |= PFLAG_INVALIDATED;
15449
15450        if (mParent != null && !mParent.isLayoutRequested()) {
15451            mParent.requestLayout();
15452        }
15453    }
15454
15455    /**
15456     * Forces this view to be laid out during the next layout pass.
15457     * This method does not call requestLayout() or forceLayout()
15458     * on the parent.
15459     */
15460    public void forceLayout() {
15461        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15462        mPrivateFlags |= PFLAG_INVALIDATED;
15463    }
15464
15465    /**
15466     * <p>
15467     * This is called to find out how big a view should be. The parent
15468     * supplies constraint information in the width and height parameters.
15469     * </p>
15470     *
15471     * <p>
15472     * The actual measurement work of a view is performed in
15473     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15474     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15475     * </p>
15476     *
15477     *
15478     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15479     *        parent
15480     * @param heightMeasureSpec Vertical space requirements as imposed by the
15481     *        parent
15482     *
15483     * @see #onMeasure(int, int)
15484     */
15485    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15486        boolean optical = isLayoutModeOptical(this);
15487        if (optical != isLayoutModeOptical(mParent)) {
15488            Insets insets = getOpticalInsets();
15489            int oWidth  = insets.left + insets.right;
15490            int oHeight = insets.top  + insets.bottom;
15491            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15492            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15493        }
15494        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15495                widthMeasureSpec != mOldWidthMeasureSpec ||
15496                heightMeasureSpec != mOldHeightMeasureSpec) {
15497
15498            // first clears the measured dimension flag
15499            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15500
15501            resolveRtlPropertiesIfNeeded();
15502
15503            // measure ourselves, this should set the measured dimension flag back
15504            onMeasure(widthMeasureSpec, heightMeasureSpec);
15505
15506            // flag not set, setMeasuredDimension() was not invoked, we raise
15507            // an exception to warn the developer
15508            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15509                throw new IllegalStateException("onMeasure() did not set the"
15510                        + " measured dimension by calling"
15511                        + " setMeasuredDimension()");
15512            }
15513
15514            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15515        }
15516
15517        mOldWidthMeasureSpec = widthMeasureSpec;
15518        mOldHeightMeasureSpec = heightMeasureSpec;
15519    }
15520
15521    /**
15522     * <p>
15523     * Measure the view and its content to determine the measured width and the
15524     * measured height. This method is invoked by {@link #measure(int, int)} and
15525     * should be overriden by subclasses to provide accurate and efficient
15526     * measurement of their contents.
15527     * </p>
15528     *
15529     * <p>
15530     * <strong>CONTRACT:</strong> When overriding this method, you
15531     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15532     * measured width and height of this view. Failure to do so will trigger an
15533     * <code>IllegalStateException</code>, thrown by
15534     * {@link #measure(int, int)}. Calling the superclass'
15535     * {@link #onMeasure(int, int)} is a valid use.
15536     * </p>
15537     *
15538     * <p>
15539     * The base class implementation of measure defaults to the background size,
15540     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15541     * override {@link #onMeasure(int, int)} to provide better measurements of
15542     * their content.
15543     * </p>
15544     *
15545     * <p>
15546     * If this method is overridden, it is the subclass's responsibility to make
15547     * sure the measured height and width are at least the view's minimum height
15548     * and width ({@link #getSuggestedMinimumHeight()} and
15549     * {@link #getSuggestedMinimumWidth()}).
15550     * </p>
15551     *
15552     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15553     *                         The requirements are encoded with
15554     *                         {@link android.view.View.MeasureSpec}.
15555     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15556     *                         The requirements are encoded with
15557     *                         {@link android.view.View.MeasureSpec}.
15558     *
15559     * @see #getMeasuredWidth()
15560     * @see #getMeasuredHeight()
15561     * @see #setMeasuredDimension(int, int)
15562     * @see #getSuggestedMinimumHeight()
15563     * @see #getSuggestedMinimumWidth()
15564     * @see android.view.View.MeasureSpec#getMode(int)
15565     * @see android.view.View.MeasureSpec#getSize(int)
15566     */
15567    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15568        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15569                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15570    }
15571
15572    /**
15573     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15574     * measured width and measured height. Failing to do so will trigger an
15575     * exception at measurement time.</p>
15576     *
15577     * @param measuredWidth The measured width of this view.  May be a complex
15578     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15579     * {@link #MEASURED_STATE_TOO_SMALL}.
15580     * @param measuredHeight The measured height of this view.  May be a complex
15581     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15582     * {@link #MEASURED_STATE_TOO_SMALL}.
15583     */
15584    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15585        boolean optical = isLayoutModeOptical(this);
15586        if (optical != isLayoutModeOptical(mParent)) {
15587            Insets insets = getOpticalInsets();
15588            int opticalWidth  = insets.left + insets.right;
15589            int opticalHeight = insets.top  + insets.bottom;
15590
15591            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
15592            measuredHeight += optical ? opticalHeight : -opticalHeight;
15593        }
15594        mMeasuredWidth = measuredWidth;
15595        mMeasuredHeight = measuredHeight;
15596
15597        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15598    }
15599
15600    /**
15601     * Merge two states as returned by {@link #getMeasuredState()}.
15602     * @param curState The current state as returned from a view or the result
15603     * of combining multiple views.
15604     * @param newState The new view state to combine.
15605     * @return Returns a new integer reflecting the combination of the two
15606     * states.
15607     */
15608    public static int combineMeasuredStates(int curState, int newState) {
15609        return curState | newState;
15610    }
15611
15612    /**
15613     * Version of {@link #resolveSizeAndState(int, int, int)}
15614     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15615     */
15616    public static int resolveSize(int size, int measureSpec) {
15617        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15618    }
15619
15620    /**
15621     * Utility to reconcile a desired size and state, with constraints imposed
15622     * by a MeasureSpec.  Will take the desired size, unless a different size
15623     * is imposed by the constraints.  The returned value is a compound integer,
15624     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15625     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15626     * size is smaller than the size the view wants to be.
15627     *
15628     * @param size How big the view wants to be
15629     * @param measureSpec Constraints imposed by the parent
15630     * @return Size information bit mask as defined by
15631     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15632     */
15633    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15634        int result = size;
15635        int specMode = MeasureSpec.getMode(measureSpec);
15636        int specSize =  MeasureSpec.getSize(measureSpec);
15637        switch (specMode) {
15638        case MeasureSpec.UNSPECIFIED:
15639            result = size;
15640            break;
15641        case MeasureSpec.AT_MOST:
15642            if (specSize < size) {
15643                result = specSize | MEASURED_STATE_TOO_SMALL;
15644            } else {
15645                result = size;
15646            }
15647            break;
15648        case MeasureSpec.EXACTLY:
15649            result = specSize;
15650            break;
15651        }
15652        return result | (childMeasuredState&MEASURED_STATE_MASK);
15653    }
15654
15655    /**
15656     * Utility to return a default size. Uses the supplied size if the
15657     * MeasureSpec imposed no constraints. Will get larger if allowed
15658     * by the MeasureSpec.
15659     *
15660     * @param size Default size for this view
15661     * @param measureSpec Constraints imposed by the parent
15662     * @return The size this view should be.
15663     */
15664    public static int getDefaultSize(int size, int measureSpec) {
15665        int result = size;
15666        int specMode = MeasureSpec.getMode(measureSpec);
15667        int specSize = MeasureSpec.getSize(measureSpec);
15668
15669        switch (specMode) {
15670        case MeasureSpec.UNSPECIFIED:
15671            result = size;
15672            break;
15673        case MeasureSpec.AT_MOST:
15674        case MeasureSpec.EXACTLY:
15675            result = specSize;
15676            break;
15677        }
15678        return result;
15679    }
15680
15681    /**
15682     * Returns the suggested minimum height that the view should use. This
15683     * returns the maximum of the view's minimum height
15684     * and the background's minimum height
15685     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15686     * <p>
15687     * When being used in {@link #onMeasure(int, int)}, the caller should still
15688     * ensure the returned height is within the requirements of the parent.
15689     *
15690     * @return The suggested minimum height of the view.
15691     */
15692    protected int getSuggestedMinimumHeight() {
15693        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15694
15695    }
15696
15697    /**
15698     * Returns the suggested minimum width that the view should use. This
15699     * returns the maximum of the view's minimum width)
15700     * and the background's minimum width
15701     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15702     * <p>
15703     * When being used in {@link #onMeasure(int, int)}, the caller should still
15704     * ensure the returned width is within the requirements of the parent.
15705     *
15706     * @return The suggested minimum width of the view.
15707     */
15708    protected int getSuggestedMinimumWidth() {
15709        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15710    }
15711
15712    /**
15713     * Returns the minimum height of the view.
15714     *
15715     * @return the minimum height the view will try to be.
15716     *
15717     * @see #setMinimumHeight(int)
15718     *
15719     * @attr ref android.R.styleable#View_minHeight
15720     */
15721    public int getMinimumHeight() {
15722        return mMinHeight;
15723    }
15724
15725    /**
15726     * Sets the minimum height of the view. It is not guaranteed the view will
15727     * be able to achieve this minimum height (for example, if its parent layout
15728     * constrains it with less available height).
15729     *
15730     * @param minHeight The minimum height the view will try to be.
15731     *
15732     * @see #getMinimumHeight()
15733     *
15734     * @attr ref android.R.styleable#View_minHeight
15735     */
15736    public void setMinimumHeight(int minHeight) {
15737        mMinHeight = minHeight;
15738        requestLayout();
15739    }
15740
15741    /**
15742     * Returns the minimum width of the view.
15743     *
15744     * @return the minimum width the view will try to be.
15745     *
15746     * @see #setMinimumWidth(int)
15747     *
15748     * @attr ref android.R.styleable#View_minWidth
15749     */
15750    public int getMinimumWidth() {
15751        return mMinWidth;
15752    }
15753
15754    /**
15755     * Sets the minimum width of the view. It is not guaranteed the view will
15756     * be able to achieve this minimum width (for example, if its parent layout
15757     * constrains it with less available width).
15758     *
15759     * @param minWidth The minimum width the view will try to be.
15760     *
15761     * @see #getMinimumWidth()
15762     *
15763     * @attr ref android.R.styleable#View_minWidth
15764     */
15765    public void setMinimumWidth(int minWidth) {
15766        mMinWidth = minWidth;
15767        requestLayout();
15768
15769    }
15770
15771    /**
15772     * Get the animation currently associated with this view.
15773     *
15774     * @return The animation that is currently playing or
15775     *         scheduled to play for this view.
15776     */
15777    public Animation getAnimation() {
15778        return mCurrentAnimation;
15779    }
15780
15781    /**
15782     * Start the specified animation now.
15783     *
15784     * @param animation the animation to start now
15785     */
15786    public void startAnimation(Animation animation) {
15787        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15788        setAnimation(animation);
15789        invalidateParentCaches();
15790        invalidate(true);
15791    }
15792
15793    /**
15794     * Cancels any animations for this view.
15795     */
15796    public void clearAnimation() {
15797        if (mCurrentAnimation != null) {
15798            mCurrentAnimation.detach();
15799        }
15800        mCurrentAnimation = null;
15801        invalidateParentIfNeeded();
15802    }
15803
15804    /**
15805     * Sets the next animation to play for this view.
15806     * If you want the animation to play immediately, use
15807     * {@link #startAnimation(android.view.animation.Animation)} instead.
15808     * This method provides allows fine-grained
15809     * control over the start time and invalidation, but you
15810     * must make sure that 1) the animation has a start time set, and
15811     * 2) the view's parent (which controls animations on its children)
15812     * will be invalidated when the animation is supposed to
15813     * start.
15814     *
15815     * @param animation The next animation, or null.
15816     */
15817    public void setAnimation(Animation animation) {
15818        mCurrentAnimation = animation;
15819
15820        if (animation != null) {
15821            // If the screen is off assume the animation start time is now instead of
15822            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15823            // would cause the animation to start when the screen turns back on
15824            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15825                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15826                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15827            }
15828            animation.reset();
15829        }
15830    }
15831
15832    /**
15833     * Invoked by a parent ViewGroup to notify the start of the animation
15834     * currently associated with this view. If you override this method,
15835     * always call super.onAnimationStart();
15836     *
15837     * @see #setAnimation(android.view.animation.Animation)
15838     * @see #getAnimation()
15839     */
15840    protected void onAnimationStart() {
15841        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
15842    }
15843
15844    /**
15845     * Invoked by a parent ViewGroup to notify the end of the animation
15846     * currently associated with this view. If you override this method,
15847     * always call super.onAnimationEnd();
15848     *
15849     * @see #setAnimation(android.view.animation.Animation)
15850     * @see #getAnimation()
15851     */
15852    protected void onAnimationEnd() {
15853        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
15854    }
15855
15856    /**
15857     * Invoked if there is a Transform that involves alpha. Subclass that can
15858     * draw themselves with the specified alpha should return true, and then
15859     * respect that alpha when their onDraw() is called. If this returns false
15860     * then the view may be redirected to draw into an offscreen buffer to
15861     * fulfill the request, which will look fine, but may be slower than if the
15862     * subclass handles it internally. The default implementation returns false.
15863     *
15864     * @param alpha The alpha (0..255) to apply to the view's drawing
15865     * @return true if the view can draw with the specified alpha.
15866     */
15867    protected boolean onSetAlpha(int alpha) {
15868        return false;
15869    }
15870
15871    /**
15872     * This is used by the RootView to perform an optimization when
15873     * the view hierarchy contains one or several SurfaceView.
15874     * SurfaceView is always considered transparent, but its children are not,
15875     * therefore all View objects remove themselves from the global transparent
15876     * region (passed as a parameter to this function).
15877     *
15878     * @param region The transparent region for this ViewAncestor (window).
15879     *
15880     * @return Returns true if the effective visibility of the view at this
15881     * point is opaque, regardless of the transparent region; returns false
15882     * if it is possible for underlying windows to be seen behind the view.
15883     *
15884     * {@hide}
15885     */
15886    public boolean gatherTransparentRegion(Region region) {
15887        final AttachInfo attachInfo = mAttachInfo;
15888        if (region != null && attachInfo != null) {
15889            final int pflags = mPrivateFlags;
15890            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
15891                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15892                // remove it from the transparent region.
15893                final int[] location = attachInfo.mTransparentLocation;
15894                getLocationInWindow(location);
15895                region.op(location[0], location[1], location[0] + mRight - mLeft,
15896                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15897            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15898                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15899                // exists, so we remove the background drawable's non-transparent
15900                // parts from this transparent region.
15901                applyDrawableToTransparentRegion(mBackground, region);
15902            }
15903        }
15904        return true;
15905    }
15906
15907    /**
15908     * Play a sound effect for this view.
15909     *
15910     * <p>The framework will play sound effects for some built in actions, such as
15911     * clicking, but you may wish to play these effects in your widget,
15912     * for instance, for internal navigation.
15913     *
15914     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15915     * {@link #isSoundEffectsEnabled()} is true.
15916     *
15917     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15918     */
15919    public void playSoundEffect(int soundConstant) {
15920        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15921            return;
15922        }
15923        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15924    }
15925
15926    /**
15927     * BZZZTT!!1!
15928     *
15929     * <p>Provide haptic feedback to the user for this view.
15930     *
15931     * <p>The framework will provide haptic feedback for some built in actions,
15932     * such as long presses, but you may wish to provide feedback for your
15933     * own widget.
15934     *
15935     * <p>The feedback will only be performed if
15936     * {@link #isHapticFeedbackEnabled()} is true.
15937     *
15938     * @param feedbackConstant One of the constants defined in
15939     * {@link HapticFeedbackConstants}
15940     */
15941    public boolean performHapticFeedback(int feedbackConstant) {
15942        return performHapticFeedback(feedbackConstant, 0);
15943    }
15944
15945    /**
15946     * BZZZTT!!1!
15947     *
15948     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15949     *
15950     * @param feedbackConstant One of the constants defined in
15951     * {@link HapticFeedbackConstants}
15952     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15953     */
15954    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15955        if (mAttachInfo == null) {
15956            return false;
15957        }
15958        //noinspection SimplifiableIfStatement
15959        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15960                && !isHapticFeedbackEnabled()) {
15961            return false;
15962        }
15963        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15964                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15965    }
15966
15967    /**
15968     * Request that the visibility of the status bar or other screen/window
15969     * decorations be changed.
15970     *
15971     * <p>This method is used to put the over device UI into temporary modes
15972     * where the user's attention is focused more on the application content,
15973     * by dimming or hiding surrounding system affordances.  This is typically
15974     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15975     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15976     * to be placed behind the action bar (and with these flags other system
15977     * affordances) so that smooth transitions between hiding and showing them
15978     * can be done.
15979     *
15980     * <p>Two representative examples of the use of system UI visibility is
15981     * implementing a content browsing application (like a magazine reader)
15982     * and a video playing application.
15983     *
15984     * <p>The first code shows a typical implementation of a View in a content
15985     * browsing application.  In this implementation, the application goes
15986     * into a content-oriented mode by hiding the status bar and action bar,
15987     * and putting the navigation elements into lights out mode.  The user can
15988     * then interact with content while in this mode.  Such an application should
15989     * provide an easy way for the user to toggle out of the mode (such as to
15990     * check information in the status bar or access notifications).  In the
15991     * implementation here, this is done simply by tapping on the content.
15992     *
15993     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15994     *      content}
15995     *
15996     * <p>This second code sample shows a typical implementation of a View
15997     * in a video playing application.  In this situation, while the video is
15998     * playing the application would like to go into a complete full-screen mode,
15999     * to use as much of the display as possible for the video.  When in this state
16000     * the user can not interact with the application; the system intercepts
16001     * touching on the screen to pop the UI out of full screen mode.  See
16002     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16003     *
16004     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16005     *      content}
16006     *
16007     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16008     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16009     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16010     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16011     */
16012    public void setSystemUiVisibility(int visibility) {
16013        if (visibility != mSystemUiVisibility) {
16014            mSystemUiVisibility = visibility;
16015            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16016                mParent.recomputeViewAttributes(this);
16017            }
16018        }
16019    }
16020
16021    /**
16022     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16023     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16024     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16025     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16026     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16027     */
16028    public int getSystemUiVisibility() {
16029        return mSystemUiVisibility;
16030    }
16031
16032    /**
16033     * Returns the current system UI visibility that is currently set for
16034     * the entire window.  This is the combination of the
16035     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16036     * views in the window.
16037     */
16038    public int getWindowSystemUiVisibility() {
16039        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16040    }
16041
16042    /**
16043     * Override to find out when the window's requested system UI visibility
16044     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16045     * This is different from the callbacks recieved through
16046     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16047     * in that this is only telling you about the local request of the window,
16048     * not the actual values applied by the system.
16049     */
16050    public void onWindowSystemUiVisibilityChanged(int visible) {
16051    }
16052
16053    /**
16054     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16055     * the view hierarchy.
16056     */
16057    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16058        onWindowSystemUiVisibilityChanged(visible);
16059    }
16060
16061    /**
16062     * Set a listener to receive callbacks when the visibility of the system bar changes.
16063     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16064     */
16065    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16066        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16067        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16068            mParent.recomputeViewAttributes(this);
16069        }
16070    }
16071
16072    /**
16073     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16074     * the view hierarchy.
16075     */
16076    public void dispatchSystemUiVisibilityChanged(int visibility) {
16077        ListenerInfo li = mListenerInfo;
16078        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16079            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16080                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16081        }
16082    }
16083
16084    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16085        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16086        if (val != mSystemUiVisibility) {
16087            setSystemUiVisibility(val);
16088            return true;
16089        }
16090        return false;
16091    }
16092
16093    /** @hide */
16094    public void setDisabledSystemUiVisibility(int flags) {
16095        if (mAttachInfo != null) {
16096            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16097                mAttachInfo.mDisabledSystemUiVisibility = flags;
16098                if (mParent != null) {
16099                    mParent.recomputeViewAttributes(this);
16100                }
16101            }
16102        }
16103    }
16104
16105    /**
16106     * Creates an image that the system displays during the drag and drop
16107     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16108     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16109     * appearance as the given View. The default also positions the center of the drag shadow
16110     * directly under the touch point. If no View is provided (the constructor with no parameters
16111     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16112     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16113     * default is an invisible drag shadow.
16114     * <p>
16115     * You are not required to use the View you provide to the constructor as the basis of the
16116     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16117     * anything you want as the drag shadow.
16118     * </p>
16119     * <p>
16120     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16121     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16122     *  size and position of the drag shadow. It uses this data to construct a
16123     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16124     *  so that your application can draw the shadow image in the Canvas.
16125     * </p>
16126     *
16127     * <div class="special reference">
16128     * <h3>Developer Guides</h3>
16129     * <p>For a guide to implementing drag and drop features, read the
16130     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16131     * </div>
16132     */
16133    public static class DragShadowBuilder {
16134        private final WeakReference<View> mView;
16135
16136        /**
16137         * Constructs a shadow image builder based on a View. By default, the resulting drag
16138         * shadow will have the same appearance and dimensions as the View, with the touch point
16139         * over the center of the View.
16140         * @param view A View. Any View in scope can be used.
16141         */
16142        public DragShadowBuilder(View view) {
16143            mView = new WeakReference<View>(view);
16144        }
16145
16146        /**
16147         * Construct a shadow builder object with no associated View.  This
16148         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16149         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16150         * to supply the drag shadow's dimensions and appearance without
16151         * reference to any View object. If they are not overridden, then the result is an
16152         * invisible drag shadow.
16153         */
16154        public DragShadowBuilder() {
16155            mView = new WeakReference<View>(null);
16156        }
16157
16158        /**
16159         * Returns the View object that had been passed to the
16160         * {@link #View.DragShadowBuilder(View)}
16161         * constructor.  If that View parameter was {@code null} or if the
16162         * {@link #View.DragShadowBuilder()}
16163         * constructor was used to instantiate the builder object, this method will return
16164         * null.
16165         *
16166         * @return The View object associate with this builder object.
16167         */
16168        @SuppressWarnings({"JavadocReference"})
16169        final public View getView() {
16170            return mView.get();
16171        }
16172
16173        /**
16174         * Provides the metrics for the shadow image. These include the dimensions of
16175         * the shadow image, and the point within that shadow that should
16176         * be centered under the touch location while dragging.
16177         * <p>
16178         * The default implementation sets the dimensions of the shadow to be the
16179         * same as the dimensions of the View itself and centers the shadow under
16180         * the touch point.
16181         * </p>
16182         *
16183         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16184         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16185         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16186         * image.
16187         *
16188         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16189         * shadow image that should be underneath the touch point during the drag and drop
16190         * operation. Your application must set {@link android.graphics.Point#x} to the
16191         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16192         */
16193        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16194            final View view = mView.get();
16195            if (view != null) {
16196                shadowSize.set(view.getWidth(), view.getHeight());
16197                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16198            } else {
16199                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16200            }
16201        }
16202
16203        /**
16204         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16205         * based on the dimensions it received from the
16206         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16207         *
16208         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16209         */
16210        public void onDrawShadow(Canvas canvas) {
16211            final View view = mView.get();
16212            if (view != null) {
16213                view.draw(canvas);
16214            } else {
16215                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16216            }
16217        }
16218    }
16219
16220    /**
16221     * Starts a drag and drop operation. When your application calls this method, it passes a
16222     * {@link android.view.View.DragShadowBuilder} object to the system. The
16223     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16224     * to get metrics for the drag shadow, and then calls the object's
16225     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16226     * <p>
16227     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16228     *  drag events to all the View objects in your application that are currently visible. It does
16229     *  this either by calling the View object's drag listener (an implementation of
16230     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16231     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16232     *  Both are passed a {@link android.view.DragEvent} object that has a
16233     *  {@link android.view.DragEvent#getAction()} value of
16234     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16235     * </p>
16236     * <p>
16237     * Your application can invoke startDrag() on any attached View object. The View object does not
16238     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16239     * be related to the View the user selected for dragging.
16240     * </p>
16241     * @param data A {@link android.content.ClipData} object pointing to the data to be
16242     * transferred by the drag and drop operation.
16243     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16244     * drag shadow.
16245     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16246     * drop operation. This Object is put into every DragEvent object sent by the system during the
16247     * current drag.
16248     * <p>
16249     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16250     * to the target Views. For example, it can contain flags that differentiate between a
16251     * a copy operation and a move operation.
16252     * </p>
16253     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16254     * so the parameter should be set to 0.
16255     * @return {@code true} if the method completes successfully, or
16256     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16257     * do a drag, and so no drag operation is in progress.
16258     */
16259    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16260            Object myLocalState, int flags) {
16261        if (ViewDebug.DEBUG_DRAG) {
16262            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16263        }
16264        boolean okay = false;
16265
16266        Point shadowSize = new Point();
16267        Point shadowTouchPoint = new Point();
16268        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16269
16270        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16271                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16272            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16273        }
16274
16275        if (ViewDebug.DEBUG_DRAG) {
16276            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16277                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16278        }
16279        Surface surface = new Surface();
16280        try {
16281            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16282                    flags, shadowSize.x, shadowSize.y, surface);
16283            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16284                    + " surface=" + surface);
16285            if (token != null) {
16286                Canvas canvas = surface.lockCanvas(null);
16287                try {
16288                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16289                    shadowBuilder.onDrawShadow(canvas);
16290                } finally {
16291                    surface.unlockCanvasAndPost(canvas);
16292                }
16293
16294                final ViewRootImpl root = getViewRootImpl();
16295
16296                // Cache the local state object for delivery with DragEvents
16297                root.setLocalDragState(myLocalState);
16298
16299                // repurpose 'shadowSize' for the last touch point
16300                root.getLastTouchPoint(shadowSize);
16301
16302                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16303                        shadowSize.x, shadowSize.y,
16304                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16305                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16306
16307                // Off and running!  Release our local surface instance; the drag
16308                // shadow surface is now managed by the system process.
16309                surface.release();
16310            }
16311        } catch (Exception e) {
16312            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16313            surface.destroy();
16314        }
16315
16316        return okay;
16317    }
16318
16319    /**
16320     * Handles drag events sent by the system following a call to
16321     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16322     *<p>
16323     * When the system calls this method, it passes a
16324     * {@link android.view.DragEvent} object. A call to
16325     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16326     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16327     * operation.
16328     * @param event The {@link android.view.DragEvent} sent by the system.
16329     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16330     * in DragEvent, indicating the type of drag event represented by this object.
16331     * @return {@code true} if the method was successful, otherwise {@code false}.
16332     * <p>
16333     *  The method should return {@code true} in response to an action type of
16334     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16335     *  operation.
16336     * </p>
16337     * <p>
16338     *  The method should also return {@code true} in response to an action type of
16339     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16340     *  {@code false} if it didn't.
16341     * </p>
16342     */
16343    public boolean onDragEvent(DragEvent event) {
16344        return false;
16345    }
16346
16347    /**
16348     * Detects if this View is enabled and has a drag event listener.
16349     * If both are true, then it calls the drag event listener with the
16350     * {@link android.view.DragEvent} it received. If the drag event listener returns
16351     * {@code true}, then dispatchDragEvent() returns {@code true}.
16352     * <p>
16353     * For all other cases, the method calls the
16354     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16355     * method and returns its result.
16356     * </p>
16357     * <p>
16358     * This ensures that a drag event is always consumed, even if the View does not have a drag
16359     * event listener. However, if the View has a listener and the listener returns true, then
16360     * onDragEvent() is not called.
16361     * </p>
16362     */
16363    public boolean dispatchDragEvent(DragEvent event) {
16364        //noinspection SimplifiableIfStatement
16365        ListenerInfo li = mListenerInfo;
16366        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16367                && li.mOnDragListener.onDrag(this, event)) {
16368            return true;
16369        }
16370        return onDragEvent(event);
16371    }
16372
16373    boolean canAcceptDrag() {
16374        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16375    }
16376
16377    /**
16378     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16379     * it is ever exposed at all.
16380     * @hide
16381     */
16382    public void onCloseSystemDialogs(String reason) {
16383    }
16384
16385    /**
16386     * Given a Drawable whose bounds have been set to draw into this view,
16387     * update a Region being computed for
16388     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16389     * that any non-transparent parts of the Drawable are removed from the
16390     * given transparent region.
16391     *
16392     * @param dr The Drawable whose transparency is to be applied to the region.
16393     * @param region A Region holding the current transparency information,
16394     * where any parts of the region that are set are considered to be
16395     * transparent.  On return, this region will be modified to have the
16396     * transparency information reduced by the corresponding parts of the
16397     * Drawable that are not transparent.
16398     * {@hide}
16399     */
16400    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16401        if (DBG) {
16402            Log.i("View", "Getting transparent region for: " + this);
16403        }
16404        final Region r = dr.getTransparentRegion();
16405        final Rect db = dr.getBounds();
16406        final AttachInfo attachInfo = mAttachInfo;
16407        if (r != null && attachInfo != null) {
16408            final int w = getRight()-getLeft();
16409            final int h = getBottom()-getTop();
16410            if (db.left > 0) {
16411                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16412                r.op(0, 0, db.left, h, Region.Op.UNION);
16413            }
16414            if (db.right < w) {
16415                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16416                r.op(db.right, 0, w, h, Region.Op.UNION);
16417            }
16418            if (db.top > 0) {
16419                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16420                r.op(0, 0, w, db.top, Region.Op.UNION);
16421            }
16422            if (db.bottom < h) {
16423                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16424                r.op(0, db.bottom, w, h, Region.Op.UNION);
16425            }
16426            final int[] location = attachInfo.mTransparentLocation;
16427            getLocationInWindow(location);
16428            r.translate(location[0], location[1]);
16429            region.op(r, Region.Op.INTERSECT);
16430        } else {
16431            region.op(db, Region.Op.DIFFERENCE);
16432        }
16433    }
16434
16435    private void checkForLongClick(int delayOffset) {
16436        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16437            mHasPerformedLongPress = false;
16438
16439            if (mPendingCheckForLongPress == null) {
16440                mPendingCheckForLongPress = new CheckForLongPress();
16441            }
16442            mPendingCheckForLongPress.rememberWindowAttachCount();
16443            postDelayed(mPendingCheckForLongPress,
16444                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16445        }
16446    }
16447
16448    /**
16449     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16450     * LayoutInflater} class, which provides a full range of options for view inflation.
16451     *
16452     * @param context The Context object for your activity or application.
16453     * @param resource The resource ID to inflate
16454     * @param root A view group that will be the parent.  Used to properly inflate the
16455     * layout_* parameters.
16456     * @see LayoutInflater
16457     */
16458    public static View inflate(Context context, int resource, ViewGroup root) {
16459        LayoutInflater factory = LayoutInflater.from(context);
16460        return factory.inflate(resource, root);
16461    }
16462
16463    /**
16464     * Scroll the view with standard behavior for scrolling beyond the normal
16465     * content boundaries. Views that call this method should override
16466     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16467     * results of an over-scroll operation.
16468     *
16469     * Views can use this method to handle any touch or fling-based scrolling.
16470     *
16471     * @param deltaX Change in X in pixels
16472     * @param deltaY Change in Y in pixels
16473     * @param scrollX Current X scroll value in pixels before applying deltaX
16474     * @param scrollY Current Y scroll value in pixels before applying deltaY
16475     * @param scrollRangeX Maximum content scroll range along the X axis
16476     * @param scrollRangeY Maximum content scroll range along the Y axis
16477     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16478     *          along the X axis.
16479     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16480     *          along the Y axis.
16481     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16482     * @return true if scrolling was clamped to an over-scroll boundary along either
16483     *          axis, false otherwise.
16484     */
16485    @SuppressWarnings({"UnusedParameters"})
16486    protected boolean overScrollBy(int deltaX, int deltaY,
16487            int scrollX, int scrollY,
16488            int scrollRangeX, int scrollRangeY,
16489            int maxOverScrollX, int maxOverScrollY,
16490            boolean isTouchEvent) {
16491        final int overScrollMode = mOverScrollMode;
16492        final boolean canScrollHorizontal =
16493                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16494        final boolean canScrollVertical =
16495                computeVerticalScrollRange() > computeVerticalScrollExtent();
16496        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16497                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16498        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16499                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16500
16501        int newScrollX = scrollX + deltaX;
16502        if (!overScrollHorizontal) {
16503            maxOverScrollX = 0;
16504        }
16505
16506        int newScrollY = scrollY + deltaY;
16507        if (!overScrollVertical) {
16508            maxOverScrollY = 0;
16509        }
16510
16511        // Clamp values if at the limits and record
16512        final int left = -maxOverScrollX;
16513        final int right = maxOverScrollX + scrollRangeX;
16514        final int top = -maxOverScrollY;
16515        final int bottom = maxOverScrollY + scrollRangeY;
16516
16517        boolean clampedX = false;
16518        if (newScrollX > right) {
16519            newScrollX = right;
16520            clampedX = true;
16521        } else if (newScrollX < left) {
16522            newScrollX = left;
16523            clampedX = true;
16524        }
16525
16526        boolean clampedY = false;
16527        if (newScrollY > bottom) {
16528            newScrollY = bottom;
16529            clampedY = true;
16530        } else if (newScrollY < top) {
16531            newScrollY = top;
16532            clampedY = true;
16533        }
16534
16535        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16536
16537        return clampedX || clampedY;
16538    }
16539
16540    /**
16541     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16542     * respond to the results of an over-scroll operation.
16543     *
16544     * @param scrollX New X scroll value in pixels
16545     * @param scrollY New Y scroll value in pixels
16546     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16547     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16548     */
16549    protected void onOverScrolled(int scrollX, int scrollY,
16550            boolean clampedX, boolean clampedY) {
16551        // Intentionally empty.
16552    }
16553
16554    /**
16555     * Returns the over-scroll mode for this view. The result will be
16556     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16557     * (allow over-scrolling only if the view content is larger than the container),
16558     * or {@link #OVER_SCROLL_NEVER}.
16559     *
16560     * @return This view's over-scroll mode.
16561     */
16562    public int getOverScrollMode() {
16563        return mOverScrollMode;
16564    }
16565
16566    /**
16567     * Set the over-scroll mode for this view. Valid over-scroll modes are
16568     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16569     * (allow over-scrolling only if the view content is larger than the container),
16570     * or {@link #OVER_SCROLL_NEVER}.
16571     *
16572     * Setting the over-scroll mode of a view will have an effect only if the
16573     * view is capable of scrolling.
16574     *
16575     * @param overScrollMode The new over-scroll mode for this view.
16576     */
16577    public void setOverScrollMode(int overScrollMode) {
16578        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16579                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16580                overScrollMode != OVER_SCROLL_NEVER) {
16581            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16582        }
16583        mOverScrollMode = overScrollMode;
16584    }
16585
16586    /**
16587     * Gets a scale factor that determines the distance the view should scroll
16588     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16589     * @return The vertical scroll scale factor.
16590     * @hide
16591     */
16592    protected float getVerticalScrollFactor() {
16593        if (mVerticalScrollFactor == 0) {
16594            TypedValue outValue = new TypedValue();
16595            if (!mContext.getTheme().resolveAttribute(
16596                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16597                throw new IllegalStateException(
16598                        "Expected theme to define listPreferredItemHeight.");
16599            }
16600            mVerticalScrollFactor = outValue.getDimension(
16601                    mContext.getResources().getDisplayMetrics());
16602        }
16603        return mVerticalScrollFactor;
16604    }
16605
16606    /**
16607     * Gets a scale factor that determines the distance the view should scroll
16608     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16609     * @return The horizontal scroll scale factor.
16610     * @hide
16611     */
16612    protected float getHorizontalScrollFactor() {
16613        // TODO: Should use something else.
16614        return getVerticalScrollFactor();
16615    }
16616
16617    /**
16618     * Return the value specifying the text direction or policy that was set with
16619     * {@link #setTextDirection(int)}.
16620     *
16621     * @return the defined text direction. It can be one of:
16622     *
16623     * {@link #TEXT_DIRECTION_INHERIT},
16624     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16625     * {@link #TEXT_DIRECTION_ANY_RTL},
16626     * {@link #TEXT_DIRECTION_LTR},
16627     * {@link #TEXT_DIRECTION_RTL},
16628     * {@link #TEXT_DIRECTION_LOCALE}
16629     *
16630     * @hide
16631     */
16632    @ViewDebug.ExportedProperty(category = "text", mapping = {
16633            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16634            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16635            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16636            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16637            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16638            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16639    })
16640    public int getRawTextDirection() {
16641        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16642    }
16643
16644    /**
16645     * Set the text direction.
16646     *
16647     * @param textDirection the direction to set. Should be one of:
16648     *
16649     * {@link #TEXT_DIRECTION_INHERIT},
16650     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16651     * {@link #TEXT_DIRECTION_ANY_RTL},
16652     * {@link #TEXT_DIRECTION_LTR},
16653     * {@link #TEXT_DIRECTION_RTL},
16654     * {@link #TEXT_DIRECTION_LOCALE}
16655     *
16656     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
16657     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
16658     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
16659     */
16660    public void setTextDirection(int textDirection) {
16661        if (getRawTextDirection() != textDirection) {
16662            // Reset the current text direction and the resolved one
16663            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
16664            resetResolvedTextDirection();
16665            // Set the new text direction
16666            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
16667            // Do resolution
16668            resolveTextDirection();
16669            // Notify change
16670            onRtlPropertiesChanged(getLayoutDirection());
16671            // Refresh
16672            requestLayout();
16673            invalidate(true);
16674        }
16675    }
16676
16677    /**
16678     * Return the resolved text direction.
16679     *
16680     * @return the resolved text direction. Returns one of:
16681     *
16682     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16683     * {@link #TEXT_DIRECTION_ANY_RTL},
16684     * {@link #TEXT_DIRECTION_LTR},
16685     * {@link #TEXT_DIRECTION_RTL},
16686     * {@link #TEXT_DIRECTION_LOCALE}
16687     */
16688    public int getTextDirection() {
16689        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16690    }
16691
16692    /**
16693     * Resolve the text direction.
16694     *
16695     * @return true if resolution has been done, false otherwise.
16696     *
16697     * @hide
16698     */
16699    public boolean resolveTextDirection() {
16700        // Reset any previous text direction resolution
16701        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16702
16703        if (hasRtlSupport()) {
16704            // Set resolved text direction flag depending on text direction flag
16705            final int textDirection = getRawTextDirection();
16706            switch(textDirection) {
16707                case TEXT_DIRECTION_INHERIT:
16708                    if (!canResolveTextDirection()) {
16709                        // We cannot do the resolution if there is no parent, so use the default one
16710                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16711                        // Resolution will need to happen again later
16712                        return false;
16713                    }
16714
16715                    View parent = ((View) mParent);
16716                    // Parent has not yet resolved, so we still return the default
16717                    if (!parent.isTextDirectionResolved()) {
16718                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16719                        // Resolution will need to happen again later
16720                        return false;
16721                    }
16722
16723                    // Set current resolved direction to the same value as the parent's one
16724                    final int parentResolvedDirection = parent.getTextDirection();
16725                    switch (parentResolvedDirection) {
16726                        case TEXT_DIRECTION_FIRST_STRONG:
16727                        case TEXT_DIRECTION_ANY_RTL:
16728                        case TEXT_DIRECTION_LTR:
16729                        case TEXT_DIRECTION_RTL:
16730                        case TEXT_DIRECTION_LOCALE:
16731                            mPrivateFlags2 |=
16732                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16733                            break;
16734                        default:
16735                            // Default resolved direction is "first strong" heuristic
16736                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16737                    }
16738                    break;
16739                case TEXT_DIRECTION_FIRST_STRONG:
16740                case TEXT_DIRECTION_ANY_RTL:
16741                case TEXT_DIRECTION_LTR:
16742                case TEXT_DIRECTION_RTL:
16743                case TEXT_DIRECTION_LOCALE:
16744                    // Resolved direction is the same as text direction
16745                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16746                    break;
16747                default:
16748                    // Default resolved direction is "first strong" heuristic
16749                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16750            }
16751        } else {
16752            // Default resolved direction is "first strong" heuristic
16753            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16754        }
16755
16756        // Set to resolved
16757        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
16758        return true;
16759    }
16760
16761    /**
16762     * Check if text direction resolution can be done.
16763     *
16764     * @return true if text direction resolution can be done otherwise return false.
16765     */
16766    private boolean canResolveTextDirection() {
16767        switch (getRawTextDirection()) {
16768            case TEXT_DIRECTION_INHERIT:
16769                return (mParent != null) && (mParent instanceof View) &&
16770                       ((View) mParent).canResolveTextDirection();
16771            default:
16772                return true;
16773        }
16774    }
16775
16776    /**
16777     * Reset resolved text direction. Text direction will be resolved during a call to
16778     * {@link #onMeasure(int, int)}.
16779     *
16780     * @hide
16781     */
16782    public void resetResolvedTextDirection() {
16783        // Reset any previous text direction resolution
16784        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16785        // Set to default value
16786        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16787    }
16788
16789    /**
16790     * @return true if text direction is inherited.
16791     *
16792     * @hide
16793     */
16794    public boolean isTextDirectionInherited() {
16795        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
16796    }
16797
16798    /**
16799     * @return true if text direction is resolved.
16800     */
16801    private boolean isTextDirectionResolved() {
16802        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
16803    }
16804
16805    /**
16806     * Return the value specifying the text alignment or policy that was set with
16807     * {@link #setTextAlignment(int)}.
16808     *
16809     * @return the defined text alignment. It can be one of:
16810     *
16811     * {@link #TEXT_ALIGNMENT_INHERIT},
16812     * {@link #TEXT_ALIGNMENT_GRAVITY},
16813     * {@link #TEXT_ALIGNMENT_CENTER},
16814     * {@link #TEXT_ALIGNMENT_TEXT_START},
16815     * {@link #TEXT_ALIGNMENT_TEXT_END},
16816     * {@link #TEXT_ALIGNMENT_VIEW_START},
16817     * {@link #TEXT_ALIGNMENT_VIEW_END}
16818     *
16819     * @hide
16820     */
16821    @ViewDebug.ExportedProperty(category = "text", mapping = {
16822            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16823            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16824            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16825            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16826            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16827            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16828            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16829    })
16830    public int getRawTextAlignment() {
16831        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
16832    }
16833
16834    /**
16835     * Set the text alignment.
16836     *
16837     * @param textAlignment The text alignment to set. Should be one of
16838     *
16839     * {@link #TEXT_ALIGNMENT_INHERIT},
16840     * {@link #TEXT_ALIGNMENT_GRAVITY},
16841     * {@link #TEXT_ALIGNMENT_CENTER},
16842     * {@link #TEXT_ALIGNMENT_TEXT_START},
16843     * {@link #TEXT_ALIGNMENT_TEXT_END},
16844     * {@link #TEXT_ALIGNMENT_VIEW_START},
16845     * {@link #TEXT_ALIGNMENT_VIEW_END}
16846     *
16847     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
16848     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
16849     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
16850     *
16851     * @attr ref android.R.styleable#View_textAlignment
16852     */
16853    public void setTextAlignment(int textAlignment) {
16854        if (textAlignment != getRawTextAlignment()) {
16855            // Reset the current and resolved text alignment
16856            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
16857            resetResolvedTextAlignment();
16858            // Set the new text alignment
16859            mPrivateFlags2 |=
16860                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
16861            // Do resolution
16862            resolveTextAlignment();
16863            // Notify change
16864            onRtlPropertiesChanged(getLayoutDirection());
16865            // Refresh
16866            requestLayout();
16867            invalidate(true);
16868        }
16869    }
16870
16871    /**
16872     * Return the resolved text alignment.
16873     *
16874     * @return the resolved text alignment. Returns one of:
16875     *
16876     * {@link #TEXT_ALIGNMENT_GRAVITY},
16877     * {@link #TEXT_ALIGNMENT_CENTER},
16878     * {@link #TEXT_ALIGNMENT_TEXT_START},
16879     * {@link #TEXT_ALIGNMENT_TEXT_END},
16880     * {@link #TEXT_ALIGNMENT_VIEW_START},
16881     * {@link #TEXT_ALIGNMENT_VIEW_END}
16882     */
16883    @ViewDebug.ExportedProperty(category = "text", mapping = {
16884            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16885            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16886            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16887            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16888            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16889            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16890            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16891    })
16892    public int getTextAlignment() {
16893        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
16894                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16895    }
16896
16897    /**
16898     * Resolve the text alignment.
16899     *
16900     * @return true if resolution has been done, false otherwise.
16901     *
16902     * @hide
16903     */
16904    public boolean resolveTextAlignment() {
16905        // Reset any previous text alignment resolution
16906        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
16907
16908        if (hasRtlSupport()) {
16909            // Set resolved text alignment flag depending on text alignment flag
16910            final int textAlignment = getRawTextAlignment();
16911            switch (textAlignment) {
16912                case TEXT_ALIGNMENT_INHERIT:
16913                    // Check if we can resolve the text alignment
16914                    if (!canResolveTextAlignment()) {
16915                        // We cannot do the resolution if there is no parent so use the default
16916                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16917                        // Resolution will need to happen again later
16918                        return false;
16919                    }
16920                    View parent = (View) mParent;
16921
16922                    // Parent has not yet resolved, so we still return the default
16923                    if (!parent.isTextAlignmentResolved()) {
16924                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16925                        // Resolution will need to happen again later
16926                        return false;
16927                    }
16928
16929                    final int parentResolvedTextAlignment = parent.getTextAlignment();
16930                    switch (parentResolvedTextAlignment) {
16931                        case TEXT_ALIGNMENT_GRAVITY:
16932                        case TEXT_ALIGNMENT_TEXT_START:
16933                        case TEXT_ALIGNMENT_TEXT_END:
16934                        case TEXT_ALIGNMENT_CENTER:
16935                        case TEXT_ALIGNMENT_VIEW_START:
16936                        case TEXT_ALIGNMENT_VIEW_END:
16937                            // Resolved text alignment is the same as the parent resolved
16938                            // text alignment
16939                            mPrivateFlags2 |=
16940                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16941                            break;
16942                        default:
16943                            // Use default resolved text alignment
16944                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16945                    }
16946                    break;
16947                case TEXT_ALIGNMENT_GRAVITY:
16948                case TEXT_ALIGNMENT_TEXT_START:
16949                case TEXT_ALIGNMENT_TEXT_END:
16950                case TEXT_ALIGNMENT_CENTER:
16951                case TEXT_ALIGNMENT_VIEW_START:
16952                case TEXT_ALIGNMENT_VIEW_END:
16953                    // Resolved text alignment is the same as text alignment
16954                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16955                    break;
16956                default:
16957                    // Use default resolved text alignment
16958                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16959            }
16960        } else {
16961            // Use default resolved text alignment
16962            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16963        }
16964
16965        // Set the resolved
16966        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
16967        return true;
16968    }
16969
16970    /**
16971     * Check if text alignment resolution can be done.
16972     *
16973     * @return true if text alignment resolution can be done otherwise return false.
16974     */
16975    private boolean canResolveTextAlignment() {
16976        switch (getRawTextAlignment()) {
16977            case TEXT_DIRECTION_INHERIT:
16978                return (mParent != null) && (mParent instanceof View) &&
16979                       ((View) mParent).canResolveTextAlignment();
16980            default:
16981                return true;
16982        }
16983    }
16984
16985    /**
16986     * Reset resolved text alignment. Text alignment will be resolved during a call to
16987     * {@link #onMeasure(int, int)}.
16988     *
16989     * @hide
16990     */
16991    public void resetResolvedTextAlignment() {
16992        // Reset any previous text alignment resolution
16993        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
16994        // Set to default
16995        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16996    }
16997
16998    /**
16999     * @return true if text alignment is inherited.
17000     *
17001     * @hide
17002     */
17003    public boolean isTextAlignmentInherited() {
17004        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17005    }
17006
17007    /**
17008     * @return true if text alignment is resolved.
17009     */
17010    private boolean isTextAlignmentResolved() {
17011        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17012    }
17013
17014    /**
17015     * Generate a value suitable for use in {@link #setId(int)}.
17016     * This value will not collide with ID values generated at build time by aapt for R.id.
17017     *
17018     * @return a generated ID value
17019     */
17020    public static int generateViewId() {
17021        for (;;) {
17022            final int result = sNextGeneratedId.get();
17023            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17024            int newValue = result + 1;
17025            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17026            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17027                return result;
17028            }
17029        }
17030    }
17031
17032    //
17033    // Properties
17034    //
17035    /**
17036     * A Property wrapper around the <code>alpha</code> functionality handled by the
17037     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17038     */
17039    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17040        @Override
17041        public void setValue(View object, float value) {
17042            object.setAlpha(value);
17043        }
17044
17045        @Override
17046        public Float get(View object) {
17047            return object.getAlpha();
17048        }
17049    };
17050
17051    /**
17052     * A Property wrapper around the <code>translationX</code> functionality handled by the
17053     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17054     */
17055    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17056        @Override
17057        public void setValue(View object, float value) {
17058            object.setTranslationX(value);
17059        }
17060
17061                @Override
17062        public Float get(View object) {
17063            return object.getTranslationX();
17064        }
17065    };
17066
17067    /**
17068     * A Property wrapper around the <code>translationY</code> functionality handled by the
17069     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17070     */
17071    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17072        @Override
17073        public void setValue(View object, float value) {
17074            object.setTranslationY(value);
17075        }
17076
17077        @Override
17078        public Float get(View object) {
17079            return object.getTranslationY();
17080        }
17081    };
17082
17083    /**
17084     * A Property wrapper around the <code>x</code> functionality handled by the
17085     * {@link View#setX(float)} and {@link View#getX()} methods.
17086     */
17087    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17088        @Override
17089        public void setValue(View object, float value) {
17090            object.setX(value);
17091        }
17092
17093        @Override
17094        public Float get(View object) {
17095            return object.getX();
17096        }
17097    };
17098
17099    /**
17100     * A Property wrapper around the <code>y</code> functionality handled by the
17101     * {@link View#setY(float)} and {@link View#getY()} methods.
17102     */
17103    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17104        @Override
17105        public void setValue(View object, float value) {
17106            object.setY(value);
17107        }
17108
17109        @Override
17110        public Float get(View object) {
17111            return object.getY();
17112        }
17113    };
17114
17115    /**
17116     * A Property wrapper around the <code>rotation</code> functionality handled by the
17117     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17118     */
17119    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17120        @Override
17121        public void setValue(View object, float value) {
17122            object.setRotation(value);
17123        }
17124
17125        @Override
17126        public Float get(View object) {
17127            return object.getRotation();
17128        }
17129    };
17130
17131    /**
17132     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17133     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17134     */
17135    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17136        @Override
17137        public void setValue(View object, float value) {
17138            object.setRotationX(value);
17139        }
17140
17141        @Override
17142        public Float get(View object) {
17143            return object.getRotationX();
17144        }
17145    };
17146
17147    /**
17148     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17149     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17150     */
17151    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17152        @Override
17153        public void setValue(View object, float value) {
17154            object.setRotationY(value);
17155        }
17156
17157        @Override
17158        public Float get(View object) {
17159            return object.getRotationY();
17160        }
17161    };
17162
17163    /**
17164     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17165     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17166     */
17167    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17168        @Override
17169        public void setValue(View object, float value) {
17170            object.setScaleX(value);
17171        }
17172
17173        @Override
17174        public Float get(View object) {
17175            return object.getScaleX();
17176        }
17177    };
17178
17179    /**
17180     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17181     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17182     */
17183    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17184        @Override
17185        public void setValue(View object, float value) {
17186            object.setScaleY(value);
17187        }
17188
17189        @Override
17190        public Float get(View object) {
17191            return object.getScaleY();
17192        }
17193    };
17194
17195    /**
17196     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17197     * Each MeasureSpec represents a requirement for either the width or the height.
17198     * A MeasureSpec is comprised of a size and a mode. There are three possible
17199     * modes:
17200     * <dl>
17201     * <dt>UNSPECIFIED</dt>
17202     * <dd>
17203     * The parent has not imposed any constraint on the child. It can be whatever size
17204     * it wants.
17205     * </dd>
17206     *
17207     * <dt>EXACTLY</dt>
17208     * <dd>
17209     * The parent has determined an exact size for the child. The child is going to be
17210     * given those bounds regardless of how big it wants to be.
17211     * </dd>
17212     *
17213     * <dt>AT_MOST</dt>
17214     * <dd>
17215     * The child can be as large as it wants up to the specified size.
17216     * </dd>
17217     * </dl>
17218     *
17219     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17220     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17221     */
17222    public static class MeasureSpec {
17223        private static final int MODE_SHIFT = 30;
17224        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17225
17226        /**
17227         * Measure specification mode: The parent has not imposed any constraint
17228         * on the child. It can be whatever size it wants.
17229         */
17230        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17231
17232        /**
17233         * Measure specification mode: The parent has determined an exact size
17234         * for the child. The child is going to be given those bounds regardless
17235         * of how big it wants to be.
17236         */
17237        public static final int EXACTLY     = 1 << MODE_SHIFT;
17238
17239        /**
17240         * Measure specification mode: The child can be as large as it wants up
17241         * to the specified size.
17242         */
17243        public static final int AT_MOST     = 2 << MODE_SHIFT;
17244
17245        /**
17246         * Creates a measure specification based on the supplied size and mode.
17247         *
17248         * The mode must always be one of the following:
17249         * <ul>
17250         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17251         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17252         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17253         * </ul>
17254         *
17255         * @param size the size of the measure specification
17256         * @param mode the mode of the measure specification
17257         * @return the measure specification based on size and mode
17258         */
17259        public static int makeMeasureSpec(int size, int mode) {
17260            return (size & ~MODE_MASK) | (mode & MODE_MASK);
17261        }
17262
17263        /**
17264         * Extracts the mode from the supplied measure specification.
17265         *
17266         * @param measureSpec the measure specification to extract the mode from
17267         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17268         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17269         *         {@link android.view.View.MeasureSpec#EXACTLY}
17270         */
17271        public static int getMode(int measureSpec) {
17272            return (measureSpec & MODE_MASK);
17273        }
17274
17275        /**
17276         * Extracts the size from the supplied measure specification.
17277         *
17278         * @param measureSpec the measure specification to extract the size from
17279         * @return the size in pixels defined in the supplied measure specification
17280         */
17281        public static int getSize(int measureSpec) {
17282            return (measureSpec & ~MODE_MASK);
17283        }
17284
17285        static int adjust(int measureSpec, int delta) {
17286            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17287        }
17288
17289        /**
17290         * Returns a String representation of the specified measure
17291         * specification.
17292         *
17293         * @param measureSpec the measure specification to convert to a String
17294         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17295         */
17296        public static String toString(int measureSpec) {
17297            int mode = getMode(measureSpec);
17298            int size = getSize(measureSpec);
17299
17300            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17301
17302            if (mode == UNSPECIFIED)
17303                sb.append("UNSPECIFIED ");
17304            else if (mode == EXACTLY)
17305                sb.append("EXACTLY ");
17306            else if (mode == AT_MOST)
17307                sb.append("AT_MOST ");
17308            else
17309                sb.append(mode).append(" ");
17310
17311            sb.append(size);
17312            return sb.toString();
17313        }
17314    }
17315
17316    class CheckForLongPress implements Runnable {
17317
17318        private int mOriginalWindowAttachCount;
17319
17320        public void run() {
17321            if (isPressed() && (mParent != null)
17322                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17323                if (performLongClick()) {
17324                    mHasPerformedLongPress = true;
17325                }
17326            }
17327        }
17328
17329        public void rememberWindowAttachCount() {
17330            mOriginalWindowAttachCount = mWindowAttachCount;
17331        }
17332    }
17333
17334    private final class CheckForTap implements Runnable {
17335        public void run() {
17336            mPrivateFlags &= ~PFLAG_PREPRESSED;
17337            setPressed(true);
17338            checkForLongClick(ViewConfiguration.getTapTimeout());
17339        }
17340    }
17341
17342    private final class PerformClick implements Runnable {
17343        public void run() {
17344            performClick();
17345        }
17346    }
17347
17348    /** @hide */
17349    public void hackTurnOffWindowResizeAnim(boolean off) {
17350        mAttachInfo.mTurnOffWindowResizeAnim = off;
17351    }
17352
17353    /**
17354     * This method returns a ViewPropertyAnimator object, which can be used to animate
17355     * specific properties on this View.
17356     *
17357     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17358     */
17359    public ViewPropertyAnimator animate() {
17360        if (mAnimator == null) {
17361            mAnimator = new ViewPropertyAnimator(this);
17362        }
17363        return mAnimator;
17364    }
17365
17366    /**
17367     * Interface definition for a callback to be invoked when a hardware key event is
17368     * dispatched to this view. The callback will be invoked before the key event is
17369     * given to the view. This is only useful for hardware keyboards; a software input
17370     * method has no obligation to trigger this listener.
17371     */
17372    public interface OnKeyListener {
17373        /**
17374         * Called when a hardware key is dispatched to a view. This allows listeners to
17375         * get a chance to respond before the target view.
17376         * <p>Key presses in software keyboards will generally NOT trigger this method,
17377         * although some may elect to do so in some situations. Do not assume a
17378         * software input method has to be key-based; even if it is, it may use key presses
17379         * in a different way than you expect, so there is no way to reliably catch soft
17380         * input key presses.
17381         *
17382         * @param v The view the key has been dispatched to.
17383         * @param keyCode The code for the physical key that was pressed
17384         * @param event The KeyEvent object containing full information about
17385         *        the event.
17386         * @return True if the listener has consumed the event, false otherwise.
17387         */
17388        boolean onKey(View v, int keyCode, KeyEvent event);
17389    }
17390
17391    /**
17392     * Interface definition for a callback to be invoked when a touch event is
17393     * dispatched to this view. The callback will be invoked before the touch
17394     * event is given to the view.
17395     */
17396    public interface OnTouchListener {
17397        /**
17398         * Called when a touch event is dispatched to a view. This allows listeners to
17399         * get a chance to respond before the target view.
17400         *
17401         * @param v The view the touch event has been dispatched to.
17402         * @param event The MotionEvent object containing full information about
17403         *        the event.
17404         * @return True if the listener has consumed the event, false otherwise.
17405         */
17406        boolean onTouch(View v, MotionEvent event);
17407    }
17408
17409    /**
17410     * Interface definition for a callback to be invoked when a hover event is
17411     * dispatched to this view. The callback will be invoked before the hover
17412     * event is given to the view.
17413     */
17414    public interface OnHoverListener {
17415        /**
17416         * Called when a hover event is dispatched to a view. This allows listeners to
17417         * get a chance to respond before the target view.
17418         *
17419         * @param v The view the hover event has been dispatched to.
17420         * @param event The MotionEvent object containing full information about
17421         *        the event.
17422         * @return True if the listener has consumed the event, false otherwise.
17423         */
17424        boolean onHover(View v, MotionEvent event);
17425    }
17426
17427    /**
17428     * Interface definition for a callback to be invoked when a generic motion event is
17429     * dispatched to this view. The callback will be invoked before the generic motion
17430     * event is given to the view.
17431     */
17432    public interface OnGenericMotionListener {
17433        /**
17434         * Called when a generic motion event is dispatched to a view. This allows listeners to
17435         * get a chance to respond before the target view.
17436         *
17437         * @param v The view the generic motion event has been dispatched to.
17438         * @param event The MotionEvent object containing full information about
17439         *        the event.
17440         * @return True if the listener has consumed the event, false otherwise.
17441         */
17442        boolean onGenericMotion(View v, MotionEvent event);
17443    }
17444
17445    /**
17446     * Interface definition for a callback to be invoked when a view has been clicked and held.
17447     */
17448    public interface OnLongClickListener {
17449        /**
17450         * Called when a view has been clicked and held.
17451         *
17452         * @param v The view that was clicked and held.
17453         *
17454         * @return true if the callback consumed the long click, false otherwise.
17455         */
17456        boolean onLongClick(View v);
17457    }
17458
17459    /**
17460     * Interface definition for a callback to be invoked when a drag is being dispatched
17461     * to this view.  The callback will be invoked before the hosting view's own
17462     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17463     * onDrag(event) behavior, it should return 'false' from this callback.
17464     *
17465     * <div class="special reference">
17466     * <h3>Developer Guides</h3>
17467     * <p>For a guide to implementing drag and drop features, read the
17468     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17469     * </div>
17470     */
17471    public interface OnDragListener {
17472        /**
17473         * Called when a drag event is dispatched to a view. This allows listeners
17474         * to get a chance to override base View behavior.
17475         *
17476         * @param v The View that received the drag event.
17477         * @param event The {@link android.view.DragEvent} object for the drag event.
17478         * @return {@code true} if the drag event was handled successfully, or {@code false}
17479         * if the drag event was not handled. Note that {@code false} will trigger the View
17480         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17481         */
17482        boolean onDrag(View v, DragEvent event);
17483    }
17484
17485    /**
17486     * Interface definition for a callback to be invoked when the focus state of
17487     * a view changed.
17488     */
17489    public interface OnFocusChangeListener {
17490        /**
17491         * Called when the focus state of a view has changed.
17492         *
17493         * @param v The view whose state has changed.
17494         * @param hasFocus The new focus state of v.
17495         */
17496        void onFocusChange(View v, boolean hasFocus);
17497    }
17498
17499    /**
17500     * Interface definition for a callback to be invoked when a view is clicked.
17501     */
17502    public interface OnClickListener {
17503        /**
17504         * Called when a view has been clicked.
17505         *
17506         * @param v The view that was clicked.
17507         */
17508        void onClick(View v);
17509    }
17510
17511    /**
17512     * Interface definition for a callback to be invoked when the context menu
17513     * for this view is being built.
17514     */
17515    public interface OnCreateContextMenuListener {
17516        /**
17517         * Called when the context menu for this view is being built. It is not
17518         * safe to hold onto the menu after this method returns.
17519         *
17520         * @param menu The context menu that is being built
17521         * @param v The view for which the context menu is being built
17522         * @param menuInfo Extra information about the item for which the
17523         *            context menu should be shown. This information will vary
17524         *            depending on the class of v.
17525         */
17526        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17527    }
17528
17529    /**
17530     * Interface definition for a callback to be invoked when the status bar changes
17531     * visibility.  This reports <strong>global</strong> changes to the system UI
17532     * state, not what the application is requesting.
17533     *
17534     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17535     */
17536    public interface OnSystemUiVisibilityChangeListener {
17537        /**
17538         * Called when the status bar changes visibility because of a call to
17539         * {@link View#setSystemUiVisibility(int)}.
17540         *
17541         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17542         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17543         * This tells you the <strong>global</strong> state of these UI visibility
17544         * flags, not what your app is currently applying.
17545         */
17546        public void onSystemUiVisibilityChange(int visibility);
17547    }
17548
17549    /**
17550     * Interface definition for a callback to be invoked when this view is attached
17551     * or detached from its window.
17552     */
17553    public interface OnAttachStateChangeListener {
17554        /**
17555         * Called when the view is attached to a window.
17556         * @param v The view that was attached
17557         */
17558        public void onViewAttachedToWindow(View v);
17559        /**
17560         * Called when the view is detached from a window.
17561         * @param v The view that was detached
17562         */
17563        public void onViewDetachedFromWindow(View v);
17564    }
17565
17566    private final class UnsetPressedState implements Runnable {
17567        public void run() {
17568            setPressed(false);
17569        }
17570    }
17571
17572    /**
17573     * Base class for derived classes that want to save and restore their own
17574     * state in {@link android.view.View#onSaveInstanceState()}.
17575     */
17576    public static class BaseSavedState extends AbsSavedState {
17577        /**
17578         * Constructor used when reading from a parcel. Reads the state of the superclass.
17579         *
17580         * @param source
17581         */
17582        public BaseSavedState(Parcel source) {
17583            super(source);
17584        }
17585
17586        /**
17587         * Constructor called by derived classes when creating their SavedState objects
17588         *
17589         * @param superState The state of the superclass of this view
17590         */
17591        public BaseSavedState(Parcelable superState) {
17592            super(superState);
17593        }
17594
17595        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17596                new Parcelable.Creator<BaseSavedState>() {
17597            public BaseSavedState createFromParcel(Parcel in) {
17598                return new BaseSavedState(in);
17599            }
17600
17601            public BaseSavedState[] newArray(int size) {
17602                return new BaseSavedState[size];
17603            }
17604        };
17605    }
17606
17607    /**
17608     * A set of information given to a view when it is attached to its parent
17609     * window.
17610     */
17611    static class AttachInfo {
17612        interface Callbacks {
17613            void playSoundEffect(int effectId);
17614            boolean performHapticFeedback(int effectId, boolean always);
17615        }
17616
17617        /**
17618         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17619         * to a Handler. This class contains the target (View) to invalidate and
17620         * the coordinates of the dirty rectangle.
17621         *
17622         * For performance purposes, this class also implements a pool of up to
17623         * POOL_LIMIT objects that get reused. This reduces memory allocations
17624         * whenever possible.
17625         */
17626        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17627            private static final int POOL_LIMIT = 10;
17628            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17629                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17630                        public InvalidateInfo newInstance() {
17631                            return new InvalidateInfo();
17632                        }
17633
17634                        public void onAcquired(InvalidateInfo element) {
17635                        }
17636
17637                        public void onReleased(InvalidateInfo element) {
17638                            element.target = null;
17639                        }
17640                    }, POOL_LIMIT)
17641            );
17642
17643            private InvalidateInfo mNext;
17644            private boolean mIsPooled;
17645
17646            View target;
17647
17648            int left;
17649            int top;
17650            int right;
17651            int bottom;
17652
17653            public void setNextPoolable(InvalidateInfo element) {
17654                mNext = element;
17655            }
17656
17657            public InvalidateInfo getNextPoolable() {
17658                return mNext;
17659            }
17660
17661            static InvalidateInfo acquire() {
17662                return sPool.acquire();
17663            }
17664
17665            void release() {
17666                sPool.release(this);
17667            }
17668
17669            public boolean isPooled() {
17670                return mIsPooled;
17671            }
17672
17673            public void setPooled(boolean isPooled) {
17674                mIsPooled = isPooled;
17675            }
17676        }
17677
17678        final IWindowSession mSession;
17679
17680        final IWindow mWindow;
17681
17682        final IBinder mWindowToken;
17683
17684        final Display mDisplay;
17685
17686        final Callbacks mRootCallbacks;
17687
17688        HardwareCanvas mHardwareCanvas;
17689
17690        /**
17691         * The top view of the hierarchy.
17692         */
17693        View mRootView;
17694
17695        IBinder mPanelParentWindowToken;
17696        Surface mSurface;
17697
17698        boolean mHardwareAccelerated;
17699        boolean mHardwareAccelerationRequested;
17700        HardwareRenderer mHardwareRenderer;
17701
17702        boolean mScreenOn;
17703
17704        /**
17705         * Scale factor used by the compatibility mode
17706         */
17707        float mApplicationScale;
17708
17709        /**
17710         * Indicates whether the application is in compatibility mode
17711         */
17712        boolean mScalingRequired;
17713
17714        /**
17715         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17716         */
17717        boolean mTurnOffWindowResizeAnim;
17718
17719        /**
17720         * Left position of this view's window
17721         */
17722        int mWindowLeft;
17723
17724        /**
17725         * Top position of this view's window
17726         */
17727        int mWindowTop;
17728
17729        /**
17730         * Indicates whether views need to use 32-bit drawing caches
17731         */
17732        boolean mUse32BitDrawingCache;
17733
17734        /**
17735         * For windows that are full-screen but using insets to layout inside
17736         * of the screen decorations, these are the current insets for the
17737         * content of the window.
17738         */
17739        final Rect mContentInsets = new Rect();
17740
17741        /**
17742         * For windows that are full-screen but using insets to layout inside
17743         * of the screen decorations, these are the current insets for the
17744         * actual visible parts of the window.
17745         */
17746        final Rect mVisibleInsets = new Rect();
17747
17748        /**
17749         * The internal insets given by this window.  This value is
17750         * supplied by the client (through
17751         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17752         * be given to the window manager when changed to be used in laying
17753         * out windows behind it.
17754         */
17755        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17756                = new ViewTreeObserver.InternalInsetsInfo();
17757
17758        /**
17759         * All views in the window's hierarchy that serve as scroll containers,
17760         * used to determine if the window can be resized or must be panned
17761         * to adjust for a soft input area.
17762         */
17763        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17764
17765        final KeyEvent.DispatcherState mKeyDispatchState
17766                = new KeyEvent.DispatcherState();
17767
17768        /**
17769         * Indicates whether the view's window currently has the focus.
17770         */
17771        boolean mHasWindowFocus;
17772
17773        /**
17774         * The current visibility of the window.
17775         */
17776        int mWindowVisibility;
17777
17778        /**
17779         * Indicates the time at which drawing started to occur.
17780         */
17781        long mDrawingTime;
17782
17783        /**
17784         * Indicates whether or not ignoring the DIRTY_MASK flags.
17785         */
17786        boolean mIgnoreDirtyState;
17787
17788        /**
17789         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17790         * to avoid clearing that flag prematurely.
17791         */
17792        boolean mSetIgnoreDirtyState = false;
17793
17794        /**
17795         * Indicates whether the view's window is currently in touch mode.
17796         */
17797        boolean mInTouchMode;
17798
17799        /**
17800         * Indicates that ViewAncestor should trigger a global layout change
17801         * the next time it performs a traversal
17802         */
17803        boolean mRecomputeGlobalAttributes;
17804
17805        /**
17806         * Always report new attributes at next traversal.
17807         */
17808        boolean mForceReportNewAttributes;
17809
17810        /**
17811         * Set during a traveral if any views want to keep the screen on.
17812         */
17813        boolean mKeepScreenOn;
17814
17815        /**
17816         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17817         */
17818        int mSystemUiVisibility;
17819
17820        /**
17821         * Hack to force certain system UI visibility flags to be cleared.
17822         */
17823        int mDisabledSystemUiVisibility;
17824
17825        /**
17826         * Last global system UI visibility reported by the window manager.
17827         */
17828        int mGlobalSystemUiVisibility;
17829
17830        /**
17831         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17832         * attached.
17833         */
17834        boolean mHasSystemUiListeners;
17835
17836        /**
17837         * Set if the visibility of any views has changed.
17838         */
17839        boolean mViewVisibilityChanged;
17840
17841        /**
17842         * Set to true if a view has been scrolled.
17843         */
17844        boolean mViewScrollChanged;
17845
17846        /**
17847         * Global to the view hierarchy used as a temporary for dealing with
17848         * x/y points in the transparent region computations.
17849         */
17850        final int[] mTransparentLocation = new int[2];
17851
17852        /**
17853         * Global to the view hierarchy used as a temporary for dealing with
17854         * x/y points in the ViewGroup.invalidateChild implementation.
17855         */
17856        final int[] mInvalidateChildLocation = new int[2];
17857
17858
17859        /**
17860         * Global to the view hierarchy used as a temporary for dealing with
17861         * x/y location when view is transformed.
17862         */
17863        final float[] mTmpTransformLocation = new float[2];
17864
17865        /**
17866         * The view tree observer used to dispatch global events like
17867         * layout, pre-draw, touch mode change, etc.
17868         */
17869        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17870
17871        /**
17872         * A Canvas used by the view hierarchy to perform bitmap caching.
17873         */
17874        Canvas mCanvas;
17875
17876        /**
17877         * The view root impl.
17878         */
17879        final ViewRootImpl mViewRootImpl;
17880
17881        /**
17882         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17883         * handler can be used to pump events in the UI events queue.
17884         */
17885        final Handler mHandler;
17886
17887        /**
17888         * Temporary for use in computing invalidate rectangles while
17889         * calling up the hierarchy.
17890         */
17891        final Rect mTmpInvalRect = new Rect();
17892
17893        /**
17894         * Temporary for use in computing hit areas with transformed views
17895         */
17896        final RectF mTmpTransformRect = new RectF();
17897
17898        /**
17899         * Temporary for use in transforming invalidation rect
17900         */
17901        final Matrix mTmpMatrix = new Matrix();
17902
17903        /**
17904         * Temporary for use in transforming invalidation rect
17905         */
17906        final Transformation mTmpTransformation = new Transformation();
17907
17908        /**
17909         * Temporary list for use in collecting focusable descendents of a view.
17910         */
17911        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17912
17913        /**
17914         * The id of the window for accessibility purposes.
17915         */
17916        int mAccessibilityWindowId = View.NO_ID;
17917
17918        /**
17919         * Whether to ingore not exposed for accessibility Views when
17920         * reporting the view tree to accessibility services.
17921         */
17922        boolean mIncludeNotImportantViews;
17923
17924        /**
17925         * The drawable for highlighting accessibility focus.
17926         */
17927        Drawable mAccessibilityFocusDrawable;
17928
17929        /**
17930         * Show where the margins, bounds and layout bounds are for each view.
17931         */
17932        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17933
17934        /**
17935         * Point used to compute visible regions.
17936         */
17937        final Point mPoint = new Point();
17938
17939        /**
17940         * Creates a new set of attachment information with the specified
17941         * events handler and thread.
17942         *
17943         * @param handler the events handler the view must use
17944         */
17945        AttachInfo(IWindowSession session, IWindow window, Display display,
17946                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17947            mSession = session;
17948            mWindow = window;
17949            mWindowToken = window.asBinder();
17950            mDisplay = display;
17951            mViewRootImpl = viewRootImpl;
17952            mHandler = handler;
17953            mRootCallbacks = effectPlayer;
17954        }
17955    }
17956
17957    /**
17958     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17959     * is supported. This avoids keeping too many unused fields in most
17960     * instances of View.</p>
17961     */
17962    private static class ScrollabilityCache implements Runnable {
17963
17964        /**
17965         * Scrollbars are not visible
17966         */
17967        public static final int OFF = 0;
17968
17969        /**
17970         * Scrollbars are visible
17971         */
17972        public static final int ON = 1;
17973
17974        /**
17975         * Scrollbars are fading away
17976         */
17977        public static final int FADING = 2;
17978
17979        public boolean fadeScrollBars;
17980
17981        public int fadingEdgeLength;
17982        public int scrollBarDefaultDelayBeforeFade;
17983        public int scrollBarFadeDuration;
17984
17985        public int scrollBarSize;
17986        public ScrollBarDrawable scrollBar;
17987        public float[] interpolatorValues;
17988        public View host;
17989
17990        public final Paint paint;
17991        public final Matrix matrix;
17992        public Shader shader;
17993
17994        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17995
17996        private static final float[] OPAQUE = { 255 };
17997        private static final float[] TRANSPARENT = { 0.0f };
17998
17999        /**
18000         * When fading should start. This time moves into the future every time
18001         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18002         */
18003        public long fadeStartTime;
18004
18005
18006        /**
18007         * The current state of the scrollbars: ON, OFF, or FADING
18008         */
18009        public int state = OFF;
18010
18011        private int mLastColor;
18012
18013        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18014            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18015            scrollBarSize = configuration.getScaledScrollBarSize();
18016            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18017            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18018
18019            paint = new Paint();
18020            matrix = new Matrix();
18021            // use use a height of 1, and then wack the matrix each time we
18022            // actually use it.
18023            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18024            paint.setShader(shader);
18025            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18026
18027            this.host = host;
18028        }
18029
18030        public void setFadeColor(int color) {
18031            if (color != mLastColor) {
18032                mLastColor = color;
18033
18034                if (color != 0) {
18035                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18036                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18037                    paint.setShader(shader);
18038                    // Restore the default transfer mode (src_over)
18039                    paint.setXfermode(null);
18040                } else {
18041                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18042                    paint.setShader(shader);
18043                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18044                }
18045            }
18046        }
18047
18048        public void run() {
18049            long now = AnimationUtils.currentAnimationTimeMillis();
18050            if (now >= fadeStartTime) {
18051
18052                // the animation fades the scrollbars out by changing
18053                // the opacity (alpha) from fully opaque to fully
18054                // transparent
18055                int nextFrame = (int) now;
18056                int framesCount = 0;
18057
18058                Interpolator interpolator = scrollBarInterpolator;
18059
18060                // Start opaque
18061                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18062
18063                // End transparent
18064                nextFrame += scrollBarFadeDuration;
18065                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18066
18067                state = FADING;
18068
18069                // Kick off the fade animation
18070                host.invalidate(true);
18071            }
18072        }
18073    }
18074
18075    /**
18076     * Resuable callback for sending
18077     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18078     */
18079    private class SendViewScrolledAccessibilityEvent implements Runnable {
18080        public volatile boolean mIsPending;
18081
18082        public void run() {
18083            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18084            mIsPending = false;
18085        }
18086    }
18087
18088    /**
18089     * <p>
18090     * This class represents a delegate that can be registered in a {@link View}
18091     * to enhance accessibility support via composition rather via inheritance.
18092     * It is specifically targeted to widget developers that extend basic View
18093     * classes i.e. classes in package android.view, that would like their
18094     * applications to be backwards compatible.
18095     * </p>
18096     * <div class="special reference">
18097     * <h3>Developer Guides</h3>
18098     * <p>For more information about making applications accessible, read the
18099     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18100     * developer guide.</p>
18101     * </div>
18102     * <p>
18103     * A scenario in which a developer would like to use an accessibility delegate
18104     * is overriding a method introduced in a later API version then the minimal API
18105     * version supported by the application. For example, the method
18106     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18107     * in API version 4 when the accessibility APIs were first introduced. If a
18108     * developer would like his application to run on API version 4 devices (assuming
18109     * all other APIs used by the application are version 4 or lower) and take advantage
18110     * of this method, instead of overriding the method which would break the application's
18111     * backwards compatibility, he can override the corresponding method in this
18112     * delegate and register the delegate in the target View if the API version of
18113     * the system is high enough i.e. the API version is same or higher to the API
18114     * version that introduced
18115     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18116     * </p>
18117     * <p>
18118     * Here is an example implementation:
18119     * </p>
18120     * <code><pre><p>
18121     * if (Build.VERSION.SDK_INT >= 14) {
18122     *     // If the API version is equal of higher than the version in
18123     *     // which onInitializeAccessibilityNodeInfo was introduced we
18124     *     // register a delegate with a customized implementation.
18125     *     View view = findViewById(R.id.view_id);
18126     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18127     *         public void onInitializeAccessibilityNodeInfo(View host,
18128     *                 AccessibilityNodeInfo info) {
18129     *             // Let the default implementation populate the info.
18130     *             super.onInitializeAccessibilityNodeInfo(host, info);
18131     *             // Set some other information.
18132     *             info.setEnabled(host.isEnabled());
18133     *         }
18134     *     });
18135     * }
18136     * </code></pre></p>
18137     * <p>
18138     * This delegate contains methods that correspond to the accessibility methods
18139     * in View. If a delegate has been specified the implementation in View hands
18140     * off handling to the corresponding method in this delegate. The default
18141     * implementation the delegate methods behaves exactly as the corresponding
18142     * method in View for the case of no accessibility delegate been set. Hence,
18143     * to customize the behavior of a View method, clients can override only the
18144     * corresponding delegate method without altering the behavior of the rest
18145     * accessibility related methods of the host view.
18146     * </p>
18147     */
18148    public static class AccessibilityDelegate {
18149
18150        /**
18151         * Sends an accessibility event of the given type. If accessibility is not
18152         * enabled this method has no effect.
18153         * <p>
18154         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18155         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18156         * been set.
18157         * </p>
18158         *
18159         * @param host The View hosting the delegate.
18160         * @param eventType The type of the event to send.
18161         *
18162         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18163         */
18164        public void sendAccessibilityEvent(View host, int eventType) {
18165            host.sendAccessibilityEventInternal(eventType);
18166        }
18167
18168        /**
18169         * Performs the specified accessibility action on the view. For
18170         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18171         * <p>
18172         * The default implementation behaves as
18173         * {@link View#performAccessibilityAction(int, Bundle)
18174         *  View#performAccessibilityAction(int, Bundle)} for the case of
18175         *  no accessibility delegate been set.
18176         * </p>
18177         *
18178         * @param action The action to perform.
18179         * @return Whether the action was performed.
18180         *
18181         * @see View#performAccessibilityAction(int, Bundle)
18182         *      View#performAccessibilityAction(int, Bundle)
18183         */
18184        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18185            return host.performAccessibilityActionInternal(action, args);
18186        }
18187
18188        /**
18189         * Sends an accessibility event. This method behaves exactly as
18190         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18191         * empty {@link AccessibilityEvent} and does not perform a check whether
18192         * accessibility is enabled.
18193         * <p>
18194         * The default implementation behaves as
18195         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18196         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18197         * the case of no accessibility delegate been set.
18198         * </p>
18199         *
18200         * @param host The View hosting the delegate.
18201         * @param event The event to send.
18202         *
18203         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18204         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18205         */
18206        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18207            host.sendAccessibilityEventUncheckedInternal(event);
18208        }
18209
18210        /**
18211         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18212         * to its children for adding their text content to the event.
18213         * <p>
18214         * The default implementation behaves as
18215         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18216         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18217         * the case of no accessibility delegate been set.
18218         * </p>
18219         *
18220         * @param host The View hosting the delegate.
18221         * @param event The event.
18222         * @return True if the event population was completed.
18223         *
18224         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18225         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18226         */
18227        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18228            return host.dispatchPopulateAccessibilityEventInternal(event);
18229        }
18230
18231        /**
18232         * Gives a chance to the host View to populate the accessibility event with its
18233         * text content.
18234         * <p>
18235         * The default implementation behaves as
18236         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18237         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18238         * the case of no accessibility delegate been set.
18239         * </p>
18240         *
18241         * @param host The View hosting the delegate.
18242         * @param event The accessibility event which to populate.
18243         *
18244         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18245         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18246         */
18247        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18248            host.onPopulateAccessibilityEventInternal(event);
18249        }
18250
18251        /**
18252         * Initializes an {@link AccessibilityEvent} with information about the
18253         * the host View which is the event source.
18254         * <p>
18255         * The default implementation behaves as
18256         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18257         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18258         * the case of no accessibility delegate been set.
18259         * </p>
18260         *
18261         * @param host The View hosting the delegate.
18262         * @param event The event to initialize.
18263         *
18264         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18265         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18266         */
18267        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18268            host.onInitializeAccessibilityEventInternal(event);
18269        }
18270
18271        /**
18272         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18273         * <p>
18274         * The default implementation behaves as
18275         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18276         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18277         * the case of no accessibility delegate been set.
18278         * </p>
18279         *
18280         * @param host The View hosting the delegate.
18281         * @param info The instance to initialize.
18282         *
18283         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18284         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18285         */
18286        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18287            host.onInitializeAccessibilityNodeInfoInternal(info);
18288        }
18289
18290        /**
18291         * Called when a child of the host View has requested sending an
18292         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18293         * to augment the event.
18294         * <p>
18295         * The default implementation behaves as
18296         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18297         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18298         * the case of no accessibility delegate been set.
18299         * </p>
18300         *
18301         * @param host The View hosting the delegate.
18302         * @param child The child which requests sending the event.
18303         * @param event The event to be sent.
18304         * @return True if the event should be sent
18305         *
18306         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18307         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18308         */
18309        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18310                AccessibilityEvent event) {
18311            return host.onRequestSendAccessibilityEventInternal(child, event);
18312        }
18313
18314        /**
18315         * Gets the provider for managing a virtual view hierarchy rooted at this View
18316         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18317         * that explore the window content.
18318         * <p>
18319         * The default implementation behaves as
18320         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18321         * the case of no accessibility delegate been set.
18322         * </p>
18323         *
18324         * @return The provider.
18325         *
18326         * @see AccessibilityNodeProvider
18327         */
18328        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18329            return null;
18330        }
18331    }
18332
18333    private class MatchIdPredicate implements Predicate<View> {
18334        public int mId;
18335
18336        @Override
18337        public boolean apply(View view) {
18338            return (view.mID == mId);
18339        }
18340    }
18341
18342    private class MatchLabelForPredicate implements Predicate<View> {
18343        private int mLabeledId;
18344
18345        @Override
18346        public boolean apply(View view) {
18347            return (view.mLabelForId == mLabeledId);
18348        }
18349    }
18350
18351    /**
18352     * Dump all private flags in readable format, useful for documentation and
18353     * sanity checking.
18354     */
18355    private static void dumpFlags() {
18356        final HashMap<String, String> found = Maps.newHashMap();
18357        try {
18358            for (Field field : View.class.getDeclaredFields()) {
18359                final int modifiers = field.getModifiers();
18360                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18361                    if (field.getType().equals(int.class)) {
18362                        final int value = field.getInt(null);
18363                        dumpFlag(found, field.getName(), value);
18364                    } else if (field.getType().equals(int[].class)) {
18365                        final int[] values = (int[]) field.get(null);
18366                        for (int i = 0; i < values.length; i++) {
18367                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18368                        }
18369                    }
18370                }
18371            }
18372        } catch (IllegalAccessException e) {
18373            throw new RuntimeException(e);
18374        }
18375
18376        final ArrayList<String> keys = Lists.newArrayList();
18377        keys.addAll(found.keySet());
18378        Collections.sort(keys);
18379        for (String key : keys) {
18380            Log.d(VIEW_LOG_TAG, found.get(key));
18381        }
18382    }
18383
18384    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18385        // Sort flags by prefix, then by bits, always keeping unique keys
18386        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18387        final int prefix = name.indexOf('_');
18388        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18389        final String output = bits + " " + name;
18390        found.put(key, output);
18391    }
18392}
18393