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     */
1868    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1869
1870    /**
1871     * Indicates that the view is tracking some sort of transient state
1872     * that the app should not need to be aware of, but that the framework
1873     * should take special care to preserve.
1874     *
1875     * @hide
1876     */
1877    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1878
1879    /**
1880     * Text direction is inherited thru {@link ViewGroup}
1881     */
1882    public static final int TEXT_DIRECTION_INHERIT = 0;
1883
1884    /**
1885     * Text direction is using "first strong algorithm". The first strong directional character
1886     * determines the paragraph direction. If there is no strong directional character, the
1887     * paragraph direction is the view's resolved layout direction.
1888     */
1889    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1890
1891    /**
1892     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1893     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1894     * If there are neither, the paragraph direction is the view's resolved layout direction.
1895     */
1896    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1897
1898    /**
1899     * Text direction is forced to LTR.
1900     */
1901    public static final int TEXT_DIRECTION_LTR = 3;
1902
1903    /**
1904     * Text direction is forced to RTL.
1905     */
1906    public static final int TEXT_DIRECTION_RTL = 4;
1907
1908    /**
1909     * Text direction is coming from the system Locale.
1910     */
1911    public static final int TEXT_DIRECTION_LOCALE = 5;
1912
1913    /**
1914     * Default text direction is inherited
1915     */
1916    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1917
1918    /**
1919     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1920     * @hide
1921     */
1922    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1923
1924    /**
1925     * Mask for use with private flags indicating bits used for text direction.
1926     * @hide
1927     */
1928    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1929            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Array of text direction flags for mapping attribute "textDirection" to correct
1933     * flag value.
1934     * @hide
1935     */
1936    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1937            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1938            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1939            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1940            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1941            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1942            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1943    };
1944
1945    /**
1946     * Indicates whether the view text direction has been resolved.
1947     * @hide
1948     */
1949    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1950            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1951
1952    /**
1953     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1954     * @hide
1955     */
1956    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1957
1958    /**
1959     * Mask for use with private flags indicating bits used for resolved text direction.
1960     * @hide
1961     */
1962    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1963            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1964
1965    /**
1966     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1967     * @hide
1968     */
1969    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1970            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1971
1972    /*
1973     * Default text alignment. The text alignment of this View is inherited from its parent.
1974     * Use with {@link #setTextAlignment(int)}
1975     */
1976    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1977
1978    /**
1979     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1980     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraphâs text direction.
1981     *
1982     * Use with {@link #setTextAlignment(int)}
1983     */
1984    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1985
1986    /**
1987     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1988     *
1989     * Use with {@link #setTextAlignment(int)}
1990     */
1991    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1992
1993    /**
1994     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1995     *
1996     * Use with {@link #setTextAlignment(int)}
1997     */
1998    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1999
2000    /**
2001     * Center the paragraph, e.g. ALIGN_CENTER.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_CENTER = 4;
2006
2007    /**
2008     * Align to the start of the view, which is ALIGN_LEFT if the viewâs resolved
2009     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2010     *
2011     * Use with {@link #setTextAlignment(int)}
2012     */
2013    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2014
2015    /**
2016     * Align to the end of the view, which is ALIGN_RIGHT if the viewâs resolved
2017     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2018     *
2019     * Use with {@link #setTextAlignment(int)}
2020     */
2021    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2022
2023    /**
2024     * Default text alignment is inherited
2025     */
2026    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2027
2028    /**
2029      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2030      * @hide
2031      */
2032    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2033
2034    /**
2035      * Mask for use with private flags indicating bits used for text alignment.
2036      * @hide
2037      */
2038    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2039
2040    /**
2041     * Array of text direction flags for mapping attribute "textAlignment" to correct
2042     * flag value.
2043     * @hide
2044     */
2045    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2046            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2047            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2048            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2049            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2050            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2051            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2052            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2053    };
2054
2055    /**
2056     * Indicates whether the view text alignment has been resolved.
2057     * @hide
2058     */
2059    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2060
2061    /**
2062     * Bit shift to get the resolved text alignment.
2063     * @hide
2064     */
2065    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2066
2067    /**
2068     * Mask for use with private flags indicating bits used for text alignment.
2069     * @hide
2070     */
2071    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2072            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2073
2074    /**
2075     * Indicates whether if the view text alignment has been resolved to gravity
2076     */
2077    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2078            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2079
2080    // Accessiblity constants for mPrivateFlags2
2081
2082    /**
2083     * Shift for the bits in {@link #mPrivateFlags2} related to the
2084     * "importantForAccessibility" attribute.
2085     */
2086    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2087
2088    /**
2089     * Automatically determine whether a view is important for accessibility.
2090     */
2091    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2092
2093    /**
2094     * The view is important for accessibility.
2095     */
2096    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2097
2098    /**
2099     * The view is not important for accessibility.
2100     */
2101    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2102
2103    /**
2104     * The default whether the view is important for accessibility.
2105     */
2106    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2107
2108    /**
2109     * Mask for obtainig the bits which specify how to determine
2110     * whether a view is important for accessibility.
2111     */
2112    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2113        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2114        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2115
2116    /**
2117     * Flag indicating whether a view has accessibility focus.
2118     */
2119    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2120
2121    /**
2122     * Flag indicating whether a view state for accessibility has changed.
2123     */
2124    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2125            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2126
2127    /**
2128     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2129     * is used to check whether later changes to the view's transform should invalidate the
2130     * view to force the quickReject test to run again.
2131     */
2132    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2133
2134    /**
2135     * Flag indicating that start/end padding has been resolved into left/right padding
2136     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2137     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2138     * during measurement. In some special cases this is required such as when an adapter-based
2139     * view measures prospective children without attaching them to a window.
2140     */
2141    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2142
2143    /**
2144     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2145     */
2146    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2147
2148    /**
2149     * Group of bits indicating that RTL properties resolution is done.
2150     */
2151    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2152            PFLAG2_TEXT_DIRECTION_RESOLVED |
2153            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2154            PFLAG2_PADDING_RESOLVED |
2155            PFLAG2_DRAWABLE_RESOLVED;
2156
2157    // There are a couple of flags left in mPrivateFlags2
2158
2159    /* End of masks for mPrivateFlags2 */
2160
2161    /* Masks for mPrivateFlags3 */
2162
2163    /**
2164     * Flag indicating that view has a transform animation set on it. This is used to track whether
2165     * an animation is cleared between successive frames, in order to tell the associated
2166     * DisplayList to clear its animation matrix.
2167     */
2168    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2169
2170    /**
2171     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2172     * animation is cleared between successive frames, in order to tell the associated
2173     * DisplayList to restore its alpha value.
2174     */
2175    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2176
2177
2178    /* End of masks for mPrivateFlags3 */
2179
2180    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2181
2182    /**
2183     * Always allow a user to over-scroll this view, provided it is a
2184     * view that can scroll.
2185     *
2186     * @see #getOverScrollMode()
2187     * @see #setOverScrollMode(int)
2188     */
2189    public static final int OVER_SCROLL_ALWAYS = 0;
2190
2191    /**
2192     * Allow a user to over-scroll this view only if the content is large
2193     * enough to meaningfully scroll, provided it is a view that can scroll.
2194     *
2195     * @see #getOverScrollMode()
2196     * @see #setOverScrollMode(int)
2197     */
2198    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2199
2200    /**
2201     * Never allow a user to over-scroll this view.
2202     *
2203     * @see #getOverScrollMode()
2204     * @see #setOverScrollMode(int)
2205     */
2206    public static final int OVER_SCROLL_NEVER = 2;
2207
2208    /**
2209     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2210     * requested the system UI (status bar) to be visible (the default).
2211     *
2212     * @see #setSystemUiVisibility(int)
2213     */
2214    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2215
2216    /**
2217     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2218     * system UI to enter an unobtrusive "low profile" mode.
2219     *
2220     * <p>This is for use in games, book readers, video players, or any other
2221     * "immersive" application where the usual system chrome is deemed too distracting.
2222     *
2223     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2224     *
2225     * @see #setSystemUiVisibility(int)
2226     */
2227    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2228
2229    /**
2230     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2231     * system navigation be temporarily hidden.
2232     *
2233     * <p>This is an even less obtrusive state than that called for by
2234     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2235     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2236     * those to disappear. This is useful (in conjunction with the
2237     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2238     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2239     * window flags) for displaying content using every last pixel on the display.
2240     *
2241     * <p>There is a limitation: because navigation controls are so important, the least user
2242     * interaction will cause them to reappear immediately.  When this happens, both
2243     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2244     * so that both elements reappear at the same time.
2245     *
2246     * @see #setSystemUiVisibility(int)
2247     */
2248    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2249
2250    /**
2251     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2252     * into the normal fullscreen mode so that its content can take over the screen
2253     * while still allowing the user to interact with the application.
2254     *
2255     * <p>This has the same visual effect as
2256     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2257     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2258     * meaning that non-critical screen decorations (such as the status bar) will be
2259     * hidden while the user is in the View's window, focusing the experience on
2260     * that content.  Unlike the window flag, if you are using ActionBar in
2261     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2262     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2263     * hide the action bar.
2264     *
2265     * <p>This approach to going fullscreen is best used over the window flag when
2266     * it is a transient state -- that is, the application does this at certain
2267     * points in its user interaction where it wants to allow the user to focus
2268     * on content, but not as a continuous state.  For situations where the application
2269     * would like to simply stay full screen the entire time (such as a game that
2270     * wants to take over the screen), the
2271     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2272     * is usually a better approach.  The state set here will be removed by the system
2273     * in various situations (such as the user moving to another application) like
2274     * the other system UI states.
2275     *
2276     * <p>When using this flag, the application should provide some easy facility
2277     * for the user to go out of it.  A common example would be in an e-book
2278     * reader, where tapping on the screen brings back whatever screen and UI
2279     * decorations that had been hidden while the user was immersed in reading
2280     * the book.
2281     *
2282     * @see #setSystemUiVisibility(int)
2283     */
2284    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2285
2286    /**
2287     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2288     * flags, we would like a stable view of the content insets given to
2289     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2290     * will always represent the worst case that the application can expect
2291     * as a continuous state.  In the stock Android UI this is the space for
2292     * the system bar, nav bar, and status bar, but not more transient elements
2293     * such as an input method.
2294     *
2295     * The stable layout your UI sees is based on the system UI modes you can
2296     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2297     * then you will get a stable layout for changes of the
2298     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2299     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2300     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2301     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2302     * with a stable layout.  (Note that you should avoid using
2303     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2304     *
2305     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2306     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2307     * then a hidden status bar will be considered a "stable" state for purposes
2308     * here.  This allows your UI to continually hide the status bar, while still
2309     * using the system UI flags to hide the action bar while still retaining
2310     * a stable layout.  Note that changing the window fullscreen flag will never
2311     * provide a stable layout for a clean transition.
2312     *
2313     * <p>If you are using ActionBar in
2314     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2315     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2316     * insets it adds to those given to the application.
2317     */
2318    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2319
2320    /**
2321     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2322     * to be layed out as if it has requested
2323     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2324     * allows it to avoid artifacts when switching in and out of that mode, at
2325     * the expense that some of its user interface may be covered by screen
2326     * decorations when they are shown.  You can perform layout of your inner
2327     * UI elements to account for the navagation system UI through the
2328     * {@link #fitSystemWindows(Rect)} method.
2329     */
2330    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2331
2332    /**
2333     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2334     * to be layed out as if it has requested
2335     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2336     * allows it to avoid artifacts when switching in and out of that mode, at
2337     * the expense that some of its user interface may be covered by screen
2338     * decorations when they are shown.  You can perform layout of your inner
2339     * UI elements to account for non-fullscreen system UI through the
2340     * {@link #fitSystemWindows(Rect)} method.
2341     */
2342    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2343
2344    /**
2345     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2346     */
2347    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2348
2349    /**
2350     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2351     */
2352    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2353
2354    /**
2355     * @hide
2356     *
2357     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2358     * out of the public fields to keep the undefined bits out of the developer's way.
2359     *
2360     * Flag to make the status bar not expandable.  Unless you also
2361     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2362     */
2363    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2364
2365    /**
2366     * @hide
2367     *
2368     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2369     * out of the public fields to keep the undefined bits out of the developer's way.
2370     *
2371     * Flag to hide notification icons and scrolling ticker text.
2372     */
2373    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2374
2375    /**
2376     * @hide
2377     *
2378     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2379     * out of the public fields to keep the undefined bits out of the developer's way.
2380     *
2381     * Flag to disable incoming notification alerts.  This will not block
2382     * icons, but it will block sound, vibrating and other visual or aural notifications.
2383     */
2384    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2385
2386    /**
2387     * @hide
2388     *
2389     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2390     * out of the public fields to keep the undefined bits out of the developer's way.
2391     *
2392     * Flag to hide only the scrolling ticker.  Note that
2393     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2394     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2395     */
2396    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2397
2398    /**
2399     * @hide
2400     *
2401     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2402     * out of the public fields to keep the undefined bits out of the developer's way.
2403     *
2404     * Flag to hide the center system info area.
2405     */
2406    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2407
2408    /**
2409     * @hide
2410     *
2411     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2412     * out of the public fields to keep the undefined bits out of the developer's way.
2413     *
2414     * Flag to hide only the home button.  Don't use this
2415     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2416     */
2417    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2418
2419    /**
2420     * @hide
2421     *
2422     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2423     * out of the public fields to keep the undefined bits out of the developer's way.
2424     *
2425     * Flag to hide only the back button. Don't use this
2426     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2427     */
2428    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2429
2430    /**
2431     * @hide
2432     *
2433     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2434     * out of the public fields to keep the undefined bits out of the developer's way.
2435     *
2436     * Flag to hide only the clock.  You might use this if your activity has
2437     * its own clock making the status bar's clock redundant.
2438     */
2439    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2440
2441    /**
2442     * @hide
2443     *
2444     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2445     * out of the public fields to keep the undefined bits out of the developer's way.
2446     *
2447     * Flag to hide only the recent apps button. Don't use this
2448     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2449     */
2450    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2451
2452    /**
2453     * @hide
2454     *
2455     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2456     * out of the public fields to keep the undefined bits out of the developer's way.
2457     *
2458     * Flag to disable the global search gesture. Don't use this
2459     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2460     */
2461    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2462
2463    /**
2464     * @hide
2465     */
2466    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2467
2468    /**
2469     * These are the system UI flags that can be cleared by events outside
2470     * of an application.  Currently this is just the ability to tap on the
2471     * screen while hiding the navigation bar to have it return.
2472     * @hide
2473     */
2474    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2475            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2476            | SYSTEM_UI_FLAG_FULLSCREEN;
2477
2478    /**
2479     * Flags that can impact the layout in relation to system UI.
2480     */
2481    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2482            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2483            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2484
2485    /**
2486     * Find views that render the specified text.
2487     *
2488     * @see #findViewsWithText(ArrayList, CharSequence, int)
2489     */
2490    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2491
2492    /**
2493     * Find find views that contain the specified content description.
2494     *
2495     * @see #findViewsWithText(ArrayList, CharSequence, int)
2496     */
2497    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2498
2499    /**
2500     * Find views that contain {@link AccessibilityNodeProvider}. Such
2501     * a View is a root of virtual view hierarchy and may contain the searched
2502     * text. If this flag is set Views with providers are automatically
2503     * added and it is a responsibility of the client to call the APIs of
2504     * the provider to determine whether the virtual tree rooted at this View
2505     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2506     * represeting the virtual views with this text.
2507     *
2508     * @see #findViewsWithText(ArrayList, CharSequence, int)
2509     *
2510     * @hide
2511     */
2512    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2513
2514    /**
2515     * The undefined cursor position.
2516     */
2517    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2518
2519    /**
2520     * Indicates that the screen has changed state and is now off.
2521     *
2522     * @see #onScreenStateChanged(int)
2523     */
2524    public static final int SCREEN_STATE_OFF = 0x0;
2525
2526    /**
2527     * Indicates that the screen has changed state and is now on.
2528     *
2529     * @see #onScreenStateChanged(int)
2530     */
2531    public static final int SCREEN_STATE_ON = 0x1;
2532
2533    /**
2534     * Controls the over-scroll mode for this view.
2535     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2536     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2537     * and {@link #OVER_SCROLL_NEVER}.
2538     */
2539    private int mOverScrollMode;
2540
2541    /**
2542     * The parent this view is attached to.
2543     * {@hide}
2544     *
2545     * @see #getParent()
2546     */
2547    protected ViewParent mParent;
2548
2549    /**
2550     * {@hide}
2551     */
2552    AttachInfo mAttachInfo;
2553
2554    /**
2555     * {@hide}
2556     */
2557    @ViewDebug.ExportedProperty(flagMapping = {
2558        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2559                name = "FORCE_LAYOUT"),
2560        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2561                name = "LAYOUT_REQUIRED"),
2562        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2563            name = "DRAWING_CACHE_INVALID", outputIf = false),
2564        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2565        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2566        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2567        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2568    })
2569    int mPrivateFlags;
2570    int mPrivateFlags2;
2571    int mPrivateFlags3;
2572
2573    /**
2574     * This view's request for the visibility of the status bar.
2575     * @hide
2576     */
2577    @ViewDebug.ExportedProperty(flagMapping = {
2578        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2579                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2580                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2581        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2582                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2583                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2584        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2585                                equals = SYSTEM_UI_FLAG_VISIBLE,
2586                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2587    })
2588    int mSystemUiVisibility;
2589
2590    /**
2591     * Reference count for transient state.
2592     * @see #setHasTransientState(boolean)
2593     */
2594    int mTransientStateCount = 0;
2595
2596    /**
2597     * Count of how many windows this view has been attached to.
2598     */
2599    int mWindowAttachCount;
2600
2601    /**
2602     * The layout parameters associated with this view and used by the parent
2603     * {@link android.view.ViewGroup} to determine how this view should be
2604     * laid out.
2605     * {@hide}
2606     */
2607    protected ViewGroup.LayoutParams mLayoutParams;
2608
2609    /**
2610     * The view flags hold various views states.
2611     * {@hide}
2612     */
2613    @ViewDebug.ExportedProperty
2614    int mViewFlags;
2615
2616    static class TransformationInfo {
2617        /**
2618         * The transform matrix for the View. This transform is calculated internally
2619         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2620         * is used by default. Do *not* use this variable directly; instead call
2621         * getMatrix(), which will automatically recalculate the matrix if necessary
2622         * to get the correct matrix based on the latest rotation and scale properties.
2623         */
2624        private final Matrix mMatrix = new Matrix();
2625
2626        /**
2627         * The transform matrix for the View. This transform is calculated internally
2628         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2629         * is used by default. Do *not* use this variable directly; instead call
2630         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2631         * to get the correct matrix based on the latest rotation and scale properties.
2632         */
2633        private Matrix mInverseMatrix;
2634
2635        /**
2636         * An internal variable that tracks whether we need to recalculate the
2637         * transform matrix, based on whether the rotation or scaleX/Y properties
2638         * have changed since the matrix was last calculated.
2639         */
2640        boolean mMatrixDirty = false;
2641
2642        /**
2643         * An internal variable that tracks whether we need to recalculate the
2644         * transform matrix, based on whether the rotation or scaleX/Y properties
2645         * have changed since the matrix was last calculated.
2646         */
2647        private boolean mInverseMatrixDirty = true;
2648
2649        /**
2650         * A variable that tracks whether we need to recalculate the
2651         * transform matrix, based on whether the rotation or scaleX/Y properties
2652         * have changed since the matrix was last calculated. This variable
2653         * is only valid after a call to updateMatrix() or to a function that
2654         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2655         */
2656        private boolean mMatrixIsIdentity = true;
2657
2658        /**
2659         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2660         */
2661        private Camera mCamera = null;
2662
2663        /**
2664         * This matrix is used when computing the matrix for 3D rotations.
2665         */
2666        private Matrix matrix3D = null;
2667
2668        /**
2669         * These prev values are used to recalculate a centered pivot point when necessary. The
2670         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2671         * set), so thes values are only used then as well.
2672         */
2673        private int mPrevWidth = -1;
2674        private int mPrevHeight = -1;
2675
2676        /**
2677         * The degrees rotation around the vertical axis through the pivot point.
2678         */
2679        @ViewDebug.ExportedProperty
2680        float mRotationY = 0f;
2681
2682        /**
2683         * The degrees rotation around the horizontal axis through the pivot point.
2684         */
2685        @ViewDebug.ExportedProperty
2686        float mRotationX = 0f;
2687
2688        /**
2689         * The degrees rotation around the pivot point.
2690         */
2691        @ViewDebug.ExportedProperty
2692        float mRotation = 0f;
2693
2694        /**
2695         * The amount of translation of the object away from its left property (post-layout).
2696         */
2697        @ViewDebug.ExportedProperty
2698        float mTranslationX = 0f;
2699
2700        /**
2701         * The amount of translation of the object away from its top property (post-layout).
2702         */
2703        @ViewDebug.ExportedProperty
2704        float mTranslationY = 0f;
2705
2706        /**
2707         * The amount of scale in the x direction around the pivot point. A
2708         * value of 1 means no scaling is applied.
2709         */
2710        @ViewDebug.ExportedProperty
2711        float mScaleX = 1f;
2712
2713        /**
2714         * The amount of scale in the y direction around the pivot point. A
2715         * value of 1 means no scaling is applied.
2716         */
2717        @ViewDebug.ExportedProperty
2718        float mScaleY = 1f;
2719
2720        /**
2721         * The x location of the point around which the view is rotated and scaled.
2722         */
2723        @ViewDebug.ExportedProperty
2724        float mPivotX = 0f;
2725
2726        /**
2727         * The y location of the point around which the view is rotated and scaled.
2728         */
2729        @ViewDebug.ExportedProperty
2730        float mPivotY = 0f;
2731
2732        /**
2733         * The opacity of the View. This is a value from 0 to 1, where 0 means
2734         * completely transparent and 1 means completely opaque.
2735         */
2736        @ViewDebug.ExportedProperty
2737        float mAlpha = 1f;
2738    }
2739
2740    TransformationInfo mTransformationInfo;
2741
2742    private boolean mLastIsOpaque;
2743
2744    /**
2745     * Convenience value to check for float values that are close enough to zero to be considered
2746     * zero.
2747     */
2748    private static final float NONZERO_EPSILON = .001f;
2749
2750    /**
2751     * The distance in pixels from the left edge of this view's parent
2752     * to the left edge of this view.
2753     * {@hide}
2754     */
2755    @ViewDebug.ExportedProperty(category = "layout")
2756    protected int mLeft;
2757    /**
2758     * The distance in pixels from the left edge of this view's parent
2759     * to the right edge of this view.
2760     * {@hide}
2761     */
2762    @ViewDebug.ExportedProperty(category = "layout")
2763    protected int mRight;
2764    /**
2765     * The distance in pixels from the top edge of this view's parent
2766     * to the top edge of this view.
2767     * {@hide}
2768     */
2769    @ViewDebug.ExportedProperty(category = "layout")
2770    protected int mTop;
2771    /**
2772     * The distance in pixels from the top edge of this view's parent
2773     * to the bottom edge of this view.
2774     * {@hide}
2775     */
2776    @ViewDebug.ExportedProperty(category = "layout")
2777    protected int mBottom;
2778
2779    /**
2780     * The offset, in pixels, by which the content of this view is scrolled
2781     * horizontally.
2782     * {@hide}
2783     */
2784    @ViewDebug.ExportedProperty(category = "scrolling")
2785    protected int mScrollX;
2786    /**
2787     * The offset, in pixels, by which the content of this view is scrolled
2788     * vertically.
2789     * {@hide}
2790     */
2791    @ViewDebug.ExportedProperty(category = "scrolling")
2792    protected int mScrollY;
2793
2794    /**
2795     * The left padding in pixels, that is the distance in pixels between the
2796     * left edge of this view and the left edge of its content.
2797     * {@hide}
2798     */
2799    @ViewDebug.ExportedProperty(category = "padding")
2800    protected int mPaddingLeft = 0;
2801    /**
2802     * The right padding in pixels, that is the distance in pixels between the
2803     * right edge of this view and the right edge of its content.
2804     * {@hide}
2805     */
2806    @ViewDebug.ExportedProperty(category = "padding")
2807    protected int mPaddingRight = 0;
2808    /**
2809     * The top padding in pixels, that is the distance in pixels between the
2810     * top edge of this view and the top edge of its content.
2811     * {@hide}
2812     */
2813    @ViewDebug.ExportedProperty(category = "padding")
2814    protected int mPaddingTop;
2815    /**
2816     * The bottom padding in pixels, that is the distance in pixels between the
2817     * bottom edge of this view and the bottom edge of its content.
2818     * {@hide}
2819     */
2820    @ViewDebug.ExportedProperty(category = "padding")
2821    protected int mPaddingBottom;
2822
2823    /**
2824     * The layout insets in pixels, that is the distance in pixels between the
2825     * visible edges of this view its bounds.
2826     */
2827    private Insets mLayoutInsets;
2828
2829    /**
2830     * Briefly describes the view and is primarily used for accessibility support.
2831     */
2832    private CharSequence mContentDescription;
2833
2834    /**
2835     * Specifies the id of a view for which this view serves as a label for
2836     * accessibility purposes.
2837     */
2838    private int mLabelForId = View.NO_ID;
2839
2840    /**
2841     * Predicate for matching labeled view id with its label for
2842     * accessibility purposes.
2843     */
2844    private MatchLabelForPredicate mMatchLabelForPredicate;
2845
2846    /**
2847     * Predicate for matching a view by its id.
2848     */
2849    private MatchIdPredicate mMatchIdPredicate;
2850
2851    /**
2852     * Cache the paddingRight set by the user to append to the scrollbar's size.
2853     *
2854     * @hide
2855     */
2856    @ViewDebug.ExportedProperty(category = "padding")
2857    protected int mUserPaddingRight;
2858
2859    /**
2860     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2861     *
2862     * @hide
2863     */
2864    @ViewDebug.ExportedProperty(category = "padding")
2865    protected int mUserPaddingBottom;
2866
2867    /**
2868     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2869     *
2870     * @hide
2871     */
2872    @ViewDebug.ExportedProperty(category = "padding")
2873    protected int mUserPaddingLeft;
2874
2875    /**
2876     * Cache the paddingStart set by the user to append to the scrollbar's size.
2877     *
2878     */
2879    @ViewDebug.ExportedProperty(category = "padding")
2880    int mUserPaddingStart;
2881
2882    /**
2883     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2884     *
2885     */
2886    @ViewDebug.ExportedProperty(category = "padding")
2887    int mUserPaddingEnd;
2888
2889    /**
2890     * Cache initial left padding.
2891     *
2892     * @hide
2893     */
2894    int mUserPaddingLeftInitial = 0;
2895
2896    /**
2897     * Cache initial right padding.
2898     *
2899     * @hide
2900     */
2901    int mUserPaddingRightInitial = 0;
2902
2903    /**
2904     * Default undefined padding
2905     */
2906    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2907
2908    /**
2909     * @hide
2910     */
2911    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2912    /**
2913     * @hide
2914     */
2915    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2916
2917    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2918    private Drawable mBackground;
2919
2920    private int mBackgroundResource;
2921    private boolean mBackgroundSizeChanged;
2922
2923    static class ListenerInfo {
2924        /**
2925         * Listener used to dispatch focus change events.
2926         * This field should be made private, so it is hidden from the SDK.
2927         * {@hide}
2928         */
2929        protected OnFocusChangeListener mOnFocusChangeListener;
2930
2931        /**
2932         * Listeners for layout change events.
2933         */
2934        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2935
2936        /**
2937         * Listeners for attach events.
2938         */
2939        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2940
2941        /**
2942         * Listener used to dispatch click events.
2943         * This field should be made private, so it is hidden from the SDK.
2944         * {@hide}
2945         */
2946        public OnClickListener mOnClickListener;
2947
2948        /**
2949         * Listener used to dispatch long click events.
2950         * This field should be made private, so it is hidden from the SDK.
2951         * {@hide}
2952         */
2953        protected OnLongClickListener mOnLongClickListener;
2954
2955        /**
2956         * Listener used to build the context menu.
2957         * This field should be made private, so it is hidden from the SDK.
2958         * {@hide}
2959         */
2960        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2961
2962        private OnKeyListener mOnKeyListener;
2963
2964        private OnTouchListener mOnTouchListener;
2965
2966        private OnHoverListener mOnHoverListener;
2967
2968        private OnGenericMotionListener mOnGenericMotionListener;
2969
2970        private OnDragListener mOnDragListener;
2971
2972        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2973    }
2974
2975    ListenerInfo mListenerInfo;
2976
2977    /**
2978     * The application environment this view lives in.
2979     * This field should be made private, so it is hidden from the SDK.
2980     * {@hide}
2981     */
2982    protected Context mContext;
2983
2984    private final Resources mResources;
2985
2986    private ScrollabilityCache mScrollCache;
2987
2988    private int[] mDrawableState = null;
2989
2990    /**
2991     * Set to true when drawing cache is enabled and cannot be created.
2992     *
2993     * @hide
2994     */
2995    public boolean mCachingFailed;
2996
2997    private Bitmap mDrawingCache;
2998    private Bitmap mUnscaledDrawingCache;
2999    private HardwareLayer mHardwareLayer;
3000    DisplayList mDisplayList;
3001
3002    /**
3003     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3004     * the user may specify which view to go to next.
3005     */
3006    private int mNextFocusLeftId = View.NO_ID;
3007
3008    /**
3009     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3010     * the user may specify which view to go to next.
3011     */
3012    private int mNextFocusRightId = View.NO_ID;
3013
3014    /**
3015     * When this view has focus and the next focus is {@link #FOCUS_UP},
3016     * the user may specify which view to go to next.
3017     */
3018    private int mNextFocusUpId = View.NO_ID;
3019
3020    /**
3021     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3022     * the user may specify which view to go to next.
3023     */
3024    private int mNextFocusDownId = View.NO_ID;
3025
3026    /**
3027     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3028     * the user may specify which view to go to next.
3029     */
3030    int mNextFocusForwardId = View.NO_ID;
3031
3032    private CheckForLongPress mPendingCheckForLongPress;
3033    private CheckForTap mPendingCheckForTap = null;
3034    private PerformClick mPerformClick;
3035    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3036
3037    private UnsetPressedState mUnsetPressedState;
3038
3039    /**
3040     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3041     * up event while a long press is invoked as soon as the long press duration is reached, so
3042     * a long press could be performed before the tap is checked, in which case the tap's action
3043     * should not be invoked.
3044     */
3045    private boolean mHasPerformedLongPress;
3046
3047    /**
3048     * The minimum height of the view. We'll try our best to have the height
3049     * of this view to at least this amount.
3050     */
3051    @ViewDebug.ExportedProperty(category = "measurement")
3052    private int mMinHeight;
3053
3054    /**
3055     * The minimum width of the view. We'll try our best to have the width
3056     * of this view to at least this amount.
3057     */
3058    @ViewDebug.ExportedProperty(category = "measurement")
3059    private int mMinWidth;
3060
3061    /**
3062     * The delegate to handle touch events that are physically in this view
3063     * but should be handled by another view.
3064     */
3065    private TouchDelegate mTouchDelegate = null;
3066
3067    /**
3068     * Solid color to use as a background when creating the drawing cache. Enables
3069     * the cache to use 16 bit bitmaps instead of 32 bit.
3070     */
3071    private int mDrawingCacheBackgroundColor = 0;
3072
3073    /**
3074     * Special tree observer used when mAttachInfo is null.
3075     */
3076    private ViewTreeObserver mFloatingTreeObserver;
3077
3078    /**
3079     * Cache the touch slop from the context that created the view.
3080     */
3081    private int mTouchSlop;
3082
3083    /**
3084     * Object that handles automatic animation of view properties.
3085     */
3086    private ViewPropertyAnimator mAnimator = null;
3087
3088    /**
3089     * Flag indicating that a drag can cross window boundaries.  When
3090     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3091     * with this flag set, all visible applications will be able to participate
3092     * in the drag operation and receive the dragged content.
3093     *
3094     * @hide
3095     */
3096    public static final int DRAG_FLAG_GLOBAL = 1;
3097
3098    /**
3099     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3100     */
3101    private float mVerticalScrollFactor;
3102
3103    /**
3104     * Position of the vertical scroll bar.
3105     */
3106    private int mVerticalScrollbarPosition;
3107
3108    /**
3109     * Position the scroll bar at the default position as determined by the system.
3110     */
3111    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3112
3113    /**
3114     * Position the scroll bar along the left edge.
3115     */
3116    public static final int SCROLLBAR_POSITION_LEFT = 1;
3117
3118    /**
3119     * Position the scroll bar along the right edge.
3120     */
3121    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3122
3123    /**
3124     * Indicates that the view does not have a layer.
3125     *
3126     * @see #getLayerType()
3127     * @see #setLayerType(int, android.graphics.Paint)
3128     * @see #LAYER_TYPE_SOFTWARE
3129     * @see #LAYER_TYPE_HARDWARE
3130     */
3131    public static final int LAYER_TYPE_NONE = 0;
3132
3133    /**
3134     * <p>Indicates that the view has a software layer. A software layer is backed
3135     * by a bitmap and causes the view to be rendered using Android's software
3136     * rendering pipeline, even if hardware acceleration is enabled.</p>
3137     *
3138     * <p>Software layers have various usages:</p>
3139     * <p>When the application is not using hardware acceleration, a software layer
3140     * is useful to apply a specific color filter and/or blending mode and/or
3141     * translucency to a view and all its children.</p>
3142     * <p>When the application is using hardware acceleration, a software layer
3143     * is useful to render drawing primitives not supported by the hardware
3144     * accelerated pipeline. It can also be used to cache a complex view tree
3145     * into a texture and reduce the complexity of drawing operations. For instance,
3146     * when animating a complex view tree with a translation, a software layer can
3147     * be used to render the view tree only once.</p>
3148     * <p>Software layers should be avoided when the affected view tree updates
3149     * often. Every update will require to re-render the software layer, which can
3150     * potentially be slow (particularly when hardware acceleration is turned on
3151     * since the layer will have to be uploaded into a hardware texture after every
3152     * update.)</p>
3153     *
3154     * @see #getLayerType()
3155     * @see #setLayerType(int, android.graphics.Paint)
3156     * @see #LAYER_TYPE_NONE
3157     * @see #LAYER_TYPE_HARDWARE
3158     */
3159    public static final int LAYER_TYPE_SOFTWARE = 1;
3160
3161    /**
3162     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3163     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3164     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3165     * rendering pipeline, but only if hardware acceleration is turned on for the
3166     * view hierarchy. When hardware acceleration is turned off, hardware layers
3167     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3168     *
3169     * <p>A hardware layer is useful to apply a specific color filter and/or
3170     * blending mode and/or translucency to a view and all its children.</p>
3171     * <p>A hardware layer can be used to cache a complex view tree into a
3172     * texture and reduce the complexity of drawing operations. For instance,
3173     * when animating a complex view tree with a translation, a hardware layer can
3174     * be used to render the view tree only once.</p>
3175     * <p>A hardware layer can also be used to increase the rendering quality when
3176     * rotation transformations are applied on a view. It can also be used to
3177     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3178     *
3179     * @see #getLayerType()
3180     * @see #setLayerType(int, android.graphics.Paint)
3181     * @see #LAYER_TYPE_NONE
3182     * @see #LAYER_TYPE_SOFTWARE
3183     */
3184    public static final int LAYER_TYPE_HARDWARE = 2;
3185
3186    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3187            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3188            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3189            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3190    })
3191    int mLayerType = LAYER_TYPE_NONE;
3192    Paint mLayerPaint;
3193    Rect mLocalDirtyRect;
3194
3195    /**
3196     * Set to true when the view is sending hover accessibility events because it
3197     * is the innermost hovered view.
3198     */
3199    private boolean mSendingHoverAccessibilityEvents;
3200
3201    /**
3202     * Delegate for injecting accessibility functionality.
3203     */
3204    AccessibilityDelegate mAccessibilityDelegate;
3205
3206    /**
3207     * Consistency verifier for debugging purposes.
3208     * @hide
3209     */
3210    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3211            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3212                    new InputEventConsistencyVerifier(this, 0) : null;
3213
3214    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3215
3216    /**
3217     * Simple constructor to use when creating a view from code.
3218     *
3219     * @param context The Context the view is running in, through which it can
3220     *        access the current theme, resources, etc.
3221     */
3222    public View(Context context) {
3223        mContext = context;
3224        mResources = context != null ? context.getResources() : null;
3225        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3226        // Set some flags defaults
3227        mPrivateFlags2 =
3228                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3229                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3230                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3231                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3232                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3233                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3234        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3235        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3236        mUserPaddingStart = UNDEFINED_PADDING;
3237        mUserPaddingEnd = UNDEFINED_PADDING;
3238    }
3239
3240    /**
3241     * Constructor that is called when inflating a view from XML. This is called
3242     * when a view is being constructed from an XML file, supplying attributes
3243     * that were specified in the XML file. This version uses a default style of
3244     * 0, so the only attribute values applied are those in the Context's Theme
3245     * and the given AttributeSet.
3246     *
3247     * <p>
3248     * The method onFinishInflate() will be called after all children have been
3249     * added.
3250     *
3251     * @param context The Context the view is running in, through which it can
3252     *        access the current theme, resources, etc.
3253     * @param attrs The attributes of the XML tag that is inflating the view.
3254     * @see #View(Context, AttributeSet, int)
3255     */
3256    public View(Context context, AttributeSet attrs) {
3257        this(context, attrs, 0);
3258    }
3259
3260    /**
3261     * Perform inflation from XML and apply a class-specific base style. This
3262     * constructor of View allows subclasses to use their own base style when
3263     * they are inflating. For example, a Button class's constructor would call
3264     * this version of the super class constructor and supply
3265     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3266     * the theme's button style to modify all of the base view attributes (in
3267     * particular its background) as well as the Button class's attributes.
3268     *
3269     * @param context The Context the view is running in, through which it can
3270     *        access the current theme, resources, etc.
3271     * @param attrs The attributes of the XML tag that is inflating the view.
3272     * @param defStyle The default style to apply to this view. If 0, no style
3273     *        will be applied (beyond what is included in the theme). This may
3274     *        either be an attribute resource, whose value will be retrieved
3275     *        from the current theme, or an explicit style resource.
3276     * @see #View(Context, AttributeSet)
3277     */
3278    public View(Context context, AttributeSet attrs, int defStyle) {
3279        this(context);
3280
3281        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3282                defStyle, 0);
3283
3284        Drawable background = null;
3285
3286        int leftPadding = -1;
3287        int topPadding = -1;
3288        int rightPadding = -1;
3289        int bottomPadding = -1;
3290        int startPadding = UNDEFINED_PADDING;
3291        int endPadding = UNDEFINED_PADDING;
3292
3293        int padding = -1;
3294
3295        int viewFlagValues = 0;
3296        int viewFlagMasks = 0;
3297
3298        boolean setScrollContainer = false;
3299
3300        int x = 0;
3301        int y = 0;
3302
3303        float tx = 0;
3304        float ty = 0;
3305        float rotation = 0;
3306        float rotationX = 0;
3307        float rotationY = 0;
3308        float sx = 1f;
3309        float sy = 1f;
3310        boolean transformSet = false;
3311
3312        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3313        int overScrollMode = mOverScrollMode;
3314        boolean initializeScrollbars = false;
3315
3316        boolean leftPaddingDefined = false;
3317        boolean rightPaddingDefined = false;
3318        boolean startPaddingDefined = false;
3319        boolean endPaddingDefined = false;
3320
3321        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3322
3323        final int N = a.getIndexCount();
3324        for (int i = 0; i < N; i++) {
3325            int attr = a.getIndex(i);
3326            switch (attr) {
3327                case com.android.internal.R.styleable.View_background:
3328                    background = a.getDrawable(attr);
3329                    break;
3330                case com.android.internal.R.styleable.View_padding:
3331                    padding = a.getDimensionPixelSize(attr, -1);
3332                    mUserPaddingLeftInitial = padding;
3333                    mUserPaddingRightInitial = padding;
3334                    leftPaddingDefined = true;
3335                    rightPaddingDefined = true;
3336                    break;
3337                 case com.android.internal.R.styleable.View_paddingLeft:
3338                    leftPadding = a.getDimensionPixelSize(attr, -1);
3339                    mUserPaddingLeftInitial = leftPadding;
3340                    leftPaddingDefined = true;
3341                    break;
3342                case com.android.internal.R.styleable.View_paddingTop:
3343                    topPadding = a.getDimensionPixelSize(attr, -1);
3344                    break;
3345                case com.android.internal.R.styleable.View_paddingRight:
3346                    rightPadding = a.getDimensionPixelSize(attr, -1);
3347                    mUserPaddingRightInitial = rightPadding;
3348                    rightPaddingDefined = true;
3349                    break;
3350                case com.android.internal.R.styleable.View_paddingBottom:
3351                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3352                    break;
3353                case com.android.internal.R.styleable.View_paddingStart:
3354                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3355                    startPaddingDefined = true;
3356                    break;
3357                case com.android.internal.R.styleable.View_paddingEnd:
3358                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3359                    endPaddingDefined = true;
3360                    break;
3361                case com.android.internal.R.styleable.View_scrollX:
3362                    x = a.getDimensionPixelOffset(attr, 0);
3363                    break;
3364                case com.android.internal.R.styleable.View_scrollY:
3365                    y = a.getDimensionPixelOffset(attr, 0);
3366                    break;
3367                case com.android.internal.R.styleable.View_alpha:
3368                    setAlpha(a.getFloat(attr, 1f));
3369                    break;
3370                case com.android.internal.R.styleable.View_transformPivotX:
3371                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3372                    break;
3373                case com.android.internal.R.styleable.View_transformPivotY:
3374                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3375                    break;
3376                case com.android.internal.R.styleable.View_translationX:
3377                    tx = a.getDimensionPixelOffset(attr, 0);
3378                    transformSet = true;
3379                    break;
3380                case com.android.internal.R.styleable.View_translationY:
3381                    ty = a.getDimensionPixelOffset(attr, 0);
3382                    transformSet = true;
3383                    break;
3384                case com.android.internal.R.styleable.View_rotation:
3385                    rotation = a.getFloat(attr, 0);
3386                    transformSet = true;
3387                    break;
3388                case com.android.internal.R.styleable.View_rotationX:
3389                    rotationX = a.getFloat(attr, 0);
3390                    transformSet = true;
3391                    break;
3392                case com.android.internal.R.styleable.View_rotationY:
3393                    rotationY = a.getFloat(attr, 0);
3394                    transformSet = true;
3395                    break;
3396                case com.android.internal.R.styleable.View_scaleX:
3397                    sx = a.getFloat(attr, 1f);
3398                    transformSet = true;
3399                    break;
3400                case com.android.internal.R.styleable.View_scaleY:
3401                    sy = a.getFloat(attr, 1f);
3402                    transformSet = true;
3403                    break;
3404                case com.android.internal.R.styleable.View_id:
3405                    mID = a.getResourceId(attr, NO_ID);
3406                    break;
3407                case com.android.internal.R.styleable.View_tag:
3408                    mTag = a.getText(attr);
3409                    break;
3410                case com.android.internal.R.styleable.View_fitsSystemWindows:
3411                    if (a.getBoolean(attr, false)) {
3412                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3413                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3414                    }
3415                    break;
3416                case com.android.internal.R.styleable.View_focusable:
3417                    if (a.getBoolean(attr, false)) {
3418                        viewFlagValues |= FOCUSABLE;
3419                        viewFlagMasks |= FOCUSABLE_MASK;
3420                    }
3421                    break;
3422                case com.android.internal.R.styleable.View_focusableInTouchMode:
3423                    if (a.getBoolean(attr, false)) {
3424                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3425                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3426                    }
3427                    break;
3428                case com.android.internal.R.styleable.View_clickable:
3429                    if (a.getBoolean(attr, false)) {
3430                        viewFlagValues |= CLICKABLE;
3431                        viewFlagMasks |= CLICKABLE;
3432                    }
3433                    break;
3434                case com.android.internal.R.styleable.View_longClickable:
3435                    if (a.getBoolean(attr, false)) {
3436                        viewFlagValues |= LONG_CLICKABLE;
3437                        viewFlagMasks |= LONG_CLICKABLE;
3438                    }
3439                    break;
3440                case com.android.internal.R.styleable.View_saveEnabled:
3441                    if (!a.getBoolean(attr, true)) {
3442                        viewFlagValues |= SAVE_DISABLED;
3443                        viewFlagMasks |= SAVE_DISABLED_MASK;
3444                    }
3445                    break;
3446                case com.android.internal.R.styleable.View_duplicateParentState:
3447                    if (a.getBoolean(attr, false)) {
3448                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3449                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3450                    }
3451                    break;
3452                case com.android.internal.R.styleable.View_visibility:
3453                    final int visibility = a.getInt(attr, 0);
3454                    if (visibility != 0) {
3455                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3456                        viewFlagMasks |= VISIBILITY_MASK;
3457                    }
3458                    break;
3459                case com.android.internal.R.styleable.View_layoutDirection:
3460                    // Clear any layout direction flags (included resolved bits) already set
3461                    mPrivateFlags2 &=
3462                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3463                    // Set the layout direction flags depending on the value of the attribute
3464                    final int layoutDirection = a.getInt(attr, -1);
3465                    final int value = (layoutDirection != -1) ?
3466                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3467                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3468                    break;
3469                case com.android.internal.R.styleable.View_drawingCacheQuality:
3470                    final int cacheQuality = a.getInt(attr, 0);
3471                    if (cacheQuality != 0) {
3472                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3473                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3474                    }
3475                    break;
3476                case com.android.internal.R.styleable.View_contentDescription:
3477                    setContentDescription(a.getString(attr));
3478                    break;
3479                case com.android.internal.R.styleable.View_labelFor:
3480                    setLabelFor(a.getResourceId(attr, NO_ID));
3481                    break;
3482                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3483                    if (!a.getBoolean(attr, true)) {
3484                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3485                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3486                    }
3487                    break;
3488                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3489                    if (!a.getBoolean(attr, true)) {
3490                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3491                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3492                    }
3493                    break;
3494                case R.styleable.View_scrollbars:
3495                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3496                    if (scrollbars != SCROLLBARS_NONE) {
3497                        viewFlagValues |= scrollbars;
3498                        viewFlagMasks |= SCROLLBARS_MASK;
3499                        initializeScrollbars = true;
3500                    }
3501                    break;
3502                //noinspection deprecation
3503                case R.styleable.View_fadingEdge:
3504                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3505                        // Ignore the attribute starting with ICS
3506                        break;
3507                    }
3508                    // With builds < ICS, fall through and apply fading edges
3509                case R.styleable.View_requiresFadingEdge:
3510                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3511                    if (fadingEdge != FADING_EDGE_NONE) {
3512                        viewFlagValues |= fadingEdge;
3513                        viewFlagMasks |= FADING_EDGE_MASK;
3514                        initializeFadingEdge(a);
3515                    }
3516                    break;
3517                case R.styleable.View_scrollbarStyle:
3518                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3519                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3520                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3521                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3522                    }
3523                    break;
3524                case R.styleable.View_isScrollContainer:
3525                    setScrollContainer = true;
3526                    if (a.getBoolean(attr, false)) {
3527                        setScrollContainer(true);
3528                    }
3529                    break;
3530                case com.android.internal.R.styleable.View_keepScreenOn:
3531                    if (a.getBoolean(attr, false)) {
3532                        viewFlagValues |= KEEP_SCREEN_ON;
3533                        viewFlagMasks |= KEEP_SCREEN_ON;
3534                    }
3535                    break;
3536                case R.styleable.View_filterTouchesWhenObscured:
3537                    if (a.getBoolean(attr, false)) {
3538                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3539                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3540                    }
3541                    break;
3542                case R.styleable.View_nextFocusLeft:
3543                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3544                    break;
3545                case R.styleable.View_nextFocusRight:
3546                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3547                    break;
3548                case R.styleable.View_nextFocusUp:
3549                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3550                    break;
3551                case R.styleable.View_nextFocusDown:
3552                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3553                    break;
3554                case R.styleable.View_nextFocusForward:
3555                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3556                    break;
3557                case R.styleable.View_minWidth:
3558                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3559                    break;
3560                case R.styleable.View_minHeight:
3561                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3562                    break;
3563                case R.styleable.View_onClick:
3564                    if (context.isRestricted()) {
3565                        throw new IllegalStateException("The android:onClick attribute cannot "
3566                                + "be used within a restricted context");
3567                    }
3568
3569                    final String handlerName = a.getString(attr);
3570                    if (handlerName != null) {
3571                        setOnClickListener(new OnClickListener() {
3572                            private Method mHandler;
3573
3574                            public void onClick(View v) {
3575                                if (mHandler == null) {
3576                                    try {
3577                                        mHandler = getContext().getClass().getMethod(handlerName,
3578                                                View.class);
3579                                    } catch (NoSuchMethodException e) {
3580                                        int id = getId();
3581                                        String idText = id == NO_ID ? "" : " with id '"
3582                                                + getContext().getResources().getResourceEntryName(
3583                                                    id) + "'";
3584                                        throw new IllegalStateException("Could not find a method " +
3585                                                handlerName + "(View) in the activity "
3586                                                + getContext().getClass() + " for onClick handler"
3587                                                + " on view " + View.this.getClass() + idText, e);
3588                                    }
3589                                }
3590
3591                                try {
3592                                    mHandler.invoke(getContext(), View.this);
3593                                } catch (IllegalAccessException e) {
3594                                    throw new IllegalStateException("Could not execute non "
3595                                            + "public method of the activity", e);
3596                                } catch (InvocationTargetException e) {
3597                                    throw new IllegalStateException("Could not execute "
3598                                            + "method of the activity", e);
3599                                }
3600                            }
3601                        });
3602                    }
3603                    break;
3604                case R.styleable.View_overScrollMode:
3605                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3606                    break;
3607                case R.styleable.View_verticalScrollbarPosition:
3608                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3609                    break;
3610                case R.styleable.View_layerType:
3611                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3612                    break;
3613                case R.styleable.View_textDirection:
3614                    // Clear any text direction flag already set
3615                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3616                    // Set the text direction flags depending on the value of the attribute
3617                    final int textDirection = a.getInt(attr, -1);
3618                    if (textDirection != -1) {
3619                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3620                    }
3621                    break;
3622                case R.styleable.View_textAlignment:
3623                    // Clear any text alignment flag already set
3624                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3625                    // Set the text alignment flag depending on the value of the attribute
3626                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3627                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3628                    break;
3629                case R.styleable.View_importantForAccessibility:
3630                    setImportantForAccessibility(a.getInt(attr,
3631                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3632                    break;
3633            }
3634        }
3635
3636        setOverScrollMode(overScrollMode);
3637
3638        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3639        // the resolved layout direction). Those cached values will be used later during padding
3640        // resolution.
3641        mUserPaddingStart = startPadding;
3642        mUserPaddingEnd = endPadding;
3643
3644        if (background != null) {
3645            setBackground(background);
3646        }
3647
3648        if (padding >= 0) {
3649            leftPadding = padding;
3650            topPadding = padding;
3651            rightPadding = padding;
3652            bottomPadding = padding;
3653            mUserPaddingLeftInitial = padding;
3654            mUserPaddingRightInitial = padding;
3655        }
3656
3657        if (isRtlCompatibilityMode()) {
3658            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3659            // left / right padding are used if defined (meaning here nothing to do). If they are not
3660            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3661            // start / end and resolve them as left / right (layout direction is not taken into account).
3662            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3663            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3664            // defined.
3665            if (!leftPaddingDefined && startPaddingDefined) {
3666                leftPadding = startPadding;
3667            }
3668            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3669            if (!rightPaddingDefined && endPaddingDefined) {
3670                rightPadding = endPadding;
3671            }
3672            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3673        } else {
3674            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3675            // values defined. Otherwise, left /right values are used.
3676            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3677            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3678            // defined.
3679            if (leftPaddingDefined) {
3680                mUserPaddingLeftInitial = leftPadding;
3681            }
3682            if (rightPaddingDefined) {
3683                mUserPaddingRightInitial = rightPadding;
3684            }
3685        }
3686
3687        internalSetPadding(
3688                mUserPaddingLeftInitial,
3689                topPadding >= 0 ? topPadding : mPaddingTop,
3690                mUserPaddingRightInitial,
3691                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3692
3693        if (viewFlagMasks != 0) {
3694            setFlags(viewFlagValues, viewFlagMasks);
3695        }
3696
3697        if (initializeScrollbars) {
3698            initializeScrollbars(a);
3699        }
3700
3701        a.recycle();
3702
3703        // Needs to be called after mViewFlags is set
3704        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3705            recomputePadding();
3706        }
3707
3708        if (x != 0 || y != 0) {
3709            scrollTo(x, y);
3710        }
3711
3712        if (transformSet) {
3713            setTranslationX(tx);
3714            setTranslationY(ty);
3715            setRotation(rotation);
3716            setRotationX(rotationX);
3717            setRotationY(rotationY);
3718            setScaleX(sx);
3719            setScaleY(sy);
3720        }
3721
3722        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3723            setScrollContainer(true);
3724        }
3725
3726        computeOpaqueFlags();
3727    }
3728
3729    /**
3730     * Non-public constructor for use in testing
3731     */
3732    View() {
3733        mResources = null;
3734    }
3735
3736    public String toString() {
3737        StringBuilder out = new StringBuilder(128);
3738        out.append(getClass().getName());
3739        out.append('{');
3740        out.append(Integer.toHexString(System.identityHashCode(this)));
3741        out.append(' ');
3742        switch (mViewFlags&VISIBILITY_MASK) {
3743            case VISIBLE: out.append('V'); break;
3744            case INVISIBLE: out.append('I'); break;
3745            case GONE: out.append('G'); break;
3746            default: out.append('.'); break;
3747        }
3748        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3749        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3750        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3751        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3752        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3753        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3754        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3755        out.append(' ');
3756        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3757        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3758        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3759        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3760            out.append('p');
3761        } else {
3762            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3763        }
3764        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3765        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3766        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3767        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3768        out.append(' ');
3769        out.append(mLeft);
3770        out.append(',');
3771        out.append(mTop);
3772        out.append('-');
3773        out.append(mRight);
3774        out.append(',');
3775        out.append(mBottom);
3776        final int id = getId();
3777        if (id != NO_ID) {
3778            out.append(" #");
3779            out.append(Integer.toHexString(id));
3780            final Resources r = mResources;
3781            if (id != 0 && r != null) {
3782                try {
3783                    String pkgname;
3784                    switch (id&0xff000000) {
3785                        case 0x7f000000:
3786                            pkgname="app";
3787                            break;
3788                        case 0x01000000:
3789                            pkgname="android";
3790                            break;
3791                        default:
3792                            pkgname = r.getResourcePackageName(id);
3793                            break;
3794                    }
3795                    String typename = r.getResourceTypeName(id);
3796                    String entryname = r.getResourceEntryName(id);
3797                    out.append(" ");
3798                    out.append(pkgname);
3799                    out.append(":");
3800                    out.append(typename);
3801                    out.append("/");
3802                    out.append(entryname);
3803                } catch (Resources.NotFoundException e) {
3804                }
3805            }
3806        }
3807        out.append("}");
3808        return out.toString();
3809    }
3810
3811    /**
3812     * <p>
3813     * Initializes the fading edges from a given set of styled attributes. This
3814     * method should be called by subclasses that need fading edges and when an
3815     * instance of these subclasses is created programmatically rather than
3816     * being inflated from XML. This method is automatically called when the XML
3817     * is inflated.
3818     * </p>
3819     *
3820     * @param a the styled attributes set to initialize the fading edges from
3821     */
3822    protected void initializeFadingEdge(TypedArray a) {
3823        initScrollCache();
3824
3825        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3826                R.styleable.View_fadingEdgeLength,
3827                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3828    }
3829
3830    /**
3831     * Returns the size of the vertical faded edges used to indicate that more
3832     * content in this view is visible.
3833     *
3834     * @return The size in pixels of the vertical faded edge or 0 if vertical
3835     *         faded edges are not enabled for this view.
3836     * @attr ref android.R.styleable#View_fadingEdgeLength
3837     */
3838    public int getVerticalFadingEdgeLength() {
3839        if (isVerticalFadingEdgeEnabled()) {
3840            ScrollabilityCache cache = mScrollCache;
3841            if (cache != null) {
3842                return cache.fadingEdgeLength;
3843            }
3844        }
3845        return 0;
3846    }
3847
3848    /**
3849     * Set the size of the faded edge used to indicate that more content in this
3850     * view is available.  Will not change whether the fading edge is enabled; use
3851     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3852     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3853     * for the vertical or horizontal fading edges.
3854     *
3855     * @param length The size in pixels of the faded edge used to indicate that more
3856     *        content in this view is visible.
3857     */
3858    public void setFadingEdgeLength(int length) {
3859        initScrollCache();
3860        mScrollCache.fadingEdgeLength = length;
3861    }
3862
3863    /**
3864     * Returns the size of the horizontal faded edges used to indicate that more
3865     * content in this view is visible.
3866     *
3867     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3868     *         faded edges are not enabled for this view.
3869     * @attr ref android.R.styleable#View_fadingEdgeLength
3870     */
3871    public int getHorizontalFadingEdgeLength() {
3872        if (isHorizontalFadingEdgeEnabled()) {
3873            ScrollabilityCache cache = mScrollCache;
3874            if (cache != null) {
3875                return cache.fadingEdgeLength;
3876            }
3877        }
3878        return 0;
3879    }
3880
3881    /**
3882     * Returns the width of the vertical scrollbar.
3883     *
3884     * @return The width in pixels of the vertical scrollbar or 0 if there
3885     *         is no vertical scrollbar.
3886     */
3887    public int getVerticalScrollbarWidth() {
3888        ScrollabilityCache cache = mScrollCache;
3889        if (cache != null) {
3890            ScrollBarDrawable scrollBar = cache.scrollBar;
3891            if (scrollBar != null) {
3892                int size = scrollBar.getSize(true);
3893                if (size <= 0) {
3894                    size = cache.scrollBarSize;
3895                }
3896                return size;
3897            }
3898            return 0;
3899        }
3900        return 0;
3901    }
3902
3903    /**
3904     * Returns the height of the horizontal scrollbar.
3905     *
3906     * @return The height in pixels of the horizontal scrollbar or 0 if
3907     *         there is no horizontal scrollbar.
3908     */
3909    protected int getHorizontalScrollbarHeight() {
3910        ScrollabilityCache cache = mScrollCache;
3911        if (cache != null) {
3912            ScrollBarDrawable scrollBar = cache.scrollBar;
3913            if (scrollBar != null) {
3914                int size = scrollBar.getSize(false);
3915                if (size <= 0) {
3916                    size = cache.scrollBarSize;
3917                }
3918                return size;
3919            }
3920            return 0;
3921        }
3922        return 0;
3923    }
3924
3925    /**
3926     * <p>
3927     * Initializes the scrollbars from a given set of styled attributes. This
3928     * method should be called by subclasses that need scrollbars and when an
3929     * instance of these subclasses is created programmatically rather than
3930     * being inflated from XML. This method is automatically called when the XML
3931     * is inflated.
3932     * </p>
3933     *
3934     * @param a the styled attributes set to initialize the scrollbars from
3935     */
3936    protected void initializeScrollbars(TypedArray a) {
3937        initScrollCache();
3938
3939        final ScrollabilityCache scrollabilityCache = mScrollCache;
3940
3941        if (scrollabilityCache.scrollBar == null) {
3942            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3943        }
3944
3945        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3946
3947        if (!fadeScrollbars) {
3948            scrollabilityCache.state = ScrollabilityCache.ON;
3949        }
3950        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3951
3952
3953        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3954                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3955                        .getScrollBarFadeDuration());
3956        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3957                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3958                ViewConfiguration.getScrollDefaultDelay());
3959
3960
3961        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3962                com.android.internal.R.styleable.View_scrollbarSize,
3963                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3964
3965        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3966        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3967
3968        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3969        if (thumb != null) {
3970            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3971        }
3972
3973        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3974                false);
3975        if (alwaysDraw) {
3976            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3977        }
3978
3979        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3980        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3981
3982        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3983        if (thumb != null) {
3984            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3985        }
3986
3987        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3988                false);
3989        if (alwaysDraw) {
3990            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3991        }
3992
3993        // Apply layout direction to the new Drawables if needed
3994        final int layoutDirection = getLayoutDirection();
3995        if (track != null) {
3996            track.setLayoutDirection(layoutDirection);
3997        }
3998        if (thumb != null) {
3999            thumb.setLayoutDirection(layoutDirection);
4000        }
4001
4002        // Re-apply user/background padding so that scrollbar(s) get added
4003        resolvePadding();
4004    }
4005
4006    /**
4007     * <p>
4008     * Initalizes the scrollability cache if necessary.
4009     * </p>
4010     */
4011    private void initScrollCache() {
4012        if (mScrollCache == null) {
4013            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4014        }
4015    }
4016
4017    private ScrollabilityCache getScrollCache() {
4018        initScrollCache();
4019        return mScrollCache;
4020    }
4021
4022    /**
4023     * Set the position of the vertical scroll bar. Should be one of
4024     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4025     * {@link #SCROLLBAR_POSITION_RIGHT}.
4026     *
4027     * @param position Where the vertical scroll bar should be positioned.
4028     */
4029    public void setVerticalScrollbarPosition(int position) {
4030        if (mVerticalScrollbarPosition != position) {
4031            mVerticalScrollbarPosition = position;
4032            computeOpaqueFlags();
4033            resolvePadding();
4034        }
4035    }
4036
4037    /**
4038     * @return The position where the vertical scroll bar will show, if applicable.
4039     * @see #setVerticalScrollbarPosition(int)
4040     */
4041    public int getVerticalScrollbarPosition() {
4042        return mVerticalScrollbarPosition;
4043    }
4044
4045    ListenerInfo getListenerInfo() {
4046        if (mListenerInfo != null) {
4047            return mListenerInfo;
4048        }
4049        mListenerInfo = new ListenerInfo();
4050        return mListenerInfo;
4051    }
4052
4053    /**
4054     * Register a callback to be invoked when focus of this view changed.
4055     *
4056     * @param l The callback that will run.
4057     */
4058    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4059        getListenerInfo().mOnFocusChangeListener = l;
4060    }
4061
4062    /**
4063     * Add a listener that will be called when the bounds of the view change due to
4064     * layout processing.
4065     *
4066     * @param listener The listener that will be called when layout bounds change.
4067     */
4068    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4069        ListenerInfo li = getListenerInfo();
4070        if (li.mOnLayoutChangeListeners == null) {
4071            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4072        }
4073        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4074            li.mOnLayoutChangeListeners.add(listener);
4075        }
4076    }
4077
4078    /**
4079     * Remove a listener for layout changes.
4080     *
4081     * @param listener The listener for layout bounds change.
4082     */
4083    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4084        ListenerInfo li = mListenerInfo;
4085        if (li == null || li.mOnLayoutChangeListeners == null) {
4086            return;
4087        }
4088        li.mOnLayoutChangeListeners.remove(listener);
4089    }
4090
4091    /**
4092     * Add a listener for attach state changes.
4093     *
4094     * This listener will be called whenever this view is attached or detached
4095     * from a window. Remove the listener using
4096     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4097     *
4098     * @param listener Listener to attach
4099     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4100     */
4101    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4102        ListenerInfo li = getListenerInfo();
4103        if (li.mOnAttachStateChangeListeners == null) {
4104            li.mOnAttachStateChangeListeners
4105                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4106        }
4107        li.mOnAttachStateChangeListeners.add(listener);
4108    }
4109
4110    /**
4111     * Remove a listener for attach state changes. The listener will receive no further
4112     * notification of window attach/detach events.
4113     *
4114     * @param listener Listener to remove
4115     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4116     */
4117    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4118        ListenerInfo li = mListenerInfo;
4119        if (li == null || li.mOnAttachStateChangeListeners == null) {
4120            return;
4121        }
4122        li.mOnAttachStateChangeListeners.remove(listener);
4123    }
4124
4125    /**
4126     * Returns the focus-change callback registered for this view.
4127     *
4128     * @return The callback, or null if one is not registered.
4129     */
4130    public OnFocusChangeListener getOnFocusChangeListener() {
4131        ListenerInfo li = mListenerInfo;
4132        return li != null ? li.mOnFocusChangeListener : null;
4133    }
4134
4135    /**
4136     * Register a callback to be invoked when this view is clicked. If this view is not
4137     * clickable, it becomes clickable.
4138     *
4139     * @param l The callback that will run
4140     *
4141     * @see #setClickable(boolean)
4142     */
4143    public void setOnClickListener(OnClickListener l) {
4144        if (!isClickable()) {
4145            setClickable(true);
4146        }
4147        getListenerInfo().mOnClickListener = l;
4148    }
4149
4150    /**
4151     * Return whether this view has an attached OnClickListener.  Returns
4152     * true if there is a listener, false if there is none.
4153     */
4154    public boolean hasOnClickListeners() {
4155        ListenerInfo li = mListenerInfo;
4156        return (li != null && li.mOnClickListener != null);
4157    }
4158
4159    /**
4160     * Register a callback to be invoked when this view is clicked and held. If this view is not
4161     * long clickable, it becomes long clickable.
4162     *
4163     * @param l The callback that will run
4164     *
4165     * @see #setLongClickable(boolean)
4166     */
4167    public void setOnLongClickListener(OnLongClickListener l) {
4168        if (!isLongClickable()) {
4169            setLongClickable(true);
4170        }
4171        getListenerInfo().mOnLongClickListener = l;
4172    }
4173
4174    /**
4175     * Register a callback to be invoked when the context menu for this view is
4176     * being built. If this view is not long clickable, it becomes long clickable.
4177     *
4178     * @param l The callback that will run
4179     *
4180     */
4181    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4182        if (!isLongClickable()) {
4183            setLongClickable(true);
4184        }
4185        getListenerInfo().mOnCreateContextMenuListener = l;
4186    }
4187
4188    /**
4189     * Call this view's OnClickListener, if it is defined.  Performs all normal
4190     * actions associated with clicking: reporting accessibility event, playing
4191     * a sound, etc.
4192     *
4193     * @return True there was an assigned OnClickListener that was called, false
4194     *         otherwise is returned.
4195     */
4196    public boolean performClick() {
4197        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4198
4199        ListenerInfo li = mListenerInfo;
4200        if (li != null && li.mOnClickListener != null) {
4201            playSoundEffect(SoundEffectConstants.CLICK);
4202            li.mOnClickListener.onClick(this);
4203            return true;
4204        }
4205
4206        return false;
4207    }
4208
4209    /**
4210     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4211     * this only calls the listener, and does not do any associated clicking
4212     * actions like reporting an accessibility event.
4213     *
4214     * @return True there was an assigned OnClickListener that was called, false
4215     *         otherwise is returned.
4216     */
4217    public boolean callOnClick() {
4218        ListenerInfo li = mListenerInfo;
4219        if (li != null && li.mOnClickListener != null) {
4220            li.mOnClickListener.onClick(this);
4221            return true;
4222        }
4223        return false;
4224    }
4225
4226    /**
4227     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4228     * OnLongClickListener did not consume the event.
4229     *
4230     * @return True if one of the above receivers consumed the event, false otherwise.
4231     */
4232    public boolean performLongClick() {
4233        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4234
4235        boolean handled = false;
4236        ListenerInfo li = mListenerInfo;
4237        if (li != null && li.mOnLongClickListener != null) {
4238            handled = li.mOnLongClickListener.onLongClick(View.this);
4239        }
4240        if (!handled) {
4241            handled = showContextMenu();
4242        }
4243        if (handled) {
4244            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4245        }
4246        return handled;
4247    }
4248
4249    /**
4250     * Performs button-related actions during a touch down event.
4251     *
4252     * @param event The event.
4253     * @return True if the down was consumed.
4254     *
4255     * @hide
4256     */
4257    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4258        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4259            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4260                return true;
4261            }
4262        }
4263        return false;
4264    }
4265
4266    /**
4267     * Bring up the context menu for this view.
4268     *
4269     * @return Whether a context menu was displayed.
4270     */
4271    public boolean showContextMenu() {
4272        return getParent().showContextMenuForChild(this);
4273    }
4274
4275    /**
4276     * Bring up the context menu for this view, referring to the item under the specified point.
4277     *
4278     * @param x The referenced x coordinate.
4279     * @param y The referenced y coordinate.
4280     * @param metaState The keyboard modifiers that were pressed.
4281     * @return Whether a context menu was displayed.
4282     *
4283     * @hide
4284     */
4285    public boolean showContextMenu(float x, float y, int metaState) {
4286        return showContextMenu();
4287    }
4288
4289    /**
4290     * Start an action mode.
4291     *
4292     * @param callback Callback that will control the lifecycle of the action mode
4293     * @return The new action mode if it is started, null otherwise
4294     *
4295     * @see ActionMode
4296     */
4297    public ActionMode startActionMode(ActionMode.Callback callback) {
4298        ViewParent parent = getParent();
4299        if (parent == null) return null;
4300        return parent.startActionModeForChild(this, callback);
4301    }
4302
4303    /**
4304     * Register a callback to be invoked when a hardware key is pressed in this view.
4305     * Key presses in software input methods will generally not trigger the methods of
4306     * this listener.
4307     * @param l the key listener to attach to this view
4308     */
4309    public void setOnKeyListener(OnKeyListener l) {
4310        getListenerInfo().mOnKeyListener = l;
4311    }
4312
4313    /**
4314     * Register a callback to be invoked when a touch event is sent to this view.
4315     * @param l the touch listener to attach to this view
4316     */
4317    public void setOnTouchListener(OnTouchListener l) {
4318        getListenerInfo().mOnTouchListener = l;
4319    }
4320
4321    /**
4322     * Register a callback to be invoked when a generic motion event is sent to this view.
4323     * @param l the generic motion listener to attach to this view
4324     */
4325    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4326        getListenerInfo().mOnGenericMotionListener = l;
4327    }
4328
4329    /**
4330     * Register a callback to be invoked when a hover event is sent to this view.
4331     * @param l the hover listener to attach to this view
4332     */
4333    public void setOnHoverListener(OnHoverListener l) {
4334        getListenerInfo().mOnHoverListener = l;
4335    }
4336
4337    /**
4338     * Register a drag event listener callback object for this View. The parameter is
4339     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4340     * View, the system calls the
4341     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4342     * @param l An implementation of {@link android.view.View.OnDragListener}.
4343     */
4344    public void setOnDragListener(OnDragListener l) {
4345        getListenerInfo().mOnDragListener = l;
4346    }
4347
4348    /**
4349     * Give this view focus. This will cause
4350     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4351     *
4352     * Note: this does not check whether this {@link View} should get focus, it just
4353     * gives it focus no matter what.  It should only be called internally by framework
4354     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4355     *
4356     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4357     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4358     *        focus moved when requestFocus() is called. It may not always
4359     *        apply, in which case use the default View.FOCUS_DOWN.
4360     * @param previouslyFocusedRect The rectangle of the view that had focus
4361     *        prior in this View's coordinate system.
4362     */
4363    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4364        if (DBG) {
4365            System.out.println(this + " requestFocus()");
4366        }
4367
4368        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4369            mPrivateFlags |= PFLAG_FOCUSED;
4370
4371            if (mParent != null) {
4372                mParent.requestChildFocus(this, this);
4373            }
4374
4375            onFocusChanged(true, direction, previouslyFocusedRect);
4376            refreshDrawableState();
4377
4378            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4379                notifyAccessibilityStateChanged();
4380            }
4381        }
4382    }
4383
4384    /**
4385     * Request that a rectangle of this view be visible on the screen,
4386     * scrolling if necessary just enough.
4387     *
4388     * <p>A View should call this if it maintains some notion of which part
4389     * of its content is interesting.  For example, a text editing view
4390     * should call this when its cursor moves.
4391     *
4392     * @param rectangle The rectangle.
4393     * @return Whether any parent scrolled.
4394     */
4395    public boolean requestRectangleOnScreen(Rect rectangle) {
4396        return requestRectangleOnScreen(rectangle, false);
4397    }
4398
4399    /**
4400     * Request that a rectangle of this view be visible on the screen,
4401     * scrolling if necessary just enough.
4402     *
4403     * <p>A View should call this if it maintains some notion of which part
4404     * of its content is interesting.  For example, a text editing view
4405     * should call this when its cursor moves.
4406     *
4407     * <p>When <code>immediate</code> is set to true, scrolling will not be
4408     * animated.
4409     *
4410     * @param rectangle The rectangle.
4411     * @param immediate True to forbid animated scrolling, false otherwise
4412     * @return Whether any parent scrolled.
4413     */
4414    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4415        if (mParent == null) {
4416            return false;
4417        }
4418
4419        View child = this;
4420
4421        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4422        position.set(rectangle);
4423
4424        ViewParent parent = mParent;
4425        boolean scrolled = false;
4426        while (parent != null) {
4427            rectangle.set((int) position.left, (int) position.top,
4428                    (int) position.right, (int) position.bottom);
4429
4430            scrolled |= parent.requestChildRectangleOnScreen(child,
4431                    rectangle, immediate);
4432
4433            if (!child.hasIdentityMatrix()) {
4434                child.getMatrix().mapRect(position);
4435            }
4436
4437            position.offset(child.mLeft, child.mTop);
4438
4439            if (!(parent instanceof View)) {
4440                break;
4441            }
4442
4443            View parentView = (View) parent;
4444
4445            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4446
4447            child = parentView;
4448            parent = child.getParent();
4449        }
4450
4451        return scrolled;
4452    }
4453
4454    /**
4455     * Called when this view wants to give up focus. If focus is cleared
4456     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4457     * <p>
4458     * <strong>Note:</strong> When a View clears focus the framework is trying
4459     * to give focus to the first focusable View from the top. Hence, if this
4460     * View is the first from the top that can take focus, then all callbacks
4461     * related to clearing focus will be invoked after wich the framework will
4462     * give focus to this view.
4463     * </p>
4464     */
4465    public void clearFocus() {
4466        if (DBG) {
4467            System.out.println(this + " clearFocus()");
4468        }
4469
4470        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4471            mPrivateFlags &= ~PFLAG_FOCUSED;
4472
4473            if (mParent != null) {
4474                mParent.clearChildFocus(this);
4475            }
4476
4477            onFocusChanged(false, 0, null);
4478
4479            refreshDrawableState();
4480
4481            ensureInputFocusOnFirstFocusable();
4482
4483            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4484                notifyAccessibilityStateChanged();
4485            }
4486        }
4487    }
4488
4489    void ensureInputFocusOnFirstFocusable() {
4490        View root = getRootView();
4491        if (root != null) {
4492            root.requestFocus();
4493        }
4494    }
4495
4496    /**
4497     * Called internally by the view system when a new view is getting focus.
4498     * This is what clears the old focus.
4499     */
4500    void unFocus() {
4501        if (DBG) {
4502            System.out.println(this + " unFocus()");
4503        }
4504
4505        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4506            mPrivateFlags &= ~PFLAG_FOCUSED;
4507
4508            onFocusChanged(false, 0, null);
4509            refreshDrawableState();
4510
4511            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4512                notifyAccessibilityStateChanged();
4513            }
4514        }
4515    }
4516
4517    /**
4518     * Returns true if this view has focus iteself, or is the ancestor of the
4519     * view that has focus.
4520     *
4521     * @return True if this view has or contains focus, false otherwise.
4522     */
4523    @ViewDebug.ExportedProperty(category = "focus")
4524    public boolean hasFocus() {
4525        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4526    }
4527
4528    /**
4529     * Returns true if this view is focusable or if it contains a reachable View
4530     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4531     * is a View whose parents do not block descendants focus.
4532     *
4533     * Only {@link #VISIBLE} views are considered focusable.
4534     *
4535     * @return True if the view is focusable or if the view contains a focusable
4536     *         View, false otherwise.
4537     *
4538     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4539     */
4540    public boolean hasFocusable() {
4541        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4542    }
4543
4544    /**
4545     * Called by the view system when the focus state of this view changes.
4546     * When the focus change event is caused by directional navigation, direction
4547     * and previouslyFocusedRect provide insight into where the focus is coming from.
4548     * When overriding, be sure to call up through to the super class so that
4549     * the standard focus handling will occur.
4550     *
4551     * @param gainFocus True if the View has focus; false otherwise.
4552     * @param direction The direction focus has moved when requestFocus()
4553     *                  is called to give this view focus. Values are
4554     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4555     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4556     *                  It may not always apply, in which case use the default.
4557     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4558     *        system, of the previously focused view.  If applicable, this will be
4559     *        passed in as finer grained information about where the focus is coming
4560     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4561     */
4562    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4563        if (gainFocus) {
4564            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4565                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4566            }
4567        }
4568
4569        InputMethodManager imm = InputMethodManager.peekInstance();
4570        if (!gainFocus) {
4571            if (isPressed()) {
4572                setPressed(false);
4573            }
4574            if (imm != null && mAttachInfo != null
4575                    && mAttachInfo.mHasWindowFocus) {
4576                imm.focusOut(this);
4577            }
4578            onFocusLost();
4579        } else if (imm != null && mAttachInfo != null
4580                && mAttachInfo.mHasWindowFocus) {
4581            imm.focusIn(this);
4582        }
4583
4584        invalidate(true);
4585        ListenerInfo li = mListenerInfo;
4586        if (li != null && li.mOnFocusChangeListener != null) {
4587            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4588        }
4589
4590        if (mAttachInfo != null) {
4591            mAttachInfo.mKeyDispatchState.reset(this);
4592        }
4593    }
4594
4595    /**
4596     * Sends an accessibility event of the given type. If accessibility is
4597     * not enabled this method has no effect. The default implementation calls
4598     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4599     * to populate information about the event source (this View), then calls
4600     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4601     * populate the text content of the event source including its descendants,
4602     * and last calls
4603     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4604     * on its parent to resuest sending of the event to interested parties.
4605     * <p>
4606     * If an {@link AccessibilityDelegate} has been specified via calling
4607     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4608     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4609     * responsible for handling this call.
4610     * </p>
4611     *
4612     * @param eventType The type of the event to send, as defined by several types from
4613     * {@link android.view.accessibility.AccessibilityEvent}, such as
4614     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4615     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4616     *
4617     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4618     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4619     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4620     * @see AccessibilityDelegate
4621     */
4622    public void sendAccessibilityEvent(int eventType) {
4623        if (mAccessibilityDelegate != null) {
4624            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4625        } else {
4626            sendAccessibilityEventInternal(eventType);
4627        }
4628    }
4629
4630    /**
4631     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4632     * {@link AccessibilityEvent} to make an announcement which is related to some
4633     * sort of a context change for which none of the events representing UI transitions
4634     * is a good fit. For example, announcing a new page in a book. If accessibility
4635     * is not enabled this method does nothing.
4636     *
4637     * @param text The announcement text.
4638     */
4639    public void announceForAccessibility(CharSequence text) {
4640        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4641            AccessibilityEvent event = AccessibilityEvent.obtain(
4642                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4643            onInitializeAccessibilityEvent(event);
4644            event.getText().add(text);
4645            event.setContentDescription(null);
4646            mParent.requestSendAccessibilityEvent(this, event);
4647        }
4648    }
4649
4650    /**
4651     * @see #sendAccessibilityEvent(int)
4652     *
4653     * Note: Called from the default {@link AccessibilityDelegate}.
4654     */
4655    void sendAccessibilityEventInternal(int eventType) {
4656        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4657            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4658        }
4659    }
4660
4661    /**
4662     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4663     * takes as an argument an empty {@link AccessibilityEvent} and does not
4664     * perform a check whether accessibility is enabled.
4665     * <p>
4666     * If an {@link AccessibilityDelegate} has been specified via calling
4667     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4668     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4669     * is responsible for handling this call.
4670     * </p>
4671     *
4672     * @param event The event to send.
4673     *
4674     * @see #sendAccessibilityEvent(int)
4675     */
4676    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4677        if (mAccessibilityDelegate != null) {
4678            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4679        } else {
4680            sendAccessibilityEventUncheckedInternal(event);
4681        }
4682    }
4683
4684    /**
4685     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4686     *
4687     * Note: Called from the default {@link AccessibilityDelegate}.
4688     */
4689    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4690        if (!isShown()) {
4691            return;
4692        }
4693        onInitializeAccessibilityEvent(event);
4694        // Only a subset of accessibility events populates text content.
4695        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4696            dispatchPopulateAccessibilityEvent(event);
4697        }
4698        // In the beginning we called #isShown(), so we know that getParent() is not null.
4699        getParent().requestSendAccessibilityEvent(this, event);
4700    }
4701
4702    /**
4703     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4704     * to its children for adding their text content to the event. Note that the
4705     * event text is populated in a separate dispatch path since we add to the
4706     * event not only the text of the source but also the text of all its descendants.
4707     * A typical implementation will call
4708     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4709     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4710     * on each child. Override this method if custom population of the event text
4711     * content is required.
4712     * <p>
4713     * If an {@link AccessibilityDelegate} has been specified via calling
4714     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4715     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4716     * is responsible for handling this call.
4717     * </p>
4718     * <p>
4719     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4720     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4721     * </p>
4722     *
4723     * @param event The event.
4724     *
4725     * @return True if the event population was completed.
4726     */
4727    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4728        if (mAccessibilityDelegate != null) {
4729            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4730        } else {
4731            return dispatchPopulateAccessibilityEventInternal(event);
4732        }
4733    }
4734
4735    /**
4736     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4737     *
4738     * Note: Called from the default {@link AccessibilityDelegate}.
4739     */
4740    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4741        onPopulateAccessibilityEvent(event);
4742        return false;
4743    }
4744
4745    /**
4746     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4747     * giving a chance to this View to populate the accessibility event with its
4748     * text content. While this method is free to modify event
4749     * attributes other than text content, doing so should normally be performed in
4750     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4751     * <p>
4752     * Example: Adding formatted date string to an accessibility event in addition
4753     *          to the text added by the super implementation:
4754     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4755     *     super.onPopulateAccessibilityEvent(event);
4756     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4757     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4758     *         mCurrentDate.getTimeInMillis(), flags);
4759     *     event.getText().add(selectedDateUtterance);
4760     * }</pre>
4761     * <p>
4762     * If an {@link AccessibilityDelegate} has been specified via calling
4763     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4764     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4765     * is responsible for handling this call.
4766     * </p>
4767     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4768     * information to the event, in case the default implementation has basic information to add.
4769     * </p>
4770     *
4771     * @param event The accessibility event which to populate.
4772     *
4773     * @see #sendAccessibilityEvent(int)
4774     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4775     */
4776    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4777        if (mAccessibilityDelegate != null) {
4778            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4779        } else {
4780            onPopulateAccessibilityEventInternal(event);
4781        }
4782    }
4783
4784    /**
4785     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4786     *
4787     * Note: Called from the default {@link AccessibilityDelegate}.
4788     */
4789    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4790
4791    }
4792
4793    /**
4794     * Initializes an {@link AccessibilityEvent} with information about
4795     * this View which is the event source. In other words, the source of
4796     * an accessibility event is the view whose state change triggered firing
4797     * the event.
4798     * <p>
4799     * Example: Setting the password property of an event in addition
4800     *          to properties set by the super implementation:
4801     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4802     *     super.onInitializeAccessibilityEvent(event);
4803     *     event.setPassword(true);
4804     * }</pre>
4805     * <p>
4806     * If an {@link AccessibilityDelegate} has been specified via calling
4807     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4808     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4809     * is responsible for handling this call.
4810     * </p>
4811     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4812     * information to the event, in case the default implementation has basic information to add.
4813     * </p>
4814     * @param event The event to initialize.
4815     *
4816     * @see #sendAccessibilityEvent(int)
4817     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4818     */
4819    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4820        if (mAccessibilityDelegate != null) {
4821            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4822        } else {
4823            onInitializeAccessibilityEventInternal(event);
4824        }
4825    }
4826
4827    /**
4828     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4829     *
4830     * Note: Called from the default {@link AccessibilityDelegate}.
4831     */
4832    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4833        event.setSource(this);
4834        event.setClassName(View.class.getName());
4835        event.setPackageName(getContext().getPackageName());
4836        event.setEnabled(isEnabled());
4837        event.setContentDescription(mContentDescription);
4838
4839        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4840            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4841            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4842                    FOCUSABLES_ALL);
4843            event.setItemCount(focusablesTempList.size());
4844            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4845            focusablesTempList.clear();
4846        }
4847    }
4848
4849    /**
4850     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4851     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4852     * This method is responsible for obtaining an accessibility node info from a
4853     * pool of reusable instances and calling
4854     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4855     * initialize the former.
4856     * <p>
4857     * Note: The client is responsible for recycling the obtained instance by calling
4858     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4859     * </p>
4860     *
4861     * @return A populated {@link AccessibilityNodeInfo}.
4862     *
4863     * @see AccessibilityNodeInfo
4864     */
4865    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4866        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4867        if (provider != null) {
4868            return provider.createAccessibilityNodeInfo(View.NO_ID);
4869        } else {
4870            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4871            onInitializeAccessibilityNodeInfo(info);
4872            return info;
4873        }
4874    }
4875
4876    /**
4877     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4878     * The base implementation sets:
4879     * <ul>
4880     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4881     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4882     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4883     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4884     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4885     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4886     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4887     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4888     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4889     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4890     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4891     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4892     * </ul>
4893     * <p>
4894     * Subclasses should override this method, call the super implementation,
4895     * and set additional attributes.
4896     * </p>
4897     * <p>
4898     * If an {@link AccessibilityDelegate} has been specified via calling
4899     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4900     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4901     * is responsible for handling this call.
4902     * </p>
4903     *
4904     * @param info The instance to initialize.
4905     */
4906    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4907        if (mAccessibilityDelegate != null) {
4908            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4909        } else {
4910            onInitializeAccessibilityNodeInfoInternal(info);
4911        }
4912    }
4913
4914    /**
4915     * Gets the location of this view in screen coordintates.
4916     *
4917     * @param outRect The output location
4918     */
4919    void getBoundsOnScreen(Rect outRect) {
4920        if (mAttachInfo == null) {
4921            return;
4922        }
4923
4924        RectF position = mAttachInfo.mTmpTransformRect;
4925        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4926
4927        if (!hasIdentityMatrix()) {
4928            getMatrix().mapRect(position);
4929        }
4930
4931        position.offset(mLeft, mTop);
4932
4933        ViewParent parent = mParent;
4934        while (parent instanceof View) {
4935            View parentView = (View) parent;
4936
4937            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4938
4939            if (!parentView.hasIdentityMatrix()) {
4940                parentView.getMatrix().mapRect(position);
4941            }
4942
4943            position.offset(parentView.mLeft, parentView.mTop);
4944
4945            parent = parentView.mParent;
4946        }
4947
4948        if (parent instanceof ViewRootImpl) {
4949            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4950            position.offset(0, -viewRootImpl.mCurScrollY);
4951        }
4952
4953        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4954
4955        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4956                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4957    }
4958
4959    /**
4960     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4961     *
4962     * Note: Called from the default {@link AccessibilityDelegate}.
4963     */
4964    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4965        Rect bounds = mAttachInfo.mTmpInvalRect;
4966
4967        getDrawingRect(bounds);
4968        info.setBoundsInParent(bounds);
4969
4970        getBoundsOnScreen(bounds);
4971        info.setBoundsInScreen(bounds);
4972
4973        ViewParent parent = getParentForAccessibility();
4974        if (parent instanceof View) {
4975            info.setParent((View) parent);
4976        }
4977
4978        if (mID != View.NO_ID) {
4979            View rootView = getRootView();
4980            if (rootView == null) {
4981                rootView = this;
4982            }
4983            View label = rootView.findLabelForView(this, mID);
4984            if (label != null) {
4985                info.setLabeledBy(label);
4986            }
4987        }
4988
4989        if (mLabelForId != View.NO_ID) {
4990            View rootView = getRootView();
4991            if (rootView == null) {
4992                rootView = this;
4993            }
4994            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
4995            if (labeled != null) {
4996                info.setLabelFor(labeled);
4997            }
4998        }
4999
5000        info.setVisibleToUser(isVisibleToUser());
5001
5002        info.setPackageName(mContext.getPackageName());
5003        info.setClassName(View.class.getName());
5004        info.setContentDescription(getContentDescription());
5005
5006        info.setEnabled(isEnabled());
5007        info.setClickable(isClickable());
5008        info.setFocusable(isFocusable());
5009        info.setFocused(isFocused());
5010        info.setAccessibilityFocused(isAccessibilityFocused());
5011        info.setSelected(isSelected());
5012        info.setLongClickable(isLongClickable());
5013
5014        // TODO: These make sense only if we are in an AdapterView but all
5015        // views can be selected. Maybe from accessibility perspective
5016        // we should report as selectable view in an AdapterView.
5017        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5018        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5019
5020        if (isFocusable()) {
5021            if (isFocused()) {
5022                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5023            } else {
5024                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5025            }
5026        }
5027
5028        if (!isAccessibilityFocused()) {
5029            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5030        } else {
5031            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5032        }
5033
5034        if (isClickable() && isEnabled()) {
5035            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5036        }
5037
5038        if (isLongClickable() && isEnabled()) {
5039            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5040        }
5041
5042        if (mContentDescription != null && mContentDescription.length() > 0) {
5043            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5044            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5045            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5046                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5047                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5048        }
5049    }
5050
5051    private View findLabelForView(View view, int labeledId) {
5052        if (mMatchLabelForPredicate == null) {
5053            mMatchLabelForPredicate = new MatchLabelForPredicate();
5054        }
5055        mMatchLabelForPredicate.mLabeledId = labeledId;
5056        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5057    }
5058
5059    /**
5060     * Computes whether this view is visible to the user. Such a view is
5061     * attached, visible, all its predecessors are visible, it is not clipped
5062     * entirely by its predecessors, and has an alpha greater than zero.
5063     *
5064     * @return Whether the view is visible on the screen.
5065     *
5066     * @hide
5067     */
5068    protected boolean isVisibleToUser() {
5069        return isVisibleToUser(null);
5070    }
5071
5072    /**
5073     * Computes whether the given portion of this view is visible to the user.
5074     * Such a view is attached, visible, all its predecessors are visible,
5075     * has an alpha greater than zero, and the specified portion is not
5076     * clipped entirely by its predecessors.
5077     *
5078     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5079     *                    <code>null</code>, and the entire view will be tested in this case.
5080     *                    When <code>true</code> is returned by the function, the actual visible
5081     *                    region will be stored in this parameter; that is, if boundInView is fully
5082     *                    contained within the view, no modification will be made, otherwise regions
5083     *                    outside of the visible area of the view will be clipped.
5084     *
5085     * @return Whether the specified portion of the view is visible on the screen.
5086     *
5087     * @hide
5088     */
5089    protected boolean isVisibleToUser(Rect boundInView) {
5090        if (mAttachInfo != null) {
5091            // Attached to invisible window means this view is not visible.
5092            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5093                return false;
5094            }
5095            // An invisible predecessor or one with alpha zero means
5096            // that this view is not visible to the user.
5097            Object current = this;
5098            while (current instanceof View) {
5099                View view = (View) current;
5100                // We have attach info so this view is attached and there is no
5101                // need to check whether we reach to ViewRootImpl on the way up.
5102                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5103                    return false;
5104                }
5105                current = view.mParent;
5106            }
5107            // Check if the view is entirely covered by its predecessors.
5108            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5109            Point offset = mAttachInfo.mPoint;
5110            if (!getGlobalVisibleRect(visibleRect, offset)) {
5111                return false;
5112            }
5113            // Check if the visible portion intersects the rectangle of interest.
5114            if (boundInView != null) {
5115                visibleRect.offset(-offset.x, -offset.y);
5116                return boundInView.intersect(visibleRect);
5117            }
5118            return true;
5119        }
5120        return false;
5121    }
5122
5123    /**
5124     * Returns the delegate for implementing accessibility support via
5125     * composition. For more details see {@link AccessibilityDelegate}.
5126     *
5127     * @return The delegate, or null if none set.
5128     *
5129     * @hide
5130     */
5131    public AccessibilityDelegate getAccessibilityDelegate() {
5132        return mAccessibilityDelegate;
5133    }
5134
5135    /**
5136     * Sets a delegate for implementing accessibility support via composition as
5137     * opposed to inheritance. The delegate's primary use is for implementing
5138     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5139     *
5140     * @param delegate The delegate instance.
5141     *
5142     * @see AccessibilityDelegate
5143     */
5144    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5145        mAccessibilityDelegate = delegate;
5146    }
5147
5148    /**
5149     * Gets the provider for managing a virtual view hierarchy rooted at this View
5150     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5151     * that explore the window content.
5152     * <p>
5153     * If this method returns an instance, this instance is responsible for managing
5154     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5155     * View including the one representing the View itself. Similarly the returned
5156     * instance is responsible for performing accessibility actions on any virtual
5157     * view or the root view itself.
5158     * </p>
5159     * <p>
5160     * If an {@link AccessibilityDelegate} has been specified via calling
5161     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5162     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5163     * is responsible for handling this call.
5164     * </p>
5165     *
5166     * @return The provider.
5167     *
5168     * @see AccessibilityNodeProvider
5169     */
5170    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5171        if (mAccessibilityDelegate != null) {
5172            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5173        } else {
5174            return null;
5175        }
5176    }
5177
5178    /**
5179     * Gets the unique identifier of this view on the screen for accessibility purposes.
5180     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5181     *
5182     * @return The view accessibility id.
5183     *
5184     * @hide
5185     */
5186    public int getAccessibilityViewId() {
5187        if (mAccessibilityViewId == NO_ID) {
5188            mAccessibilityViewId = sNextAccessibilityViewId++;
5189        }
5190        return mAccessibilityViewId;
5191    }
5192
5193    /**
5194     * Gets the unique identifier of the window in which this View reseides.
5195     *
5196     * @return The window accessibility id.
5197     *
5198     * @hide
5199     */
5200    public int getAccessibilityWindowId() {
5201        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5202    }
5203
5204    /**
5205     * Gets the {@link View} description. It briefly describes the view and is
5206     * primarily used for accessibility support. Set this property to enable
5207     * better accessibility support for your application. This is especially
5208     * true for views that do not have textual representation (For example,
5209     * ImageButton).
5210     *
5211     * @return The content description.
5212     *
5213     * @attr ref android.R.styleable#View_contentDescription
5214     */
5215    @ViewDebug.ExportedProperty(category = "accessibility")
5216    public CharSequence getContentDescription() {
5217        return mContentDescription;
5218    }
5219
5220    /**
5221     * Sets the {@link View} description. It briefly describes the view and is
5222     * primarily used for accessibility support. Set this property to enable
5223     * better accessibility support for your application. This is especially
5224     * true for views that do not have textual representation (For example,
5225     * ImageButton).
5226     *
5227     * @param contentDescription The content description.
5228     *
5229     * @attr ref android.R.styleable#View_contentDescription
5230     */
5231    @RemotableViewMethod
5232    public void setContentDescription(CharSequence contentDescription) {
5233        if (mContentDescription == null) {
5234            if (contentDescription == null) {
5235                return;
5236            }
5237        } else if (mContentDescription.equals(contentDescription)) {
5238            return;
5239        }
5240        mContentDescription = contentDescription;
5241        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5242        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5243             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5244        }
5245        notifyAccessibilityStateChanged();
5246    }
5247
5248    /**
5249     * Gets the id of a view for which this view serves as a label for
5250     * accessibility purposes.
5251     *
5252     * @return The labeled view id.
5253     */
5254    @ViewDebug.ExportedProperty(category = "accessibility")
5255    public int getLabelFor() {
5256        return mLabelForId;
5257    }
5258
5259    /**
5260     * Sets the id of a view for which this view serves as a label for
5261     * accessibility purposes.
5262     *
5263     * @param id The labeled view id.
5264     */
5265    @RemotableViewMethod
5266    public void setLabelFor(int id) {
5267        mLabelForId = id;
5268        if (mLabelForId != View.NO_ID
5269                && mID == View.NO_ID) {
5270            mID = generateViewId();
5271        }
5272    }
5273
5274    /**
5275     * Invoked whenever this view loses focus, either by losing window focus or by losing
5276     * focus within its window. This method can be used to clear any state tied to the
5277     * focus. For instance, if a button is held pressed with the trackball and the window
5278     * loses focus, this method can be used to cancel the press.
5279     *
5280     * Subclasses of View overriding this method should always call super.onFocusLost().
5281     *
5282     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5283     * @see #onWindowFocusChanged(boolean)
5284     *
5285     * @hide pending API council approval
5286     */
5287    protected void onFocusLost() {
5288        resetPressedState();
5289    }
5290
5291    private void resetPressedState() {
5292        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5293            return;
5294        }
5295
5296        if (isPressed()) {
5297            setPressed(false);
5298
5299            if (!mHasPerformedLongPress) {
5300                removeLongPressCallback();
5301            }
5302        }
5303    }
5304
5305    /**
5306     * Returns true if this view has focus
5307     *
5308     * @return True if this view has focus, false otherwise.
5309     */
5310    @ViewDebug.ExportedProperty(category = "focus")
5311    public boolean isFocused() {
5312        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5313    }
5314
5315    /**
5316     * Find the view in the hierarchy rooted at this view that currently has
5317     * focus.
5318     *
5319     * @return The view that currently has focus, or null if no focused view can
5320     *         be found.
5321     */
5322    public View findFocus() {
5323        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5324    }
5325
5326    /**
5327     * Indicates whether this view is one of the set of scrollable containers in
5328     * its window.
5329     *
5330     * @return whether this view is one of the set of scrollable containers in
5331     * its window
5332     *
5333     * @attr ref android.R.styleable#View_isScrollContainer
5334     */
5335    public boolean isScrollContainer() {
5336        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5337    }
5338
5339    /**
5340     * Change whether this view is one of the set of scrollable containers in
5341     * its window.  This will be used to determine whether the window can
5342     * resize or must pan when a soft input area is open -- scrollable
5343     * containers allow the window to use resize mode since the container
5344     * will appropriately shrink.
5345     *
5346     * @attr ref android.R.styleable#View_isScrollContainer
5347     */
5348    public void setScrollContainer(boolean isScrollContainer) {
5349        if (isScrollContainer) {
5350            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5351                mAttachInfo.mScrollContainers.add(this);
5352                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5353            }
5354            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5355        } else {
5356            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5357                mAttachInfo.mScrollContainers.remove(this);
5358            }
5359            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5360        }
5361    }
5362
5363    /**
5364     * Returns the quality of the drawing cache.
5365     *
5366     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5367     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5368     *
5369     * @see #setDrawingCacheQuality(int)
5370     * @see #setDrawingCacheEnabled(boolean)
5371     * @see #isDrawingCacheEnabled()
5372     *
5373     * @attr ref android.R.styleable#View_drawingCacheQuality
5374     */
5375    public int getDrawingCacheQuality() {
5376        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5377    }
5378
5379    /**
5380     * Set the drawing cache quality of this view. This value is used only when the
5381     * drawing cache is enabled
5382     *
5383     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5384     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5385     *
5386     * @see #getDrawingCacheQuality()
5387     * @see #setDrawingCacheEnabled(boolean)
5388     * @see #isDrawingCacheEnabled()
5389     *
5390     * @attr ref android.R.styleable#View_drawingCacheQuality
5391     */
5392    public void setDrawingCacheQuality(int quality) {
5393        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5394    }
5395
5396    /**
5397     * Returns whether the screen should remain on, corresponding to the current
5398     * value of {@link #KEEP_SCREEN_ON}.
5399     *
5400     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5401     *
5402     * @see #setKeepScreenOn(boolean)
5403     *
5404     * @attr ref android.R.styleable#View_keepScreenOn
5405     */
5406    public boolean getKeepScreenOn() {
5407        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5408    }
5409
5410    /**
5411     * Controls whether the screen should remain on, modifying the
5412     * value of {@link #KEEP_SCREEN_ON}.
5413     *
5414     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5415     *
5416     * @see #getKeepScreenOn()
5417     *
5418     * @attr ref android.R.styleable#View_keepScreenOn
5419     */
5420    public void setKeepScreenOn(boolean keepScreenOn) {
5421        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5422    }
5423
5424    /**
5425     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5426     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5427     *
5428     * @attr ref android.R.styleable#View_nextFocusLeft
5429     */
5430    public int getNextFocusLeftId() {
5431        return mNextFocusLeftId;
5432    }
5433
5434    /**
5435     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5436     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5437     * decide automatically.
5438     *
5439     * @attr ref android.R.styleable#View_nextFocusLeft
5440     */
5441    public void setNextFocusLeftId(int nextFocusLeftId) {
5442        mNextFocusLeftId = nextFocusLeftId;
5443    }
5444
5445    /**
5446     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5447     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5448     *
5449     * @attr ref android.R.styleable#View_nextFocusRight
5450     */
5451    public int getNextFocusRightId() {
5452        return mNextFocusRightId;
5453    }
5454
5455    /**
5456     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5457     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5458     * decide automatically.
5459     *
5460     * @attr ref android.R.styleable#View_nextFocusRight
5461     */
5462    public void setNextFocusRightId(int nextFocusRightId) {
5463        mNextFocusRightId = nextFocusRightId;
5464    }
5465
5466    /**
5467     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5468     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5469     *
5470     * @attr ref android.R.styleable#View_nextFocusUp
5471     */
5472    public int getNextFocusUpId() {
5473        return mNextFocusUpId;
5474    }
5475
5476    /**
5477     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5478     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5479     * decide automatically.
5480     *
5481     * @attr ref android.R.styleable#View_nextFocusUp
5482     */
5483    public void setNextFocusUpId(int nextFocusUpId) {
5484        mNextFocusUpId = nextFocusUpId;
5485    }
5486
5487    /**
5488     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5489     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5490     *
5491     * @attr ref android.R.styleable#View_nextFocusDown
5492     */
5493    public int getNextFocusDownId() {
5494        return mNextFocusDownId;
5495    }
5496
5497    /**
5498     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5499     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5500     * decide automatically.
5501     *
5502     * @attr ref android.R.styleable#View_nextFocusDown
5503     */
5504    public void setNextFocusDownId(int nextFocusDownId) {
5505        mNextFocusDownId = nextFocusDownId;
5506    }
5507
5508    /**
5509     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5510     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5511     *
5512     * @attr ref android.R.styleable#View_nextFocusForward
5513     */
5514    public int getNextFocusForwardId() {
5515        return mNextFocusForwardId;
5516    }
5517
5518    /**
5519     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5520     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5521     * decide automatically.
5522     *
5523     * @attr ref android.R.styleable#View_nextFocusForward
5524     */
5525    public void setNextFocusForwardId(int nextFocusForwardId) {
5526        mNextFocusForwardId = nextFocusForwardId;
5527    }
5528
5529    /**
5530     * Returns the visibility of this view and all of its ancestors
5531     *
5532     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5533     */
5534    public boolean isShown() {
5535        View current = this;
5536        //noinspection ConstantConditions
5537        do {
5538            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5539                return false;
5540            }
5541            ViewParent parent = current.mParent;
5542            if (parent == null) {
5543                return false; // We are not attached to the view root
5544            }
5545            if (!(parent instanceof View)) {
5546                return true;
5547            }
5548            current = (View) parent;
5549        } while (current != null);
5550
5551        return false;
5552    }
5553
5554    /**
5555     * Called by the view hierarchy when the content insets for a window have
5556     * changed, to allow it to adjust its content to fit within those windows.
5557     * The content insets tell you the space that the status bar, input method,
5558     * and other system windows infringe on the application's window.
5559     *
5560     * <p>You do not normally need to deal with this function, since the default
5561     * window decoration given to applications takes care of applying it to the
5562     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5563     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5564     * and your content can be placed under those system elements.  You can then
5565     * use this method within your view hierarchy if you have parts of your UI
5566     * which you would like to ensure are not being covered.
5567     *
5568     * <p>The default implementation of this method simply applies the content
5569     * inset's to the view's padding, consuming that content (modifying the
5570     * insets to be 0), and returning true.  This behavior is off by default, but can
5571     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5572     *
5573     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5574     * insets object is propagated down the hierarchy, so any changes made to it will
5575     * be seen by all following views (including potentially ones above in
5576     * the hierarchy since this is a depth-first traversal).  The first view
5577     * that returns true will abort the entire traversal.
5578     *
5579     * <p>The default implementation works well for a situation where it is
5580     * used with a container that covers the entire window, allowing it to
5581     * apply the appropriate insets to its content on all edges.  If you need
5582     * a more complicated layout (such as two different views fitting system
5583     * windows, one on the top of the window, and one on the bottom),
5584     * you can override the method and handle the insets however you would like.
5585     * Note that the insets provided by the framework are always relative to the
5586     * far edges of the window, not accounting for the location of the called view
5587     * within that window.  (In fact when this method is called you do not yet know
5588     * where the layout will place the view, as it is done before layout happens.)
5589     *
5590     * <p>Note: unlike many View methods, there is no dispatch phase to this
5591     * call.  If you are overriding it in a ViewGroup and want to allow the
5592     * call to continue to your children, you must be sure to call the super
5593     * implementation.
5594     *
5595     * <p>Here is a sample layout that makes use of fitting system windows
5596     * to have controls for a video view placed inside of the window decorations
5597     * that it hides and shows.  This can be used with code like the second
5598     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5599     *
5600     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5601     *
5602     * @param insets Current content insets of the window.  Prior to
5603     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5604     * the insets or else you and Android will be unhappy.
5605     *
5606     * @return Return true if this view applied the insets and it should not
5607     * continue propagating further down the hierarchy, false otherwise.
5608     * @see #getFitsSystemWindows()
5609     * @see #setFitsSystemWindows(boolean)
5610     * @see #setSystemUiVisibility(int)
5611     */
5612    protected boolean fitSystemWindows(Rect insets) {
5613        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5614            mUserPaddingStart = UNDEFINED_PADDING;
5615            mUserPaddingEnd = UNDEFINED_PADDING;
5616            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5617                    || mAttachInfo == null
5618                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5619                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5620                return true;
5621            } else {
5622                internalSetPadding(0, 0, 0, 0);
5623                return false;
5624            }
5625        }
5626        return false;
5627    }
5628
5629    /**
5630     * Sets whether or not this view should account for system screen decorations
5631     * such as the status bar and inset its content; that is, controlling whether
5632     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5633     * executed.  See that method for more details.
5634     *
5635     * <p>Note that if you are providing your own implementation of
5636     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5637     * flag to true -- your implementation will be overriding the default
5638     * implementation that checks this flag.
5639     *
5640     * @param fitSystemWindows If true, then the default implementation of
5641     * {@link #fitSystemWindows(Rect)} will be executed.
5642     *
5643     * @attr ref android.R.styleable#View_fitsSystemWindows
5644     * @see #getFitsSystemWindows()
5645     * @see #fitSystemWindows(Rect)
5646     * @see #setSystemUiVisibility(int)
5647     */
5648    public void setFitsSystemWindows(boolean fitSystemWindows) {
5649        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5650    }
5651
5652    /**
5653     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5654     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5655     * will be executed.
5656     *
5657     * @return Returns true if the default implementation of
5658     * {@link #fitSystemWindows(Rect)} will be executed.
5659     *
5660     * @attr ref android.R.styleable#View_fitsSystemWindows
5661     * @see #setFitsSystemWindows()
5662     * @see #fitSystemWindows(Rect)
5663     * @see #setSystemUiVisibility(int)
5664     */
5665    public boolean getFitsSystemWindows() {
5666        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5667    }
5668
5669    /** @hide */
5670    public boolean fitsSystemWindows() {
5671        return getFitsSystemWindows();
5672    }
5673
5674    /**
5675     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5676     */
5677    public void requestFitSystemWindows() {
5678        if (mParent != null) {
5679            mParent.requestFitSystemWindows();
5680        }
5681    }
5682
5683    /**
5684     * For use by PhoneWindow to make its own system window fitting optional.
5685     * @hide
5686     */
5687    public void makeOptionalFitsSystemWindows() {
5688        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5689    }
5690
5691    /**
5692     * Returns the visibility status for this view.
5693     *
5694     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5695     * @attr ref android.R.styleable#View_visibility
5696     */
5697    @ViewDebug.ExportedProperty(mapping = {
5698        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5699        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5700        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5701    })
5702    public int getVisibility() {
5703        return mViewFlags & VISIBILITY_MASK;
5704    }
5705
5706    /**
5707     * Set the enabled state of this view.
5708     *
5709     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5710     * @attr ref android.R.styleable#View_visibility
5711     */
5712    @RemotableViewMethod
5713    public void setVisibility(int visibility) {
5714        setFlags(visibility, VISIBILITY_MASK);
5715        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5716    }
5717
5718    /**
5719     * Returns the enabled status for this view. The interpretation of the
5720     * enabled state varies by subclass.
5721     *
5722     * @return True if this view is enabled, false otherwise.
5723     */
5724    @ViewDebug.ExportedProperty
5725    public boolean isEnabled() {
5726        return (mViewFlags & ENABLED_MASK) == ENABLED;
5727    }
5728
5729    /**
5730     * Set the enabled state of this view. The interpretation of the enabled
5731     * state varies by subclass.
5732     *
5733     * @param enabled True if this view is enabled, false otherwise.
5734     */
5735    @RemotableViewMethod
5736    public void setEnabled(boolean enabled) {
5737        if (enabled == isEnabled()) return;
5738
5739        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5740
5741        /*
5742         * The View most likely has to change its appearance, so refresh
5743         * the drawable state.
5744         */
5745        refreshDrawableState();
5746
5747        // Invalidate too, since the default behavior for views is to be
5748        // be drawn at 50% alpha rather than to change the drawable.
5749        invalidate(true);
5750    }
5751
5752    /**
5753     * Set whether this view can receive the focus.
5754     *
5755     * Setting this to false will also ensure that this view is not focusable
5756     * in touch mode.
5757     *
5758     * @param focusable If true, this view can receive the focus.
5759     *
5760     * @see #setFocusableInTouchMode(boolean)
5761     * @attr ref android.R.styleable#View_focusable
5762     */
5763    public void setFocusable(boolean focusable) {
5764        if (!focusable) {
5765            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5766        }
5767        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5768    }
5769
5770    /**
5771     * Set whether this view can receive focus while in touch mode.
5772     *
5773     * Setting this to true will also ensure that this view is focusable.
5774     *
5775     * @param focusableInTouchMode If true, this view can receive the focus while
5776     *   in touch mode.
5777     *
5778     * @see #setFocusable(boolean)
5779     * @attr ref android.R.styleable#View_focusableInTouchMode
5780     */
5781    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5782        // Focusable in touch mode should always be set before the focusable flag
5783        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5784        // which, in touch mode, will not successfully request focus on this view
5785        // because the focusable in touch mode flag is not set
5786        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5787        if (focusableInTouchMode) {
5788            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5789        }
5790    }
5791
5792    /**
5793     * Set whether this view should have sound effects enabled for events such as
5794     * clicking and touching.
5795     *
5796     * <p>You may wish to disable sound effects for a view if you already play sounds,
5797     * for instance, a dial key that plays dtmf tones.
5798     *
5799     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5800     * @see #isSoundEffectsEnabled()
5801     * @see #playSoundEffect(int)
5802     * @attr ref android.R.styleable#View_soundEffectsEnabled
5803     */
5804    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5805        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5806    }
5807
5808    /**
5809     * @return whether this view should have sound effects enabled for events such as
5810     *     clicking and touching.
5811     *
5812     * @see #setSoundEffectsEnabled(boolean)
5813     * @see #playSoundEffect(int)
5814     * @attr ref android.R.styleable#View_soundEffectsEnabled
5815     */
5816    @ViewDebug.ExportedProperty
5817    public boolean isSoundEffectsEnabled() {
5818        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5819    }
5820
5821    /**
5822     * Set whether this view should have haptic feedback for events such as
5823     * long presses.
5824     *
5825     * <p>You may wish to disable haptic feedback if your view already controls
5826     * its own haptic feedback.
5827     *
5828     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5829     * @see #isHapticFeedbackEnabled()
5830     * @see #performHapticFeedback(int)
5831     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5832     */
5833    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5834        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5835    }
5836
5837    /**
5838     * @return whether this view should have haptic feedback enabled for events
5839     * long presses.
5840     *
5841     * @see #setHapticFeedbackEnabled(boolean)
5842     * @see #performHapticFeedback(int)
5843     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5844     */
5845    @ViewDebug.ExportedProperty
5846    public boolean isHapticFeedbackEnabled() {
5847        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5848    }
5849
5850    /**
5851     * Returns the layout direction for this view.
5852     *
5853     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5854     *   {@link #LAYOUT_DIRECTION_RTL},
5855     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5856     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5857     * @attr ref android.R.styleable#View_layoutDirection
5858     *
5859     * @hide
5860     */
5861    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5862        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5863        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5864        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5865        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5866    })
5867    public int getRawLayoutDirection() {
5868        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5869    }
5870
5871    /**
5872     * Set the layout direction for this view. This will propagate a reset of layout direction
5873     * resolution to the view's children and resolve layout direction for this view.
5874     *
5875     * @param layoutDirection the layout direction to set. Should be one of:
5876     *
5877     * {@link #LAYOUT_DIRECTION_LTR},
5878     * {@link #LAYOUT_DIRECTION_RTL},
5879     * {@link #LAYOUT_DIRECTION_INHERIT},
5880     * {@link #LAYOUT_DIRECTION_LOCALE}.
5881     *
5882     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5883     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5884     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5885     *
5886     * @attr ref android.R.styleable#View_layoutDirection
5887     */
5888    @RemotableViewMethod
5889    public void setLayoutDirection(int layoutDirection) {
5890        if (getRawLayoutDirection() != layoutDirection) {
5891            // Reset the current layout direction and the resolved one
5892            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5893            resetRtlProperties();
5894            // Set the new layout direction (filtered)
5895            mPrivateFlags2 |=
5896                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
5897            // We need to resolve all RTL properties as they all depend on layout direction
5898            resolveRtlPropertiesIfNeeded();
5899            requestLayout();
5900            invalidate(true);
5901        }
5902    }
5903
5904    /**
5905     * Returns the resolved layout direction for this view.
5906     *
5907     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5908     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5909     *
5910     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
5911     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
5912     */
5913    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5914        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5915        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5916    })
5917    public int getLayoutDirection() {
5918        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
5919        if (targetSdkVersion < JELLY_BEAN_MR1) {
5920            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
5921            return LAYOUT_DIRECTION_LTR;
5922        }
5923        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
5924                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5925    }
5926
5927    /**
5928     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5929     * layout attribute and/or the inherited value from the parent
5930     *
5931     * @return true if the layout is right-to-left.
5932     *
5933     * @hide
5934     */
5935    @ViewDebug.ExportedProperty(category = "layout")
5936    public boolean isLayoutRtl() {
5937        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
5938    }
5939
5940    /**
5941     * Indicates whether the view is currently tracking transient state that the
5942     * app should not need to concern itself with saving and restoring, but that
5943     * the framework should take special note to preserve when possible.
5944     *
5945     * <p>A view with transient state cannot be trivially rebound from an external
5946     * data source, such as an adapter binding item views in a list. This may be
5947     * because the view is performing an animation, tracking user selection
5948     * of content, or similar.</p>
5949     *
5950     * @return true if the view has transient state
5951     */
5952    @ViewDebug.ExportedProperty(category = "layout")
5953    public boolean hasTransientState() {
5954        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
5955    }
5956
5957    /**
5958     * Set whether this view is currently tracking transient state that the
5959     * framework should attempt to preserve when possible. This flag is reference counted,
5960     * so every call to setHasTransientState(true) should be paired with a later call
5961     * to setHasTransientState(false).
5962     *
5963     * <p>A view with transient state cannot be trivially rebound from an external
5964     * data source, such as an adapter binding item views in a list. This may be
5965     * because the view is performing an animation, tracking user selection
5966     * of content, or similar.</p>
5967     *
5968     * @param hasTransientState true if this view has transient state
5969     */
5970    public void setHasTransientState(boolean hasTransientState) {
5971        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5972                mTransientStateCount - 1;
5973        if (mTransientStateCount < 0) {
5974            mTransientStateCount = 0;
5975            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5976                    "unmatched pair of setHasTransientState calls");
5977        }
5978        if ((hasTransientState && mTransientStateCount == 1) ||
5979                (!hasTransientState && mTransientStateCount == 0)) {
5980            // update flag if we've just incremented up from 0 or decremented down to 0
5981            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
5982                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
5983            if (mParent != null) {
5984                try {
5985                    mParent.childHasTransientStateChanged(this, hasTransientState);
5986                } catch (AbstractMethodError e) {
5987                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5988                            " does not fully implement ViewParent", e);
5989                }
5990            }
5991        }
5992    }
5993
5994    /**
5995     * If this view doesn't do any drawing on its own, set this flag to
5996     * allow further optimizations. By default, this flag is not set on
5997     * View, but could be set on some View subclasses such as ViewGroup.
5998     *
5999     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6000     * you should clear this flag.
6001     *
6002     * @param willNotDraw whether or not this View draw on its own
6003     */
6004    public void setWillNotDraw(boolean willNotDraw) {
6005        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6006    }
6007
6008    /**
6009     * Returns whether or not this View draws on its own.
6010     *
6011     * @return true if this view has nothing to draw, false otherwise
6012     */
6013    @ViewDebug.ExportedProperty(category = "drawing")
6014    public boolean willNotDraw() {
6015        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6016    }
6017
6018    /**
6019     * When a View's drawing cache is enabled, drawing is redirected to an
6020     * offscreen bitmap. Some views, like an ImageView, must be able to
6021     * bypass this mechanism if they already draw a single bitmap, to avoid
6022     * unnecessary usage of the memory.
6023     *
6024     * @param willNotCacheDrawing true if this view does not cache its
6025     *        drawing, false otherwise
6026     */
6027    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6028        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6029    }
6030
6031    /**
6032     * Returns whether or not this View can cache its drawing or not.
6033     *
6034     * @return true if this view does not cache its drawing, false otherwise
6035     */
6036    @ViewDebug.ExportedProperty(category = "drawing")
6037    public boolean willNotCacheDrawing() {
6038        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6039    }
6040
6041    /**
6042     * Indicates whether this view reacts to click events or not.
6043     *
6044     * @return true if the view is clickable, false otherwise
6045     *
6046     * @see #setClickable(boolean)
6047     * @attr ref android.R.styleable#View_clickable
6048     */
6049    @ViewDebug.ExportedProperty
6050    public boolean isClickable() {
6051        return (mViewFlags & CLICKABLE) == CLICKABLE;
6052    }
6053
6054    /**
6055     * Enables or disables click events for this view. When a view
6056     * is clickable it will change its state to "pressed" on every click.
6057     * Subclasses should set the view clickable to visually react to
6058     * user's clicks.
6059     *
6060     * @param clickable true to make the view clickable, false otherwise
6061     *
6062     * @see #isClickable()
6063     * @attr ref android.R.styleable#View_clickable
6064     */
6065    public void setClickable(boolean clickable) {
6066        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6067    }
6068
6069    /**
6070     * Indicates whether this view reacts to long click events or not.
6071     *
6072     * @return true if the view is long clickable, false otherwise
6073     *
6074     * @see #setLongClickable(boolean)
6075     * @attr ref android.R.styleable#View_longClickable
6076     */
6077    public boolean isLongClickable() {
6078        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6079    }
6080
6081    /**
6082     * Enables or disables long click events for this view. When a view is long
6083     * clickable it reacts to the user holding down the button for a longer
6084     * duration than a tap. This event can either launch the listener or a
6085     * context menu.
6086     *
6087     * @param longClickable true to make the view long clickable, false otherwise
6088     * @see #isLongClickable()
6089     * @attr ref android.R.styleable#View_longClickable
6090     */
6091    public void setLongClickable(boolean longClickable) {
6092        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6093    }
6094
6095    /**
6096     * Sets the pressed state for this view.
6097     *
6098     * @see #isClickable()
6099     * @see #setClickable(boolean)
6100     *
6101     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6102     *        the View's internal state from a previously set "pressed" state.
6103     */
6104    public void setPressed(boolean pressed) {
6105        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6106
6107        if (pressed) {
6108            mPrivateFlags |= PFLAG_PRESSED;
6109        } else {
6110            mPrivateFlags &= ~PFLAG_PRESSED;
6111        }
6112
6113        if (needsRefresh) {
6114            refreshDrawableState();
6115        }
6116        dispatchSetPressed(pressed);
6117    }
6118
6119    /**
6120     * Dispatch setPressed to all of this View's children.
6121     *
6122     * @see #setPressed(boolean)
6123     *
6124     * @param pressed The new pressed state
6125     */
6126    protected void dispatchSetPressed(boolean pressed) {
6127    }
6128
6129    /**
6130     * Indicates whether the view is currently in pressed state. Unless
6131     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6132     * the pressed state.
6133     *
6134     * @see #setPressed(boolean)
6135     * @see #isClickable()
6136     * @see #setClickable(boolean)
6137     *
6138     * @return true if the view is currently pressed, false otherwise
6139     */
6140    public boolean isPressed() {
6141        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6142    }
6143
6144    /**
6145     * Indicates whether this view will save its state (that is,
6146     * whether its {@link #onSaveInstanceState} method will be called).
6147     *
6148     * @return Returns true if the view state saving is enabled, else false.
6149     *
6150     * @see #setSaveEnabled(boolean)
6151     * @attr ref android.R.styleable#View_saveEnabled
6152     */
6153    public boolean isSaveEnabled() {
6154        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6155    }
6156
6157    /**
6158     * Controls whether the saving of this view's state is
6159     * enabled (that is, whether its {@link #onSaveInstanceState} method
6160     * will be called).  Note that even if freezing is enabled, the
6161     * view still must have an id assigned to it (via {@link #setId(int)})
6162     * for its state to be saved.  This flag can only disable the
6163     * saving of this view; any child views may still have their state saved.
6164     *
6165     * @param enabled Set to false to <em>disable</em> state saving, or true
6166     * (the default) to allow it.
6167     *
6168     * @see #isSaveEnabled()
6169     * @see #setId(int)
6170     * @see #onSaveInstanceState()
6171     * @attr ref android.R.styleable#View_saveEnabled
6172     */
6173    public void setSaveEnabled(boolean enabled) {
6174        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6175    }
6176
6177    /**
6178     * Gets whether the framework should discard touches when the view's
6179     * window is obscured by another visible window.
6180     * Refer to the {@link View} security documentation for more details.
6181     *
6182     * @return True if touch filtering is enabled.
6183     *
6184     * @see #setFilterTouchesWhenObscured(boolean)
6185     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6186     */
6187    @ViewDebug.ExportedProperty
6188    public boolean getFilterTouchesWhenObscured() {
6189        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6190    }
6191
6192    /**
6193     * Sets whether the framework should discard touches when the view's
6194     * window is obscured by another visible window.
6195     * Refer to the {@link View} security documentation for more details.
6196     *
6197     * @param enabled True if touch filtering should be enabled.
6198     *
6199     * @see #getFilterTouchesWhenObscured
6200     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6201     */
6202    public void setFilterTouchesWhenObscured(boolean enabled) {
6203        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6204                FILTER_TOUCHES_WHEN_OBSCURED);
6205    }
6206
6207    /**
6208     * Indicates whether the entire hierarchy under this view will save its
6209     * state when a state saving traversal occurs from its parent.  The default
6210     * is true; if false, these views will not be saved unless
6211     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6212     *
6213     * @return Returns true if the view state saving from parent is enabled, else false.
6214     *
6215     * @see #setSaveFromParentEnabled(boolean)
6216     */
6217    public boolean isSaveFromParentEnabled() {
6218        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6219    }
6220
6221    /**
6222     * Controls whether the entire hierarchy under this view will save its
6223     * state when a state saving traversal occurs from its parent.  The default
6224     * is true; if false, these views will not be saved unless
6225     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6226     *
6227     * @param enabled Set to false to <em>disable</em> state saving, or true
6228     * (the default) to allow it.
6229     *
6230     * @see #isSaveFromParentEnabled()
6231     * @see #setId(int)
6232     * @see #onSaveInstanceState()
6233     */
6234    public void setSaveFromParentEnabled(boolean enabled) {
6235        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6236    }
6237
6238
6239    /**
6240     * Returns whether this View is able to take focus.
6241     *
6242     * @return True if this view can take focus, or false otherwise.
6243     * @attr ref android.R.styleable#View_focusable
6244     */
6245    @ViewDebug.ExportedProperty(category = "focus")
6246    public final boolean isFocusable() {
6247        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6248    }
6249
6250    /**
6251     * When a view is focusable, it may not want to take focus when in touch mode.
6252     * For example, a button would like focus when the user is navigating via a D-pad
6253     * so that the user can click on it, but once the user starts touching the screen,
6254     * the button shouldn't take focus
6255     * @return Whether the view is focusable in touch mode.
6256     * @attr ref android.R.styleable#View_focusableInTouchMode
6257     */
6258    @ViewDebug.ExportedProperty
6259    public final boolean isFocusableInTouchMode() {
6260        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6261    }
6262
6263    /**
6264     * Find the nearest view in the specified direction that can take focus.
6265     * This does not actually give focus to that view.
6266     *
6267     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6268     *
6269     * @return The nearest focusable in the specified direction, or null if none
6270     *         can be found.
6271     */
6272    public View focusSearch(int direction) {
6273        if (mParent != null) {
6274            return mParent.focusSearch(this, direction);
6275        } else {
6276            return null;
6277        }
6278    }
6279
6280    /**
6281     * This method is the last chance for the focused view and its ancestors to
6282     * respond to an arrow key. This is called when the focused view did not
6283     * consume the key internally, nor could the view system find a new view in
6284     * the requested direction to give focus to.
6285     *
6286     * @param focused The currently focused view.
6287     * @param direction The direction focus wants to move. One of FOCUS_UP,
6288     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6289     * @return True if the this view consumed this unhandled move.
6290     */
6291    public boolean dispatchUnhandledMove(View focused, int direction) {
6292        return false;
6293    }
6294
6295    /**
6296     * If a user manually specified the next view id for a particular direction,
6297     * use the root to look up the view.
6298     * @param root The root view of the hierarchy containing this view.
6299     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6300     * or FOCUS_BACKWARD.
6301     * @return The user specified next view, or null if there is none.
6302     */
6303    View findUserSetNextFocus(View root, int direction) {
6304        switch (direction) {
6305            case FOCUS_LEFT:
6306                if (mNextFocusLeftId == View.NO_ID) return null;
6307                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6308            case FOCUS_RIGHT:
6309                if (mNextFocusRightId == View.NO_ID) return null;
6310                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6311            case FOCUS_UP:
6312                if (mNextFocusUpId == View.NO_ID) return null;
6313                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6314            case FOCUS_DOWN:
6315                if (mNextFocusDownId == View.NO_ID) return null;
6316                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6317            case FOCUS_FORWARD:
6318                if (mNextFocusForwardId == View.NO_ID) return null;
6319                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6320            case FOCUS_BACKWARD: {
6321                if (mID == View.NO_ID) return null;
6322                final int id = mID;
6323                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6324                    @Override
6325                    public boolean apply(View t) {
6326                        return t.mNextFocusForwardId == id;
6327                    }
6328                });
6329            }
6330        }
6331        return null;
6332    }
6333
6334    private View findViewInsideOutShouldExist(View root, int id) {
6335        if (mMatchIdPredicate == null) {
6336            mMatchIdPredicate = new MatchIdPredicate();
6337        }
6338        mMatchIdPredicate.mId = id;
6339        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6340        if (result == null) {
6341            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6342        }
6343        return result;
6344    }
6345
6346    /**
6347     * Find and return all focusable views that are descendants of this view,
6348     * possibly including this view if it is focusable itself.
6349     *
6350     * @param direction The direction of the focus
6351     * @return A list of focusable views
6352     */
6353    public ArrayList<View> getFocusables(int direction) {
6354        ArrayList<View> result = new ArrayList<View>(24);
6355        addFocusables(result, direction);
6356        return result;
6357    }
6358
6359    /**
6360     * Add any focusable views that are descendants of this view (possibly
6361     * including this view if it is focusable itself) to views.  If we are in touch mode,
6362     * only add views that are also focusable in touch mode.
6363     *
6364     * @param views Focusable views found so far
6365     * @param direction The direction of the focus
6366     */
6367    public void addFocusables(ArrayList<View> views, int direction) {
6368        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6369    }
6370
6371    /**
6372     * Adds any focusable views that are descendants of this view (possibly
6373     * including this view if it is focusable itself) to views. This method
6374     * adds all focusable views regardless if we are in touch mode or
6375     * only views focusable in touch mode if we are in touch mode or
6376     * only views that can take accessibility focus if accessibility is enabeld
6377     * depending on the focusable mode paramater.
6378     *
6379     * @param views Focusable views found so far or null if all we are interested is
6380     *        the number of focusables.
6381     * @param direction The direction of the focus.
6382     * @param focusableMode The type of focusables to be added.
6383     *
6384     * @see #FOCUSABLES_ALL
6385     * @see #FOCUSABLES_TOUCH_MODE
6386     */
6387    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6388        if (views == null) {
6389            return;
6390        }
6391        if (!isFocusable()) {
6392            return;
6393        }
6394        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6395                && isInTouchMode() && !isFocusableInTouchMode()) {
6396            return;
6397        }
6398        views.add(this);
6399    }
6400
6401    /**
6402     * Finds the Views that contain given text. The containment is case insensitive.
6403     * The search is performed by either the text that the View renders or the content
6404     * description that describes the view for accessibility purposes and the view does
6405     * not render or both. Clients can specify how the search is to be performed via
6406     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6407     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6408     *
6409     * @param outViews The output list of matching Views.
6410     * @param searched The text to match against.
6411     *
6412     * @see #FIND_VIEWS_WITH_TEXT
6413     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6414     * @see #setContentDescription(CharSequence)
6415     */
6416    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6417        if (getAccessibilityNodeProvider() != null) {
6418            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6419                outViews.add(this);
6420            }
6421        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6422                && (searched != null && searched.length() > 0)
6423                && (mContentDescription != null && mContentDescription.length() > 0)) {
6424            String searchedLowerCase = searched.toString().toLowerCase();
6425            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6426            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6427                outViews.add(this);
6428            }
6429        }
6430    }
6431
6432    /**
6433     * Find and return all touchable views that are descendants of this view,
6434     * possibly including this view if it is touchable itself.
6435     *
6436     * @return A list of touchable views
6437     */
6438    public ArrayList<View> getTouchables() {
6439        ArrayList<View> result = new ArrayList<View>();
6440        addTouchables(result);
6441        return result;
6442    }
6443
6444    /**
6445     * Add any touchable views that are descendants of this view (possibly
6446     * including this view if it is touchable itself) to views.
6447     *
6448     * @param views Touchable views found so far
6449     */
6450    public void addTouchables(ArrayList<View> views) {
6451        final int viewFlags = mViewFlags;
6452
6453        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6454                && (viewFlags & ENABLED_MASK) == ENABLED) {
6455            views.add(this);
6456        }
6457    }
6458
6459    /**
6460     * Returns whether this View is accessibility focused.
6461     *
6462     * @return True if this View is accessibility focused.
6463     */
6464    boolean isAccessibilityFocused() {
6465        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6466    }
6467
6468    /**
6469     * Call this to try to give accessibility focus to this view.
6470     *
6471     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6472     * returns false or the view is no visible or the view already has accessibility
6473     * focus.
6474     *
6475     * See also {@link #focusSearch(int)}, which is what you call to say that you
6476     * have focus, and you want your parent to look for the next one.
6477     *
6478     * @return Whether this view actually took accessibility focus.
6479     *
6480     * @hide
6481     */
6482    public boolean requestAccessibilityFocus() {
6483        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6484        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6485            return false;
6486        }
6487        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6488            return false;
6489        }
6490        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6491            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6492            ViewRootImpl viewRootImpl = getViewRootImpl();
6493            if (viewRootImpl != null) {
6494                viewRootImpl.setAccessibilityFocus(this, null);
6495            }
6496            invalidate();
6497            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6498            notifyAccessibilityStateChanged();
6499            return true;
6500        }
6501        return false;
6502    }
6503
6504    /**
6505     * Call this to try to clear accessibility focus of this view.
6506     *
6507     * See also {@link #focusSearch(int)}, which is what you call to say that you
6508     * have focus, and you want your parent to look for the next one.
6509     *
6510     * @hide
6511     */
6512    public void clearAccessibilityFocus() {
6513        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6514            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6515            invalidate();
6516            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6517            notifyAccessibilityStateChanged();
6518        }
6519        // Clear the global reference of accessibility focus if this
6520        // view or any of its descendants had accessibility focus.
6521        ViewRootImpl viewRootImpl = getViewRootImpl();
6522        if (viewRootImpl != null) {
6523            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6524            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6525                viewRootImpl.setAccessibilityFocus(null, null);
6526            }
6527        }
6528    }
6529
6530    private void sendAccessibilityHoverEvent(int eventType) {
6531        // Since we are not delivering to a client accessibility events from not
6532        // important views (unless the clinet request that) we need to fire the
6533        // event from the deepest view exposed to the client. As a consequence if
6534        // the user crosses a not exposed view the client will see enter and exit
6535        // of the exposed predecessor followed by and enter and exit of that same
6536        // predecessor when entering and exiting the not exposed descendant. This
6537        // is fine since the client has a clear idea which view is hovered at the
6538        // price of a couple more events being sent. This is a simple and
6539        // working solution.
6540        View source = this;
6541        while (true) {
6542            if (source.includeForAccessibility()) {
6543                source.sendAccessibilityEvent(eventType);
6544                return;
6545            }
6546            ViewParent parent = source.getParent();
6547            if (parent instanceof View) {
6548                source = (View) parent;
6549            } else {
6550                return;
6551            }
6552        }
6553    }
6554
6555    /**
6556     * Clears accessibility focus without calling any callback methods
6557     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6558     * is used for clearing accessibility focus when giving this focus to
6559     * another view.
6560     */
6561    void clearAccessibilityFocusNoCallbacks() {
6562        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6563            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6564            invalidate();
6565        }
6566    }
6567
6568    /**
6569     * Call this to try to give focus to a specific view or to one of its
6570     * descendants.
6571     *
6572     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6573     * false), or if it is focusable and it is not focusable in touch mode
6574     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6575     *
6576     * See also {@link #focusSearch(int)}, which is what you call to say that you
6577     * have focus, and you want your parent to look for the next one.
6578     *
6579     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6580     * {@link #FOCUS_DOWN} and <code>null</code>.
6581     *
6582     * @return Whether this view or one of its descendants actually took focus.
6583     */
6584    public final boolean requestFocus() {
6585        return requestFocus(View.FOCUS_DOWN);
6586    }
6587
6588    /**
6589     * Call this to try to give focus to a specific view or to one of its
6590     * descendants and give it a hint about what direction focus is heading.
6591     *
6592     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6593     * false), or if it is focusable and it is not focusable in touch mode
6594     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6595     *
6596     * See also {@link #focusSearch(int)}, which is what you call to say that you
6597     * have focus, and you want your parent to look for the next one.
6598     *
6599     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6600     * <code>null</code> set for the previously focused rectangle.
6601     *
6602     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6603     * @return Whether this view or one of its descendants actually took focus.
6604     */
6605    public final boolean requestFocus(int direction) {
6606        return requestFocus(direction, null);
6607    }
6608
6609    /**
6610     * Call this to try to give focus to a specific view or to one of its descendants
6611     * and give it hints about the direction and a specific rectangle that the focus
6612     * is coming from.  The rectangle can help give larger views a finer grained hint
6613     * about where focus is coming from, and therefore, where to show selection, or
6614     * forward focus change internally.
6615     *
6616     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6617     * false), or if it is focusable and it is not focusable in touch mode
6618     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6619     *
6620     * A View will not take focus if it is not visible.
6621     *
6622     * A View will not take focus if one of its parents has
6623     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6624     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6625     *
6626     * See also {@link #focusSearch(int)}, which is what you call to say that you
6627     * have focus, and you want your parent to look for the next one.
6628     *
6629     * You may wish to override this method if your custom {@link View} has an internal
6630     * {@link View} that it wishes to forward the request to.
6631     *
6632     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6633     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6634     *        to give a finer grained hint about where focus is coming from.  May be null
6635     *        if there is no hint.
6636     * @return Whether this view or one of its descendants actually took focus.
6637     */
6638    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6639        return requestFocusNoSearch(direction, previouslyFocusedRect);
6640    }
6641
6642    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6643        // need to be focusable
6644        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6645                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6646            return false;
6647        }
6648
6649        // need to be focusable in touch mode if in touch mode
6650        if (isInTouchMode() &&
6651            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6652               return false;
6653        }
6654
6655        // need to not have any parents blocking us
6656        if (hasAncestorThatBlocksDescendantFocus()) {
6657            return false;
6658        }
6659
6660        handleFocusGainInternal(direction, previouslyFocusedRect);
6661        return true;
6662    }
6663
6664    /**
6665     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6666     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6667     * touch mode to request focus when they are touched.
6668     *
6669     * @return Whether this view or one of its descendants actually took focus.
6670     *
6671     * @see #isInTouchMode()
6672     *
6673     */
6674    public final boolean requestFocusFromTouch() {
6675        // Leave touch mode if we need to
6676        if (isInTouchMode()) {
6677            ViewRootImpl viewRoot = getViewRootImpl();
6678            if (viewRoot != null) {
6679                viewRoot.ensureTouchMode(false);
6680            }
6681        }
6682        return requestFocus(View.FOCUS_DOWN);
6683    }
6684
6685    /**
6686     * @return Whether any ancestor of this view blocks descendant focus.
6687     */
6688    private boolean hasAncestorThatBlocksDescendantFocus() {
6689        ViewParent ancestor = mParent;
6690        while (ancestor instanceof ViewGroup) {
6691            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6692            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6693                return true;
6694            } else {
6695                ancestor = vgAncestor.getParent();
6696            }
6697        }
6698        return false;
6699    }
6700
6701    /**
6702     * Gets the mode for determining whether this View is important for accessibility
6703     * which is if it fires accessibility events and if it is reported to
6704     * accessibility services that query the screen.
6705     *
6706     * @return The mode for determining whether a View is important for accessibility.
6707     *
6708     * @attr ref android.R.styleable#View_importantForAccessibility
6709     *
6710     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6711     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6712     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6713     */
6714    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6715            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6716            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6717            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6718        })
6719    public int getImportantForAccessibility() {
6720        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6721                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6722    }
6723
6724    /**
6725     * Sets how to determine whether this view is important for accessibility
6726     * which is if it fires accessibility events and if it is reported to
6727     * accessibility services that query the screen.
6728     *
6729     * @param mode How to determine whether this view is important for accessibility.
6730     *
6731     * @attr ref android.R.styleable#View_importantForAccessibility
6732     *
6733     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6734     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6735     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6736     */
6737    public void setImportantForAccessibility(int mode) {
6738        if (mode != getImportantForAccessibility()) {
6739            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6740            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6741                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6742            notifyAccessibilityStateChanged();
6743        }
6744    }
6745
6746    /**
6747     * Gets whether this view should be exposed for accessibility.
6748     *
6749     * @return Whether the view is exposed for accessibility.
6750     *
6751     * @hide
6752     */
6753    public boolean isImportantForAccessibility() {
6754        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6755                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6756        switch (mode) {
6757            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6758                return true;
6759            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6760                return false;
6761            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6762                return isActionableForAccessibility() || hasListenersForAccessibility()
6763                        || getAccessibilityNodeProvider() != null;
6764            default:
6765                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6766                        + mode);
6767        }
6768    }
6769
6770    /**
6771     * Gets the parent for accessibility purposes. Note that the parent for
6772     * accessibility is not necessary the immediate parent. It is the first
6773     * predecessor that is important for accessibility.
6774     *
6775     * @return The parent for accessibility purposes.
6776     */
6777    public ViewParent getParentForAccessibility() {
6778        if (mParent instanceof View) {
6779            View parentView = (View) mParent;
6780            if (parentView.includeForAccessibility()) {
6781                return mParent;
6782            } else {
6783                return mParent.getParentForAccessibility();
6784            }
6785        }
6786        return null;
6787    }
6788
6789    /**
6790     * Adds the children of a given View for accessibility. Since some Views are
6791     * not important for accessibility the children for accessibility are not
6792     * necessarily direct children of the riew, rather they are the first level of
6793     * descendants important for accessibility.
6794     *
6795     * @param children The list of children for accessibility.
6796     */
6797    public void addChildrenForAccessibility(ArrayList<View> children) {
6798        if (includeForAccessibility()) {
6799            children.add(this);
6800        }
6801    }
6802
6803    /**
6804     * Whether to regard this view for accessibility. A view is regarded for
6805     * accessibility if it is important for accessibility or the querying
6806     * accessibility service has explicitly requested that view not
6807     * important for accessibility are regarded.
6808     *
6809     * @return Whether to regard the view for accessibility.
6810     *
6811     * @hide
6812     */
6813    public boolean includeForAccessibility() {
6814        if (mAttachInfo != null) {
6815            return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility();
6816        }
6817        return false;
6818    }
6819
6820    /**
6821     * Returns whether the View is considered actionable from
6822     * accessibility perspective. Such view are important for
6823     * accessibility.
6824     *
6825     * @return True if the view is actionable for accessibility.
6826     *
6827     * @hide
6828     */
6829    public boolean isActionableForAccessibility() {
6830        return (isClickable() || isLongClickable() || isFocusable());
6831    }
6832
6833    /**
6834     * Returns whether the View has registered callbacks wich makes it
6835     * important for accessibility.
6836     *
6837     * @return True if the view is actionable for accessibility.
6838     */
6839    private boolean hasListenersForAccessibility() {
6840        ListenerInfo info = getListenerInfo();
6841        return mTouchDelegate != null || info.mOnKeyListener != null
6842                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6843                || info.mOnHoverListener != null || info.mOnDragListener != null;
6844    }
6845
6846    /**
6847     * Notifies accessibility services that some view's important for
6848     * accessibility state has changed. Note that such notifications
6849     * are made at most once every
6850     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6851     * to avoid unnecessary load to the system. Also once a view has
6852     * made a notifucation this method is a NOP until the notification has
6853     * been sent to clients.
6854     *
6855     * @hide
6856     *
6857     * TODO: Makse sure this method is called for any view state change
6858     *       that is interesting for accessilility purposes.
6859     */
6860    public void notifyAccessibilityStateChanged() {
6861        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6862            return;
6863        }
6864        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6865            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6866            if (mParent != null) {
6867                mParent.childAccessibilityStateChanged(this);
6868            }
6869        }
6870    }
6871
6872    /**
6873     * Reset the state indicating the this view has requested clients
6874     * interested in its accessibility state to be notified.
6875     *
6876     * @hide
6877     */
6878    public void resetAccessibilityStateChanged() {
6879        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6880    }
6881
6882    /**
6883     * Performs the specified accessibility action on the view. For
6884     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6885     * <p>
6886     * If an {@link AccessibilityDelegate} has been specified via calling
6887     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6888     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6889     * is responsible for handling this call.
6890     * </p>
6891     *
6892     * @param action The action to perform.
6893     * @param arguments Optional action arguments.
6894     * @return Whether the action was performed.
6895     */
6896    public boolean performAccessibilityAction(int action, Bundle arguments) {
6897      if (mAccessibilityDelegate != null) {
6898          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6899      } else {
6900          return performAccessibilityActionInternal(action, arguments);
6901      }
6902    }
6903
6904   /**
6905    * @see #performAccessibilityAction(int, Bundle)
6906    *
6907    * Note: Called from the default {@link AccessibilityDelegate}.
6908    */
6909    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6910        switch (action) {
6911            case AccessibilityNodeInfo.ACTION_CLICK: {
6912                if (isClickable()) {
6913                    performClick();
6914                    return true;
6915                }
6916            } break;
6917            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6918                if (isLongClickable()) {
6919                    performLongClick();
6920                    return true;
6921                }
6922            } break;
6923            case AccessibilityNodeInfo.ACTION_FOCUS: {
6924                if (!hasFocus()) {
6925                    // Get out of touch mode since accessibility
6926                    // wants to move focus around.
6927                    getViewRootImpl().ensureTouchMode(false);
6928                    return requestFocus();
6929                }
6930            } break;
6931            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6932                if (hasFocus()) {
6933                    clearFocus();
6934                    return !isFocused();
6935                }
6936            } break;
6937            case AccessibilityNodeInfo.ACTION_SELECT: {
6938                if (!isSelected()) {
6939                    setSelected(true);
6940                    return isSelected();
6941                }
6942            } break;
6943            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6944                if (isSelected()) {
6945                    setSelected(false);
6946                    return !isSelected();
6947                }
6948            } break;
6949            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6950                if (!isAccessibilityFocused()) {
6951                    return requestAccessibilityFocus();
6952                }
6953            } break;
6954            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6955                if (isAccessibilityFocused()) {
6956                    clearAccessibilityFocus();
6957                    return true;
6958                }
6959            } break;
6960            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6961                if (arguments != null) {
6962                    final int granularity = arguments.getInt(
6963                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6964                    return nextAtGranularity(granularity);
6965                }
6966            } break;
6967            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6968                if (arguments != null) {
6969                    final int granularity = arguments.getInt(
6970                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6971                    return previousAtGranularity(granularity);
6972                }
6973            } break;
6974        }
6975        return false;
6976    }
6977
6978    private boolean nextAtGranularity(int granularity) {
6979        CharSequence text = getIterableTextForAccessibility();
6980        if (text == null || text.length() == 0) {
6981            return false;
6982        }
6983        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6984        if (iterator == null) {
6985            return false;
6986        }
6987        final int current = getAccessibilityCursorPosition();
6988        final int[] range = iterator.following(current);
6989        if (range == null) {
6990            return false;
6991        }
6992        final int start = range[0];
6993        final int end = range[1];
6994        setAccessibilityCursorPosition(end);
6995        sendViewTextTraversedAtGranularityEvent(
6996                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6997                granularity, start, end);
6998        return true;
6999    }
7000
7001    private boolean previousAtGranularity(int granularity) {
7002        CharSequence text = getIterableTextForAccessibility();
7003        if (text == null || text.length() == 0) {
7004            return false;
7005        }
7006        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7007        if (iterator == null) {
7008            return false;
7009        }
7010        int current = getAccessibilityCursorPosition();
7011        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7012            current = text.length();
7013        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
7014            // When traversing by character we always put the cursor after the character
7015            // to ease edit and have to compensate before asking the for previous segment.
7016            current--;
7017        }
7018        final int[] range = iterator.preceding(current);
7019        if (range == null) {
7020            return false;
7021        }
7022        final int start = range[0];
7023        final int end = range[1];
7024        // Always put the cursor after the character to ease edit.
7025        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
7026            setAccessibilityCursorPosition(end);
7027        } else {
7028            setAccessibilityCursorPosition(start);
7029        }
7030        sendViewTextTraversedAtGranularityEvent(
7031                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
7032                granularity, start, end);
7033        return true;
7034    }
7035
7036    /**
7037     * Gets the text reported for accessibility purposes.
7038     *
7039     * @return The accessibility text.
7040     *
7041     * @hide
7042     */
7043    public CharSequence getIterableTextForAccessibility() {
7044        return getContentDescription();
7045    }
7046
7047    /**
7048     * @hide
7049     */
7050    public int getAccessibilityCursorPosition() {
7051        return mAccessibilityCursorPosition;
7052    }
7053
7054    /**
7055     * @hide
7056     */
7057    public void setAccessibilityCursorPosition(int position) {
7058        mAccessibilityCursorPosition = position;
7059    }
7060
7061    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7062            int fromIndex, int toIndex) {
7063        if (mParent == null) {
7064            return;
7065        }
7066        AccessibilityEvent event = AccessibilityEvent.obtain(
7067                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7068        onInitializeAccessibilityEvent(event);
7069        onPopulateAccessibilityEvent(event);
7070        event.setFromIndex(fromIndex);
7071        event.setToIndex(toIndex);
7072        event.setAction(action);
7073        event.setMovementGranularity(granularity);
7074        mParent.requestSendAccessibilityEvent(this, event);
7075    }
7076
7077    /**
7078     * @hide
7079     */
7080    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7081        switch (granularity) {
7082            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7083                CharSequence text = getIterableTextForAccessibility();
7084                if (text != null && text.length() > 0) {
7085                    CharacterTextSegmentIterator iterator =
7086                        CharacterTextSegmentIterator.getInstance(
7087                                mContext.getResources().getConfiguration().locale);
7088                    iterator.initialize(text.toString());
7089                    return iterator;
7090                }
7091            } break;
7092            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7093                CharSequence text = getIterableTextForAccessibility();
7094                if (text != null && text.length() > 0) {
7095                    WordTextSegmentIterator iterator =
7096                        WordTextSegmentIterator.getInstance(
7097                                mContext.getResources().getConfiguration().locale);
7098                    iterator.initialize(text.toString());
7099                    return iterator;
7100                }
7101            } break;
7102            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7103                CharSequence text = getIterableTextForAccessibility();
7104                if (text != null && text.length() > 0) {
7105                    ParagraphTextSegmentIterator iterator =
7106                        ParagraphTextSegmentIterator.getInstance();
7107                    iterator.initialize(text.toString());
7108                    return iterator;
7109                }
7110            } break;
7111        }
7112        return null;
7113    }
7114
7115    /**
7116     * @hide
7117     */
7118    public void dispatchStartTemporaryDetach() {
7119        clearAccessibilityFocus();
7120        clearDisplayList();
7121
7122        onStartTemporaryDetach();
7123    }
7124
7125    /**
7126     * This is called when a container is going to temporarily detach a child, with
7127     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7128     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7129     * {@link #onDetachedFromWindow()} when the container is done.
7130     */
7131    public void onStartTemporaryDetach() {
7132        removeUnsetPressCallback();
7133        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7134    }
7135
7136    /**
7137     * @hide
7138     */
7139    public void dispatchFinishTemporaryDetach() {
7140        onFinishTemporaryDetach();
7141    }
7142
7143    /**
7144     * Called after {@link #onStartTemporaryDetach} when the container is done
7145     * changing the view.
7146     */
7147    public void onFinishTemporaryDetach() {
7148    }
7149
7150    /**
7151     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7152     * for this view's window.  Returns null if the view is not currently attached
7153     * to the window.  Normally you will not need to use this directly, but
7154     * just use the standard high-level event callbacks like
7155     * {@link #onKeyDown(int, KeyEvent)}.
7156     */
7157    public KeyEvent.DispatcherState getKeyDispatcherState() {
7158        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7159    }
7160
7161    /**
7162     * Dispatch a key event before it is processed by any input method
7163     * associated with the view hierarchy.  This can be used to intercept
7164     * key events in special situations before the IME consumes them; a
7165     * typical example would be handling the BACK key to update the application's
7166     * UI instead of allowing the IME to see it and close itself.
7167     *
7168     * @param event The key event to be dispatched.
7169     * @return True if the event was handled, false otherwise.
7170     */
7171    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7172        return onKeyPreIme(event.getKeyCode(), event);
7173    }
7174
7175    /**
7176     * Dispatch a key event to the next view on the focus path. This path runs
7177     * from the top of the view tree down to the currently focused view. If this
7178     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7179     * the next node down the focus path. This method also fires any key
7180     * listeners.
7181     *
7182     * @param event The key event to be dispatched.
7183     * @return True if the event was handled, false otherwise.
7184     */
7185    public boolean dispatchKeyEvent(KeyEvent event) {
7186        if (mInputEventConsistencyVerifier != null) {
7187            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7188        }
7189
7190        // Give any attached key listener a first crack at the event.
7191        //noinspection SimplifiableIfStatement
7192        ListenerInfo li = mListenerInfo;
7193        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7194                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7195            return true;
7196        }
7197
7198        if (event.dispatch(this, mAttachInfo != null
7199                ? mAttachInfo.mKeyDispatchState : null, this)) {
7200            return true;
7201        }
7202
7203        if (mInputEventConsistencyVerifier != null) {
7204            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7205        }
7206        return false;
7207    }
7208
7209    /**
7210     * Dispatches a key shortcut event.
7211     *
7212     * @param event The key event to be dispatched.
7213     * @return True if the event was handled by the view, false otherwise.
7214     */
7215    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7216        return onKeyShortcut(event.getKeyCode(), event);
7217    }
7218
7219    /**
7220     * Pass the touch screen motion event down to the target view, or this
7221     * view if it is the target.
7222     *
7223     * @param event The motion event to be dispatched.
7224     * @return True if the event was handled by the view, false otherwise.
7225     */
7226    public boolean dispatchTouchEvent(MotionEvent event) {
7227        if (mInputEventConsistencyVerifier != null) {
7228            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7229        }
7230
7231        if (onFilterTouchEventForSecurity(event)) {
7232            //noinspection SimplifiableIfStatement
7233            ListenerInfo li = mListenerInfo;
7234            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7235                    && li.mOnTouchListener.onTouch(this, event)) {
7236                return true;
7237            }
7238
7239            if (onTouchEvent(event)) {
7240                return true;
7241            }
7242        }
7243
7244        if (mInputEventConsistencyVerifier != null) {
7245            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7246        }
7247        return false;
7248    }
7249
7250    /**
7251     * Filter the touch event to apply security policies.
7252     *
7253     * @param event The motion event to be filtered.
7254     * @return True if the event should be dispatched, false if the event should be dropped.
7255     *
7256     * @see #getFilterTouchesWhenObscured
7257     */
7258    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7259        //noinspection RedundantIfStatement
7260        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7261                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7262            // Window is obscured, drop this touch.
7263            return false;
7264        }
7265        return true;
7266    }
7267
7268    /**
7269     * Pass a trackball motion event down to the focused view.
7270     *
7271     * @param event The motion event to be dispatched.
7272     * @return True if the event was handled by the view, false otherwise.
7273     */
7274    public boolean dispatchTrackballEvent(MotionEvent event) {
7275        if (mInputEventConsistencyVerifier != null) {
7276            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7277        }
7278
7279        return onTrackballEvent(event);
7280    }
7281
7282    /**
7283     * Dispatch a generic motion event.
7284     * <p>
7285     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7286     * are delivered to the view under the pointer.  All other generic motion events are
7287     * delivered to the focused view.  Hover events are handled specially and are delivered
7288     * to {@link #onHoverEvent(MotionEvent)}.
7289     * </p>
7290     *
7291     * @param event The motion event to be dispatched.
7292     * @return True if the event was handled by the view, false otherwise.
7293     */
7294    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7295        if (mInputEventConsistencyVerifier != null) {
7296            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7297        }
7298
7299        final int source = event.getSource();
7300        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7301            final int action = event.getAction();
7302            if (action == MotionEvent.ACTION_HOVER_ENTER
7303                    || action == MotionEvent.ACTION_HOVER_MOVE
7304                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7305                if (dispatchHoverEvent(event)) {
7306                    return true;
7307                }
7308            } else if (dispatchGenericPointerEvent(event)) {
7309                return true;
7310            }
7311        } else if (dispatchGenericFocusedEvent(event)) {
7312            return true;
7313        }
7314
7315        if (dispatchGenericMotionEventInternal(event)) {
7316            return true;
7317        }
7318
7319        if (mInputEventConsistencyVerifier != null) {
7320            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7321        }
7322        return false;
7323    }
7324
7325    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7326        //noinspection SimplifiableIfStatement
7327        ListenerInfo li = mListenerInfo;
7328        if (li != null && li.mOnGenericMotionListener != null
7329                && (mViewFlags & ENABLED_MASK) == ENABLED
7330                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7331            return true;
7332        }
7333
7334        if (onGenericMotionEvent(event)) {
7335            return true;
7336        }
7337
7338        if (mInputEventConsistencyVerifier != null) {
7339            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7340        }
7341        return false;
7342    }
7343
7344    /**
7345     * Dispatch a hover event.
7346     * <p>
7347     * Do not call this method directly.
7348     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7349     * </p>
7350     *
7351     * @param event The motion event to be dispatched.
7352     * @return True if the event was handled by the view, false otherwise.
7353     */
7354    protected boolean dispatchHoverEvent(MotionEvent event) {
7355        //noinspection SimplifiableIfStatement
7356        ListenerInfo li = mListenerInfo;
7357        if (li != null && li.mOnHoverListener != null
7358                && (mViewFlags & ENABLED_MASK) == ENABLED
7359                && li.mOnHoverListener.onHover(this, event)) {
7360            return true;
7361        }
7362
7363        return onHoverEvent(event);
7364    }
7365
7366    /**
7367     * Returns true if the view has a child to which it has recently sent
7368     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7369     * it does not have a hovered child, then it must be the innermost hovered view.
7370     * @hide
7371     */
7372    protected boolean hasHoveredChild() {
7373        return false;
7374    }
7375
7376    /**
7377     * Dispatch a generic motion event to the view under the first pointer.
7378     * <p>
7379     * Do not call this method directly.
7380     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7381     * </p>
7382     *
7383     * @param event The motion event to be dispatched.
7384     * @return True if the event was handled by the view, false otherwise.
7385     */
7386    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7387        return false;
7388    }
7389
7390    /**
7391     * Dispatch a generic motion event to the currently focused view.
7392     * <p>
7393     * Do not call this method directly.
7394     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7395     * </p>
7396     *
7397     * @param event The motion event to be dispatched.
7398     * @return True if the event was handled by the view, false otherwise.
7399     */
7400    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7401        return false;
7402    }
7403
7404    /**
7405     * Dispatch a pointer event.
7406     * <p>
7407     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7408     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7409     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7410     * and should not be expected to handle other pointing device features.
7411     * </p>
7412     *
7413     * @param event The motion event to be dispatched.
7414     * @return True if the event was handled by the view, false otherwise.
7415     * @hide
7416     */
7417    public final boolean dispatchPointerEvent(MotionEvent event) {
7418        if (event.isTouchEvent()) {
7419            return dispatchTouchEvent(event);
7420        } else {
7421            return dispatchGenericMotionEvent(event);
7422        }
7423    }
7424
7425    /**
7426     * Called when the window containing this view gains or loses window focus.
7427     * ViewGroups should override to route to their children.
7428     *
7429     * @param hasFocus True if the window containing this view now has focus,
7430     *        false otherwise.
7431     */
7432    public void dispatchWindowFocusChanged(boolean hasFocus) {
7433        onWindowFocusChanged(hasFocus);
7434    }
7435
7436    /**
7437     * Called when the window containing this view gains or loses focus.  Note
7438     * that this is separate from view focus: to receive key events, both
7439     * your view and its window must have focus.  If a window is displayed
7440     * on top of yours that takes input focus, then your own window will lose
7441     * focus but the view focus will remain unchanged.
7442     *
7443     * @param hasWindowFocus True if the window containing this view now has
7444     *        focus, false otherwise.
7445     */
7446    public void onWindowFocusChanged(boolean hasWindowFocus) {
7447        InputMethodManager imm = InputMethodManager.peekInstance();
7448        if (!hasWindowFocus) {
7449            if (isPressed()) {
7450                setPressed(false);
7451            }
7452            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7453                imm.focusOut(this);
7454            }
7455            removeLongPressCallback();
7456            removeTapCallback();
7457            onFocusLost();
7458        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7459            imm.focusIn(this);
7460        }
7461        refreshDrawableState();
7462    }
7463
7464    /**
7465     * Returns true if this view is in a window that currently has window focus.
7466     * Note that this is not the same as the view itself having focus.
7467     *
7468     * @return True if this view is in a window that currently has window focus.
7469     */
7470    public boolean hasWindowFocus() {
7471        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7472    }
7473
7474    /**
7475     * Dispatch a view visibility change down the view hierarchy.
7476     * ViewGroups should override to route to their children.
7477     * @param changedView The view whose visibility changed. Could be 'this' or
7478     * an ancestor view.
7479     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7480     * {@link #INVISIBLE} or {@link #GONE}.
7481     */
7482    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7483        onVisibilityChanged(changedView, visibility);
7484    }
7485
7486    /**
7487     * Called when the visibility of the view or an ancestor of the view is changed.
7488     * @param changedView The view whose visibility changed. Could be 'this' or
7489     * an ancestor view.
7490     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7491     * {@link #INVISIBLE} or {@link #GONE}.
7492     */
7493    protected void onVisibilityChanged(View changedView, int visibility) {
7494        if (visibility == VISIBLE) {
7495            if (mAttachInfo != null) {
7496                initialAwakenScrollBars();
7497            } else {
7498                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7499            }
7500        }
7501    }
7502
7503    /**
7504     * Dispatch a hint about whether this view is displayed. For instance, when
7505     * a View moves out of the screen, it might receives a display hint indicating
7506     * the view is not displayed. Applications should not <em>rely</em> on this hint
7507     * as there is no guarantee that they will receive one.
7508     *
7509     * @param hint A hint about whether or not this view is displayed:
7510     * {@link #VISIBLE} or {@link #INVISIBLE}.
7511     */
7512    public void dispatchDisplayHint(int hint) {
7513        onDisplayHint(hint);
7514    }
7515
7516    /**
7517     * Gives this view a hint about whether is displayed or not. For instance, when
7518     * a View moves out of the screen, it might receives a display hint indicating
7519     * the view is not displayed. Applications should not <em>rely</em> on this hint
7520     * as there is no guarantee that they will receive one.
7521     *
7522     * @param hint A hint about whether or not this view is displayed:
7523     * {@link #VISIBLE} or {@link #INVISIBLE}.
7524     */
7525    protected void onDisplayHint(int hint) {
7526    }
7527
7528    /**
7529     * Dispatch a window visibility change down the view hierarchy.
7530     * ViewGroups should override to route to their children.
7531     *
7532     * @param visibility The new visibility of the window.
7533     *
7534     * @see #onWindowVisibilityChanged(int)
7535     */
7536    public void dispatchWindowVisibilityChanged(int visibility) {
7537        onWindowVisibilityChanged(visibility);
7538    }
7539
7540    /**
7541     * Called when the window containing has change its visibility
7542     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7543     * that this tells you whether or not your window is being made visible
7544     * to the window manager; this does <em>not</em> tell you whether or not
7545     * your window is obscured by other windows on the screen, even if it
7546     * is itself visible.
7547     *
7548     * @param visibility The new visibility of the window.
7549     */
7550    protected void onWindowVisibilityChanged(int visibility) {
7551        if (visibility == VISIBLE) {
7552            initialAwakenScrollBars();
7553        }
7554    }
7555
7556    /**
7557     * Returns the current visibility of the window this view is attached to
7558     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7559     *
7560     * @return Returns the current visibility of the view's window.
7561     */
7562    public int getWindowVisibility() {
7563        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7564    }
7565
7566    /**
7567     * Retrieve the overall visible display size in which the window this view is
7568     * attached to has been positioned in.  This takes into account screen
7569     * decorations above the window, for both cases where the window itself
7570     * is being position inside of them or the window is being placed under
7571     * then and covered insets are used for the window to position its content
7572     * inside.  In effect, this tells you the available area where content can
7573     * be placed and remain visible to users.
7574     *
7575     * <p>This function requires an IPC back to the window manager to retrieve
7576     * the requested information, so should not be used in performance critical
7577     * code like drawing.
7578     *
7579     * @param outRect Filled in with the visible display frame.  If the view
7580     * is not attached to a window, this is simply the raw display size.
7581     */
7582    public void getWindowVisibleDisplayFrame(Rect outRect) {
7583        if (mAttachInfo != null) {
7584            try {
7585                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7586            } catch (RemoteException e) {
7587                return;
7588            }
7589            // XXX This is really broken, and probably all needs to be done
7590            // in the window manager, and we need to know more about whether
7591            // we want the area behind or in front of the IME.
7592            final Rect insets = mAttachInfo.mVisibleInsets;
7593            outRect.left += insets.left;
7594            outRect.top += insets.top;
7595            outRect.right -= insets.right;
7596            outRect.bottom -= insets.bottom;
7597            return;
7598        }
7599        // The view is not attached to a display so we don't have a context.
7600        // Make a best guess about the display size.
7601        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7602        d.getRectSize(outRect);
7603    }
7604
7605    /**
7606     * Dispatch a notification about a resource configuration change down
7607     * the view hierarchy.
7608     * ViewGroups should override to route to their children.
7609     *
7610     * @param newConfig The new resource configuration.
7611     *
7612     * @see #onConfigurationChanged(android.content.res.Configuration)
7613     */
7614    public void dispatchConfigurationChanged(Configuration newConfig) {
7615        onConfigurationChanged(newConfig);
7616    }
7617
7618    /**
7619     * Called when the current configuration of the resources being used
7620     * by the application have changed.  You can use this to decide when
7621     * to reload resources that can changed based on orientation and other
7622     * configuration characterstics.  You only need to use this if you are
7623     * not relying on the normal {@link android.app.Activity} mechanism of
7624     * recreating the activity instance upon a configuration change.
7625     *
7626     * @param newConfig The new resource configuration.
7627     */
7628    protected void onConfigurationChanged(Configuration newConfig) {
7629    }
7630
7631    /**
7632     * Private function to aggregate all per-view attributes in to the view
7633     * root.
7634     */
7635    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7636        performCollectViewAttributes(attachInfo, visibility);
7637    }
7638
7639    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7640        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7641            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7642                attachInfo.mKeepScreenOn = true;
7643            }
7644            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7645            ListenerInfo li = mListenerInfo;
7646            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7647                attachInfo.mHasSystemUiListeners = true;
7648            }
7649        }
7650    }
7651
7652    void needGlobalAttributesUpdate(boolean force) {
7653        final AttachInfo ai = mAttachInfo;
7654        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7655            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7656                    || ai.mHasSystemUiListeners) {
7657                ai.mRecomputeGlobalAttributes = true;
7658            }
7659        }
7660    }
7661
7662    /**
7663     * Returns whether the device is currently in touch mode.  Touch mode is entered
7664     * once the user begins interacting with the device by touch, and affects various
7665     * things like whether focus is always visible to the user.
7666     *
7667     * @return Whether the device is in touch mode.
7668     */
7669    @ViewDebug.ExportedProperty
7670    public boolean isInTouchMode() {
7671        if (mAttachInfo != null) {
7672            return mAttachInfo.mInTouchMode;
7673        } else {
7674            return ViewRootImpl.isInTouchMode();
7675        }
7676    }
7677
7678    /**
7679     * Returns the context the view is running in, through which it can
7680     * access the current theme, resources, etc.
7681     *
7682     * @return The view's Context.
7683     */
7684    @ViewDebug.CapturedViewProperty
7685    public final Context getContext() {
7686        return mContext;
7687    }
7688
7689    /**
7690     * Handle a key event before it is processed by any input method
7691     * associated with the view hierarchy.  This can be used to intercept
7692     * key events in special situations before the IME consumes them; a
7693     * typical example would be handling the BACK key to update the application's
7694     * UI instead of allowing the IME to see it and close itself.
7695     *
7696     * @param keyCode The value in event.getKeyCode().
7697     * @param event Description of the key event.
7698     * @return If you handled the event, return true. If you want to allow the
7699     *         event to be handled by the next receiver, return false.
7700     */
7701    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7702        return false;
7703    }
7704
7705    /**
7706     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7707     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7708     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7709     * is released, if the view is enabled and clickable.
7710     *
7711     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7712     * although some may elect to do so in some situations. Do not rely on this to
7713     * catch software key presses.
7714     *
7715     * @param keyCode A key code that represents the button pressed, from
7716     *                {@link android.view.KeyEvent}.
7717     * @param event   The KeyEvent object that defines the button action.
7718     */
7719    public boolean onKeyDown(int keyCode, KeyEvent event) {
7720        boolean result = false;
7721
7722        switch (keyCode) {
7723            case KeyEvent.KEYCODE_DPAD_CENTER:
7724            case KeyEvent.KEYCODE_ENTER: {
7725                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7726                    return true;
7727                }
7728                // Long clickable items don't necessarily have to be clickable
7729                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7730                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7731                        (event.getRepeatCount() == 0)) {
7732                    setPressed(true);
7733                    checkForLongClick(0);
7734                    return true;
7735                }
7736                break;
7737            }
7738        }
7739        return result;
7740    }
7741
7742    /**
7743     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7744     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7745     * the event).
7746     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7747     * although some may elect to do so in some situations. Do not rely on this to
7748     * catch software key presses.
7749     */
7750    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7751        return false;
7752    }
7753
7754    /**
7755     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7756     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7757     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7758     * {@link KeyEvent#KEYCODE_ENTER} is released.
7759     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7760     * although some may elect to do so in some situations. Do not rely on this to
7761     * catch software key presses.
7762     *
7763     * @param keyCode A key code that represents the button pressed, from
7764     *                {@link android.view.KeyEvent}.
7765     * @param event   The KeyEvent object that defines the button action.
7766     */
7767    public boolean onKeyUp(int keyCode, KeyEvent event) {
7768        boolean result = false;
7769
7770        switch (keyCode) {
7771            case KeyEvent.KEYCODE_DPAD_CENTER:
7772            case KeyEvent.KEYCODE_ENTER: {
7773                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7774                    return true;
7775                }
7776                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7777                    setPressed(false);
7778
7779                    if (!mHasPerformedLongPress) {
7780                        // This is a tap, so remove the longpress check
7781                        removeLongPressCallback();
7782
7783                        result = performClick();
7784                    }
7785                }
7786                break;
7787            }
7788        }
7789        return result;
7790    }
7791
7792    /**
7793     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7794     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7795     * the event).
7796     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7797     * although some may elect to do so in some situations. Do not rely on this to
7798     * catch software key presses.
7799     *
7800     * @param keyCode     A key code that represents the button pressed, from
7801     *                    {@link android.view.KeyEvent}.
7802     * @param repeatCount The number of times the action was made.
7803     * @param event       The KeyEvent object that defines the button action.
7804     */
7805    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7806        return false;
7807    }
7808
7809    /**
7810     * Called on the focused view when a key shortcut event is not handled.
7811     * Override this method to implement local key shortcuts for the View.
7812     * Key shortcuts can also be implemented by setting the
7813     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7814     *
7815     * @param keyCode The value in event.getKeyCode().
7816     * @param event Description of the key event.
7817     * @return If you handled the event, return true. If you want to allow the
7818     *         event to be handled by the next receiver, return false.
7819     */
7820    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7821        return false;
7822    }
7823
7824    /**
7825     * Check whether the called view is a text editor, in which case it
7826     * would make sense to automatically display a soft input window for
7827     * it.  Subclasses should override this if they implement
7828     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7829     * a call on that method would return a non-null InputConnection, and
7830     * they are really a first-class editor that the user would normally
7831     * start typing on when the go into a window containing your view.
7832     *
7833     * <p>The default implementation always returns false.  This does
7834     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7835     * will not be called or the user can not otherwise perform edits on your
7836     * view; it is just a hint to the system that this is not the primary
7837     * purpose of this view.
7838     *
7839     * @return Returns true if this view is a text editor, else false.
7840     */
7841    public boolean onCheckIsTextEditor() {
7842        return false;
7843    }
7844
7845    /**
7846     * Create a new InputConnection for an InputMethod to interact
7847     * with the view.  The default implementation returns null, since it doesn't
7848     * support input methods.  You can override this to implement such support.
7849     * This is only needed for views that take focus and text input.
7850     *
7851     * <p>When implementing this, you probably also want to implement
7852     * {@link #onCheckIsTextEditor()} to indicate you will return a
7853     * non-null InputConnection.
7854     *
7855     * @param outAttrs Fill in with attribute information about the connection.
7856     */
7857    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7858        return null;
7859    }
7860
7861    /**
7862     * Called by the {@link android.view.inputmethod.InputMethodManager}
7863     * when a view who is not the current
7864     * input connection target is trying to make a call on the manager.  The
7865     * default implementation returns false; you can override this to return
7866     * true for certain views if you are performing InputConnection proxying
7867     * to them.
7868     * @param view The View that is making the InputMethodManager call.
7869     * @return Return true to allow the call, false to reject.
7870     */
7871    public boolean checkInputConnectionProxy(View view) {
7872        return false;
7873    }
7874
7875    /**
7876     * Show the context menu for this view. It is not safe to hold on to the
7877     * menu after returning from this method.
7878     *
7879     * You should normally not overload this method. Overload
7880     * {@link #onCreateContextMenu(ContextMenu)} or define an
7881     * {@link OnCreateContextMenuListener} to add items to the context menu.
7882     *
7883     * @param menu The context menu to populate
7884     */
7885    public void createContextMenu(ContextMenu menu) {
7886        ContextMenuInfo menuInfo = getContextMenuInfo();
7887
7888        // Sets the current menu info so all items added to menu will have
7889        // my extra info set.
7890        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7891
7892        onCreateContextMenu(menu);
7893        ListenerInfo li = mListenerInfo;
7894        if (li != null && li.mOnCreateContextMenuListener != null) {
7895            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7896        }
7897
7898        // Clear the extra information so subsequent items that aren't mine don't
7899        // have my extra info.
7900        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7901
7902        if (mParent != null) {
7903            mParent.createContextMenu(menu);
7904        }
7905    }
7906
7907    /**
7908     * Views should implement this if they have extra information to associate
7909     * with the context menu. The return result is supplied as a parameter to
7910     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7911     * callback.
7912     *
7913     * @return Extra information about the item for which the context menu
7914     *         should be shown. This information will vary across different
7915     *         subclasses of View.
7916     */
7917    protected ContextMenuInfo getContextMenuInfo() {
7918        return null;
7919    }
7920
7921    /**
7922     * Views should implement this if the view itself is going to add items to
7923     * the context menu.
7924     *
7925     * @param menu the context menu to populate
7926     */
7927    protected void onCreateContextMenu(ContextMenu menu) {
7928    }
7929
7930    /**
7931     * Implement this method to handle trackball motion events.  The
7932     * <em>relative</em> movement of the trackball since the last event
7933     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7934     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7935     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7936     * they will often be fractional values, representing the more fine-grained
7937     * movement information available from a trackball).
7938     *
7939     * @param event The motion event.
7940     * @return True if the event was handled, false otherwise.
7941     */
7942    public boolean onTrackballEvent(MotionEvent event) {
7943        return false;
7944    }
7945
7946    /**
7947     * Implement this method to handle generic motion events.
7948     * <p>
7949     * Generic motion events describe joystick movements, mouse hovers, track pad
7950     * touches, scroll wheel movements and other input events.  The
7951     * {@link MotionEvent#getSource() source} of the motion event specifies
7952     * the class of input that was received.  Implementations of this method
7953     * must examine the bits in the source before processing the event.
7954     * The following code example shows how this is done.
7955     * </p><p>
7956     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7957     * are delivered to the view under the pointer.  All other generic motion events are
7958     * delivered to the focused view.
7959     * </p>
7960     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7961     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7962     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7963     *             // process the joystick movement...
7964     *             return true;
7965     *         }
7966     *     }
7967     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7968     *         switch (event.getAction()) {
7969     *             case MotionEvent.ACTION_HOVER_MOVE:
7970     *                 // process the mouse hover movement...
7971     *                 return true;
7972     *             case MotionEvent.ACTION_SCROLL:
7973     *                 // process the scroll wheel movement...
7974     *                 return true;
7975     *         }
7976     *     }
7977     *     return super.onGenericMotionEvent(event);
7978     * }</pre>
7979     *
7980     * @param event The generic motion event being processed.
7981     * @return True if the event was handled, false otherwise.
7982     */
7983    public boolean onGenericMotionEvent(MotionEvent event) {
7984        return false;
7985    }
7986
7987    /**
7988     * Implement this method to handle hover events.
7989     * <p>
7990     * This method is called whenever a pointer is hovering into, over, or out of the
7991     * bounds of a view and the view is not currently being touched.
7992     * Hover events are represented as pointer events with action
7993     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7994     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7995     * </p>
7996     * <ul>
7997     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7998     * when the pointer enters the bounds of the view.</li>
7999     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8000     * when the pointer has already entered the bounds of the view and has moved.</li>
8001     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8002     * when the pointer has exited the bounds of the view or when the pointer is
8003     * about to go down due to a button click, tap, or similar user action that
8004     * causes the view to be touched.</li>
8005     * </ul>
8006     * <p>
8007     * The view should implement this method to return true to indicate that it is
8008     * handling the hover event, such as by changing its drawable state.
8009     * </p><p>
8010     * The default implementation calls {@link #setHovered} to update the hovered state
8011     * of the view when a hover enter or hover exit event is received, if the view
8012     * is enabled and is clickable.  The default implementation also sends hover
8013     * accessibility events.
8014     * </p>
8015     *
8016     * @param event The motion event that describes the hover.
8017     * @return True if the view handled the hover event.
8018     *
8019     * @see #isHovered
8020     * @see #setHovered
8021     * @see #onHoverChanged
8022     */
8023    public boolean onHoverEvent(MotionEvent event) {
8024        // The root view may receive hover (or touch) events that are outside the bounds of
8025        // the window.  This code ensures that we only send accessibility events for
8026        // hovers that are actually within the bounds of the root view.
8027        final int action = event.getActionMasked();
8028        if (!mSendingHoverAccessibilityEvents) {
8029            if ((action == MotionEvent.ACTION_HOVER_ENTER
8030                    || action == MotionEvent.ACTION_HOVER_MOVE)
8031                    && !hasHoveredChild()
8032                    && pointInView(event.getX(), event.getY())) {
8033                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8034                mSendingHoverAccessibilityEvents = true;
8035            }
8036        } else {
8037            if (action == MotionEvent.ACTION_HOVER_EXIT
8038                    || (action == MotionEvent.ACTION_MOVE
8039                            && !pointInView(event.getX(), event.getY()))) {
8040                mSendingHoverAccessibilityEvents = false;
8041                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8042                // If the window does not have input focus we take away accessibility
8043                // focus as soon as the user stop hovering over the view.
8044                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8045                    getViewRootImpl().setAccessibilityFocus(null, null);
8046                }
8047            }
8048        }
8049
8050        if (isHoverable()) {
8051            switch (action) {
8052                case MotionEvent.ACTION_HOVER_ENTER:
8053                    setHovered(true);
8054                    break;
8055                case MotionEvent.ACTION_HOVER_EXIT:
8056                    setHovered(false);
8057                    break;
8058            }
8059
8060            // Dispatch the event to onGenericMotionEvent before returning true.
8061            // This is to provide compatibility with existing applications that
8062            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8063            // break because of the new default handling for hoverable views
8064            // in onHoverEvent.
8065            // Note that onGenericMotionEvent will be called by default when
8066            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8067            dispatchGenericMotionEventInternal(event);
8068            return true;
8069        }
8070
8071        return false;
8072    }
8073
8074    /**
8075     * Returns true if the view should handle {@link #onHoverEvent}
8076     * by calling {@link #setHovered} to change its hovered state.
8077     *
8078     * @return True if the view is hoverable.
8079     */
8080    private boolean isHoverable() {
8081        final int viewFlags = mViewFlags;
8082        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8083            return false;
8084        }
8085
8086        return (viewFlags & CLICKABLE) == CLICKABLE
8087                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8088    }
8089
8090    /**
8091     * Returns true if the view is currently hovered.
8092     *
8093     * @return True if the view is currently hovered.
8094     *
8095     * @see #setHovered
8096     * @see #onHoverChanged
8097     */
8098    @ViewDebug.ExportedProperty
8099    public boolean isHovered() {
8100        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8101    }
8102
8103    /**
8104     * Sets whether the view is currently hovered.
8105     * <p>
8106     * Calling this method also changes the drawable state of the view.  This
8107     * enables the view to react to hover by using different drawable resources
8108     * to change its appearance.
8109     * </p><p>
8110     * The {@link #onHoverChanged} method is called when the hovered state changes.
8111     * </p>
8112     *
8113     * @param hovered True if the view is hovered.
8114     *
8115     * @see #isHovered
8116     * @see #onHoverChanged
8117     */
8118    public void setHovered(boolean hovered) {
8119        if (hovered) {
8120            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8121                mPrivateFlags |= PFLAG_HOVERED;
8122                refreshDrawableState();
8123                onHoverChanged(true);
8124            }
8125        } else {
8126            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8127                mPrivateFlags &= ~PFLAG_HOVERED;
8128                refreshDrawableState();
8129                onHoverChanged(false);
8130            }
8131        }
8132    }
8133
8134    /**
8135     * Implement this method to handle hover state changes.
8136     * <p>
8137     * This method is called whenever the hover state changes as a result of a
8138     * call to {@link #setHovered}.
8139     * </p>
8140     *
8141     * @param hovered The current hover state, as returned by {@link #isHovered}.
8142     *
8143     * @see #isHovered
8144     * @see #setHovered
8145     */
8146    public void onHoverChanged(boolean hovered) {
8147    }
8148
8149    /**
8150     * Implement this method to handle touch screen motion events.
8151     *
8152     * @param event The motion event.
8153     * @return True if the event was handled, false otherwise.
8154     */
8155    public boolean onTouchEvent(MotionEvent event) {
8156        final int viewFlags = mViewFlags;
8157
8158        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8159            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8160                setPressed(false);
8161            }
8162            // A disabled view that is clickable still consumes the touch
8163            // events, it just doesn't respond to them.
8164            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8165                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8166        }
8167
8168        if (mTouchDelegate != null) {
8169            if (mTouchDelegate.onTouchEvent(event)) {
8170                return true;
8171            }
8172        }
8173
8174        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8175                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8176            switch (event.getAction()) {
8177                case MotionEvent.ACTION_UP:
8178                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8179                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8180                        // take focus if we don't have it already and we should in
8181                        // touch mode.
8182                        boolean focusTaken = false;
8183                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8184                            focusTaken = requestFocus();
8185                        }
8186
8187                        if (prepressed) {
8188                            // The button is being released before we actually
8189                            // showed it as pressed.  Make it show the pressed
8190                            // state now (before scheduling the click) to ensure
8191                            // the user sees it.
8192                            setPressed(true);
8193                       }
8194
8195                        if (!mHasPerformedLongPress) {
8196                            // This is a tap, so remove the longpress check
8197                            removeLongPressCallback();
8198
8199                            // Only perform take click actions if we were in the pressed state
8200                            if (!focusTaken) {
8201                                // Use a Runnable and post this rather than calling
8202                                // performClick directly. This lets other visual state
8203                                // of the view update before click actions start.
8204                                if (mPerformClick == null) {
8205                                    mPerformClick = new PerformClick();
8206                                }
8207                                if (!post(mPerformClick)) {
8208                                    performClick();
8209                                }
8210                            }
8211                        }
8212
8213                        if (mUnsetPressedState == null) {
8214                            mUnsetPressedState = new UnsetPressedState();
8215                        }
8216
8217                        if (prepressed) {
8218                            postDelayed(mUnsetPressedState,
8219                                    ViewConfiguration.getPressedStateDuration());
8220                        } else if (!post(mUnsetPressedState)) {
8221                            // If the post failed, unpress right now
8222                            mUnsetPressedState.run();
8223                        }
8224                        removeTapCallback();
8225                    }
8226                    break;
8227
8228                case MotionEvent.ACTION_DOWN:
8229                    mHasPerformedLongPress = false;
8230
8231                    if (performButtonActionOnTouchDown(event)) {
8232                        break;
8233                    }
8234
8235                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8236                    boolean isInScrollingContainer = isInScrollingContainer();
8237
8238                    // For views inside a scrolling container, delay the pressed feedback for
8239                    // a short period in case this is a scroll.
8240                    if (isInScrollingContainer) {
8241                        mPrivateFlags |= PFLAG_PREPRESSED;
8242                        if (mPendingCheckForTap == null) {
8243                            mPendingCheckForTap = new CheckForTap();
8244                        }
8245                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8246                    } else {
8247                        // Not inside a scrolling container, so show the feedback right away
8248                        setPressed(true);
8249                        checkForLongClick(0);
8250                    }
8251                    break;
8252
8253                case MotionEvent.ACTION_CANCEL:
8254                    setPressed(false);
8255                    removeTapCallback();
8256                    removeLongPressCallback();
8257                    break;
8258
8259                case MotionEvent.ACTION_MOVE:
8260                    final int x = (int) event.getX();
8261                    final int y = (int) event.getY();
8262
8263                    // Be lenient about moving outside of buttons
8264                    if (!pointInView(x, y, mTouchSlop)) {
8265                        // Outside button
8266                        removeTapCallback();
8267                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8268                            // Remove any future long press/tap checks
8269                            removeLongPressCallback();
8270
8271                            setPressed(false);
8272                        }
8273                    }
8274                    break;
8275            }
8276            return true;
8277        }
8278
8279        return false;
8280    }
8281
8282    /**
8283     * @hide
8284     */
8285    public boolean isInScrollingContainer() {
8286        ViewParent p = getParent();
8287        while (p != null && p instanceof ViewGroup) {
8288            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8289                return true;
8290            }
8291            p = p.getParent();
8292        }
8293        return false;
8294    }
8295
8296    /**
8297     * Remove the longpress detection timer.
8298     */
8299    private void removeLongPressCallback() {
8300        if (mPendingCheckForLongPress != null) {
8301          removeCallbacks(mPendingCheckForLongPress);
8302        }
8303    }
8304
8305    /**
8306     * Remove the pending click action
8307     */
8308    private void removePerformClickCallback() {
8309        if (mPerformClick != null) {
8310            removeCallbacks(mPerformClick);
8311        }
8312    }
8313
8314    /**
8315     * Remove the prepress detection timer.
8316     */
8317    private void removeUnsetPressCallback() {
8318        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8319            setPressed(false);
8320            removeCallbacks(mUnsetPressedState);
8321        }
8322    }
8323
8324    /**
8325     * Remove the tap detection timer.
8326     */
8327    private void removeTapCallback() {
8328        if (mPendingCheckForTap != null) {
8329            mPrivateFlags &= ~PFLAG_PREPRESSED;
8330            removeCallbacks(mPendingCheckForTap);
8331        }
8332    }
8333
8334    /**
8335     * Cancels a pending long press.  Your subclass can use this if you
8336     * want the context menu to come up if the user presses and holds
8337     * at the same place, but you don't want it to come up if they press
8338     * and then move around enough to cause scrolling.
8339     */
8340    public void cancelLongPress() {
8341        removeLongPressCallback();
8342
8343        /*
8344         * The prepressed state handled by the tap callback is a display
8345         * construct, but the tap callback will post a long press callback
8346         * less its own timeout. Remove it here.
8347         */
8348        removeTapCallback();
8349    }
8350
8351    /**
8352     * Remove the pending callback for sending a
8353     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8354     */
8355    private void removeSendViewScrolledAccessibilityEventCallback() {
8356        if (mSendViewScrolledAccessibilityEvent != null) {
8357            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8358            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8359        }
8360    }
8361
8362    /**
8363     * Sets the TouchDelegate for this View.
8364     */
8365    public void setTouchDelegate(TouchDelegate delegate) {
8366        mTouchDelegate = delegate;
8367    }
8368
8369    /**
8370     * Gets the TouchDelegate for this View.
8371     */
8372    public TouchDelegate getTouchDelegate() {
8373        return mTouchDelegate;
8374    }
8375
8376    /**
8377     * Set flags controlling behavior of this view.
8378     *
8379     * @param flags Constant indicating the value which should be set
8380     * @param mask Constant indicating the bit range that should be changed
8381     */
8382    void setFlags(int flags, int mask) {
8383        int old = mViewFlags;
8384        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8385
8386        int changed = mViewFlags ^ old;
8387        if (changed == 0) {
8388            return;
8389        }
8390        int privateFlags = mPrivateFlags;
8391
8392        /* Check if the FOCUSABLE bit has changed */
8393        if (((changed & FOCUSABLE_MASK) != 0) &&
8394                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8395            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8396                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8397                /* Give up focus if we are no longer focusable */
8398                clearFocus();
8399            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8400                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8401                /*
8402                 * Tell the view system that we are now available to take focus
8403                 * if no one else already has it.
8404                 */
8405                if (mParent != null) mParent.focusableViewAvailable(this);
8406            }
8407            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8408                notifyAccessibilityStateChanged();
8409            }
8410        }
8411
8412        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8413            if ((changed & VISIBILITY_MASK) != 0) {
8414                /*
8415                 * If this view is becoming visible, invalidate it in case it changed while
8416                 * it was not visible. Marking it drawn ensures that the invalidation will
8417                 * go through.
8418                 */
8419                mPrivateFlags |= PFLAG_DRAWN;
8420                invalidate(true);
8421
8422                needGlobalAttributesUpdate(true);
8423
8424                // a view becoming visible is worth notifying the parent
8425                // about in case nothing has focus.  even if this specific view
8426                // isn't focusable, it may contain something that is, so let
8427                // the root view try to give this focus if nothing else does.
8428                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8429                    mParent.focusableViewAvailable(this);
8430                }
8431            }
8432        }
8433
8434        /* Check if the GONE bit has changed */
8435        if ((changed & GONE) != 0) {
8436            needGlobalAttributesUpdate(false);
8437            requestLayout();
8438
8439            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8440                if (hasFocus()) clearFocus();
8441                clearAccessibilityFocus();
8442                destroyDrawingCache();
8443                if (mParent instanceof View) {
8444                    // GONE views noop invalidation, so invalidate the parent
8445                    ((View) mParent).invalidate(true);
8446                }
8447                // Mark the view drawn to ensure that it gets invalidated properly the next
8448                // time it is visible and gets invalidated
8449                mPrivateFlags |= PFLAG_DRAWN;
8450            }
8451            if (mAttachInfo != null) {
8452                mAttachInfo.mViewVisibilityChanged = true;
8453            }
8454        }
8455
8456        /* Check if the VISIBLE bit has changed */
8457        if ((changed & INVISIBLE) != 0) {
8458            needGlobalAttributesUpdate(false);
8459            /*
8460             * If this view is becoming invisible, set the DRAWN flag so that
8461             * the next invalidate() will not be skipped.
8462             */
8463            mPrivateFlags |= PFLAG_DRAWN;
8464
8465            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8466                // root view becoming invisible shouldn't clear focus and accessibility focus
8467                if (getRootView() != this) {
8468                    clearFocus();
8469                    clearAccessibilityFocus();
8470                }
8471            }
8472            if (mAttachInfo != null) {
8473                mAttachInfo.mViewVisibilityChanged = true;
8474            }
8475        }
8476
8477        if ((changed & VISIBILITY_MASK) != 0) {
8478            if (mParent instanceof ViewGroup) {
8479                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8480                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8481                ((View) mParent).invalidate(true);
8482            } else if (mParent != null) {
8483                mParent.invalidateChild(this, null);
8484            }
8485            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8486        }
8487
8488        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8489            destroyDrawingCache();
8490        }
8491
8492        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8493            destroyDrawingCache();
8494            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8495            invalidateParentCaches();
8496        }
8497
8498        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8499            destroyDrawingCache();
8500            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8501        }
8502
8503        if ((changed & DRAW_MASK) != 0) {
8504            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8505                if (mBackground != null) {
8506                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8507                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8508                } else {
8509                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8510                }
8511            } else {
8512                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8513            }
8514            requestLayout();
8515            invalidate(true);
8516        }
8517
8518        if ((changed & KEEP_SCREEN_ON) != 0) {
8519            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8520                mParent.recomputeViewAttributes(this);
8521            }
8522        }
8523
8524        if (AccessibilityManager.getInstance(mContext).isEnabled()
8525                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8526                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8527            notifyAccessibilityStateChanged();
8528        }
8529    }
8530
8531    /**
8532     * Change the view's z order in the tree, so it's on top of other sibling
8533     * views
8534     */
8535    public void bringToFront() {
8536        if (mParent != null) {
8537            mParent.bringChildToFront(this);
8538        }
8539    }
8540
8541    /**
8542     * This is called in response to an internal scroll in this view (i.e., the
8543     * view scrolled its own contents). This is typically as a result of
8544     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8545     * called.
8546     *
8547     * @param l Current horizontal scroll origin.
8548     * @param t Current vertical scroll origin.
8549     * @param oldl Previous horizontal scroll origin.
8550     * @param oldt Previous vertical scroll origin.
8551     */
8552    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8553        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8554            postSendViewScrolledAccessibilityEventCallback();
8555        }
8556
8557        mBackgroundSizeChanged = true;
8558
8559        final AttachInfo ai = mAttachInfo;
8560        if (ai != null) {
8561            ai.mViewScrollChanged = true;
8562        }
8563    }
8564
8565    /**
8566     * Interface definition for a callback to be invoked when the layout bounds of a view
8567     * changes due to layout processing.
8568     */
8569    public interface OnLayoutChangeListener {
8570        /**
8571         * Called when the focus state of a view has changed.
8572         *
8573         * @param v The view whose state has changed.
8574         * @param left The new value of the view's left property.
8575         * @param top The new value of the view's top property.
8576         * @param right The new value of the view's right property.
8577         * @param bottom The new value of the view's bottom property.
8578         * @param oldLeft The previous value of the view's left property.
8579         * @param oldTop The previous value of the view's top property.
8580         * @param oldRight The previous value of the view's right property.
8581         * @param oldBottom The previous value of the view's bottom property.
8582         */
8583        void onLayoutChange(View v, int left, int top, int right, int bottom,
8584            int oldLeft, int oldTop, int oldRight, int oldBottom);
8585    }
8586
8587    /**
8588     * This is called during layout when the size of this view has changed. If
8589     * you were just added to the view hierarchy, you're called with the old
8590     * values of 0.
8591     *
8592     * @param w Current width of this view.
8593     * @param h Current height of this view.
8594     * @param oldw Old width of this view.
8595     * @param oldh Old height of this view.
8596     */
8597    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8598    }
8599
8600    /**
8601     * Called by draw to draw the child views. This may be overridden
8602     * by derived classes to gain control just before its children are drawn
8603     * (but after its own view has been drawn).
8604     * @param canvas the canvas on which to draw the view
8605     */
8606    protected void dispatchDraw(Canvas canvas) {
8607
8608    }
8609
8610    /**
8611     * Gets the parent of this view. Note that the parent is a
8612     * ViewParent and not necessarily a View.
8613     *
8614     * @return Parent of this view.
8615     */
8616    public final ViewParent getParent() {
8617        return mParent;
8618    }
8619
8620    /**
8621     * Set the horizontal scrolled position of your view. This will cause a call to
8622     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8623     * invalidated.
8624     * @param value the x position to scroll to
8625     */
8626    public void setScrollX(int value) {
8627        scrollTo(value, mScrollY);
8628    }
8629
8630    /**
8631     * Set the vertical scrolled position of your view. This will cause a call to
8632     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8633     * invalidated.
8634     * @param value the y position to scroll to
8635     */
8636    public void setScrollY(int value) {
8637        scrollTo(mScrollX, value);
8638    }
8639
8640    /**
8641     * Return the scrolled left position of this view. This is the left edge of
8642     * the displayed part of your view. You do not need to draw any pixels
8643     * farther left, since those are outside of the frame of your view on
8644     * screen.
8645     *
8646     * @return The left edge of the displayed part of your view, in pixels.
8647     */
8648    public final int getScrollX() {
8649        return mScrollX;
8650    }
8651
8652    /**
8653     * Return the scrolled top position of this view. This is the top edge of
8654     * the displayed part of your view. You do not need to draw any pixels above
8655     * it, since those are outside of the frame of your view on screen.
8656     *
8657     * @return The top edge of the displayed part of your view, in pixels.
8658     */
8659    public final int getScrollY() {
8660        return mScrollY;
8661    }
8662
8663    /**
8664     * Return the width of the your view.
8665     *
8666     * @return The width of your view, in pixels.
8667     */
8668    @ViewDebug.ExportedProperty(category = "layout")
8669    public final int getWidth() {
8670        return mRight - mLeft;
8671    }
8672
8673    /**
8674     * Return the height of your view.
8675     *
8676     * @return The height of your view, in pixels.
8677     */
8678    @ViewDebug.ExportedProperty(category = "layout")
8679    public final int getHeight() {
8680        return mBottom - mTop;
8681    }
8682
8683    /**
8684     * Return the visible drawing bounds of your view. Fills in the output
8685     * rectangle with the values from getScrollX(), getScrollY(),
8686     * getWidth(), and getHeight(). These bounds do not account for any
8687     * transformation properties currently set on the view, such as
8688     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8689     *
8690     * @param outRect The (scrolled) drawing bounds of the view.
8691     */
8692    public void getDrawingRect(Rect outRect) {
8693        outRect.left = mScrollX;
8694        outRect.top = mScrollY;
8695        outRect.right = mScrollX + (mRight - mLeft);
8696        outRect.bottom = mScrollY + (mBottom - mTop);
8697    }
8698
8699    /**
8700     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8701     * raw width component (that is the result is masked by
8702     * {@link #MEASURED_SIZE_MASK}).
8703     *
8704     * @return The raw measured width of this view.
8705     */
8706    public final int getMeasuredWidth() {
8707        return mMeasuredWidth & MEASURED_SIZE_MASK;
8708    }
8709
8710    /**
8711     * Return the full width measurement information for this view as computed
8712     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8713     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8714     * This should be used during measurement and layout calculations only. Use
8715     * {@link #getWidth()} to see how wide a view is after layout.
8716     *
8717     * @return The measured width of this view as a bit mask.
8718     */
8719    public final int getMeasuredWidthAndState() {
8720        return mMeasuredWidth;
8721    }
8722
8723    /**
8724     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8725     * raw width component (that is the result is masked by
8726     * {@link #MEASURED_SIZE_MASK}).
8727     *
8728     * @return The raw measured height of this view.
8729     */
8730    public final int getMeasuredHeight() {
8731        return mMeasuredHeight & MEASURED_SIZE_MASK;
8732    }
8733
8734    /**
8735     * Return the full height measurement information for this view as computed
8736     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8737     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8738     * This should be used during measurement and layout calculations only. Use
8739     * {@link #getHeight()} to see how wide a view is after layout.
8740     *
8741     * @return The measured width of this view as a bit mask.
8742     */
8743    public final int getMeasuredHeightAndState() {
8744        return mMeasuredHeight;
8745    }
8746
8747    /**
8748     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8749     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8750     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8751     * and the height component is at the shifted bits
8752     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8753     */
8754    public final int getMeasuredState() {
8755        return (mMeasuredWidth&MEASURED_STATE_MASK)
8756                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8757                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8758    }
8759
8760    /**
8761     * The transform matrix of this view, which is calculated based on the current
8762     * roation, scale, and pivot properties.
8763     *
8764     * @see #getRotation()
8765     * @see #getScaleX()
8766     * @see #getScaleY()
8767     * @see #getPivotX()
8768     * @see #getPivotY()
8769     * @return The current transform matrix for the view
8770     */
8771    public Matrix getMatrix() {
8772        if (mTransformationInfo != null) {
8773            updateMatrix();
8774            return mTransformationInfo.mMatrix;
8775        }
8776        return Matrix.IDENTITY_MATRIX;
8777    }
8778
8779    /**
8780     * Utility function to determine if the value is far enough away from zero to be
8781     * considered non-zero.
8782     * @param value A floating point value to check for zero-ness
8783     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8784     */
8785    private static boolean nonzero(float value) {
8786        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8787    }
8788
8789    /**
8790     * Returns true if the transform matrix is the identity matrix.
8791     * Recomputes the matrix if necessary.
8792     *
8793     * @return True if the transform matrix is the identity matrix, false otherwise.
8794     */
8795    final boolean hasIdentityMatrix() {
8796        if (mTransformationInfo != null) {
8797            updateMatrix();
8798            return mTransformationInfo.mMatrixIsIdentity;
8799        }
8800        return true;
8801    }
8802
8803    void ensureTransformationInfo() {
8804        if (mTransformationInfo == null) {
8805            mTransformationInfo = new TransformationInfo();
8806        }
8807    }
8808
8809    /**
8810     * Recomputes the transform matrix if necessary.
8811     */
8812    private void updateMatrix() {
8813        final TransformationInfo info = mTransformationInfo;
8814        if (info == null) {
8815            return;
8816        }
8817        if (info.mMatrixDirty) {
8818            // transform-related properties have changed since the last time someone
8819            // asked for the matrix; recalculate it with the current values
8820
8821            // Figure out if we need to update the pivot point
8822            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8823                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8824                    info.mPrevWidth = mRight - mLeft;
8825                    info.mPrevHeight = mBottom - mTop;
8826                    info.mPivotX = info.mPrevWidth / 2f;
8827                    info.mPivotY = info.mPrevHeight / 2f;
8828                }
8829            }
8830            info.mMatrix.reset();
8831            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8832                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8833                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8834                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8835            } else {
8836                if (info.mCamera == null) {
8837                    info.mCamera = new Camera();
8838                    info.matrix3D = new Matrix();
8839                }
8840                info.mCamera.save();
8841                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8842                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8843                info.mCamera.getMatrix(info.matrix3D);
8844                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8845                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8846                        info.mPivotY + info.mTranslationY);
8847                info.mMatrix.postConcat(info.matrix3D);
8848                info.mCamera.restore();
8849            }
8850            info.mMatrixDirty = false;
8851            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8852            info.mInverseMatrixDirty = true;
8853        }
8854    }
8855
8856   /**
8857     * Utility method to retrieve the inverse of the current mMatrix property.
8858     * We cache the matrix to avoid recalculating it when transform properties
8859     * have not changed.
8860     *
8861     * @return The inverse of the current matrix of this view.
8862     */
8863    final Matrix getInverseMatrix() {
8864        final TransformationInfo info = mTransformationInfo;
8865        if (info != null) {
8866            updateMatrix();
8867            if (info.mInverseMatrixDirty) {
8868                if (info.mInverseMatrix == null) {
8869                    info.mInverseMatrix = new Matrix();
8870                }
8871                info.mMatrix.invert(info.mInverseMatrix);
8872                info.mInverseMatrixDirty = false;
8873            }
8874            return info.mInverseMatrix;
8875        }
8876        return Matrix.IDENTITY_MATRIX;
8877    }
8878
8879    /**
8880     * Gets the distance along the Z axis from the camera to this view.
8881     *
8882     * @see #setCameraDistance(float)
8883     *
8884     * @return The distance along the Z axis.
8885     */
8886    public float getCameraDistance() {
8887        ensureTransformationInfo();
8888        final float dpi = mResources.getDisplayMetrics().densityDpi;
8889        final TransformationInfo info = mTransformationInfo;
8890        if (info.mCamera == null) {
8891            info.mCamera = new Camera();
8892            info.matrix3D = new Matrix();
8893        }
8894        return -(info.mCamera.getLocationZ() * dpi);
8895    }
8896
8897    /**
8898     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8899     * views are drawn) from the camera to this view. The camera's distance
8900     * affects 3D transformations, for instance rotations around the X and Y
8901     * axis. If the rotationX or rotationY properties are changed and this view is
8902     * large (more than half the size of the screen), it is recommended to always
8903     * use a camera distance that's greater than the height (X axis rotation) or
8904     * the width (Y axis rotation) of this view.</p>
8905     *
8906     * <p>The distance of the camera from the view plane can have an affect on the
8907     * perspective distortion of the view when it is rotated around the x or y axis.
8908     * For example, a large distance will result in a large viewing angle, and there
8909     * will not be much perspective distortion of the view as it rotates. A short
8910     * distance may cause much more perspective distortion upon rotation, and can
8911     * also result in some drawing artifacts if the rotated view ends up partially
8912     * behind the camera (which is why the recommendation is to use a distance at
8913     * least as far as the size of the view, if the view is to be rotated.)</p>
8914     *
8915     * <p>The distance is expressed in "depth pixels." The default distance depends
8916     * on the screen density. For instance, on a medium density display, the
8917     * default distance is 1280. On a high density display, the default distance
8918     * is 1920.</p>
8919     *
8920     * <p>If you want to specify a distance that leads to visually consistent
8921     * results across various densities, use the following formula:</p>
8922     * <pre>
8923     * float scale = context.getResources().getDisplayMetrics().density;
8924     * view.setCameraDistance(distance * scale);
8925     * </pre>
8926     *
8927     * <p>The density scale factor of a high density display is 1.5,
8928     * and 1920 = 1280 * 1.5.</p>
8929     *
8930     * @param distance The distance in "depth pixels", if negative the opposite
8931     *        value is used
8932     *
8933     * @see #setRotationX(float)
8934     * @see #setRotationY(float)
8935     */
8936    public void setCameraDistance(float distance) {
8937        invalidateViewProperty(true, false);
8938
8939        ensureTransformationInfo();
8940        final float dpi = mResources.getDisplayMetrics().densityDpi;
8941        final TransformationInfo info = mTransformationInfo;
8942        if (info.mCamera == null) {
8943            info.mCamera = new Camera();
8944            info.matrix3D = new Matrix();
8945        }
8946
8947        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8948        info.mMatrixDirty = true;
8949
8950        invalidateViewProperty(false, false);
8951        if (mDisplayList != null) {
8952            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8953        }
8954        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8955            // View was rejected last time it was drawn by its parent; this may have changed
8956            invalidateParentIfNeeded();
8957        }
8958    }
8959
8960    /**
8961     * The degrees that the view is rotated around the pivot point.
8962     *
8963     * @see #setRotation(float)
8964     * @see #getPivotX()
8965     * @see #getPivotY()
8966     *
8967     * @return The degrees of rotation.
8968     */
8969    @ViewDebug.ExportedProperty(category = "drawing")
8970    public float getRotation() {
8971        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8972    }
8973
8974    /**
8975     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8976     * result in clockwise rotation.
8977     *
8978     * @param rotation The degrees of rotation.
8979     *
8980     * @see #getRotation()
8981     * @see #getPivotX()
8982     * @see #getPivotY()
8983     * @see #setRotationX(float)
8984     * @see #setRotationY(float)
8985     *
8986     * @attr ref android.R.styleable#View_rotation
8987     */
8988    public void setRotation(float rotation) {
8989        ensureTransformationInfo();
8990        final TransformationInfo info = mTransformationInfo;
8991        if (info.mRotation != rotation) {
8992            // Double-invalidation is necessary to capture view's old and new areas
8993            invalidateViewProperty(true, false);
8994            info.mRotation = rotation;
8995            info.mMatrixDirty = true;
8996            invalidateViewProperty(false, true);
8997            if (mDisplayList != null) {
8998                mDisplayList.setRotation(rotation);
8999            }
9000            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9001                // View was rejected last time it was drawn by its parent; this may have changed
9002                invalidateParentIfNeeded();
9003            }
9004        }
9005    }
9006
9007    /**
9008     * The degrees that the view is rotated around the vertical axis through the pivot point.
9009     *
9010     * @see #getPivotX()
9011     * @see #getPivotY()
9012     * @see #setRotationY(float)
9013     *
9014     * @return The degrees of Y rotation.
9015     */
9016    @ViewDebug.ExportedProperty(category = "drawing")
9017    public float getRotationY() {
9018        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9019    }
9020
9021    /**
9022     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9023     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9024     * down the y axis.
9025     *
9026     * When rotating large views, it is recommended to adjust the camera distance
9027     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9028     *
9029     * @param rotationY The degrees of Y rotation.
9030     *
9031     * @see #getRotationY()
9032     * @see #getPivotX()
9033     * @see #getPivotY()
9034     * @see #setRotation(float)
9035     * @see #setRotationX(float)
9036     * @see #setCameraDistance(float)
9037     *
9038     * @attr ref android.R.styleable#View_rotationY
9039     */
9040    public void setRotationY(float rotationY) {
9041        ensureTransformationInfo();
9042        final TransformationInfo info = mTransformationInfo;
9043        if (info.mRotationY != rotationY) {
9044            invalidateViewProperty(true, false);
9045            info.mRotationY = rotationY;
9046            info.mMatrixDirty = true;
9047            invalidateViewProperty(false, true);
9048            if (mDisplayList != null) {
9049                mDisplayList.setRotationY(rotationY);
9050            }
9051            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9052                // View was rejected last time it was drawn by its parent; this may have changed
9053                invalidateParentIfNeeded();
9054            }
9055        }
9056    }
9057
9058    /**
9059     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9060     *
9061     * @see #getPivotX()
9062     * @see #getPivotY()
9063     * @see #setRotationX(float)
9064     *
9065     * @return The degrees of X rotation.
9066     */
9067    @ViewDebug.ExportedProperty(category = "drawing")
9068    public float getRotationX() {
9069        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9070    }
9071
9072    /**
9073     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9074     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9075     * x axis.
9076     *
9077     * When rotating large views, it is recommended to adjust the camera distance
9078     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9079     *
9080     * @param rotationX The degrees of X rotation.
9081     *
9082     * @see #getRotationX()
9083     * @see #getPivotX()
9084     * @see #getPivotY()
9085     * @see #setRotation(float)
9086     * @see #setRotationY(float)
9087     * @see #setCameraDistance(float)
9088     *
9089     * @attr ref android.R.styleable#View_rotationX
9090     */
9091    public void setRotationX(float rotationX) {
9092        ensureTransformationInfo();
9093        final TransformationInfo info = mTransformationInfo;
9094        if (info.mRotationX != rotationX) {
9095            invalidateViewProperty(true, false);
9096            info.mRotationX = rotationX;
9097            info.mMatrixDirty = true;
9098            invalidateViewProperty(false, true);
9099            if (mDisplayList != null) {
9100                mDisplayList.setRotationX(rotationX);
9101            }
9102            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9103                // View was rejected last time it was drawn by its parent; this may have changed
9104                invalidateParentIfNeeded();
9105            }
9106        }
9107    }
9108
9109    /**
9110     * The amount that the view is scaled in x around the pivot point, as a proportion of
9111     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9112     *
9113     * <p>By default, this is 1.0f.
9114     *
9115     * @see #getPivotX()
9116     * @see #getPivotY()
9117     * @return The scaling factor.
9118     */
9119    @ViewDebug.ExportedProperty(category = "drawing")
9120    public float getScaleX() {
9121        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9122    }
9123
9124    /**
9125     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9126     * the view's unscaled width. A value of 1 means that no scaling is applied.
9127     *
9128     * @param scaleX The scaling factor.
9129     * @see #getPivotX()
9130     * @see #getPivotY()
9131     *
9132     * @attr ref android.R.styleable#View_scaleX
9133     */
9134    public void setScaleX(float scaleX) {
9135        ensureTransformationInfo();
9136        final TransformationInfo info = mTransformationInfo;
9137        if (info.mScaleX != scaleX) {
9138            invalidateViewProperty(true, false);
9139            info.mScaleX = scaleX;
9140            info.mMatrixDirty = true;
9141            invalidateViewProperty(false, true);
9142            if (mDisplayList != null) {
9143                mDisplayList.setScaleX(scaleX);
9144            }
9145            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9146                // View was rejected last time it was drawn by its parent; this may have changed
9147                invalidateParentIfNeeded();
9148            }
9149        }
9150    }
9151
9152    /**
9153     * The amount that the view is scaled in y around the pivot point, as a proportion of
9154     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9155     *
9156     * <p>By default, this is 1.0f.
9157     *
9158     * @see #getPivotX()
9159     * @see #getPivotY()
9160     * @return The scaling factor.
9161     */
9162    @ViewDebug.ExportedProperty(category = "drawing")
9163    public float getScaleY() {
9164        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9165    }
9166
9167    /**
9168     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9169     * the view's unscaled width. A value of 1 means that no scaling is applied.
9170     *
9171     * @param scaleY The scaling factor.
9172     * @see #getPivotX()
9173     * @see #getPivotY()
9174     *
9175     * @attr ref android.R.styleable#View_scaleY
9176     */
9177    public void setScaleY(float scaleY) {
9178        ensureTransformationInfo();
9179        final TransformationInfo info = mTransformationInfo;
9180        if (info.mScaleY != scaleY) {
9181            invalidateViewProperty(true, false);
9182            info.mScaleY = scaleY;
9183            info.mMatrixDirty = true;
9184            invalidateViewProperty(false, true);
9185            if (mDisplayList != null) {
9186                mDisplayList.setScaleY(scaleY);
9187            }
9188            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9189                // View was rejected last time it was drawn by its parent; this may have changed
9190                invalidateParentIfNeeded();
9191            }
9192        }
9193    }
9194
9195    /**
9196     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9197     * and {@link #setScaleX(float) scaled}.
9198     *
9199     * @see #getRotation()
9200     * @see #getScaleX()
9201     * @see #getScaleY()
9202     * @see #getPivotY()
9203     * @return The x location of the pivot point.
9204     *
9205     * @attr ref android.R.styleable#View_transformPivotX
9206     */
9207    @ViewDebug.ExportedProperty(category = "drawing")
9208    public float getPivotX() {
9209        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9210    }
9211
9212    /**
9213     * Sets the x location of the point around which the view is
9214     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9215     * By default, the pivot point is centered on the object.
9216     * Setting this property disables this behavior and causes the view to use only the
9217     * explicitly set pivotX and pivotY values.
9218     *
9219     * @param pivotX The x location of the pivot point.
9220     * @see #getRotation()
9221     * @see #getScaleX()
9222     * @see #getScaleY()
9223     * @see #getPivotY()
9224     *
9225     * @attr ref android.R.styleable#View_transformPivotX
9226     */
9227    public void setPivotX(float pivotX) {
9228        ensureTransformationInfo();
9229        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9230        final TransformationInfo info = mTransformationInfo;
9231        if (info.mPivotX != pivotX) {
9232            invalidateViewProperty(true, false);
9233            info.mPivotX = pivotX;
9234            info.mMatrixDirty = true;
9235            invalidateViewProperty(false, true);
9236            if (mDisplayList != null) {
9237                mDisplayList.setPivotX(pivotX);
9238            }
9239            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9240                // View was rejected last time it was drawn by its parent; this may have changed
9241                invalidateParentIfNeeded();
9242            }
9243        }
9244    }
9245
9246    /**
9247     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9248     * and {@link #setScaleY(float) scaled}.
9249     *
9250     * @see #getRotation()
9251     * @see #getScaleX()
9252     * @see #getScaleY()
9253     * @see #getPivotY()
9254     * @return The y location of the pivot point.
9255     *
9256     * @attr ref android.R.styleable#View_transformPivotY
9257     */
9258    @ViewDebug.ExportedProperty(category = "drawing")
9259    public float getPivotY() {
9260        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9261    }
9262
9263    /**
9264     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9265     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9266     * Setting this property disables this behavior and causes the view to use only the
9267     * explicitly set pivotX and pivotY values.
9268     *
9269     * @param pivotY The y location of the pivot point.
9270     * @see #getRotation()
9271     * @see #getScaleX()
9272     * @see #getScaleY()
9273     * @see #getPivotY()
9274     *
9275     * @attr ref android.R.styleable#View_transformPivotY
9276     */
9277    public void setPivotY(float pivotY) {
9278        ensureTransformationInfo();
9279        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9280        final TransformationInfo info = mTransformationInfo;
9281        if (info.mPivotY != pivotY) {
9282            invalidateViewProperty(true, false);
9283            info.mPivotY = pivotY;
9284            info.mMatrixDirty = true;
9285            invalidateViewProperty(false, true);
9286            if (mDisplayList != null) {
9287                mDisplayList.setPivotY(pivotY);
9288            }
9289            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9290                // View was rejected last time it was drawn by its parent; this may have changed
9291                invalidateParentIfNeeded();
9292            }
9293        }
9294    }
9295
9296    /**
9297     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9298     * completely transparent and 1 means the view is completely opaque.
9299     *
9300     * <p>By default this is 1.0f.
9301     * @return The opacity of the view.
9302     */
9303    @ViewDebug.ExportedProperty(category = "drawing")
9304    public float getAlpha() {
9305        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9306    }
9307
9308    /**
9309     * Returns whether this View has content which overlaps. This function, intended to be
9310     * overridden by specific View types, is an optimization when alpha is set on a view. If
9311     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9312     * and then composited it into place, which can be expensive. If the view has no overlapping
9313     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9314     * An example of overlapping rendering is a TextView with a background image, such as a
9315     * Button. An example of non-overlapping rendering is a TextView with no background, or
9316     * an ImageView with only the foreground image. The default implementation returns true;
9317     * subclasses should override if they have cases which can be optimized.
9318     *
9319     * @return true if the content in this view might overlap, false otherwise.
9320     */
9321    public boolean hasOverlappingRendering() {
9322        return true;
9323    }
9324
9325    /**
9326     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9327     * completely transparent and 1 means the view is completely opaque.</p>
9328     *
9329     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9330     * responsible for applying the opacity itself. Otherwise, calling this method is
9331     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9332     * setting a hardware layer.</p>
9333     *
9334     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9335     * performance implications. It is generally best to use the alpha property sparingly and
9336     * transiently, as in the case of fading animations.</p>
9337     *
9338     * @param alpha The opacity of the view.
9339     *
9340     * @see #setLayerType(int, android.graphics.Paint)
9341     *
9342     * @attr ref android.R.styleable#View_alpha
9343     */
9344    public void setAlpha(float alpha) {
9345        ensureTransformationInfo();
9346        if (mTransformationInfo.mAlpha != alpha) {
9347            mTransformationInfo.mAlpha = alpha;
9348            if (onSetAlpha((int) (alpha * 255))) {
9349                mPrivateFlags |= PFLAG_ALPHA_SET;
9350                // subclass is handling alpha - don't optimize rendering cache invalidation
9351                invalidateParentCaches();
9352                invalidate(true);
9353            } else {
9354                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9355                invalidateViewProperty(true, false);
9356                if (mDisplayList != null) {
9357                    mDisplayList.setAlpha(alpha);
9358                }
9359            }
9360        }
9361    }
9362
9363    /**
9364     * Faster version of setAlpha() which performs the same steps except there are
9365     * no calls to invalidate(). The caller of this function should perform proper invalidation
9366     * on the parent and this object. The return value indicates whether the subclass handles
9367     * alpha (the return value for onSetAlpha()).
9368     *
9369     * @param alpha The new value for the alpha property
9370     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9371     *         the new value for the alpha property is different from the old value
9372     */
9373    boolean setAlphaNoInvalidation(float alpha) {
9374        ensureTransformationInfo();
9375        if (mTransformationInfo.mAlpha != alpha) {
9376            mTransformationInfo.mAlpha = alpha;
9377            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9378            if (subclassHandlesAlpha) {
9379                mPrivateFlags |= PFLAG_ALPHA_SET;
9380                return true;
9381            } else {
9382                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9383                if (mDisplayList != null) {
9384                    mDisplayList.setAlpha(alpha);
9385                }
9386            }
9387        }
9388        return false;
9389    }
9390
9391    /**
9392     * Top position of this view relative to its parent.
9393     *
9394     * @return The top of this view, in pixels.
9395     */
9396    @ViewDebug.CapturedViewProperty
9397    public final int getTop() {
9398        return mTop;
9399    }
9400
9401    /**
9402     * Sets the top position of this view relative to its parent. This method is meant to be called
9403     * by the layout system and should not generally be called otherwise, because the property
9404     * may be changed at any time by the layout.
9405     *
9406     * @param top The top of this view, in pixels.
9407     */
9408    public final void setTop(int top) {
9409        if (top != mTop) {
9410            updateMatrix();
9411            final boolean matrixIsIdentity = mTransformationInfo == null
9412                    || mTransformationInfo.mMatrixIsIdentity;
9413            if (matrixIsIdentity) {
9414                if (mAttachInfo != null) {
9415                    int minTop;
9416                    int yLoc;
9417                    if (top < mTop) {
9418                        minTop = top;
9419                        yLoc = top - mTop;
9420                    } else {
9421                        minTop = mTop;
9422                        yLoc = 0;
9423                    }
9424                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9425                }
9426            } else {
9427                // Double-invalidation is necessary to capture view's old and new areas
9428                invalidate(true);
9429            }
9430
9431            int width = mRight - mLeft;
9432            int oldHeight = mBottom - mTop;
9433
9434            mTop = top;
9435            if (mDisplayList != null) {
9436                mDisplayList.setTop(mTop);
9437            }
9438
9439            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9440
9441            if (!matrixIsIdentity) {
9442                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9443                    // A change in dimension means an auto-centered pivot point changes, too
9444                    mTransformationInfo.mMatrixDirty = true;
9445                }
9446                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9447                invalidate(true);
9448            }
9449            mBackgroundSizeChanged = true;
9450            invalidateParentIfNeeded();
9451            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9452                // View was rejected last time it was drawn by its parent; this may have changed
9453                invalidateParentIfNeeded();
9454            }
9455        }
9456    }
9457
9458    /**
9459     * Bottom position of this view relative to its parent.
9460     *
9461     * @return The bottom of this view, in pixels.
9462     */
9463    @ViewDebug.CapturedViewProperty
9464    public final int getBottom() {
9465        return mBottom;
9466    }
9467
9468    /**
9469     * True if this view has changed since the last time being drawn.
9470     *
9471     * @return The dirty state of this view.
9472     */
9473    public boolean isDirty() {
9474        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9475    }
9476
9477    /**
9478     * Sets the bottom position of this view relative to its parent. This method is meant to be
9479     * called by the layout system and should not generally be called otherwise, because the
9480     * property may be changed at any time by the layout.
9481     *
9482     * @param bottom The bottom of this view, in pixels.
9483     */
9484    public final void setBottom(int bottom) {
9485        if (bottom != mBottom) {
9486            updateMatrix();
9487            final boolean matrixIsIdentity = mTransformationInfo == null
9488                    || mTransformationInfo.mMatrixIsIdentity;
9489            if (matrixIsIdentity) {
9490                if (mAttachInfo != null) {
9491                    int maxBottom;
9492                    if (bottom < mBottom) {
9493                        maxBottom = mBottom;
9494                    } else {
9495                        maxBottom = bottom;
9496                    }
9497                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9498                }
9499            } else {
9500                // Double-invalidation is necessary to capture view's old and new areas
9501                invalidate(true);
9502            }
9503
9504            int width = mRight - mLeft;
9505            int oldHeight = mBottom - mTop;
9506
9507            mBottom = bottom;
9508            if (mDisplayList != null) {
9509                mDisplayList.setBottom(mBottom);
9510            }
9511
9512            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9513
9514            if (!matrixIsIdentity) {
9515                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9516                    // A change in dimension means an auto-centered pivot point changes, too
9517                    mTransformationInfo.mMatrixDirty = true;
9518                }
9519                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9520                invalidate(true);
9521            }
9522            mBackgroundSizeChanged = true;
9523            invalidateParentIfNeeded();
9524            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9525                // View was rejected last time it was drawn by its parent; this may have changed
9526                invalidateParentIfNeeded();
9527            }
9528        }
9529    }
9530
9531    /**
9532     * Left position of this view relative to its parent.
9533     *
9534     * @return The left edge of this view, in pixels.
9535     */
9536    @ViewDebug.CapturedViewProperty
9537    public final int getLeft() {
9538        return mLeft;
9539    }
9540
9541    /**
9542     * Sets the left position of this view relative to its parent. This method is meant to be called
9543     * by the layout system and should not generally be called otherwise, because the property
9544     * may be changed at any time by the layout.
9545     *
9546     * @param left The bottom of this view, in pixels.
9547     */
9548    public final void setLeft(int left) {
9549        if (left != mLeft) {
9550            updateMatrix();
9551            final boolean matrixIsIdentity = mTransformationInfo == null
9552                    || mTransformationInfo.mMatrixIsIdentity;
9553            if (matrixIsIdentity) {
9554                if (mAttachInfo != null) {
9555                    int minLeft;
9556                    int xLoc;
9557                    if (left < mLeft) {
9558                        minLeft = left;
9559                        xLoc = left - mLeft;
9560                    } else {
9561                        minLeft = mLeft;
9562                        xLoc = 0;
9563                    }
9564                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9565                }
9566            } else {
9567                // Double-invalidation is necessary to capture view's old and new areas
9568                invalidate(true);
9569            }
9570
9571            int oldWidth = mRight - mLeft;
9572            int height = mBottom - mTop;
9573
9574            mLeft = left;
9575            if (mDisplayList != null) {
9576                mDisplayList.setLeft(left);
9577            }
9578
9579            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9580
9581            if (!matrixIsIdentity) {
9582                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9583                    // A change in dimension means an auto-centered pivot point changes, too
9584                    mTransformationInfo.mMatrixDirty = true;
9585                }
9586                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9587                invalidate(true);
9588            }
9589            mBackgroundSizeChanged = true;
9590            invalidateParentIfNeeded();
9591            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9592                // View was rejected last time it was drawn by its parent; this may have changed
9593                invalidateParentIfNeeded();
9594            }
9595        }
9596    }
9597
9598    /**
9599     * Right position of this view relative to its parent.
9600     *
9601     * @return The right edge of this view, in pixels.
9602     */
9603    @ViewDebug.CapturedViewProperty
9604    public final int getRight() {
9605        return mRight;
9606    }
9607
9608    /**
9609     * Sets the right position of this view relative to its parent. This method is meant to be called
9610     * by the layout system and should not generally be called otherwise, because the property
9611     * may be changed at any time by the layout.
9612     *
9613     * @param right The bottom of this view, in pixels.
9614     */
9615    public final void setRight(int right) {
9616        if (right != mRight) {
9617            updateMatrix();
9618            final boolean matrixIsIdentity = mTransformationInfo == null
9619                    || mTransformationInfo.mMatrixIsIdentity;
9620            if (matrixIsIdentity) {
9621                if (mAttachInfo != null) {
9622                    int maxRight;
9623                    if (right < mRight) {
9624                        maxRight = mRight;
9625                    } else {
9626                        maxRight = right;
9627                    }
9628                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9629                }
9630            } else {
9631                // Double-invalidation is necessary to capture view's old and new areas
9632                invalidate(true);
9633            }
9634
9635            int oldWidth = mRight - mLeft;
9636            int height = mBottom - mTop;
9637
9638            mRight = right;
9639            if (mDisplayList != null) {
9640                mDisplayList.setRight(mRight);
9641            }
9642
9643            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9644
9645            if (!matrixIsIdentity) {
9646                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9647                    // A change in dimension means an auto-centered pivot point changes, too
9648                    mTransformationInfo.mMatrixDirty = true;
9649                }
9650                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9651                invalidate(true);
9652            }
9653            mBackgroundSizeChanged = true;
9654            invalidateParentIfNeeded();
9655            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9656                // View was rejected last time it was drawn by its parent; this may have changed
9657                invalidateParentIfNeeded();
9658            }
9659        }
9660    }
9661
9662    /**
9663     * The visual x position of this view, in pixels. This is equivalent to the
9664     * {@link #setTranslationX(float) translationX} property plus the current
9665     * {@link #getLeft() left} property.
9666     *
9667     * @return The visual x position of this view, in pixels.
9668     */
9669    @ViewDebug.ExportedProperty(category = "drawing")
9670    public float getX() {
9671        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9672    }
9673
9674    /**
9675     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9676     * {@link #setTranslationX(float) translationX} property to be the difference between
9677     * the x value passed in and the current {@link #getLeft() left} property.
9678     *
9679     * @param x The visual x position of this view, in pixels.
9680     */
9681    public void setX(float x) {
9682        setTranslationX(x - mLeft);
9683    }
9684
9685    /**
9686     * The visual y position of this view, in pixels. This is equivalent to the
9687     * {@link #setTranslationY(float) translationY} property plus the current
9688     * {@link #getTop() top} property.
9689     *
9690     * @return The visual y position of this view, in pixels.
9691     */
9692    @ViewDebug.ExportedProperty(category = "drawing")
9693    public float getY() {
9694        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9695    }
9696
9697    /**
9698     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9699     * {@link #setTranslationY(float) translationY} property to be the difference between
9700     * the y value passed in and the current {@link #getTop() top} property.
9701     *
9702     * @param y The visual y position of this view, in pixels.
9703     */
9704    public void setY(float y) {
9705        setTranslationY(y - mTop);
9706    }
9707
9708
9709    /**
9710     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9711     * This position is post-layout, in addition to wherever the object's
9712     * layout placed it.
9713     *
9714     * @return The horizontal position of this view relative to its left position, in pixels.
9715     */
9716    @ViewDebug.ExportedProperty(category = "drawing")
9717    public float getTranslationX() {
9718        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9719    }
9720
9721    /**
9722     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9723     * This effectively positions the object post-layout, in addition to wherever the object's
9724     * layout placed it.
9725     *
9726     * @param translationX The horizontal position of this view relative to its left position,
9727     * in pixels.
9728     *
9729     * @attr ref android.R.styleable#View_translationX
9730     */
9731    public void setTranslationX(float translationX) {
9732        ensureTransformationInfo();
9733        final TransformationInfo info = mTransformationInfo;
9734        if (info.mTranslationX != translationX) {
9735            // Double-invalidation is necessary to capture view's old and new areas
9736            invalidateViewProperty(true, false);
9737            info.mTranslationX = translationX;
9738            info.mMatrixDirty = true;
9739            invalidateViewProperty(false, true);
9740            if (mDisplayList != null) {
9741                mDisplayList.setTranslationX(translationX);
9742            }
9743            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9744                // View was rejected last time it was drawn by its parent; this may have changed
9745                invalidateParentIfNeeded();
9746            }
9747        }
9748    }
9749
9750    /**
9751     * The horizontal location of this view relative to its {@link #getTop() top} position.
9752     * This position is post-layout, in addition to wherever the object's
9753     * layout placed it.
9754     *
9755     * @return The vertical position of this view relative to its top position,
9756     * in pixels.
9757     */
9758    @ViewDebug.ExportedProperty(category = "drawing")
9759    public float getTranslationY() {
9760        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9761    }
9762
9763    /**
9764     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9765     * This effectively positions the object post-layout, in addition to wherever the object's
9766     * layout placed it.
9767     *
9768     * @param translationY The vertical position of this view relative to its top position,
9769     * in pixels.
9770     *
9771     * @attr ref android.R.styleable#View_translationY
9772     */
9773    public void setTranslationY(float translationY) {
9774        ensureTransformationInfo();
9775        final TransformationInfo info = mTransformationInfo;
9776        if (info.mTranslationY != translationY) {
9777            invalidateViewProperty(true, false);
9778            info.mTranslationY = translationY;
9779            info.mMatrixDirty = true;
9780            invalidateViewProperty(false, true);
9781            if (mDisplayList != null) {
9782                mDisplayList.setTranslationY(translationY);
9783            }
9784            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9785                // View was rejected last time it was drawn by its parent; this may have changed
9786                invalidateParentIfNeeded();
9787            }
9788        }
9789    }
9790
9791    /**
9792     * Hit rectangle in parent's coordinates
9793     *
9794     * @param outRect The hit rectangle of the view.
9795     */
9796    public void getHitRect(Rect outRect) {
9797        updateMatrix();
9798        final TransformationInfo info = mTransformationInfo;
9799        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9800            outRect.set(mLeft, mTop, mRight, mBottom);
9801        } else {
9802            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9803            tmpRect.set(-info.mPivotX, -info.mPivotY,
9804                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9805            info.mMatrix.mapRect(tmpRect);
9806            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9807                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9808        }
9809    }
9810
9811    /**
9812     * Determines whether the given point, in local coordinates is inside the view.
9813     */
9814    /*package*/ final boolean pointInView(float localX, float localY) {
9815        return localX >= 0 && localX < (mRight - mLeft)
9816                && localY >= 0 && localY < (mBottom - mTop);
9817    }
9818
9819    /**
9820     * Utility method to determine whether the given point, in local coordinates,
9821     * is inside the view, where the area of the view is expanded by the slop factor.
9822     * This method is called while processing touch-move events to determine if the event
9823     * is still within the view.
9824     */
9825    private boolean pointInView(float localX, float localY, float slop) {
9826        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9827                localY < ((mBottom - mTop) + slop);
9828    }
9829
9830    /**
9831     * When a view has focus and the user navigates away from it, the next view is searched for
9832     * starting from the rectangle filled in by this method.
9833     *
9834     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
9835     * of the view.  However, if your view maintains some idea of internal selection,
9836     * such as a cursor, or a selected row or column, you should override this method and
9837     * fill in a more specific rectangle.
9838     *
9839     * @param r The rectangle to fill in, in this view's coordinates.
9840     */
9841    public void getFocusedRect(Rect r) {
9842        getDrawingRect(r);
9843    }
9844
9845    /**
9846     * If some part of this view is not clipped by any of its parents, then
9847     * return that area in r in global (root) coordinates. To convert r to local
9848     * coordinates (without taking possible View rotations into account), offset
9849     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9850     * If the view is completely clipped or translated out, return false.
9851     *
9852     * @param r If true is returned, r holds the global coordinates of the
9853     *        visible portion of this view.
9854     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9855     *        between this view and its root. globalOffet may be null.
9856     * @return true if r is non-empty (i.e. part of the view is visible at the
9857     *         root level.
9858     */
9859    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9860        int width = mRight - mLeft;
9861        int height = mBottom - mTop;
9862        if (width > 0 && height > 0) {
9863            r.set(0, 0, width, height);
9864            if (globalOffset != null) {
9865                globalOffset.set(-mScrollX, -mScrollY);
9866            }
9867            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9868        }
9869        return false;
9870    }
9871
9872    public final boolean getGlobalVisibleRect(Rect r) {
9873        return getGlobalVisibleRect(r, null);
9874    }
9875
9876    public final boolean getLocalVisibleRect(Rect r) {
9877        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9878        if (getGlobalVisibleRect(r, offset)) {
9879            r.offset(-offset.x, -offset.y); // make r local
9880            return true;
9881        }
9882        return false;
9883    }
9884
9885    /**
9886     * Offset this view's vertical location by the specified number of pixels.
9887     *
9888     * @param offset the number of pixels to offset the view by
9889     */
9890    public void offsetTopAndBottom(int offset) {
9891        if (offset != 0) {
9892            updateMatrix();
9893            final boolean matrixIsIdentity = mTransformationInfo == null
9894                    || mTransformationInfo.mMatrixIsIdentity;
9895            if (matrixIsIdentity) {
9896                if (mDisplayList != null) {
9897                    invalidateViewProperty(false, false);
9898                } else {
9899                    final ViewParent p = mParent;
9900                    if (p != null && mAttachInfo != null) {
9901                        final Rect r = mAttachInfo.mTmpInvalRect;
9902                        int minTop;
9903                        int maxBottom;
9904                        int yLoc;
9905                        if (offset < 0) {
9906                            minTop = mTop + offset;
9907                            maxBottom = mBottom;
9908                            yLoc = offset;
9909                        } else {
9910                            minTop = mTop;
9911                            maxBottom = mBottom + offset;
9912                            yLoc = 0;
9913                        }
9914                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9915                        p.invalidateChild(this, r);
9916                    }
9917                }
9918            } else {
9919                invalidateViewProperty(false, false);
9920            }
9921
9922            mTop += offset;
9923            mBottom += offset;
9924            if (mDisplayList != null) {
9925                mDisplayList.offsetTopBottom(offset);
9926                invalidateViewProperty(false, false);
9927            } else {
9928                if (!matrixIsIdentity) {
9929                    invalidateViewProperty(false, true);
9930                }
9931                invalidateParentIfNeeded();
9932            }
9933        }
9934    }
9935
9936    /**
9937     * Offset this view's horizontal location by the specified amount of pixels.
9938     *
9939     * @param offset the numer of pixels to offset the view by
9940     */
9941    public void offsetLeftAndRight(int offset) {
9942        if (offset != 0) {
9943            updateMatrix();
9944            final boolean matrixIsIdentity = mTransformationInfo == null
9945                    || mTransformationInfo.mMatrixIsIdentity;
9946            if (matrixIsIdentity) {
9947                if (mDisplayList != null) {
9948                    invalidateViewProperty(false, false);
9949                } else {
9950                    final ViewParent p = mParent;
9951                    if (p != null && mAttachInfo != null) {
9952                        final Rect r = mAttachInfo.mTmpInvalRect;
9953                        int minLeft;
9954                        int maxRight;
9955                        if (offset < 0) {
9956                            minLeft = mLeft + offset;
9957                            maxRight = mRight;
9958                        } else {
9959                            minLeft = mLeft;
9960                            maxRight = mRight + offset;
9961                        }
9962                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9963                        p.invalidateChild(this, r);
9964                    }
9965                }
9966            } else {
9967                invalidateViewProperty(false, false);
9968            }
9969
9970            mLeft += offset;
9971            mRight += offset;
9972            if (mDisplayList != null) {
9973                mDisplayList.offsetLeftRight(offset);
9974                invalidateViewProperty(false, false);
9975            } else {
9976                if (!matrixIsIdentity) {
9977                    invalidateViewProperty(false, true);
9978                }
9979                invalidateParentIfNeeded();
9980            }
9981        }
9982    }
9983
9984    /**
9985     * Get the LayoutParams associated with this view. All views should have
9986     * layout parameters. These supply parameters to the <i>parent</i> of this
9987     * view specifying how it should be arranged. There are many subclasses of
9988     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9989     * of ViewGroup that are responsible for arranging their children.
9990     *
9991     * This method may return null if this View is not attached to a parent
9992     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9993     * was not invoked successfully. When a View is attached to a parent
9994     * ViewGroup, this method must not return null.
9995     *
9996     * @return The LayoutParams associated with this view, or null if no
9997     *         parameters have been set yet
9998     */
9999    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10000    public ViewGroup.LayoutParams getLayoutParams() {
10001        return mLayoutParams;
10002    }
10003
10004    /**
10005     * Set the layout parameters associated with this view. These supply
10006     * parameters to the <i>parent</i> of this view specifying how it should be
10007     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10008     * correspond to the different subclasses of ViewGroup that are responsible
10009     * for arranging their children.
10010     *
10011     * @param params The layout parameters for this view, cannot be null
10012     */
10013    public void setLayoutParams(ViewGroup.LayoutParams params) {
10014        if (params == null) {
10015            throw new NullPointerException("Layout parameters cannot be null");
10016        }
10017        mLayoutParams = params;
10018        resolveLayoutParams();
10019        if (mParent instanceof ViewGroup) {
10020            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10021        }
10022        requestLayout();
10023    }
10024
10025    /**
10026     * Resolve the layout parameters depending on the resolved layout direction
10027     *
10028     * @hide
10029     */
10030    public void resolveLayoutParams() {
10031        if (mLayoutParams != null) {
10032            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10033        }
10034    }
10035
10036    /**
10037     * Set the scrolled position of your view. This will cause a call to
10038     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10039     * invalidated.
10040     * @param x the x position to scroll to
10041     * @param y the y position to scroll to
10042     */
10043    public void scrollTo(int x, int y) {
10044        if (mScrollX != x || mScrollY != y) {
10045            int oldX = mScrollX;
10046            int oldY = mScrollY;
10047            mScrollX = x;
10048            mScrollY = y;
10049            invalidateParentCaches();
10050            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10051            if (!awakenScrollBars()) {
10052                postInvalidateOnAnimation();
10053            }
10054        }
10055    }
10056
10057    /**
10058     * Move the scrolled position of your view. This will cause a call to
10059     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10060     * invalidated.
10061     * @param x the amount of pixels to scroll by horizontally
10062     * @param y the amount of pixels to scroll by vertically
10063     */
10064    public void scrollBy(int x, int y) {
10065        scrollTo(mScrollX + x, mScrollY + y);
10066    }
10067
10068    /**
10069     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10070     * animation to fade the scrollbars out after a default delay. If a subclass
10071     * provides animated scrolling, the start delay should equal the duration
10072     * of the scrolling animation.</p>
10073     *
10074     * <p>The animation starts only if at least one of the scrollbars is
10075     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10076     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10077     * this method returns true, and false otherwise. If the animation is
10078     * started, this method calls {@link #invalidate()}; in that case the
10079     * caller should not call {@link #invalidate()}.</p>
10080     *
10081     * <p>This method should be invoked every time a subclass directly updates
10082     * the scroll parameters.</p>
10083     *
10084     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10085     * and {@link #scrollTo(int, int)}.</p>
10086     *
10087     * @return true if the animation is played, false otherwise
10088     *
10089     * @see #awakenScrollBars(int)
10090     * @see #scrollBy(int, int)
10091     * @see #scrollTo(int, int)
10092     * @see #isHorizontalScrollBarEnabled()
10093     * @see #isVerticalScrollBarEnabled()
10094     * @see #setHorizontalScrollBarEnabled(boolean)
10095     * @see #setVerticalScrollBarEnabled(boolean)
10096     */
10097    protected boolean awakenScrollBars() {
10098        return mScrollCache != null &&
10099                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10100    }
10101
10102    /**
10103     * Trigger the scrollbars to draw.
10104     * This method differs from awakenScrollBars() only in its default duration.
10105     * initialAwakenScrollBars() will show the scroll bars for longer than
10106     * usual to give the user more of a chance to notice them.
10107     *
10108     * @return true if the animation is played, false otherwise.
10109     */
10110    private boolean initialAwakenScrollBars() {
10111        return mScrollCache != null &&
10112                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10113    }
10114
10115    /**
10116     * <p>
10117     * Trigger the scrollbars to draw. When invoked this method starts an
10118     * animation to fade the scrollbars out after a fixed delay. If a subclass
10119     * provides animated scrolling, the start delay should equal the duration of
10120     * the scrolling animation.
10121     * </p>
10122     *
10123     * <p>
10124     * The animation starts only if at least one of the scrollbars is enabled,
10125     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10126     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10127     * this method returns true, and false otherwise. If the animation is
10128     * started, this method calls {@link #invalidate()}; in that case the caller
10129     * should not call {@link #invalidate()}.
10130     * </p>
10131     *
10132     * <p>
10133     * This method should be invoked everytime a subclass directly updates the
10134     * scroll parameters.
10135     * </p>
10136     *
10137     * @param startDelay the delay, in milliseconds, after which the animation
10138     *        should start; when the delay is 0, the animation starts
10139     *        immediately
10140     * @return true if the animation is played, false otherwise
10141     *
10142     * @see #scrollBy(int, int)
10143     * @see #scrollTo(int, int)
10144     * @see #isHorizontalScrollBarEnabled()
10145     * @see #isVerticalScrollBarEnabled()
10146     * @see #setHorizontalScrollBarEnabled(boolean)
10147     * @see #setVerticalScrollBarEnabled(boolean)
10148     */
10149    protected boolean awakenScrollBars(int startDelay) {
10150        return awakenScrollBars(startDelay, true);
10151    }
10152
10153    /**
10154     * <p>
10155     * Trigger the scrollbars to draw. When invoked this method starts an
10156     * animation to fade the scrollbars out after a fixed delay. If a subclass
10157     * provides animated scrolling, the start delay should equal the duration of
10158     * the scrolling animation.
10159     * </p>
10160     *
10161     * <p>
10162     * The animation starts only if at least one of the scrollbars is enabled,
10163     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10164     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10165     * this method returns true, and false otherwise. If the animation is
10166     * started, this method calls {@link #invalidate()} if the invalidate parameter
10167     * is set to true; in that case the caller
10168     * should not call {@link #invalidate()}.
10169     * </p>
10170     *
10171     * <p>
10172     * This method should be invoked everytime a subclass directly updates the
10173     * scroll parameters.
10174     * </p>
10175     *
10176     * @param startDelay the delay, in milliseconds, after which the animation
10177     *        should start; when the delay is 0, the animation starts
10178     *        immediately
10179     *
10180     * @param invalidate Wheter this method should call invalidate
10181     *
10182     * @return true if the animation is played, false otherwise
10183     *
10184     * @see #scrollBy(int, int)
10185     * @see #scrollTo(int, int)
10186     * @see #isHorizontalScrollBarEnabled()
10187     * @see #isVerticalScrollBarEnabled()
10188     * @see #setHorizontalScrollBarEnabled(boolean)
10189     * @see #setVerticalScrollBarEnabled(boolean)
10190     */
10191    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10192        final ScrollabilityCache scrollCache = mScrollCache;
10193
10194        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10195            return false;
10196        }
10197
10198        if (scrollCache.scrollBar == null) {
10199            scrollCache.scrollBar = new ScrollBarDrawable();
10200        }
10201
10202        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10203
10204            if (invalidate) {
10205                // Invalidate to show the scrollbars
10206                postInvalidateOnAnimation();
10207            }
10208
10209            if (scrollCache.state == ScrollabilityCache.OFF) {
10210                // FIXME: this is copied from WindowManagerService.
10211                // We should get this value from the system when it
10212                // is possible to do so.
10213                final int KEY_REPEAT_FIRST_DELAY = 750;
10214                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10215            }
10216
10217            // Tell mScrollCache when we should start fading. This may
10218            // extend the fade start time if one was already scheduled
10219            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10220            scrollCache.fadeStartTime = fadeStartTime;
10221            scrollCache.state = ScrollabilityCache.ON;
10222
10223            // Schedule our fader to run, unscheduling any old ones first
10224            if (mAttachInfo != null) {
10225                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10226                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10227            }
10228
10229            return true;
10230        }
10231
10232        return false;
10233    }
10234
10235    /**
10236     * Do not invalidate views which are not visible and which are not running an animation. They
10237     * will not get drawn and they should not set dirty flags as if they will be drawn
10238     */
10239    private boolean skipInvalidate() {
10240        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10241                (!(mParent instanceof ViewGroup) ||
10242                        !((ViewGroup) mParent).isViewTransitioning(this));
10243    }
10244    /**
10245     * Mark the area defined by dirty as needing to be drawn. If the view is
10246     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10247     * in the future. This must be called from a UI thread. To call from a non-UI
10248     * thread, call {@link #postInvalidate()}.
10249     *
10250     * WARNING: This method is destructive to dirty.
10251     * @param dirty the rectangle representing the bounds of the dirty region
10252     */
10253    public void invalidate(Rect dirty) {
10254        if (skipInvalidate()) {
10255            return;
10256        }
10257        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10258                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10259                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10260            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10261            mPrivateFlags |= PFLAG_INVALIDATED;
10262            mPrivateFlags |= PFLAG_DIRTY;
10263            final ViewParent p = mParent;
10264            final AttachInfo ai = mAttachInfo;
10265            //noinspection PointlessBooleanExpression,ConstantConditions
10266            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10267                if (p != null && ai != null && ai.mHardwareAccelerated) {
10268                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10269                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10270                    p.invalidateChild(this, null);
10271                    return;
10272                }
10273            }
10274            if (p != null && ai != null) {
10275                final int scrollX = mScrollX;
10276                final int scrollY = mScrollY;
10277                final Rect r = ai.mTmpInvalRect;
10278                r.set(dirty.left - scrollX, dirty.top - scrollY,
10279                        dirty.right - scrollX, dirty.bottom - scrollY);
10280                mParent.invalidateChild(this, r);
10281            }
10282        }
10283    }
10284
10285    /**
10286     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10287     * The coordinates of the dirty rect are relative to the view.
10288     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10289     * will be called at some point in the future. This must be called from
10290     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10291     * @param l the left position of the dirty region
10292     * @param t the top position of the dirty region
10293     * @param r the right position of the dirty region
10294     * @param b the bottom position of the dirty region
10295     */
10296    public void invalidate(int l, int t, int r, int b) {
10297        if (skipInvalidate()) {
10298            return;
10299        }
10300        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10301                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10302                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10303            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10304            mPrivateFlags |= PFLAG_INVALIDATED;
10305            mPrivateFlags |= PFLAG_DIRTY;
10306            final ViewParent p = mParent;
10307            final AttachInfo ai = mAttachInfo;
10308            //noinspection PointlessBooleanExpression,ConstantConditions
10309            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10310                if (p != null && ai != null && ai.mHardwareAccelerated) {
10311                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10312                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10313                    p.invalidateChild(this, null);
10314                    return;
10315                }
10316            }
10317            if (p != null && ai != null && l < r && t < b) {
10318                final int scrollX = mScrollX;
10319                final int scrollY = mScrollY;
10320                final Rect tmpr = ai.mTmpInvalRect;
10321                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10322                p.invalidateChild(this, tmpr);
10323            }
10324        }
10325    }
10326
10327    /**
10328     * Invalidate the whole view. If the view is visible,
10329     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10330     * the future. This must be called from a UI thread. To call from a non-UI thread,
10331     * call {@link #postInvalidate()}.
10332     */
10333    public void invalidate() {
10334        invalidate(true);
10335    }
10336
10337    /**
10338     * This is where the invalidate() work actually happens. A full invalidate()
10339     * causes the drawing cache to be invalidated, but this function can be called with
10340     * invalidateCache set to false to skip that invalidation step for cases that do not
10341     * need it (for example, a component that remains at the same dimensions with the same
10342     * content).
10343     *
10344     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10345     * well. This is usually true for a full invalidate, but may be set to false if the
10346     * View's contents or dimensions have not changed.
10347     */
10348    void invalidate(boolean invalidateCache) {
10349        if (skipInvalidate()) {
10350            return;
10351        }
10352        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10353                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10354                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10355            mLastIsOpaque = isOpaque();
10356            mPrivateFlags &= ~PFLAG_DRAWN;
10357            mPrivateFlags |= PFLAG_DIRTY;
10358            if (invalidateCache) {
10359                mPrivateFlags |= PFLAG_INVALIDATED;
10360                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10361            }
10362            final AttachInfo ai = mAttachInfo;
10363            final ViewParent p = mParent;
10364            //noinspection PointlessBooleanExpression,ConstantConditions
10365            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10366                if (p != null && ai != null && ai.mHardwareAccelerated) {
10367                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10368                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10369                    p.invalidateChild(this, null);
10370                    return;
10371                }
10372            }
10373
10374            if (p != null && ai != null) {
10375                final Rect r = ai.mTmpInvalRect;
10376                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10377                // Don't call invalidate -- we don't want to internally scroll
10378                // our own bounds
10379                p.invalidateChild(this, r);
10380            }
10381        }
10382    }
10383
10384    /**
10385     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10386     * set any flags or handle all of the cases handled by the default invalidation methods.
10387     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10388     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10389     * walk up the hierarchy, transforming the dirty rect as necessary.
10390     *
10391     * The method also handles normal invalidation logic if display list properties are not
10392     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10393     * backup approach, to handle these cases used in the various property-setting methods.
10394     *
10395     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10396     * are not being used in this view
10397     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10398     * list properties are not being used in this view
10399     */
10400    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10401        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10402            if (invalidateParent) {
10403                invalidateParentCaches();
10404            }
10405            if (forceRedraw) {
10406                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10407            }
10408            invalidate(false);
10409        } else {
10410            final AttachInfo ai = mAttachInfo;
10411            final ViewParent p = mParent;
10412            if (p != null && ai != null) {
10413                final Rect r = ai.mTmpInvalRect;
10414                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10415                if (mParent instanceof ViewGroup) {
10416                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10417                } else {
10418                    mParent.invalidateChild(this, r);
10419                }
10420            }
10421        }
10422    }
10423
10424    /**
10425     * Utility method to transform a given Rect by the current matrix of this view.
10426     */
10427    void transformRect(final Rect rect) {
10428        if (!getMatrix().isIdentity()) {
10429            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10430            boundingRect.set(rect);
10431            getMatrix().mapRect(boundingRect);
10432            rect.set((int) (boundingRect.left - 0.5f),
10433                    (int) (boundingRect.top - 0.5f),
10434                    (int) (boundingRect.right + 0.5f),
10435                    (int) (boundingRect.bottom + 0.5f));
10436        }
10437    }
10438
10439    /**
10440     * Used to indicate that the parent of this view should clear its caches. This functionality
10441     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10442     * which is necessary when various parent-managed properties of the view change, such as
10443     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10444     * clears the parent caches and does not causes an invalidate event.
10445     *
10446     * @hide
10447     */
10448    protected void invalidateParentCaches() {
10449        if (mParent instanceof View) {
10450            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10451        }
10452    }
10453
10454    /**
10455     * Used to indicate that the parent of this view should be invalidated. This functionality
10456     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10457     * which is necessary when various parent-managed properties of the view change, such as
10458     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10459     * an invalidation event to the parent.
10460     *
10461     * @hide
10462     */
10463    protected void invalidateParentIfNeeded() {
10464        if (isHardwareAccelerated() && mParent instanceof View) {
10465            ((View) mParent).invalidate(true);
10466        }
10467    }
10468
10469    /**
10470     * Indicates whether this View is opaque. An opaque View guarantees that it will
10471     * draw all the pixels overlapping its bounds using a fully opaque color.
10472     *
10473     * Subclasses of View should override this method whenever possible to indicate
10474     * whether an instance is opaque. Opaque Views are treated in a special way by
10475     * the View hierarchy, possibly allowing it to perform optimizations during
10476     * invalidate/draw passes.
10477     *
10478     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10479     */
10480    @ViewDebug.ExportedProperty(category = "drawing")
10481    public boolean isOpaque() {
10482        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10483                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10484    }
10485
10486    /**
10487     * @hide
10488     */
10489    protected void computeOpaqueFlags() {
10490        // Opaque if:
10491        //   - Has a background
10492        //   - Background is opaque
10493        //   - Doesn't have scrollbars or scrollbars are inside overlay
10494
10495        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10496            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10497        } else {
10498            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10499        }
10500
10501        final int flags = mViewFlags;
10502        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10503                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10504            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10505        } else {
10506            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10507        }
10508    }
10509
10510    /**
10511     * @hide
10512     */
10513    protected boolean hasOpaqueScrollbars() {
10514        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10515    }
10516
10517    /**
10518     * @return A handler associated with the thread running the View. This
10519     * handler can be used to pump events in the UI events queue.
10520     */
10521    public Handler getHandler() {
10522        if (mAttachInfo != null) {
10523            return mAttachInfo.mHandler;
10524        }
10525        return null;
10526    }
10527
10528    /**
10529     * Gets the view root associated with the View.
10530     * @return The view root, or null if none.
10531     * @hide
10532     */
10533    public ViewRootImpl getViewRootImpl() {
10534        if (mAttachInfo != null) {
10535            return mAttachInfo.mViewRootImpl;
10536        }
10537        return null;
10538    }
10539
10540    /**
10541     * <p>Causes the Runnable to be added to the message queue.
10542     * The runnable will be run on the user interface thread.</p>
10543     *
10544     * @param action The Runnable that will be executed.
10545     *
10546     * @return Returns true if the Runnable was successfully placed in to the
10547     *         message queue.  Returns false on failure, usually because the
10548     *         looper processing the message queue is exiting.
10549     *
10550     * @see #postDelayed
10551     * @see #removeCallbacks
10552     */
10553    public boolean post(Runnable action) {
10554        final AttachInfo attachInfo = mAttachInfo;
10555        if (attachInfo != null) {
10556            return attachInfo.mHandler.post(action);
10557        }
10558        // Assume that post will succeed later
10559        ViewRootImpl.getRunQueue().post(action);
10560        return true;
10561    }
10562
10563    /**
10564     * <p>Causes the Runnable to be added to the message queue, to be run
10565     * after the specified amount of time elapses.
10566     * The runnable will be run on the user interface thread.</p>
10567     *
10568     * @param action The Runnable that will be executed.
10569     * @param delayMillis The delay (in milliseconds) until the Runnable
10570     *        will be executed.
10571     *
10572     * @return true if the Runnable was successfully placed in to the
10573     *         message queue.  Returns false on failure, usually because the
10574     *         looper processing the message queue is exiting.  Note that a
10575     *         result of true does not mean the Runnable will be processed --
10576     *         if the looper is quit before the delivery time of the message
10577     *         occurs then the message will be dropped.
10578     *
10579     * @see #post
10580     * @see #removeCallbacks
10581     */
10582    public boolean postDelayed(Runnable action, long delayMillis) {
10583        final AttachInfo attachInfo = mAttachInfo;
10584        if (attachInfo != null) {
10585            return attachInfo.mHandler.postDelayed(action, delayMillis);
10586        }
10587        // Assume that post will succeed later
10588        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10589        return true;
10590    }
10591
10592    /**
10593     * <p>Causes the Runnable to execute on the next animation time step.
10594     * The runnable will be run on the user interface thread.</p>
10595     *
10596     * @param action The Runnable that will be executed.
10597     *
10598     * @see #postOnAnimationDelayed
10599     * @see #removeCallbacks
10600     */
10601    public void postOnAnimation(Runnable action) {
10602        final AttachInfo attachInfo = mAttachInfo;
10603        if (attachInfo != null) {
10604            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10605                    Choreographer.CALLBACK_ANIMATION, action, null);
10606        } else {
10607            // Assume that post will succeed later
10608            ViewRootImpl.getRunQueue().post(action);
10609        }
10610    }
10611
10612    /**
10613     * <p>Causes the Runnable to execute on the next animation time step,
10614     * after the specified amount of time elapses.
10615     * The runnable will be run on the user interface thread.</p>
10616     *
10617     * @param action The Runnable that will be executed.
10618     * @param delayMillis The delay (in milliseconds) until the Runnable
10619     *        will be executed.
10620     *
10621     * @see #postOnAnimation
10622     * @see #removeCallbacks
10623     */
10624    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10625        final AttachInfo attachInfo = mAttachInfo;
10626        if (attachInfo != null) {
10627            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10628                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10629        } else {
10630            // Assume that post will succeed later
10631            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10632        }
10633    }
10634
10635    /**
10636     * <p>Removes the specified Runnable from the message queue.</p>
10637     *
10638     * @param action The Runnable to remove from the message handling queue
10639     *
10640     * @return true if this view could ask the Handler to remove the Runnable,
10641     *         false otherwise. When the returned value is true, the Runnable
10642     *         may or may not have been actually removed from the message queue
10643     *         (for instance, if the Runnable was not in the queue already.)
10644     *
10645     * @see #post
10646     * @see #postDelayed
10647     * @see #postOnAnimation
10648     * @see #postOnAnimationDelayed
10649     */
10650    public boolean removeCallbacks(Runnable action) {
10651        if (action != null) {
10652            final AttachInfo attachInfo = mAttachInfo;
10653            if (attachInfo != null) {
10654                attachInfo.mHandler.removeCallbacks(action);
10655                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10656                        Choreographer.CALLBACK_ANIMATION, action, null);
10657            } else {
10658                // Assume that post will succeed later
10659                ViewRootImpl.getRunQueue().removeCallbacks(action);
10660            }
10661        }
10662        return true;
10663    }
10664
10665    /**
10666     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10667     * Use this to invalidate the View from a non-UI thread.</p>
10668     *
10669     * <p>This method can be invoked from outside of the UI thread
10670     * only when this View is attached to a window.</p>
10671     *
10672     * @see #invalidate()
10673     * @see #postInvalidateDelayed(long)
10674     */
10675    public void postInvalidate() {
10676        postInvalidateDelayed(0);
10677    }
10678
10679    /**
10680     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10681     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10682     *
10683     * <p>This method can be invoked from outside of the UI thread
10684     * only when this View is attached to a window.</p>
10685     *
10686     * @param left The left coordinate of the rectangle to invalidate.
10687     * @param top The top coordinate of the rectangle to invalidate.
10688     * @param right The right coordinate of the rectangle to invalidate.
10689     * @param bottom The bottom coordinate of the rectangle to invalidate.
10690     *
10691     * @see #invalidate(int, int, int, int)
10692     * @see #invalidate(Rect)
10693     * @see #postInvalidateDelayed(long, int, int, int, int)
10694     */
10695    public void postInvalidate(int left, int top, int right, int bottom) {
10696        postInvalidateDelayed(0, left, top, right, bottom);
10697    }
10698
10699    /**
10700     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10701     * loop. Waits for the specified amount of time.</p>
10702     *
10703     * <p>This method can be invoked from outside of the UI thread
10704     * only when this View is attached to a window.</p>
10705     *
10706     * @param delayMilliseconds the duration in milliseconds to delay the
10707     *         invalidation by
10708     *
10709     * @see #invalidate()
10710     * @see #postInvalidate()
10711     */
10712    public void postInvalidateDelayed(long delayMilliseconds) {
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            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10718        }
10719    }
10720
10721    /**
10722     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10723     * through the event loop. Waits for the specified amount of time.</p>
10724     *
10725     * <p>This method can be invoked from outside of the UI thread
10726     * only when this View is attached to a window.</p>
10727     *
10728     * @param delayMilliseconds the duration in milliseconds to delay the
10729     *         invalidation by
10730     * @param left The left coordinate of the rectangle to invalidate.
10731     * @param top The top coordinate of the rectangle to invalidate.
10732     * @param right The right coordinate of the rectangle to invalidate.
10733     * @param bottom The bottom coordinate of the rectangle to invalidate.
10734     *
10735     * @see #invalidate(int, int, int, int)
10736     * @see #invalidate(Rect)
10737     * @see #postInvalidate(int, int, int, int)
10738     */
10739    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10740            int right, int bottom) {
10741
10742        // We try only with the AttachInfo because there's no point in invalidating
10743        // if we are not attached to our window
10744        final AttachInfo attachInfo = mAttachInfo;
10745        if (attachInfo != null) {
10746            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10747            info.target = this;
10748            info.left = left;
10749            info.top = top;
10750            info.right = right;
10751            info.bottom = bottom;
10752
10753            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10754        }
10755    }
10756
10757    /**
10758     * <p>Cause an invalidate to happen on the next animation time step, typically the
10759     * next display frame.</p>
10760     *
10761     * <p>This method can be invoked from outside of the UI thread
10762     * only when this View is attached to a window.</p>
10763     *
10764     * @see #invalidate()
10765     */
10766    public void postInvalidateOnAnimation() {
10767        // We try only with the AttachInfo because there's no point in invalidating
10768        // if we are not attached to our window
10769        final AttachInfo attachInfo = mAttachInfo;
10770        if (attachInfo != null) {
10771            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10772        }
10773    }
10774
10775    /**
10776     * <p>Cause an invalidate of the specified area to happen on the next animation
10777     * time step, typically the next display frame.</p>
10778     *
10779     * <p>This method can be invoked from outside of the UI thread
10780     * only when this View is attached to a window.</p>
10781     *
10782     * @param left The left coordinate of the rectangle to invalidate.
10783     * @param top The top coordinate of the rectangle to invalidate.
10784     * @param right The right coordinate of the rectangle to invalidate.
10785     * @param bottom The bottom coordinate of the rectangle to invalidate.
10786     *
10787     * @see #invalidate(int, int, int, int)
10788     * @see #invalidate(Rect)
10789     */
10790    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10791        // We try only with the AttachInfo because there's no point in invalidating
10792        // if we are not attached to our window
10793        final AttachInfo attachInfo = mAttachInfo;
10794        if (attachInfo != null) {
10795            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10796            info.target = this;
10797            info.left = left;
10798            info.top = top;
10799            info.right = right;
10800            info.bottom = bottom;
10801
10802            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10803        }
10804    }
10805
10806    /**
10807     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10808     * This event is sent at most once every
10809     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10810     */
10811    private void postSendViewScrolledAccessibilityEventCallback() {
10812        if (mSendViewScrolledAccessibilityEvent == null) {
10813            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10814        }
10815        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10816            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10817            postDelayed(mSendViewScrolledAccessibilityEvent,
10818                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10819        }
10820    }
10821
10822    /**
10823     * Called by a parent to request that a child update its values for mScrollX
10824     * and mScrollY if necessary. This will typically be done if the child is
10825     * animating a scroll using a {@link android.widget.Scroller Scroller}
10826     * object.
10827     */
10828    public void computeScroll() {
10829    }
10830
10831    /**
10832     * <p>Indicate whether the horizontal edges are faded when the view is
10833     * scrolled horizontally.</p>
10834     *
10835     * @return true if the horizontal edges should are faded on scroll, false
10836     *         otherwise
10837     *
10838     * @see #setHorizontalFadingEdgeEnabled(boolean)
10839     *
10840     * @attr ref android.R.styleable#View_requiresFadingEdge
10841     */
10842    public boolean isHorizontalFadingEdgeEnabled() {
10843        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10844    }
10845
10846    /**
10847     * <p>Define whether the horizontal edges should be faded when this view
10848     * is scrolled horizontally.</p>
10849     *
10850     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10851     *                                    be faded when the view is scrolled
10852     *                                    horizontally
10853     *
10854     * @see #isHorizontalFadingEdgeEnabled()
10855     *
10856     * @attr ref android.R.styleable#View_requiresFadingEdge
10857     */
10858    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10859        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10860            if (horizontalFadingEdgeEnabled) {
10861                initScrollCache();
10862            }
10863
10864            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10865        }
10866    }
10867
10868    /**
10869     * <p>Indicate whether the vertical edges are faded when the view is
10870     * scrolled horizontally.</p>
10871     *
10872     * @return true if the vertical edges should are faded on scroll, false
10873     *         otherwise
10874     *
10875     * @see #setVerticalFadingEdgeEnabled(boolean)
10876     *
10877     * @attr ref android.R.styleable#View_requiresFadingEdge
10878     */
10879    public boolean isVerticalFadingEdgeEnabled() {
10880        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10881    }
10882
10883    /**
10884     * <p>Define whether the vertical edges should be faded when this view
10885     * is scrolled vertically.</p>
10886     *
10887     * @param verticalFadingEdgeEnabled true if the vertical edges should
10888     *                                  be faded when the view is scrolled
10889     *                                  vertically
10890     *
10891     * @see #isVerticalFadingEdgeEnabled()
10892     *
10893     * @attr ref android.R.styleable#View_requiresFadingEdge
10894     */
10895    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10896        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10897            if (verticalFadingEdgeEnabled) {
10898                initScrollCache();
10899            }
10900
10901            mViewFlags ^= FADING_EDGE_VERTICAL;
10902        }
10903    }
10904
10905    /**
10906     * Returns the strength, or intensity, of the top 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 top fade as a float between 0.0f and 1.0f
10914     */
10915    protected float getTopFadingEdgeStrength() {
10916        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10917    }
10918
10919    /**
10920     * Returns the strength, or intensity, of the bottom 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 bottom fade as a float between 0.0f and 1.0f
10928     */
10929    protected float getBottomFadingEdgeStrength() {
10930        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10931                computeVerticalScrollRange() ? 1.0f : 0.0f;
10932    }
10933
10934    /**
10935     * Returns the strength, or intensity, of the left faded edge. The strength is
10936     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10937     * returns 0.0 or 1.0 but no value in between.
10938     *
10939     * Subclasses should override this method to provide a smoother fade transition
10940     * when scrolling occurs.
10941     *
10942     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10943     */
10944    protected float getLeftFadingEdgeStrength() {
10945        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10946    }
10947
10948    /**
10949     * Returns the strength, or intensity, of the right faded edge. The strength is
10950     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10951     * returns 0.0 or 1.0 but no value in between.
10952     *
10953     * Subclasses should override this method to provide a smoother fade transition
10954     * when scrolling occurs.
10955     *
10956     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10957     */
10958    protected float getRightFadingEdgeStrength() {
10959        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10960                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10961    }
10962
10963    /**
10964     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10965     * scrollbar is not drawn by default.</p>
10966     *
10967     * @return true if the horizontal scrollbar should be painted, false
10968     *         otherwise
10969     *
10970     * @see #setHorizontalScrollBarEnabled(boolean)
10971     */
10972    public boolean isHorizontalScrollBarEnabled() {
10973        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10974    }
10975
10976    /**
10977     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10978     * scrollbar is not drawn by default.</p>
10979     *
10980     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10981     *                                   be painted
10982     *
10983     * @see #isHorizontalScrollBarEnabled()
10984     */
10985    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10986        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10987            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10988            computeOpaqueFlags();
10989            resolvePadding();
10990        }
10991    }
10992
10993    /**
10994     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10995     * scrollbar is not drawn by default.</p>
10996     *
10997     * @return true if the vertical scrollbar should be painted, false
10998     *         otherwise
10999     *
11000     * @see #setVerticalScrollBarEnabled(boolean)
11001     */
11002    public boolean isVerticalScrollBarEnabled() {
11003        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11004    }
11005
11006    /**
11007     * <p>Define whether the vertical scrollbar should be drawn or not. The
11008     * scrollbar is not drawn by default.</p>
11009     *
11010     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11011     *                                 be painted
11012     *
11013     * @see #isVerticalScrollBarEnabled()
11014     */
11015    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11016        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11017            mViewFlags ^= SCROLLBARS_VERTICAL;
11018            computeOpaqueFlags();
11019            resolvePadding();
11020        }
11021    }
11022
11023    /**
11024     * @hide
11025     */
11026    protected void recomputePadding() {
11027        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11028    }
11029
11030    /**
11031     * Define whether scrollbars will fade when the view is not scrolling.
11032     *
11033     * @param fadeScrollbars wheter to enable fading
11034     *
11035     * @attr ref android.R.styleable#View_fadeScrollbars
11036     */
11037    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11038        initScrollCache();
11039        final ScrollabilityCache scrollabilityCache = mScrollCache;
11040        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11041        if (fadeScrollbars) {
11042            scrollabilityCache.state = ScrollabilityCache.OFF;
11043        } else {
11044            scrollabilityCache.state = ScrollabilityCache.ON;
11045        }
11046    }
11047
11048    /**
11049     *
11050     * Returns true if scrollbars will fade when this view is not scrolling
11051     *
11052     * @return true if scrollbar fading is enabled
11053     *
11054     * @attr ref android.R.styleable#View_fadeScrollbars
11055     */
11056    public boolean isScrollbarFadingEnabled() {
11057        return mScrollCache != null && mScrollCache.fadeScrollBars;
11058    }
11059
11060    /**
11061     *
11062     * Returns the delay before scrollbars fade.
11063     *
11064     * @return the delay before scrollbars fade
11065     *
11066     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11067     */
11068    public int getScrollBarDefaultDelayBeforeFade() {
11069        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11070                mScrollCache.scrollBarDefaultDelayBeforeFade;
11071    }
11072
11073    /**
11074     * Define the delay before scrollbars fade.
11075     *
11076     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11077     *
11078     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11079     */
11080    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11081        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11082    }
11083
11084    /**
11085     *
11086     * Returns the scrollbar fade duration.
11087     *
11088     * @return the scrollbar fade duration
11089     *
11090     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11091     */
11092    public int getScrollBarFadeDuration() {
11093        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11094                mScrollCache.scrollBarFadeDuration;
11095    }
11096
11097    /**
11098     * Define the scrollbar fade duration.
11099     *
11100     * @param scrollBarFadeDuration - the scrollbar fade duration
11101     *
11102     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11103     */
11104    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11105        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11106    }
11107
11108    /**
11109     *
11110     * Returns the scrollbar size.
11111     *
11112     * @return the scrollbar size
11113     *
11114     * @attr ref android.R.styleable#View_scrollbarSize
11115     */
11116    public int getScrollBarSize() {
11117        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11118                mScrollCache.scrollBarSize;
11119    }
11120
11121    /**
11122     * Define the scrollbar size.
11123     *
11124     * @param scrollBarSize - the scrollbar size
11125     *
11126     * @attr ref android.R.styleable#View_scrollbarSize
11127     */
11128    public void setScrollBarSize(int scrollBarSize) {
11129        getScrollCache().scrollBarSize = scrollBarSize;
11130    }
11131
11132    /**
11133     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11134     * inset. When inset, they add to the padding of the view. And the scrollbars
11135     * can be drawn inside the padding area or on the edge of the view. For example,
11136     * if a view has a background drawable and you want to draw the scrollbars
11137     * inside the padding specified by the drawable, you can use
11138     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11139     * appear at the edge of the view, ignoring the padding, then you can use
11140     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11141     * @param style the style of the scrollbars. Should be one of
11142     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11143     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11144     * @see #SCROLLBARS_INSIDE_OVERLAY
11145     * @see #SCROLLBARS_INSIDE_INSET
11146     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11147     * @see #SCROLLBARS_OUTSIDE_INSET
11148     *
11149     * @attr ref android.R.styleable#View_scrollbarStyle
11150     */
11151    public void setScrollBarStyle(int style) {
11152        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11153            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11154            computeOpaqueFlags();
11155            resolvePadding();
11156        }
11157    }
11158
11159    /**
11160     * <p>Returns the current scrollbar style.</p>
11161     * @return the current scrollbar style
11162     * @see #SCROLLBARS_INSIDE_OVERLAY
11163     * @see #SCROLLBARS_INSIDE_INSET
11164     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11165     * @see #SCROLLBARS_OUTSIDE_INSET
11166     *
11167     * @attr ref android.R.styleable#View_scrollbarStyle
11168     */
11169    @ViewDebug.ExportedProperty(mapping = {
11170            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11171            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11172            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11173            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11174    })
11175    public int getScrollBarStyle() {
11176        return mViewFlags & SCROLLBARS_STYLE_MASK;
11177    }
11178
11179    /**
11180     * <p>Compute the horizontal range that the horizontal scrollbar
11181     * represents.</p>
11182     *
11183     * <p>The range is expressed in arbitrary units that must be the same as the
11184     * units used by {@link #computeHorizontalScrollExtent()} and
11185     * {@link #computeHorizontalScrollOffset()}.</p>
11186     *
11187     * <p>The default range is the drawing width of this view.</p>
11188     *
11189     * @return the total horizontal range represented by the horizontal
11190     *         scrollbar
11191     *
11192     * @see #computeHorizontalScrollExtent()
11193     * @see #computeHorizontalScrollOffset()
11194     * @see android.widget.ScrollBarDrawable
11195     */
11196    protected int computeHorizontalScrollRange() {
11197        return getWidth();
11198    }
11199
11200    /**
11201     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11202     * within the horizontal range. This value is used to compute the position
11203     * of the thumb within the scrollbar's track.</p>
11204     *
11205     * <p>The range is expressed in arbitrary units that must be the same as the
11206     * units used by {@link #computeHorizontalScrollRange()} and
11207     * {@link #computeHorizontalScrollExtent()}.</p>
11208     *
11209     * <p>The default offset is the scroll offset of this view.</p>
11210     *
11211     * @return the horizontal offset of the scrollbar's thumb
11212     *
11213     * @see #computeHorizontalScrollRange()
11214     * @see #computeHorizontalScrollExtent()
11215     * @see android.widget.ScrollBarDrawable
11216     */
11217    protected int computeHorizontalScrollOffset() {
11218        return mScrollX;
11219    }
11220
11221    /**
11222     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11223     * within the horizontal range. This value is used to compute the length
11224     * of the thumb within the scrollbar's track.</p>
11225     *
11226     * <p>The range is expressed in arbitrary units that must be the same as the
11227     * units used by {@link #computeHorizontalScrollRange()} and
11228     * {@link #computeHorizontalScrollOffset()}.</p>
11229     *
11230     * <p>The default extent is the drawing width of this view.</p>
11231     *
11232     * @return the horizontal extent of the scrollbar's thumb
11233     *
11234     * @see #computeHorizontalScrollRange()
11235     * @see #computeHorizontalScrollOffset()
11236     * @see android.widget.ScrollBarDrawable
11237     */
11238    protected int computeHorizontalScrollExtent() {
11239        return getWidth();
11240    }
11241
11242    /**
11243     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11244     *
11245     * <p>The range is expressed in arbitrary units that must be the same as the
11246     * units used by {@link #computeVerticalScrollExtent()} and
11247     * {@link #computeVerticalScrollOffset()}.</p>
11248     *
11249     * @return the total vertical range represented by the vertical scrollbar
11250     *
11251     * <p>The default range is the drawing height of this view.</p>
11252     *
11253     * @see #computeVerticalScrollExtent()
11254     * @see #computeVerticalScrollOffset()
11255     * @see android.widget.ScrollBarDrawable
11256     */
11257    protected int computeVerticalScrollRange() {
11258        return getHeight();
11259    }
11260
11261    /**
11262     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11263     * within the horizontal range. This value is used to compute the position
11264     * of the thumb within the scrollbar's track.</p>
11265     *
11266     * <p>The range is expressed in arbitrary units that must be the same as the
11267     * units used by {@link #computeVerticalScrollRange()} and
11268     * {@link #computeVerticalScrollExtent()}.</p>
11269     *
11270     * <p>The default offset is the scroll offset of this view.</p>
11271     *
11272     * @return the vertical offset of the scrollbar's thumb
11273     *
11274     * @see #computeVerticalScrollRange()
11275     * @see #computeVerticalScrollExtent()
11276     * @see android.widget.ScrollBarDrawable
11277     */
11278    protected int computeVerticalScrollOffset() {
11279        return mScrollY;
11280    }
11281
11282    /**
11283     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11284     * within the vertical range. This value is used to compute the length
11285     * of the thumb within the scrollbar's track.</p>
11286     *
11287     * <p>The range is expressed in arbitrary units that must be the same as the
11288     * units used by {@link #computeVerticalScrollRange()} and
11289     * {@link #computeVerticalScrollOffset()}.</p>
11290     *
11291     * <p>The default extent is the drawing height of this view.</p>
11292     *
11293     * @return the vertical extent of the scrollbar's thumb
11294     *
11295     * @see #computeVerticalScrollRange()
11296     * @see #computeVerticalScrollOffset()
11297     * @see android.widget.ScrollBarDrawable
11298     */
11299    protected int computeVerticalScrollExtent() {
11300        return getHeight();
11301    }
11302
11303    /**
11304     * Check if this view can be scrolled horizontally in a certain direction.
11305     *
11306     * @param direction Negative to check scrolling left, positive to check scrolling right.
11307     * @return true if this view can be scrolled in the specified direction, false otherwise.
11308     */
11309    public boolean canScrollHorizontally(int direction) {
11310        final int offset = computeHorizontalScrollOffset();
11311        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11312        if (range == 0) return false;
11313        if (direction < 0) {
11314            return offset > 0;
11315        } else {
11316            return offset < range - 1;
11317        }
11318    }
11319
11320    /**
11321     * Check if this view can be scrolled vertically in a certain direction.
11322     *
11323     * @param direction Negative to check scrolling up, positive to check scrolling down.
11324     * @return true if this view can be scrolled in the specified direction, false otherwise.
11325     */
11326    public boolean canScrollVertically(int direction) {
11327        final int offset = computeVerticalScrollOffset();
11328        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11329        if (range == 0) return false;
11330        if (direction < 0) {
11331            return offset > 0;
11332        } else {
11333            return offset < range - 1;
11334        }
11335    }
11336
11337    /**
11338     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11339     * scrollbars are painted only if they have been awakened first.</p>
11340     *
11341     * @param canvas the canvas on which to draw the scrollbars
11342     *
11343     * @see #awakenScrollBars(int)
11344     */
11345    protected final void onDrawScrollBars(Canvas canvas) {
11346        // scrollbars are drawn only when the animation is running
11347        final ScrollabilityCache cache = mScrollCache;
11348        if (cache != null) {
11349
11350            int state = cache.state;
11351
11352            if (state == ScrollabilityCache.OFF) {
11353                return;
11354            }
11355
11356            boolean invalidate = false;
11357
11358            if (state == ScrollabilityCache.FADING) {
11359                // We're fading -- get our fade interpolation
11360                if (cache.interpolatorValues == null) {
11361                    cache.interpolatorValues = new float[1];
11362                }
11363
11364                float[] values = cache.interpolatorValues;
11365
11366                // Stops the animation if we're done
11367                if (cache.scrollBarInterpolator.timeToValues(values) ==
11368                        Interpolator.Result.FREEZE_END) {
11369                    cache.state = ScrollabilityCache.OFF;
11370                } else {
11371                    cache.scrollBar.setAlpha(Math.round(values[0]));
11372                }
11373
11374                // This will make the scroll bars inval themselves after
11375                // drawing. We only want this when we're fading so that
11376                // we prevent excessive redraws
11377                invalidate = true;
11378            } else {
11379                // We're just on -- but we may have been fading before so
11380                // reset alpha
11381                cache.scrollBar.setAlpha(255);
11382            }
11383
11384
11385            final int viewFlags = mViewFlags;
11386
11387            final boolean drawHorizontalScrollBar =
11388                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11389            final boolean drawVerticalScrollBar =
11390                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11391                && !isVerticalScrollBarHidden();
11392
11393            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11394                final int width = mRight - mLeft;
11395                final int height = mBottom - mTop;
11396
11397                final ScrollBarDrawable scrollBar = cache.scrollBar;
11398
11399                final int scrollX = mScrollX;
11400                final int scrollY = mScrollY;
11401                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11402
11403                int left, top, right, bottom;
11404
11405                if (drawHorizontalScrollBar) {
11406                    int size = scrollBar.getSize(false);
11407                    if (size <= 0) {
11408                        size = cache.scrollBarSize;
11409                    }
11410
11411                    scrollBar.setParameters(computeHorizontalScrollRange(),
11412                                            computeHorizontalScrollOffset(),
11413                                            computeHorizontalScrollExtent(), false);
11414                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11415                            getVerticalScrollbarWidth() : 0;
11416                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11417                    left = scrollX + (mPaddingLeft & inside);
11418                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11419                    bottom = top + size;
11420                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11421                    if (invalidate) {
11422                        invalidate(left, top, right, bottom);
11423                    }
11424                }
11425
11426                if (drawVerticalScrollBar) {
11427                    int size = scrollBar.getSize(true);
11428                    if (size <= 0) {
11429                        size = cache.scrollBarSize;
11430                    }
11431
11432                    scrollBar.setParameters(computeVerticalScrollRange(),
11433                                            computeVerticalScrollOffset(),
11434                                            computeVerticalScrollExtent(), true);
11435                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11436                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11437                        verticalScrollbarPosition = isLayoutRtl() ?
11438                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11439                    }
11440                    switch (verticalScrollbarPosition) {
11441                        default:
11442                        case SCROLLBAR_POSITION_RIGHT:
11443                            left = scrollX + width - size - (mUserPaddingRight & inside);
11444                            break;
11445                        case SCROLLBAR_POSITION_LEFT:
11446                            left = scrollX + (mUserPaddingLeft & inside);
11447                            break;
11448                    }
11449                    top = scrollY + (mPaddingTop & inside);
11450                    right = left + size;
11451                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11452                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11453                    if (invalidate) {
11454                        invalidate(left, top, right, bottom);
11455                    }
11456                }
11457            }
11458        }
11459    }
11460
11461    /**
11462     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11463     * FastScroller is visible.
11464     * @return whether to temporarily hide the vertical scrollbar
11465     * @hide
11466     */
11467    protected boolean isVerticalScrollBarHidden() {
11468        return false;
11469    }
11470
11471    /**
11472     * <p>Draw the horizontal scrollbar if
11473     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11474     *
11475     * @param canvas the canvas on which to draw the scrollbar
11476     * @param scrollBar the scrollbar's drawable
11477     *
11478     * @see #isHorizontalScrollBarEnabled()
11479     * @see #computeHorizontalScrollRange()
11480     * @see #computeHorizontalScrollExtent()
11481     * @see #computeHorizontalScrollOffset()
11482     * @see android.widget.ScrollBarDrawable
11483     * @hide
11484     */
11485    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11486            int l, int t, int r, int b) {
11487        scrollBar.setBounds(l, t, r, b);
11488        scrollBar.draw(canvas);
11489    }
11490
11491    /**
11492     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11493     * returns true.</p>
11494     *
11495     * @param canvas the canvas on which to draw the scrollbar
11496     * @param scrollBar the scrollbar's drawable
11497     *
11498     * @see #isVerticalScrollBarEnabled()
11499     * @see #computeVerticalScrollRange()
11500     * @see #computeVerticalScrollExtent()
11501     * @see #computeVerticalScrollOffset()
11502     * @see android.widget.ScrollBarDrawable
11503     * @hide
11504     */
11505    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11506            int l, int t, int r, int b) {
11507        scrollBar.setBounds(l, t, r, b);
11508        scrollBar.draw(canvas);
11509    }
11510
11511    /**
11512     * Implement this to do your drawing.
11513     *
11514     * @param canvas the canvas on which the background will be drawn
11515     */
11516    protected void onDraw(Canvas canvas) {
11517    }
11518
11519    /*
11520     * Caller is responsible for calling requestLayout if necessary.
11521     * (This allows addViewInLayout to not request a new layout.)
11522     */
11523    void assignParent(ViewParent parent) {
11524        if (mParent == null) {
11525            mParent = parent;
11526        } else if (parent == null) {
11527            mParent = null;
11528        } else {
11529            throw new RuntimeException("view " + this + " being added, but"
11530                    + " it already has a parent");
11531        }
11532    }
11533
11534    /**
11535     * This is called when the view is attached to a window.  At this point it
11536     * has a Surface and will start drawing.  Note that this function is
11537     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11538     * however it may be called any time before the first onDraw -- including
11539     * before or after {@link #onMeasure(int, int)}.
11540     *
11541     * @see #onDetachedFromWindow()
11542     */
11543    protected void onAttachedToWindow() {
11544        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11545            mParent.requestTransparentRegion(this);
11546        }
11547
11548        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11549            initialAwakenScrollBars();
11550            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11551        }
11552
11553        jumpDrawablesToCurrentState();
11554
11555        clearAccessibilityFocus();
11556        if (isFocused()) {
11557            InputMethodManager imm = InputMethodManager.peekInstance();
11558            imm.focusIn(this);
11559        }
11560
11561        if (mAttachInfo != null && mDisplayList != null) {
11562            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11563        }
11564    }
11565
11566    /**
11567     * Resolve all RTL related properties.
11568     *
11569     * @hide
11570     */
11571    public void resolveRtlPropertiesIfNeeded() {
11572        if (!needRtlPropertiesResolution()) return;
11573
11574        // Order is important here: LayoutDirection MUST be resolved first
11575        if (!isLayoutDirectionResolved()) {
11576            resolveLayoutDirection();
11577            resolveLayoutParams();
11578        }
11579        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11580        if (!isTextDirectionResolved()) {
11581            resolveTextDirection();
11582        }
11583        if (!isTextAlignmentResolved()) {
11584            resolveTextAlignment();
11585        }
11586        if (!isPaddingResolved()) {
11587            resolvePadding();
11588        }
11589        if (!isDrawablesResolved()) {
11590            resolveDrawables();
11591        }
11592        onRtlPropertiesChanged(getLayoutDirection());
11593    }
11594
11595    /**
11596     * Reset resolution of all RTL related properties.
11597     *
11598     * @hide
11599     */
11600    public void resetRtlProperties() {
11601        resetResolvedLayoutDirection();
11602        resetResolvedTextDirection();
11603        resetResolvedTextAlignment();
11604        resetResolvedPadding();
11605        resetResolvedDrawables();
11606    }
11607
11608    /**
11609     * @see #onScreenStateChanged(int)
11610     */
11611    void dispatchScreenStateChanged(int screenState) {
11612        onScreenStateChanged(screenState);
11613    }
11614
11615    /**
11616     * This method is called whenever the state of the screen this view is
11617     * attached to changes. A state change will usually occurs when the screen
11618     * turns on or off (whether it happens automatically or the user does it
11619     * manually.)
11620     *
11621     * @param screenState The new state of the screen. Can be either
11622     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11623     */
11624    public void onScreenStateChanged(int screenState) {
11625    }
11626
11627    /**
11628     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11629     */
11630    private boolean hasRtlSupport() {
11631        return mContext.getApplicationInfo().hasRtlSupport();
11632    }
11633
11634    /**
11635     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11636     * RTL not supported)
11637     */
11638    private boolean isRtlCompatibilityMode() {
11639        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11640        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11641    }
11642
11643    /**
11644     * @return true if RTL properties need resolution.
11645     */
11646    private boolean needRtlPropertiesResolution() {
11647        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11648    }
11649
11650    /**
11651     * Called when any RTL property (layout direction or text direction or text alignment) has
11652     * been changed.
11653     *
11654     * Subclasses need to override this method to take care of cached information that depends on the
11655     * resolved layout direction, or to inform child views that inherit their layout direction.
11656     *
11657     * The default implementation does nothing.
11658     *
11659     * @param layoutDirection the direction of the layout
11660     *
11661     * @see #LAYOUT_DIRECTION_LTR
11662     * @see #LAYOUT_DIRECTION_RTL
11663     */
11664    public void onRtlPropertiesChanged(int layoutDirection) {
11665    }
11666
11667    /**
11668     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11669     * that the parent directionality can and will be resolved before its children.
11670     *
11671     * @return true if resolution has been done, false otherwise.
11672     *
11673     * @hide
11674     */
11675    public boolean resolveLayoutDirection() {
11676        // Clear any previous layout direction resolution
11677        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11678
11679        if (hasRtlSupport()) {
11680            // Set resolved depending on layout direction
11681            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11682                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11683                case LAYOUT_DIRECTION_INHERIT:
11684                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11685                    // later to get the correct resolved value
11686                    if (!canResolveLayoutDirection()) return false;
11687
11688                    View parent = ((View) mParent);
11689                    // Parent has not yet resolved, LTR is still the default
11690                    if (!parent.isLayoutDirectionResolved()) return false;
11691
11692                    if (parent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11693                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11694                    }
11695                    break;
11696                case LAYOUT_DIRECTION_RTL:
11697                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11698                    break;
11699                case LAYOUT_DIRECTION_LOCALE:
11700                    if((LAYOUT_DIRECTION_RTL ==
11701                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11702                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11703                    }
11704                    break;
11705                default:
11706                    // Nothing to do, LTR by default
11707            }
11708        }
11709
11710        // Set to resolved
11711        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11712        return true;
11713    }
11714
11715    /**
11716     * Check if layout direction resolution can be done.
11717     *
11718     * @return true if layout direction resolution can be done otherwise return false.
11719     *
11720     * @hide
11721     */
11722    public boolean canResolveLayoutDirection() {
11723        switch (getRawLayoutDirection()) {
11724            case LAYOUT_DIRECTION_INHERIT:
11725                return (mParent != null) && (mParent instanceof ViewGroup) &&
11726                       ((ViewGroup) mParent).canResolveLayoutDirection();
11727            default:
11728                return true;
11729        }
11730    }
11731
11732    /**
11733     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11734     * {@link #onMeasure(int, int)}.
11735     *
11736     * @hide
11737     */
11738    public void resetResolvedLayoutDirection() {
11739        // Reset the current resolved bits
11740        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11741    }
11742
11743    /**
11744     * @return true if the layout direction is inherited.
11745     *
11746     * @hide
11747     */
11748    public boolean isLayoutDirectionInherited() {
11749        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11750    }
11751
11752    /**
11753     * @return true if layout direction has been resolved.
11754     */
11755    private boolean isLayoutDirectionResolved() {
11756        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11757    }
11758
11759    /**
11760     * Return if padding has been resolved
11761     *
11762     * @hide
11763     */
11764    boolean isPaddingResolved() {
11765        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11766    }
11767
11768    /**
11769     * Resolve padding depending on layout direction.
11770     *
11771     * @hide
11772     */
11773    public void resolvePadding() {
11774        if (!isRtlCompatibilityMode()) {
11775            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11776            // If start / end padding are defined, they will be resolved (hence overriding) to
11777            // left / right or right / left depending on the resolved layout direction.
11778            // If start / end padding are not defined, use the left / right ones.
11779            int resolvedLayoutDirection = getLayoutDirection();
11780            // Set user padding to initial values ...
11781            mUserPaddingLeft = mUserPaddingLeftInitial;
11782            mUserPaddingRight = mUserPaddingRightInitial;
11783            // ... then resolve it.
11784            switch (resolvedLayoutDirection) {
11785                case LAYOUT_DIRECTION_RTL:
11786                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11787                        mUserPaddingRight = mUserPaddingStart;
11788                    }
11789                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11790                        mUserPaddingLeft = mUserPaddingEnd;
11791                    }
11792                    break;
11793                case LAYOUT_DIRECTION_LTR:
11794                default:
11795                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11796                        mUserPaddingLeft = mUserPaddingStart;
11797                    }
11798                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11799                        mUserPaddingRight = mUserPaddingEnd;
11800                    }
11801            }
11802
11803            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11804
11805            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11806                    mUserPaddingBottom);
11807            onRtlPropertiesChanged(resolvedLayoutDirection);
11808        }
11809
11810        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11811    }
11812
11813    /**
11814     * Reset the resolved layout direction.
11815     *
11816     * @hide
11817     */
11818    public void resetResolvedPadding() {
11819        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11820    }
11821
11822    /**
11823     * This is called when the view is detached from a window.  At this point it
11824     * no longer has a surface for drawing.
11825     *
11826     * @see #onAttachedToWindow()
11827     */
11828    protected void onDetachedFromWindow() {
11829        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
11830
11831        removeUnsetPressCallback();
11832        removeLongPressCallback();
11833        removePerformClickCallback();
11834        removeSendViewScrolledAccessibilityEventCallback();
11835
11836        destroyDrawingCache();
11837
11838        destroyLayer(false);
11839
11840        if (mAttachInfo != null) {
11841            if (mDisplayList != null) {
11842                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11843            }
11844            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11845        } else {
11846            // Should never happen
11847            clearDisplayList();
11848        }
11849
11850        mCurrentAnimation = null;
11851
11852        resetRtlProperties();
11853        onRtlPropertiesChanged(LAYOUT_DIRECTION_DEFAULT);
11854        resetAccessibilityStateChanged();
11855    }
11856
11857    /**
11858     * @return The number of times this view has been attached to a window
11859     */
11860    protected int getWindowAttachCount() {
11861        return mWindowAttachCount;
11862    }
11863
11864    /**
11865     * Retrieve a unique token identifying the window this view is attached to.
11866     * @return Return the window's token for use in
11867     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11868     */
11869    public IBinder getWindowToken() {
11870        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11871    }
11872
11873    /**
11874     * Retrieve a unique token identifying the top-level "real" window of
11875     * the window that this view is attached to.  That is, this is like
11876     * {@link #getWindowToken}, except if the window this view in is a panel
11877     * window (attached to another containing window), then the token of
11878     * the containing window is returned instead.
11879     *
11880     * @return Returns the associated window token, either
11881     * {@link #getWindowToken()} or the containing window's token.
11882     */
11883    public IBinder getApplicationWindowToken() {
11884        AttachInfo ai = mAttachInfo;
11885        if (ai != null) {
11886            IBinder appWindowToken = ai.mPanelParentWindowToken;
11887            if (appWindowToken == null) {
11888                appWindowToken = ai.mWindowToken;
11889            }
11890            return appWindowToken;
11891        }
11892        return null;
11893    }
11894
11895    /**
11896     * Gets the logical display to which the view's window has been attached.
11897     *
11898     * @return The logical display, or null if the view is not currently attached to a window.
11899     */
11900    public Display getDisplay() {
11901        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
11902    }
11903
11904    /**
11905     * Retrieve private session object this view hierarchy is using to
11906     * communicate with the window manager.
11907     * @return the session object to communicate with the window manager
11908     */
11909    /*package*/ IWindowSession getWindowSession() {
11910        return mAttachInfo != null ? mAttachInfo.mSession : null;
11911    }
11912
11913    /**
11914     * @param info the {@link android.view.View.AttachInfo} to associated with
11915     *        this view
11916     */
11917    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11918        //System.out.println("Attached! " + this);
11919        mAttachInfo = info;
11920        mWindowAttachCount++;
11921        // We will need to evaluate the drawable state at least once.
11922        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
11923        if (mFloatingTreeObserver != null) {
11924            info.mTreeObserver.merge(mFloatingTreeObserver);
11925            mFloatingTreeObserver = null;
11926        }
11927        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
11928            mAttachInfo.mScrollContainers.add(this);
11929            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
11930        }
11931        performCollectViewAttributes(mAttachInfo, visibility);
11932        onAttachedToWindow();
11933
11934        ListenerInfo li = mListenerInfo;
11935        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11936                li != null ? li.mOnAttachStateChangeListeners : null;
11937        if (listeners != null && listeners.size() > 0) {
11938            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11939            // perform the dispatching. The iterator is a safe guard against listeners that
11940            // could mutate the list by calling the various add/remove methods. This prevents
11941            // the array from being modified while we iterate it.
11942            for (OnAttachStateChangeListener listener : listeners) {
11943                listener.onViewAttachedToWindow(this);
11944            }
11945        }
11946
11947        int vis = info.mWindowVisibility;
11948        if (vis != GONE) {
11949            onWindowVisibilityChanged(vis);
11950        }
11951        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
11952            // If nobody has evaluated the drawable state yet, then do it now.
11953            refreshDrawableState();
11954        }
11955        needGlobalAttributesUpdate(false);
11956    }
11957
11958    void dispatchDetachedFromWindow() {
11959        AttachInfo info = mAttachInfo;
11960        if (info != null) {
11961            int vis = info.mWindowVisibility;
11962            if (vis != GONE) {
11963                onWindowVisibilityChanged(GONE);
11964            }
11965        }
11966
11967        onDetachedFromWindow();
11968
11969        ListenerInfo li = mListenerInfo;
11970        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11971                li != null ? li.mOnAttachStateChangeListeners : null;
11972        if (listeners != null && listeners.size() > 0) {
11973            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11974            // perform the dispatching. The iterator is a safe guard against listeners that
11975            // could mutate the list by calling the various add/remove methods. This prevents
11976            // the array from being modified while we iterate it.
11977            for (OnAttachStateChangeListener listener : listeners) {
11978                listener.onViewDetachedFromWindow(this);
11979            }
11980        }
11981
11982        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
11983            mAttachInfo.mScrollContainers.remove(this);
11984            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
11985        }
11986
11987        mAttachInfo = null;
11988    }
11989
11990    /**
11991     * Store this view hierarchy's frozen state into the given container.
11992     *
11993     * @param container The SparseArray in which to save the view's state.
11994     *
11995     * @see #restoreHierarchyState(android.util.SparseArray)
11996     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11997     * @see #onSaveInstanceState()
11998     */
11999    public void saveHierarchyState(SparseArray<Parcelable> container) {
12000        dispatchSaveInstanceState(container);
12001    }
12002
12003    /**
12004     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12005     * this view and its children. May be overridden to modify how freezing happens to a
12006     * view's children; for example, some views may want to not store state for their children.
12007     *
12008     * @param container The SparseArray in which to save the view's state.
12009     *
12010     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12011     * @see #saveHierarchyState(android.util.SparseArray)
12012     * @see #onSaveInstanceState()
12013     */
12014    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12015        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12016            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12017            Parcelable state = onSaveInstanceState();
12018            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12019                throw new IllegalStateException(
12020                        "Derived class did not call super.onSaveInstanceState()");
12021            }
12022            if (state != null) {
12023                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12024                // + ": " + state);
12025                container.put(mID, state);
12026            }
12027        }
12028    }
12029
12030    /**
12031     * Hook allowing a view to generate a representation of its internal state
12032     * that can later be used to create a new instance with that same state.
12033     * This state should only contain information that is not persistent or can
12034     * not be reconstructed later. For example, you will never store your
12035     * current position on screen because that will be computed again when a
12036     * new instance of the view is placed in its view hierarchy.
12037     * <p>
12038     * Some examples of things you may store here: the current cursor position
12039     * in a text view (but usually not the text itself since that is stored in a
12040     * content provider or other persistent storage), the currently selected
12041     * item in a list view.
12042     *
12043     * @return Returns a Parcelable object containing the view's current dynamic
12044     *         state, or null if there is nothing interesting to save. The
12045     *         default implementation returns null.
12046     * @see #onRestoreInstanceState(android.os.Parcelable)
12047     * @see #saveHierarchyState(android.util.SparseArray)
12048     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12049     * @see #setSaveEnabled(boolean)
12050     */
12051    protected Parcelable onSaveInstanceState() {
12052        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12053        return BaseSavedState.EMPTY_STATE;
12054    }
12055
12056    /**
12057     * Restore this view hierarchy's frozen state from the given container.
12058     *
12059     * @param container The SparseArray which holds previously frozen states.
12060     *
12061     * @see #saveHierarchyState(android.util.SparseArray)
12062     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12063     * @see #onRestoreInstanceState(android.os.Parcelable)
12064     */
12065    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12066        dispatchRestoreInstanceState(container);
12067    }
12068
12069    /**
12070     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12071     * state for this view and its children. May be overridden to modify how restoring
12072     * happens to a view's children; for example, some views may want to not store state
12073     * for their children.
12074     *
12075     * @param container The SparseArray which holds previously saved state.
12076     *
12077     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12078     * @see #restoreHierarchyState(android.util.SparseArray)
12079     * @see #onRestoreInstanceState(android.os.Parcelable)
12080     */
12081    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12082        if (mID != NO_ID) {
12083            Parcelable state = container.get(mID);
12084            if (state != null) {
12085                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12086                // + ": " + state);
12087                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12088                onRestoreInstanceState(state);
12089                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12090                    throw new IllegalStateException(
12091                            "Derived class did not call super.onRestoreInstanceState()");
12092                }
12093            }
12094        }
12095    }
12096
12097    /**
12098     * Hook allowing a view to re-apply a representation of its internal state that had previously
12099     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12100     * null state.
12101     *
12102     * @param state The frozen state that had previously been returned by
12103     *        {@link #onSaveInstanceState}.
12104     *
12105     * @see #onSaveInstanceState()
12106     * @see #restoreHierarchyState(android.util.SparseArray)
12107     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12108     */
12109    protected void onRestoreInstanceState(Parcelable state) {
12110        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12111        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12112            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12113                    + "received " + state.getClass().toString() + " instead. This usually happens "
12114                    + "when two views of different type have the same id in the same hierarchy. "
12115                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12116                    + "other views do not use the same id.");
12117        }
12118    }
12119
12120    /**
12121     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12122     *
12123     * @return the drawing start time in milliseconds
12124     */
12125    public long getDrawingTime() {
12126        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12127    }
12128
12129    /**
12130     * <p>Enables or disables the duplication of the parent's state into this view. When
12131     * duplication is enabled, this view gets its drawable state from its parent rather
12132     * than from its own internal properties.</p>
12133     *
12134     * <p>Note: in the current implementation, setting this property to true after the
12135     * view was added to a ViewGroup might have no effect at all. This property should
12136     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12137     *
12138     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12139     * property is enabled, an exception will be thrown.</p>
12140     *
12141     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12142     * parent, these states should not be affected by this method.</p>
12143     *
12144     * @param enabled True to enable duplication of the parent's drawable state, false
12145     *                to disable it.
12146     *
12147     * @see #getDrawableState()
12148     * @see #isDuplicateParentStateEnabled()
12149     */
12150    public void setDuplicateParentStateEnabled(boolean enabled) {
12151        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12152    }
12153
12154    /**
12155     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12156     *
12157     * @return True if this view's drawable state is duplicated from the parent,
12158     *         false otherwise
12159     *
12160     * @see #getDrawableState()
12161     * @see #setDuplicateParentStateEnabled(boolean)
12162     */
12163    public boolean isDuplicateParentStateEnabled() {
12164        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12165    }
12166
12167    /**
12168     * <p>Specifies the type of layer backing this view. The layer can be
12169     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12170     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12171     *
12172     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12173     * instance that controls how the layer is composed on screen. The following
12174     * properties of the paint are taken into account when composing the layer:</p>
12175     * <ul>
12176     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12177     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12178     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12179     * </ul>
12180     *
12181     * <p>If this view has an alpha value set to < 1.0 by calling
12182     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12183     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12184     * equivalent to setting a hardware layer on this view and providing a paint with
12185     * the desired alpha value.</p>
12186     *
12187     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
12188     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
12189     * for more information on when and how to use layers.</p>
12190     *
12191     * @param layerType The type of layer to use with this view, must be one of
12192     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12193     *        {@link #LAYER_TYPE_HARDWARE}
12194     * @param paint The paint used to compose the layer. This argument is optional
12195     *        and can be null. It is ignored when the layer type is
12196     *        {@link #LAYER_TYPE_NONE}
12197     *
12198     * @see #getLayerType()
12199     * @see #LAYER_TYPE_NONE
12200     * @see #LAYER_TYPE_SOFTWARE
12201     * @see #LAYER_TYPE_HARDWARE
12202     * @see #setAlpha(float)
12203     *
12204     * @attr ref android.R.styleable#View_layerType
12205     */
12206    public void setLayerType(int layerType, Paint paint) {
12207        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12208            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12209                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12210        }
12211
12212        if (layerType == mLayerType) {
12213            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12214                mLayerPaint = paint == null ? new Paint() : paint;
12215                invalidateParentCaches();
12216                invalidate(true);
12217            }
12218            return;
12219        }
12220
12221        // Destroy any previous software drawing cache if needed
12222        switch (mLayerType) {
12223            case LAYER_TYPE_HARDWARE:
12224                destroyLayer(false);
12225                // fall through - non-accelerated views may use software layer mechanism instead
12226            case LAYER_TYPE_SOFTWARE:
12227                destroyDrawingCache();
12228                break;
12229            default:
12230                break;
12231        }
12232
12233        mLayerType = layerType;
12234        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12235        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12236        mLocalDirtyRect = layerDisabled ? null : new Rect();
12237
12238        invalidateParentCaches();
12239        invalidate(true);
12240    }
12241
12242    /**
12243     * Updates the {@link Paint} object used with the current layer (used only if the current
12244     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12245     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12246     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12247     * ensure that the view gets redrawn immediately.
12248     *
12249     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12250     * instance that controls how the layer is composed on screen. The following
12251     * properties of the paint are taken into account when composing the layer:</p>
12252     * <ul>
12253     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12254     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12255     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12256     * </ul>
12257     *
12258     * <p>If this view has an alpha value set to < 1.0 by calling
12259     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12260     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12261     * equivalent to setting a hardware layer on this view and providing a paint with
12262     * the desired alpha value.</p>
12263     *
12264     * @param paint The paint used to compose the layer. This argument is optional
12265     *        and can be null. It is ignored when the layer type is
12266     *        {@link #LAYER_TYPE_NONE}
12267     *
12268     * @see #setLayerType(int, android.graphics.Paint)
12269     */
12270    public void setLayerPaint(Paint paint) {
12271        int layerType = getLayerType();
12272        if (layerType != LAYER_TYPE_NONE) {
12273            mLayerPaint = paint == null ? new Paint() : paint;
12274            if (layerType == LAYER_TYPE_HARDWARE) {
12275                HardwareLayer layer = getHardwareLayer();
12276                if (layer != null) {
12277                    layer.setLayerPaint(paint);
12278                }
12279                invalidateViewProperty(false, false);
12280            } else {
12281                invalidate();
12282            }
12283        }
12284    }
12285
12286    /**
12287     * Indicates whether this view has a static layer. A view with layer type
12288     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12289     * dynamic.
12290     */
12291    boolean hasStaticLayer() {
12292        return true;
12293    }
12294
12295    /**
12296     * Indicates what type of layer is currently associated with this view. By default
12297     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12298     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12299     * for more information on the different types of layers.
12300     *
12301     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12302     *         {@link #LAYER_TYPE_HARDWARE}
12303     *
12304     * @see #setLayerType(int, android.graphics.Paint)
12305     * @see #buildLayer()
12306     * @see #LAYER_TYPE_NONE
12307     * @see #LAYER_TYPE_SOFTWARE
12308     * @see #LAYER_TYPE_HARDWARE
12309     */
12310    public int getLayerType() {
12311        return mLayerType;
12312    }
12313
12314    /**
12315     * Forces this view's layer to be created and this view to be rendered
12316     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12317     * invoking this method will have no effect.
12318     *
12319     * This method can for instance be used to render a view into its layer before
12320     * starting an animation. If this view is complex, rendering into the layer
12321     * before starting the animation will avoid skipping frames.
12322     *
12323     * @throws IllegalStateException If this view is not attached to a window
12324     *
12325     * @see #setLayerType(int, android.graphics.Paint)
12326     */
12327    public void buildLayer() {
12328        if (mLayerType == LAYER_TYPE_NONE) return;
12329
12330        if (mAttachInfo == null) {
12331            throw new IllegalStateException("This view must be attached to a window first");
12332        }
12333
12334        switch (mLayerType) {
12335            case LAYER_TYPE_HARDWARE:
12336                if (mAttachInfo.mHardwareRenderer != null &&
12337                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12338                        mAttachInfo.mHardwareRenderer.validate()) {
12339                    getHardwareLayer();
12340                }
12341                break;
12342            case LAYER_TYPE_SOFTWARE:
12343                buildDrawingCache(true);
12344                break;
12345        }
12346    }
12347
12348    /**
12349     * <p>Returns a hardware layer that can be used to draw this view again
12350     * without executing its draw method.</p>
12351     *
12352     * @return A HardwareLayer ready to render, or null if an error occurred.
12353     */
12354    HardwareLayer getHardwareLayer() {
12355        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12356                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12357            return null;
12358        }
12359
12360        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12361
12362        final int width = mRight - mLeft;
12363        final int height = mBottom - mTop;
12364
12365        if (width == 0 || height == 0) {
12366            return null;
12367        }
12368
12369        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12370            if (mHardwareLayer == null) {
12371                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12372                        width, height, isOpaque());
12373                mLocalDirtyRect.set(0, 0, width, height);
12374            } else {
12375                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12376                    if (mHardwareLayer.resize(width, height)) {
12377                        mLocalDirtyRect.set(0, 0, width, height);
12378                    }
12379                }
12380
12381                // This should not be necessary but applications that change
12382                // the parameters of their background drawable without calling
12383                // this.setBackground(Drawable) can leave the view in a bad state
12384                // (for instance isOpaque() returns true, but the background is
12385                // not opaque.)
12386                computeOpaqueFlags();
12387
12388                final boolean opaque = isOpaque();
12389                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12390                    mHardwareLayer.setOpaque(opaque);
12391                    mLocalDirtyRect.set(0, 0, width, height);
12392                }
12393            }
12394
12395            // The layer is not valid if the underlying GPU resources cannot be allocated
12396            if (!mHardwareLayer.isValid()) {
12397                return null;
12398            }
12399
12400            mHardwareLayer.setLayerPaint(mLayerPaint);
12401            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12402            ViewRootImpl viewRoot = getViewRootImpl();
12403            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12404
12405            mLocalDirtyRect.setEmpty();
12406        }
12407
12408        return mHardwareLayer;
12409    }
12410
12411    /**
12412     * Destroys this View's hardware layer if possible.
12413     *
12414     * @return True if the layer was destroyed, false otherwise.
12415     *
12416     * @see #setLayerType(int, android.graphics.Paint)
12417     * @see #LAYER_TYPE_HARDWARE
12418     */
12419    boolean destroyLayer(boolean valid) {
12420        if (mHardwareLayer != null) {
12421            AttachInfo info = mAttachInfo;
12422            if (info != null && info.mHardwareRenderer != null &&
12423                    info.mHardwareRenderer.isEnabled() &&
12424                    (valid || info.mHardwareRenderer.validate())) {
12425                mHardwareLayer.destroy();
12426                mHardwareLayer = null;
12427
12428                if (mDisplayList != null) {
12429                    mDisplayList.reset();
12430                }
12431                invalidate(true);
12432                invalidateParentCaches();
12433            }
12434            return true;
12435        }
12436        return false;
12437    }
12438
12439    /**
12440     * Destroys all hardware rendering resources. This method is invoked
12441     * when the system needs to reclaim resources. Upon execution of this
12442     * method, you should free any OpenGL resources created by the view.
12443     *
12444     * Note: you <strong>must</strong> call
12445     * <code>super.destroyHardwareResources()</code> when overriding
12446     * this method.
12447     *
12448     * @hide
12449     */
12450    protected void destroyHardwareResources() {
12451        destroyLayer(true);
12452    }
12453
12454    /**
12455     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12456     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12457     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12458     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12459     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12460     * null.</p>
12461     *
12462     * <p>Enabling the drawing cache is similar to
12463     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12464     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12465     * drawing cache has no effect on rendering because the system uses a different mechanism
12466     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12467     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12468     * for information on how to enable software and hardware layers.</p>
12469     *
12470     * <p>This API can be used to manually generate
12471     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12472     * {@link #getDrawingCache()}.</p>
12473     *
12474     * @param enabled true to enable the drawing cache, false otherwise
12475     *
12476     * @see #isDrawingCacheEnabled()
12477     * @see #getDrawingCache()
12478     * @see #buildDrawingCache()
12479     * @see #setLayerType(int, android.graphics.Paint)
12480     */
12481    public void setDrawingCacheEnabled(boolean enabled) {
12482        mCachingFailed = false;
12483        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12484    }
12485
12486    /**
12487     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12488     *
12489     * @return true if the drawing cache is enabled
12490     *
12491     * @see #setDrawingCacheEnabled(boolean)
12492     * @see #getDrawingCache()
12493     */
12494    @ViewDebug.ExportedProperty(category = "drawing")
12495    public boolean isDrawingCacheEnabled() {
12496        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12497    }
12498
12499    /**
12500     * Debugging utility which recursively outputs the dirty state of a view and its
12501     * descendants.
12502     *
12503     * @hide
12504     */
12505    @SuppressWarnings({"UnusedDeclaration"})
12506    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12507        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12508                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12509                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12510                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12511        if (clear) {
12512            mPrivateFlags &= clearMask;
12513        }
12514        if (this instanceof ViewGroup) {
12515            ViewGroup parent = (ViewGroup) this;
12516            final int count = parent.getChildCount();
12517            for (int i = 0; i < count; i++) {
12518                final View child = parent.getChildAt(i);
12519                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12520            }
12521        }
12522    }
12523
12524    /**
12525     * This method is used by ViewGroup to cause its children to restore or recreate their
12526     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12527     * to recreate its own display list, which would happen if it went through the normal
12528     * draw/dispatchDraw mechanisms.
12529     *
12530     * @hide
12531     */
12532    protected void dispatchGetDisplayList() {}
12533
12534    /**
12535     * A view that is not attached or hardware accelerated cannot create a display list.
12536     * This method checks these conditions and returns the appropriate result.
12537     *
12538     * @return true if view has the ability to create a display list, false otherwise.
12539     *
12540     * @hide
12541     */
12542    public boolean canHaveDisplayList() {
12543        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12544    }
12545
12546    /**
12547     * @return The HardwareRenderer associated with that view or null if hardware rendering
12548     * is not supported or this this has not been attached to a window.
12549     *
12550     * @hide
12551     */
12552    public HardwareRenderer getHardwareRenderer() {
12553        if (mAttachInfo != null) {
12554            return mAttachInfo.mHardwareRenderer;
12555        }
12556        return null;
12557    }
12558
12559    /**
12560     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12561     * Otherwise, the same display list will be returned (after having been rendered into
12562     * along the way, depending on the invalidation state of the view).
12563     *
12564     * @param displayList The previous version of this displayList, could be null.
12565     * @param isLayer Whether the requester of the display list is a layer. If so,
12566     * the view will avoid creating a layer inside the resulting display list.
12567     * @return A new or reused DisplayList object.
12568     */
12569    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12570        if (!canHaveDisplayList()) {
12571            return null;
12572        }
12573
12574        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12575                displayList == null || !displayList.isValid() ||
12576                (!isLayer && mRecreateDisplayList))) {
12577            // Don't need to recreate the display list, just need to tell our
12578            // children to restore/recreate theirs
12579            if (displayList != null && displayList.isValid() &&
12580                    !isLayer && !mRecreateDisplayList) {
12581                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12582                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12583                dispatchGetDisplayList();
12584
12585                return displayList;
12586            }
12587
12588            if (!isLayer) {
12589                // If we got here, we're recreating it. Mark it as such to ensure that
12590                // we copy in child display lists into ours in drawChild()
12591                mRecreateDisplayList = true;
12592            }
12593            if (displayList == null) {
12594                final String name = getClass().getSimpleName();
12595                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12596                // If we're creating a new display list, make sure our parent gets invalidated
12597                // since they will need to recreate their display list to account for this
12598                // new child display list.
12599                invalidateParentCaches();
12600            }
12601
12602            boolean caching = false;
12603            final HardwareCanvas canvas = displayList.start();
12604            int width = mRight - mLeft;
12605            int height = mBottom - mTop;
12606
12607            try {
12608                canvas.setViewport(width, height);
12609                // The dirty rect should always be null for a display list
12610                canvas.onPreDraw(null);
12611                int layerType = getLayerType();
12612                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12613                    if (layerType == LAYER_TYPE_HARDWARE) {
12614                        final HardwareLayer layer = getHardwareLayer();
12615                        if (layer != null && layer.isValid()) {
12616                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12617                        } else {
12618                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12619                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12620                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12621                        }
12622                        caching = true;
12623                    } else {
12624                        buildDrawingCache(true);
12625                        Bitmap cache = getDrawingCache(true);
12626                        if (cache != null) {
12627                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12628                            caching = true;
12629                        }
12630                    }
12631                } else {
12632
12633                    computeScroll();
12634
12635                    canvas.translate(-mScrollX, -mScrollY);
12636                    if (!isLayer) {
12637                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12638                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12639                    }
12640
12641                    // Fast path for layouts with no backgrounds
12642                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12643                        dispatchDraw(canvas);
12644                    } else {
12645                        draw(canvas);
12646                    }
12647                }
12648            } finally {
12649                canvas.onPostDraw();
12650
12651                displayList.end();
12652                displayList.setCaching(caching);
12653                if (isLayer) {
12654                    displayList.setLeftTopRightBottom(0, 0, width, height);
12655                } else {
12656                    setDisplayListProperties(displayList);
12657                }
12658            }
12659        } else if (!isLayer) {
12660            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12661            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12662        }
12663
12664        return displayList;
12665    }
12666
12667    /**
12668     * Get the DisplayList for the HardwareLayer
12669     *
12670     * @param layer The HardwareLayer whose DisplayList we want
12671     * @return A DisplayList fopr the specified HardwareLayer
12672     */
12673    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12674        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12675        layer.setDisplayList(displayList);
12676        return displayList;
12677    }
12678
12679
12680    /**
12681     * <p>Returns a display list that can be used to draw this view again
12682     * without executing its draw method.</p>
12683     *
12684     * @return A DisplayList ready to replay, or null if caching is not enabled.
12685     *
12686     * @hide
12687     */
12688    public DisplayList getDisplayList() {
12689        mDisplayList = getDisplayList(mDisplayList, false);
12690        return mDisplayList;
12691    }
12692
12693    private void clearDisplayList() {
12694        if (mDisplayList != null) {
12695            mDisplayList.invalidate();
12696            mDisplayList.clear();
12697        }
12698    }
12699
12700    /**
12701     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12702     *
12703     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12704     *
12705     * @see #getDrawingCache(boolean)
12706     */
12707    public Bitmap getDrawingCache() {
12708        return getDrawingCache(false);
12709    }
12710
12711    /**
12712     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12713     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12714     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12715     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12716     * request the drawing cache by calling this method and draw it on screen if the
12717     * returned bitmap is not null.</p>
12718     *
12719     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12720     * this method will create a bitmap of the same size as this view. Because this bitmap
12721     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12722     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12723     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12724     * size than the view. This implies that your application must be able to handle this
12725     * size.</p>
12726     *
12727     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12728     *        the current density of the screen when the application is in compatibility
12729     *        mode.
12730     *
12731     * @return A bitmap representing this view or null if cache is disabled.
12732     *
12733     * @see #setDrawingCacheEnabled(boolean)
12734     * @see #isDrawingCacheEnabled()
12735     * @see #buildDrawingCache(boolean)
12736     * @see #destroyDrawingCache()
12737     */
12738    public Bitmap getDrawingCache(boolean autoScale) {
12739        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12740            return null;
12741        }
12742        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12743            buildDrawingCache(autoScale);
12744        }
12745        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12746    }
12747
12748    /**
12749     * <p>Frees the resources used by the drawing cache. If you call
12750     * {@link #buildDrawingCache()} manually without calling
12751     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12752     * should cleanup the cache with this method afterwards.</p>
12753     *
12754     * @see #setDrawingCacheEnabled(boolean)
12755     * @see #buildDrawingCache()
12756     * @see #getDrawingCache()
12757     */
12758    public void destroyDrawingCache() {
12759        if (mDrawingCache != null) {
12760            mDrawingCache.recycle();
12761            mDrawingCache = null;
12762        }
12763        if (mUnscaledDrawingCache != null) {
12764            mUnscaledDrawingCache.recycle();
12765            mUnscaledDrawingCache = null;
12766        }
12767    }
12768
12769    /**
12770     * Setting a solid background color for the drawing cache's bitmaps will improve
12771     * performance and memory usage. Note, though that this should only be used if this
12772     * view will always be drawn on top of a solid color.
12773     *
12774     * @param color The background color to use for the drawing cache's bitmap
12775     *
12776     * @see #setDrawingCacheEnabled(boolean)
12777     * @see #buildDrawingCache()
12778     * @see #getDrawingCache()
12779     */
12780    public void setDrawingCacheBackgroundColor(int color) {
12781        if (color != mDrawingCacheBackgroundColor) {
12782            mDrawingCacheBackgroundColor = color;
12783            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12784        }
12785    }
12786
12787    /**
12788     * @see #setDrawingCacheBackgroundColor(int)
12789     *
12790     * @return The background color to used for the drawing cache's bitmap
12791     */
12792    public int getDrawingCacheBackgroundColor() {
12793        return mDrawingCacheBackgroundColor;
12794    }
12795
12796    /**
12797     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12798     *
12799     * @see #buildDrawingCache(boolean)
12800     */
12801    public void buildDrawingCache() {
12802        buildDrawingCache(false);
12803    }
12804
12805    /**
12806     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12807     *
12808     * <p>If you call {@link #buildDrawingCache()} manually without calling
12809     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12810     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12811     *
12812     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12813     * this method will create a bitmap of the same size as this view. Because this bitmap
12814     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12815     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12816     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12817     * size than the view. This implies that your application must be able to handle this
12818     * size.</p>
12819     *
12820     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12821     * you do not need the drawing cache bitmap, calling this method will increase memory
12822     * usage and cause the view to be rendered in software once, thus negatively impacting
12823     * performance.</p>
12824     *
12825     * @see #getDrawingCache()
12826     * @see #destroyDrawingCache()
12827     */
12828    public void buildDrawingCache(boolean autoScale) {
12829        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
12830                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12831            mCachingFailed = false;
12832
12833            int width = mRight - mLeft;
12834            int height = mBottom - mTop;
12835
12836            final AttachInfo attachInfo = mAttachInfo;
12837            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12838
12839            if (autoScale && scalingRequired) {
12840                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12841                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12842            }
12843
12844            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12845            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12846            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12847
12848            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
12849            final long drawingCacheSize =
12850                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
12851            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
12852                if (width > 0 && height > 0) {
12853                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
12854                            + projectedBitmapSize + " bytes, only "
12855                            + drawingCacheSize + " available");
12856                }
12857                destroyDrawingCache();
12858                mCachingFailed = true;
12859                return;
12860            }
12861
12862            boolean clear = true;
12863            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12864
12865            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12866                Bitmap.Config quality;
12867                if (!opaque) {
12868                    // Never pick ARGB_4444 because it looks awful
12869                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12870                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12871                        case DRAWING_CACHE_QUALITY_AUTO:
12872                            quality = Bitmap.Config.ARGB_8888;
12873                            break;
12874                        case DRAWING_CACHE_QUALITY_LOW:
12875                            quality = Bitmap.Config.ARGB_8888;
12876                            break;
12877                        case DRAWING_CACHE_QUALITY_HIGH:
12878                            quality = Bitmap.Config.ARGB_8888;
12879                            break;
12880                        default:
12881                            quality = Bitmap.Config.ARGB_8888;
12882                            break;
12883                    }
12884                } else {
12885                    // Optimization for translucent windows
12886                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12887                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12888                }
12889
12890                // Try to cleanup memory
12891                if (bitmap != null) bitmap.recycle();
12892
12893                try {
12894                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12895                            width, height, quality);
12896                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12897                    if (autoScale) {
12898                        mDrawingCache = bitmap;
12899                    } else {
12900                        mUnscaledDrawingCache = bitmap;
12901                    }
12902                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12903                } catch (OutOfMemoryError e) {
12904                    // If there is not enough memory to create the bitmap cache, just
12905                    // ignore the issue as bitmap caches are not required to draw the
12906                    // view hierarchy
12907                    if (autoScale) {
12908                        mDrawingCache = null;
12909                    } else {
12910                        mUnscaledDrawingCache = null;
12911                    }
12912                    mCachingFailed = true;
12913                    return;
12914                }
12915
12916                clear = drawingCacheBackgroundColor != 0;
12917            }
12918
12919            Canvas canvas;
12920            if (attachInfo != null) {
12921                canvas = attachInfo.mCanvas;
12922                if (canvas == null) {
12923                    canvas = new Canvas();
12924                }
12925                canvas.setBitmap(bitmap);
12926                // Temporarily clobber the cached Canvas in case one of our children
12927                // is also using a drawing cache. Without this, the children would
12928                // steal the canvas by attaching their own bitmap to it and bad, bad
12929                // thing would happen (invisible views, corrupted drawings, etc.)
12930                attachInfo.mCanvas = null;
12931            } else {
12932                // This case should hopefully never or seldom happen
12933                canvas = new Canvas(bitmap);
12934            }
12935
12936            if (clear) {
12937                bitmap.eraseColor(drawingCacheBackgroundColor);
12938            }
12939
12940            computeScroll();
12941            final int restoreCount = canvas.save();
12942
12943            if (autoScale && scalingRequired) {
12944                final float scale = attachInfo.mApplicationScale;
12945                canvas.scale(scale, scale);
12946            }
12947
12948            canvas.translate(-mScrollX, -mScrollY);
12949
12950            mPrivateFlags |= PFLAG_DRAWN;
12951            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12952                    mLayerType != LAYER_TYPE_NONE) {
12953                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
12954            }
12955
12956            // Fast path for layouts with no backgrounds
12957            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12958                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12959                dispatchDraw(canvas);
12960            } else {
12961                draw(canvas);
12962            }
12963
12964            canvas.restoreToCount(restoreCount);
12965            canvas.setBitmap(null);
12966
12967            if (attachInfo != null) {
12968                // Restore the cached Canvas for our siblings
12969                attachInfo.mCanvas = canvas;
12970            }
12971        }
12972    }
12973
12974    /**
12975     * Create a snapshot of the view into a bitmap.  We should probably make
12976     * some form of this public, but should think about the API.
12977     */
12978    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12979        int width = mRight - mLeft;
12980        int height = mBottom - mTop;
12981
12982        final AttachInfo attachInfo = mAttachInfo;
12983        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12984        width = (int) ((width * scale) + 0.5f);
12985        height = (int) ((height * scale) + 0.5f);
12986
12987        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12988                width > 0 ? width : 1, height > 0 ? height : 1, quality);
12989        if (bitmap == null) {
12990            throw new OutOfMemoryError();
12991        }
12992
12993        Resources resources = getResources();
12994        if (resources != null) {
12995            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12996        }
12997
12998        Canvas canvas;
12999        if (attachInfo != null) {
13000            canvas = attachInfo.mCanvas;
13001            if (canvas == null) {
13002                canvas = new Canvas();
13003            }
13004            canvas.setBitmap(bitmap);
13005            // Temporarily clobber the cached Canvas in case one of our children
13006            // is also using a drawing cache. Without this, the children would
13007            // steal the canvas by attaching their own bitmap to it and bad, bad
13008            // things would happen (invisible views, corrupted drawings, etc.)
13009            attachInfo.mCanvas = null;
13010        } else {
13011            // This case should hopefully never or seldom happen
13012            canvas = new Canvas(bitmap);
13013        }
13014
13015        if ((backgroundColor & 0xff000000) != 0) {
13016            bitmap.eraseColor(backgroundColor);
13017        }
13018
13019        computeScroll();
13020        final int restoreCount = canvas.save();
13021        canvas.scale(scale, scale);
13022        canvas.translate(-mScrollX, -mScrollY);
13023
13024        // Temporarily remove the dirty mask
13025        int flags = mPrivateFlags;
13026        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13027
13028        // Fast path for layouts with no backgrounds
13029        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13030            dispatchDraw(canvas);
13031        } else {
13032            draw(canvas);
13033        }
13034
13035        mPrivateFlags = flags;
13036
13037        canvas.restoreToCount(restoreCount);
13038        canvas.setBitmap(null);
13039
13040        if (attachInfo != null) {
13041            // Restore the cached Canvas for our siblings
13042            attachInfo.mCanvas = canvas;
13043        }
13044
13045        return bitmap;
13046    }
13047
13048    /**
13049     * Indicates whether this View is currently in edit mode. A View is usually
13050     * in edit mode when displayed within a developer tool. For instance, if
13051     * this View is being drawn by a visual user interface builder, this method
13052     * should return true.
13053     *
13054     * Subclasses should check the return value of this method to provide
13055     * different behaviors if their normal behavior might interfere with the
13056     * host environment. For instance: the class spawns a thread in its
13057     * constructor, the drawing code relies on device-specific features, etc.
13058     *
13059     * This method is usually checked in the drawing code of custom widgets.
13060     *
13061     * @return True if this View is in edit mode, false otherwise.
13062     */
13063    public boolean isInEditMode() {
13064        return false;
13065    }
13066
13067    /**
13068     * If the View draws content inside its padding and enables fading edges,
13069     * it needs to support padding offsets. Padding offsets are added to the
13070     * fading edges to extend the length of the fade so that it covers pixels
13071     * drawn inside the padding.
13072     *
13073     * Subclasses of this class should override this method if they need
13074     * to draw content inside the padding.
13075     *
13076     * @return True if padding offset must be applied, false otherwise.
13077     *
13078     * @see #getLeftPaddingOffset()
13079     * @see #getRightPaddingOffset()
13080     * @see #getTopPaddingOffset()
13081     * @see #getBottomPaddingOffset()
13082     *
13083     * @since CURRENT
13084     */
13085    protected boolean isPaddingOffsetRequired() {
13086        return false;
13087    }
13088
13089    /**
13090     * Amount by which to extend the left fading region. Called only when
13091     * {@link #isPaddingOffsetRequired()} returns true.
13092     *
13093     * @return The left padding offset in pixels.
13094     *
13095     * @see #isPaddingOffsetRequired()
13096     *
13097     * @since CURRENT
13098     */
13099    protected int getLeftPaddingOffset() {
13100        return 0;
13101    }
13102
13103    /**
13104     * Amount by which to extend the right fading region. Called only when
13105     * {@link #isPaddingOffsetRequired()} returns true.
13106     *
13107     * @return The right padding offset in pixels.
13108     *
13109     * @see #isPaddingOffsetRequired()
13110     *
13111     * @since CURRENT
13112     */
13113    protected int getRightPaddingOffset() {
13114        return 0;
13115    }
13116
13117    /**
13118     * Amount by which to extend the top fading region. Called only when
13119     * {@link #isPaddingOffsetRequired()} returns true.
13120     *
13121     * @return The top padding offset in pixels.
13122     *
13123     * @see #isPaddingOffsetRequired()
13124     *
13125     * @since CURRENT
13126     */
13127    protected int getTopPaddingOffset() {
13128        return 0;
13129    }
13130
13131    /**
13132     * Amount by which to extend the bottom fading region. Called only when
13133     * {@link #isPaddingOffsetRequired()} returns true.
13134     *
13135     * @return The bottom padding offset in pixels.
13136     *
13137     * @see #isPaddingOffsetRequired()
13138     *
13139     * @since CURRENT
13140     */
13141    protected int getBottomPaddingOffset() {
13142        return 0;
13143    }
13144
13145    /**
13146     * @hide
13147     * @param offsetRequired
13148     */
13149    protected int getFadeTop(boolean offsetRequired) {
13150        int top = mPaddingTop;
13151        if (offsetRequired) top += getTopPaddingOffset();
13152        return top;
13153    }
13154
13155    /**
13156     * @hide
13157     * @param offsetRequired
13158     */
13159    protected int getFadeHeight(boolean offsetRequired) {
13160        int padding = mPaddingTop;
13161        if (offsetRequired) padding += getTopPaddingOffset();
13162        return mBottom - mTop - mPaddingBottom - padding;
13163    }
13164
13165    /**
13166     * <p>Indicates whether this view is attached to a hardware accelerated
13167     * window or not.</p>
13168     *
13169     * <p>Even if this method returns true, it does not mean that every call
13170     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13171     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13172     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13173     * window is hardware accelerated,
13174     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13175     * return false, and this method will return true.</p>
13176     *
13177     * @return True if the view is attached to a window and the window is
13178     *         hardware accelerated; false in any other case.
13179     */
13180    public boolean isHardwareAccelerated() {
13181        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13182    }
13183
13184    /**
13185     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13186     * case of an active Animation being run on the view.
13187     */
13188    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13189            Animation a, boolean scalingRequired) {
13190        Transformation invalidationTransform;
13191        final int flags = parent.mGroupFlags;
13192        final boolean initialized = a.isInitialized();
13193        if (!initialized) {
13194            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13195            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13196            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13197            onAnimationStart();
13198        }
13199
13200        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13201        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13202            if (parent.mInvalidationTransformation == null) {
13203                parent.mInvalidationTransformation = new Transformation();
13204            }
13205            invalidationTransform = parent.mInvalidationTransformation;
13206            a.getTransformation(drawingTime, invalidationTransform, 1f);
13207        } else {
13208            invalidationTransform = parent.mChildTransformation;
13209        }
13210
13211        if (more) {
13212            if (!a.willChangeBounds()) {
13213                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13214                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13215                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13216                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13217                    // The child need to draw an animation, potentially offscreen, so
13218                    // make sure we do not cancel invalidate requests
13219                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13220                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13221                }
13222            } else {
13223                if (parent.mInvalidateRegion == null) {
13224                    parent.mInvalidateRegion = new RectF();
13225                }
13226                final RectF region = parent.mInvalidateRegion;
13227                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13228                        invalidationTransform);
13229
13230                // The child need to draw an animation, potentially offscreen, so
13231                // make sure we do not cancel invalidate requests
13232                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13233
13234                final int left = mLeft + (int) region.left;
13235                final int top = mTop + (int) region.top;
13236                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13237                        top + (int) (region.height() + .5f));
13238            }
13239        }
13240        return more;
13241    }
13242
13243    /**
13244     * This method is called by getDisplayList() when a display list is created or re-rendered.
13245     * It sets or resets the current value of all properties on that display list (resetting is
13246     * necessary when a display list is being re-created, because we need to make sure that
13247     * previously-set transform values
13248     */
13249    void setDisplayListProperties(DisplayList displayList) {
13250        if (displayList != null) {
13251            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13252            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13253            if (mParent instanceof ViewGroup) {
13254                displayList.setClipChildren(
13255                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13256            }
13257            float alpha = 1;
13258            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13259                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13260                ViewGroup parentVG = (ViewGroup) mParent;
13261                final boolean hasTransform =
13262                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13263                if (hasTransform) {
13264                    Transformation transform = parentVG.mChildTransformation;
13265                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13266                    if (transformType != Transformation.TYPE_IDENTITY) {
13267                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13268                            alpha = transform.getAlpha();
13269                        }
13270                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13271                            displayList.setStaticMatrix(transform.getMatrix());
13272                        }
13273                    }
13274                }
13275            }
13276            if (mTransformationInfo != null) {
13277                alpha *= mTransformationInfo.mAlpha;
13278                if (alpha < 1) {
13279                    final int multipliedAlpha = (int) (255 * alpha);
13280                    if (onSetAlpha(multipliedAlpha)) {
13281                        alpha = 1;
13282                    }
13283                }
13284                displayList.setTransformationInfo(alpha,
13285                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13286                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13287                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13288                        mTransformationInfo.mScaleY);
13289                if (mTransformationInfo.mCamera == null) {
13290                    mTransformationInfo.mCamera = new Camera();
13291                    mTransformationInfo.matrix3D = new Matrix();
13292                }
13293                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13294                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13295                    displayList.setPivotX(getPivotX());
13296                    displayList.setPivotY(getPivotY());
13297                }
13298            } else if (alpha < 1) {
13299                displayList.setAlpha(alpha);
13300            }
13301        }
13302    }
13303
13304    /**
13305     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13306     * This draw() method is an implementation detail and is not intended to be overridden or
13307     * to be called from anywhere else other than ViewGroup.drawChild().
13308     */
13309    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13310        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13311        boolean more = false;
13312        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13313        final int flags = parent.mGroupFlags;
13314
13315        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13316            parent.mChildTransformation.clear();
13317            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13318        }
13319
13320        Transformation transformToApply = null;
13321        boolean concatMatrix = false;
13322
13323        boolean scalingRequired = false;
13324        boolean caching;
13325        int layerType = getLayerType();
13326
13327        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13328        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13329                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13330            caching = true;
13331            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13332            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13333        } else {
13334            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13335        }
13336
13337        final Animation a = getAnimation();
13338        if (a != null) {
13339            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13340            concatMatrix = a.willChangeTransformationMatrix();
13341            if (concatMatrix) {
13342                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13343            }
13344            transformToApply = parent.mChildTransformation;
13345        } else {
13346            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM &&
13347                    mDisplayList != null) {
13348                // No longer animating: clear out old animation matrix
13349                mDisplayList.setAnimationMatrix(null);
13350                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13351            }
13352            if (!useDisplayListProperties &&
13353                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13354                final boolean hasTransform =
13355                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13356                if (hasTransform) {
13357                    final int transformType = parent.mChildTransformation.getTransformationType();
13358                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13359                            parent.mChildTransformation : null;
13360                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13361                }
13362            }
13363        }
13364
13365        concatMatrix |= !childHasIdentityMatrix;
13366
13367        // Sets the flag as early as possible to allow draw() implementations
13368        // to call invalidate() successfully when doing animations
13369        mPrivateFlags |= PFLAG_DRAWN;
13370
13371        if (!concatMatrix &&
13372                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13373                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13374                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13375                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13376            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13377            return more;
13378        }
13379        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13380
13381        if (hardwareAccelerated) {
13382            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13383            // retain the flag's value temporarily in the mRecreateDisplayList flag
13384            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13385            mPrivateFlags &= ~PFLAG_INVALIDATED;
13386        }
13387
13388        DisplayList displayList = null;
13389        Bitmap cache = null;
13390        boolean hasDisplayList = false;
13391        if (caching) {
13392            if (!hardwareAccelerated) {
13393                if (layerType != LAYER_TYPE_NONE) {
13394                    layerType = LAYER_TYPE_SOFTWARE;
13395                    buildDrawingCache(true);
13396                }
13397                cache = getDrawingCache(true);
13398            } else {
13399                switch (layerType) {
13400                    case LAYER_TYPE_SOFTWARE:
13401                        if (useDisplayListProperties) {
13402                            hasDisplayList = canHaveDisplayList();
13403                        } else {
13404                            buildDrawingCache(true);
13405                            cache = getDrawingCache(true);
13406                        }
13407                        break;
13408                    case LAYER_TYPE_HARDWARE:
13409                        if (useDisplayListProperties) {
13410                            hasDisplayList = canHaveDisplayList();
13411                        }
13412                        break;
13413                    case LAYER_TYPE_NONE:
13414                        // Delay getting the display list until animation-driven alpha values are
13415                        // set up and possibly passed on to the view
13416                        hasDisplayList = canHaveDisplayList();
13417                        break;
13418                }
13419            }
13420        }
13421        useDisplayListProperties &= hasDisplayList;
13422        if (useDisplayListProperties) {
13423            displayList = getDisplayList();
13424            if (!displayList.isValid()) {
13425                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13426                // to getDisplayList(), the display list will be marked invalid and we should not
13427                // try to use it again.
13428                displayList = null;
13429                hasDisplayList = false;
13430                useDisplayListProperties = false;
13431            }
13432        }
13433
13434        int sx = 0;
13435        int sy = 0;
13436        if (!hasDisplayList) {
13437            computeScroll();
13438            sx = mScrollX;
13439            sy = mScrollY;
13440        }
13441
13442        final boolean hasNoCache = cache == null || hasDisplayList;
13443        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13444                layerType != LAYER_TYPE_HARDWARE;
13445
13446        int restoreTo = -1;
13447        if (!useDisplayListProperties || transformToApply != null) {
13448            restoreTo = canvas.save();
13449        }
13450        if (offsetForScroll) {
13451            canvas.translate(mLeft - sx, mTop - sy);
13452        } else {
13453            if (!useDisplayListProperties) {
13454                canvas.translate(mLeft, mTop);
13455            }
13456            if (scalingRequired) {
13457                if (useDisplayListProperties) {
13458                    // TODO: Might not need this if we put everything inside the DL
13459                    restoreTo = canvas.save();
13460                }
13461                // mAttachInfo cannot be null, otherwise scalingRequired == false
13462                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13463                canvas.scale(scale, scale);
13464            }
13465        }
13466
13467        float alpha = useDisplayListProperties ? 1 : getAlpha();
13468        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13469                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13470            if (transformToApply != null || !childHasIdentityMatrix) {
13471                int transX = 0;
13472                int transY = 0;
13473
13474                if (offsetForScroll) {
13475                    transX = -sx;
13476                    transY = -sy;
13477                }
13478
13479                if (transformToApply != null) {
13480                    if (concatMatrix) {
13481                        if (useDisplayListProperties) {
13482                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13483                        } else {
13484                            // Undo the scroll translation, apply the transformation matrix,
13485                            // then redo the scroll translate to get the correct result.
13486                            canvas.translate(-transX, -transY);
13487                            canvas.concat(transformToApply.getMatrix());
13488                            canvas.translate(transX, transY);
13489                        }
13490                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13491                    }
13492
13493                    float transformAlpha = transformToApply.getAlpha();
13494                    if (transformAlpha < 1) {
13495                        alpha *= transformAlpha;
13496                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13497                    }
13498                }
13499
13500                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13501                    canvas.translate(-transX, -transY);
13502                    canvas.concat(getMatrix());
13503                    canvas.translate(transX, transY);
13504                }
13505            }
13506
13507            // Deal with alpha if it is or used to be <1
13508            if (alpha < 1 ||
13509                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13510                if (alpha < 1) {
13511                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13512                } else {
13513                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13514                }
13515                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13516                if (hasNoCache) {
13517                    final int multipliedAlpha = (int) (255 * alpha);
13518                    if (!onSetAlpha(multipliedAlpha)) {
13519                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13520                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13521                                layerType != LAYER_TYPE_NONE) {
13522                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13523                        }
13524                        if (useDisplayListProperties) {
13525                            displayList.setAlpha(alpha * getAlpha());
13526                        } else  if (layerType == LAYER_TYPE_NONE) {
13527                            final int scrollX = hasDisplayList ? 0 : sx;
13528                            final int scrollY = hasDisplayList ? 0 : sy;
13529                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13530                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13531                        }
13532                    } else {
13533                        // Alpha is handled by the child directly, clobber the layer's alpha
13534                        mPrivateFlags |= PFLAG_ALPHA_SET;
13535                    }
13536                }
13537            }
13538        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13539            onSetAlpha(255);
13540            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13541        }
13542
13543        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13544                !useDisplayListProperties) {
13545            if (offsetForScroll) {
13546                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13547            } else {
13548                if (!scalingRequired || cache == null) {
13549                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13550                } else {
13551                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13552                }
13553            }
13554        }
13555
13556        if (!useDisplayListProperties && hasDisplayList) {
13557            displayList = getDisplayList();
13558            if (!displayList.isValid()) {
13559                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13560                // to getDisplayList(), the display list will be marked invalid and we should not
13561                // try to use it again.
13562                displayList = null;
13563                hasDisplayList = false;
13564            }
13565        }
13566
13567        if (hasNoCache) {
13568            boolean layerRendered = false;
13569            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13570                final HardwareLayer layer = getHardwareLayer();
13571                if (layer != null && layer.isValid()) {
13572                    mLayerPaint.setAlpha((int) (alpha * 255));
13573                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13574                    layerRendered = true;
13575                } else {
13576                    final int scrollX = hasDisplayList ? 0 : sx;
13577                    final int scrollY = hasDisplayList ? 0 : sy;
13578                    canvas.saveLayer(scrollX, scrollY,
13579                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13580                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13581                }
13582            }
13583
13584            if (!layerRendered) {
13585                if (!hasDisplayList) {
13586                    // Fast path for layouts with no backgrounds
13587                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13588                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13589                        dispatchDraw(canvas);
13590                    } else {
13591                        draw(canvas);
13592                    }
13593                } else {
13594                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13595                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13596                }
13597            }
13598        } else if (cache != null) {
13599            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13600            Paint cachePaint;
13601
13602            if (layerType == LAYER_TYPE_NONE) {
13603                cachePaint = parent.mCachePaint;
13604                if (cachePaint == null) {
13605                    cachePaint = new Paint();
13606                    cachePaint.setDither(false);
13607                    parent.mCachePaint = cachePaint;
13608                }
13609                if (alpha < 1) {
13610                    cachePaint.setAlpha((int) (alpha * 255));
13611                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13612                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13613                    cachePaint.setAlpha(255);
13614                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13615                }
13616            } else {
13617                cachePaint = mLayerPaint;
13618                cachePaint.setAlpha((int) (alpha * 255));
13619            }
13620            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13621        }
13622
13623        if (restoreTo >= 0) {
13624            canvas.restoreToCount(restoreTo);
13625        }
13626
13627        if (a != null && !more) {
13628            if (!hardwareAccelerated && !a.getFillAfter()) {
13629                onSetAlpha(255);
13630            }
13631            parent.finishAnimatingView(this, a);
13632        }
13633
13634        if (more && hardwareAccelerated) {
13635            // invalidation is the trigger to recreate display lists, so if we're using
13636            // display lists to render, force an invalidate to allow the animation to
13637            // continue drawing another frame
13638            parent.invalidate(true);
13639            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13640                // alpha animations should cause the child to recreate its display list
13641                invalidate(true);
13642            }
13643        }
13644
13645        mRecreateDisplayList = false;
13646
13647        return more;
13648    }
13649
13650    /**
13651     * Manually render this view (and all of its children) to the given Canvas.
13652     * The view must have already done a full layout before this function is
13653     * called.  When implementing a view, implement
13654     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13655     * If you do need to override this method, call the superclass version.
13656     *
13657     * @param canvas The Canvas to which the View is rendered.
13658     */
13659    public void draw(Canvas canvas) {
13660        final int privateFlags = mPrivateFlags;
13661        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13662                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13663        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13664
13665        /*
13666         * Draw traversal performs several drawing steps which must be executed
13667         * in the appropriate order:
13668         *
13669         *      1. Draw the background
13670         *      2. If necessary, save the canvas' layers to prepare for fading
13671         *      3. Draw view's content
13672         *      4. Draw children
13673         *      5. If necessary, draw the fading edges and restore layers
13674         *      6. Draw decorations (scrollbars for instance)
13675         */
13676
13677        // Step 1, draw the background, if needed
13678        int saveCount;
13679
13680        if (!dirtyOpaque) {
13681            final Drawable background = mBackground;
13682            if (background != null) {
13683                final int scrollX = mScrollX;
13684                final int scrollY = mScrollY;
13685
13686                if (mBackgroundSizeChanged) {
13687                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13688                    mBackgroundSizeChanged = false;
13689                }
13690
13691                if ((scrollX | scrollY) == 0) {
13692                    background.draw(canvas);
13693                } else {
13694                    canvas.translate(scrollX, scrollY);
13695                    background.draw(canvas);
13696                    canvas.translate(-scrollX, -scrollY);
13697                }
13698            }
13699        }
13700
13701        // skip step 2 & 5 if possible (common case)
13702        final int viewFlags = mViewFlags;
13703        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13704        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13705        if (!verticalEdges && !horizontalEdges) {
13706            // Step 3, draw the content
13707            if (!dirtyOpaque) onDraw(canvas);
13708
13709            // Step 4, draw the children
13710            dispatchDraw(canvas);
13711
13712            // Step 6, draw decorations (scrollbars)
13713            onDrawScrollBars(canvas);
13714
13715            // we're done...
13716            return;
13717        }
13718
13719        /*
13720         * Here we do the full fledged routine...
13721         * (this is an uncommon case where speed matters less,
13722         * this is why we repeat some of the tests that have been
13723         * done above)
13724         */
13725
13726        boolean drawTop = false;
13727        boolean drawBottom = false;
13728        boolean drawLeft = false;
13729        boolean drawRight = false;
13730
13731        float topFadeStrength = 0.0f;
13732        float bottomFadeStrength = 0.0f;
13733        float leftFadeStrength = 0.0f;
13734        float rightFadeStrength = 0.0f;
13735
13736        // Step 2, save the canvas' layers
13737        int paddingLeft = mPaddingLeft;
13738
13739        final boolean offsetRequired = isPaddingOffsetRequired();
13740        if (offsetRequired) {
13741            paddingLeft += getLeftPaddingOffset();
13742        }
13743
13744        int left = mScrollX + paddingLeft;
13745        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13746        int top = mScrollY + getFadeTop(offsetRequired);
13747        int bottom = top + getFadeHeight(offsetRequired);
13748
13749        if (offsetRequired) {
13750            right += getRightPaddingOffset();
13751            bottom += getBottomPaddingOffset();
13752        }
13753
13754        final ScrollabilityCache scrollabilityCache = mScrollCache;
13755        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13756        int length = (int) fadeHeight;
13757
13758        // clip the fade length if top and bottom fades overlap
13759        // overlapping fades produce odd-looking artifacts
13760        if (verticalEdges && (top + length > bottom - length)) {
13761            length = (bottom - top) / 2;
13762        }
13763
13764        // also clip horizontal fades if necessary
13765        if (horizontalEdges && (left + length > right - length)) {
13766            length = (right - left) / 2;
13767        }
13768
13769        if (verticalEdges) {
13770            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13771            drawTop = topFadeStrength * fadeHeight > 1.0f;
13772            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13773            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13774        }
13775
13776        if (horizontalEdges) {
13777            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13778            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13779            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13780            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13781        }
13782
13783        saveCount = canvas.getSaveCount();
13784
13785        int solidColor = getSolidColor();
13786        if (solidColor == 0) {
13787            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13788
13789            if (drawTop) {
13790                canvas.saveLayer(left, top, right, top + length, null, flags);
13791            }
13792
13793            if (drawBottom) {
13794                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13795            }
13796
13797            if (drawLeft) {
13798                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13799            }
13800
13801            if (drawRight) {
13802                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13803            }
13804        } else {
13805            scrollabilityCache.setFadeColor(solidColor);
13806        }
13807
13808        // Step 3, draw the content
13809        if (!dirtyOpaque) onDraw(canvas);
13810
13811        // Step 4, draw the children
13812        dispatchDraw(canvas);
13813
13814        // Step 5, draw the fade effect and restore layers
13815        final Paint p = scrollabilityCache.paint;
13816        final Matrix matrix = scrollabilityCache.matrix;
13817        final Shader fade = scrollabilityCache.shader;
13818
13819        if (drawTop) {
13820            matrix.setScale(1, fadeHeight * topFadeStrength);
13821            matrix.postTranslate(left, top);
13822            fade.setLocalMatrix(matrix);
13823            canvas.drawRect(left, top, right, top + length, p);
13824        }
13825
13826        if (drawBottom) {
13827            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13828            matrix.postRotate(180);
13829            matrix.postTranslate(left, bottom);
13830            fade.setLocalMatrix(matrix);
13831            canvas.drawRect(left, bottom - length, right, bottom, p);
13832        }
13833
13834        if (drawLeft) {
13835            matrix.setScale(1, fadeHeight * leftFadeStrength);
13836            matrix.postRotate(-90);
13837            matrix.postTranslate(left, top);
13838            fade.setLocalMatrix(matrix);
13839            canvas.drawRect(left, top, left + length, bottom, p);
13840        }
13841
13842        if (drawRight) {
13843            matrix.setScale(1, fadeHeight * rightFadeStrength);
13844            matrix.postRotate(90);
13845            matrix.postTranslate(right, top);
13846            fade.setLocalMatrix(matrix);
13847            canvas.drawRect(right - length, top, right, bottom, p);
13848        }
13849
13850        canvas.restoreToCount(saveCount);
13851
13852        // Step 6, draw decorations (scrollbars)
13853        onDrawScrollBars(canvas);
13854    }
13855
13856    /**
13857     * Override this if your view is known to always be drawn on top of a solid color background,
13858     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13859     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13860     * should be set to 0xFF.
13861     *
13862     * @see #setVerticalFadingEdgeEnabled(boolean)
13863     * @see #setHorizontalFadingEdgeEnabled(boolean)
13864     *
13865     * @return The known solid color background for this view, or 0 if the color may vary
13866     */
13867    @ViewDebug.ExportedProperty(category = "drawing")
13868    public int getSolidColor() {
13869        return 0;
13870    }
13871
13872    /**
13873     * Build a human readable string representation of the specified view flags.
13874     *
13875     * @param flags the view flags to convert to a string
13876     * @return a String representing the supplied flags
13877     */
13878    private static String printFlags(int flags) {
13879        String output = "";
13880        int numFlags = 0;
13881        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13882            output += "TAKES_FOCUS";
13883            numFlags++;
13884        }
13885
13886        switch (flags & VISIBILITY_MASK) {
13887        case INVISIBLE:
13888            if (numFlags > 0) {
13889                output += " ";
13890            }
13891            output += "INVISIBLE";
13892            // USELESS HERE numFlags++;
13893            break;
13894        case GONE:
13895            if (numFlags > 0) {
13896                output += " ";
13897            }
13898            output += "GONE";
13899            // USELESS HERE numFlags++;
13900            break;
13901        default:
13902            break;
13903        }
13904        return output;
13905    }
13906
13907    /**
13908     * Build a human readable string representation of the specified private
13909     * view flags.
13910     *
13911     * @param privateFlags the private view flags to convert to a string
13912     * @return a String representing the supplied flags
13913     */
13914    private static String printPrivateFlags(int privateFlags) {
13915        String output = "";
13916        int numFlags = 0;
13917
13918        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
13919            output += "WANTS_FOCUS";
13920            numFlags++;
13921        }
13922
13923        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
13924            if (numFlags > 0) {
13925                output += " ";
13926            }
13927            output += "FOCUSED";
13928            numFlags++;
13929        }
13930
13931        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
13932            if (numFlags > 0) {
13933                output += " ";
13934            }
13935            output += "SELECTED";
13936            numFlags++;
13937        }
13938
13939        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
13940            if (numFlags > 0) {
13941                output += " ";
13942            }
13943            output += "IS_ROOT_NAMESPACE";
13944            numFlags++;
13945        }
13946
13947        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
13948            if (numFlags > 0) {
13949                output += " ";
13950            }
13951            output += "HAS_BOUNDS";
13952            numFlags++;
13953        }
13954
13955        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
13956            if (numFlags > 0) {
13957                output += " ";
13958            }
13959            output += "DRAWN";
13960            // USELESS HERE numFlags++;
13961        }
13962        return output;
13963    }
13964
13965    /**
13966     * <p>Indicates whether or not this view's layout will be requested during
13967     * the next hierarchy layout pass.</p>
13968     *
13969     * @return true if the layout will be forced during next layout pass
13970     */
13971    public boolean isLayoutRequested() {
13972        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
13973    }
13974
13975    /**
13976     * Assign a size and position to a view and all of its
13977     * descendants
13978     *
13979     * <p>This is the second phase of the layout mechanism.
13980     * (The first is measuring). In this phase, each parent calls
13981     * layout on all of its children to position them.
13982     * This is typically done using the child measurements
13983     * that were stored in the measure pass().</p>
13984     *
13985     * <p>Derived classes should not override this method.
13986     * Derived classes with children should override
13987     * onLayout. In that method, they should
13988     * call layout on each of their children.</p>
13989     *
13990     * @param l Left position, relative to parent
13991     * @param t Top position, relative to parent
13992     * @param r Right position, relative to parent
13993     * @param b Bottom position, relative to parent
13994     */
13995    @SuppressWarnings({"unchecked"})
13996    public void layout(int l, int t, int r, int b) {
13997        int oldL = mLeft;
13998        int oldT = mTop;
13999        int oldB = mBottom;
14000        int oldR = mRight;
14001        boolean changed = setFrame(l, t, r, b);
14002        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14003            onLayout(changed, l, t, r, b);
14004            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14005
14006            ListenerInfo li = mListenerInfo;
14007            if (li != null && li.mOnLayoutChangeListeners != null) {
14008                ArrayList<OnLayoutChangeListener> listenersCopy =
14009                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14010                int numListeners = listenersCopy.size();
14011                for (int i = 0; i < numListeners; ++i) {
14012                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14013                }
14014            }
14015        }
14016        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14017    }
14018
14019    /**
14020     * Called from layout when this view should
14021     * assign a size and position to each of its children.
14022     *
14023     * Derived classes with children should override
14024     * this method and call layout on each of
14025     * their children.
14026     * @param changed This is a new size or position for this view
14027     * @param left Left position, relative to parent
14028     * @param top Top position, relative to parent
14029     * @param right Right position, relative to parent
14030     * @param bottom Bottom position, relative to parent
14031     */
14032    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14033    }
14034
14035    /**
14036     * Assign a size and position to this view.
14037     *
14038     * This is called from layout.
14039     *
14040     * @param left Left position, relative to parent
14041     * @param top Top position, relative to parent
14042     * @param right Right position, relative to parent
14043     * @param bottom Bottom position, relative to parent
14044     * @return true if the new size and position are different than the
14045     *         previous ones
14046     * {@hide}
14047     */
14048    protected boolean setFrame(int left, int top, int right, int bottom) {
14049        boolean changed = false;
14050
14051        if (DBG) {
14052            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14053                    + right + "," + bottom + ")");
14054        }
14055
14056        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14057            changed = true;
14058
14059            // Remember our drawn bit
14060            int drawn = mPrivateFlags & PFLAG_DRAWN;
14061
14062            int oldWidth = mRight - mLeft;
14063            int oldHeight = mBottom - mTop;
14064            int newWidth = right - left;
14065            int newHeight = bottom - top;
14066            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14067
14068            // Invalidate our old position
14069            invalidate(sizeChanged);
14070
14071            mLeft = left;
14072            mTop = top;
14073            mRight = right;
14074            mBottom = bottom;
14075            if (mDisplayList != null) {
14076                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14077            }
14078
14079            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14080
14081
14082            if (sizeChanged) {
14083                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14084                    // A change in dimension means an auto-centered pivot point changes, too
14085                    if (mTransformationInfo != null) {
14086                        mTransformationInfo.mMatrixDirty = true;
14087                    }
14088                }
14089                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14090            }
14091
14092            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14093                // If we are visible, force the DRAWN bit to on so that
14094                // this invalidate will go through (at least to our parent).
14095                // This is because someone may have invalidated this view
14096                // before this call to setFrame came in, thereby clearing
14097                // the DRAWN bit.
14098                mPrivateFlags |= PFLAG_DRAWN;
14099                invalidate(sizeChanged);
14100                // parent display list may need to be recreated based on a change in the bounds
14101                // of any child
14102                invalidateParentCaches();
14103            }
14104
14105            // Reset drawn bit to original value (invalidate turns it off)
14106            mPrivateFlags |= drawn;
14107
14108            mBackgroundSizeChanged = true;
14109        }
14110        return changed;
14111    }
14112
14113    /**
14114     * Finalize inflating a view from XML.  This is called as the last phase
14115     * of inflation, after all child views have been added.
14116     *
14117     * <p>Even if the subclass overrides onFinishInflate, they should always be
14118     * sure to call the super method, so that we get called.
14119     */
14120    protected void onFinishInflate() {
14121    }
14122
14123    /**
14124     * Returns the resources associated with this view.
14125     *
14126     * @return Resources object.
14127     */
14128    public Resources getResources() {
14129        return mResources;
14130    }
14131
14132    /**
14133     * Invalidates the specified Drawable.
14134     *
14135     * @param drawable the drawable to invalidate
14136     */
14137    public void invalidateDrawable(Drawable drawable) {
14138        if (verifyDrawable(drawable)) {
14139            final Rect dirty = drawable.getBounds();
14140            final int scrollX = mScrollX;
14141            final int scrollY = mScrollY;
14142
14143            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14144                    dirty.right + scrollX, dirty.bottom + scrollY);
14145        }
14146    }
14147
14148    /**
14149     * Schedules an action on a drawable to occur at a specified time.
14150     *
14151     * @param who the recipient of the action
14152     * @param what the action to run on the drawable
14153     * @param when the time at which the action must occur. Uses the
14154     *        {@link SystemClock#uptimeMillis} timebase.
14155     */
14156    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14157        if (verifyDrawable(who) && what != null) {
14158            final long delay = when - SystemClock.uptimeMillis();
14159            if (mAttachInfo != null) {
14160                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14161                        Choreographer.CALLBACK_ANIMATION, what, who,
14162                        Choreographer.subtractFrameDelay(delay));
14163            } else {
14164                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14165            }
14166        }
14167    }
14168
14169    /**
14170     * Cancels a scheduled action on a drawable.
14171     *
14172     * @param who the recipient of the action
14173     * @param what the action to cancel
14174     */
14175    public void unscheduleDrawable(Drawable who, Runnable what) {
14176        if (verifyDrawable(who) && what != null) {
14177            if (mAttachInfo != null) {
14178                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14179                        Choreographer.CALLBACK_ANIMATION, what, who);
14180            } else {
14181                ViewRootImpl.getRunQueue().removeCallbacks(what);
14182            }
14183        }
14184    }
14185
14186    /**
14187     * Unschedule any events associated with the given Drawable.  This can be
14188     * used when selecting a new Drawable into a view, so that the previous
14189     * one is completely unscheduled.
14190     *
14191     * @param who The Drawable to unschedule.
14192     *
14193     * @see #drawableStateChanged
14194     */
14195    public void unscheduleDrawable(Drawable who) {
14196        if (mAttachInfo != null && who != null) {
14197            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14198                    Choreographer.CALLBACK_ANIMATION, null, who);
14199        }
14200    }
14201
14202    /**
14203     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14204     * that the View directionality can and will be resolved before its Drawables.
14205     *
14206     * Will call {@link View#onResolveDrawables} when resolution is done.
14207     *
14208     * @hide
14209     */
14210    protected void resolveDrawables() {
14211        if (canResolveLayoutDirection()) {
14212            if (mBackground != null) {
14213                mBackground.setLayoutDirection(getLayoutDirection());
14214            }
14215            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14216            onResolveDrawables(getLayoutDirection());
14217        }
14218    }
14219
14220    /**
14221     * Called when layout direction has been resolved.
14222     *
14223     * The default implementation does nothing.
14224     *
14225     * @param layoutDirection The resolved layout direction.
14226     *
14227     * @see #LAYOUT_DIRECTION_LTR
14228     * @see #LAYOUT_DIRECTION_RTL
14229     *
14230     * @hide
14231     */
14232    public void onResolveDrawables(int layoutDirection) {
14233    }
14234
14235    /**
14236     * @hide
14237     */
14238    protected void resetResolvedDrawables() {
14239        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14240    }
14241
14242    private boolean isDrawablesResolved() {
14243        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14244    }
14245
14246    /**
14247     * If your view subclass is displaying its own Drawable objects, it should
14248     * override this function and return true for any Drawable it is
14249     * displaying.  This allows animations for those drawables to be
14250     * scheduled.
14251     *
14252     * <p>Be sure to call through to the super class when overriding this
14253     * function.
14254     *
14255     * @param who The Drawable to verify.  Return true if it is one you are
14256     *            displaying, else return the result of calling through to the
14257     *            super class.
14258     *
14259     * @return boolean If true than the Drawable is being displayed in the
14260     *         view; else false and it is not allowed to animate.
14261     *
14262     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14263     * @see #drawableStateChanged()
14264     */
14265    protected boolean verifyDrawable(Drawable who) {
14266        return who == mBackground;
14267    }
14268
14269    /**
14270     * This function is called whenever the state of the view changes in such
14271     * a way that it impacts the state of drawables being shown.
14272     *
14273     * <p>Be sure to call through to the superclass when overriding this
14274     * function.
14275     *
14276     * @see Drawable#setState(int[])
14277     */
14278    protected void drawableStateChanged() {
14279        Drawable d = mBackground;
14280        if (d != null && d.isStateful()) {
14281            d.setState(getDrawableState());
14282        }
14283    }
14284
14285    /**
14286     * Call this to force a view to update its drawable state. This will cause
14287     * drawableStateChanged to be called on this view. Views that are interested
14288     * in the new state should call getDrawableState.
14289     *
14290     * @see #drawableStateChanged
14291     * @see #getDrawableState
14292     */
14293    public void refreshDrawableState() {
14294        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14295        drawableStateChanged();
14296
14297        ViewParent parent = mParent;
14298        if (parent != null) {
14299            parent.childDrawableStateChanged(this);
14300        }
14301    }
14302
14303    /**
14304     * Return an array of resource IDs of the drawable states representing the
14305     * current state of the view.
14306     *
14307     * @return The current drawable state
14308     *
14309     * @see Drawable#setState(int[])
14310     * @see #drawableStateChanged()
14311     * @see #onCreateDrawableState(int)
14312     */
14313    public final int[] getDrawableState() {
14314        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14315            return mDrawableState;
14316        } else {
14317            mDrawableState = onCreateDrawableState(0);
14318            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14319            return mDrawableState;
14320        }
14321    }
14322
14323    /**
14324     * Generate the new {@link android.graphics.drawable.Drawable} state for
14325     * this view. This is called by the view
14326     * system when the cached Drawable state is determined to be invalid.  To
14327     * retrieve the current state, you should use {@link #getDrawableState}.
14328     *
14329     * @param extraSpace if non-zero, this is the number of extra entries you
14330     * would like in the returned array in which you can place your own
14331     * states.
14332     *
14333     * @return Returns an array holding the current {@link Drawable} state of
14334     * the view.
14335     *
14336     * @see #mergeDrawableStates(int[], int[])
14337     */
14338    protected int[] onCreateDrawableState(int extraSpace) {
14339        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14340                mParent instanceof View) {
14341            return ((View) mParent).onCreateDrawableState(extraSpace);
14342        }
14343
14344        int[] drawableState;
14345
14346        int privateFlags = mPrivateFlags;
14347
14348        int viewStateIndex = 0;
14349        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14350        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14351        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14352        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14353        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14354        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14355        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14356                HardwareRenderer.isAvailable()) {
14357            // This is set if HW acceleration is requested, even if the current
14358            // process doesn't allow it.  This is just to allow app preview
14359            // windows to better match their app.
14360            viewStateIndex |= VIEW_STATE_ACCELERATED;
14361        }
14362        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14363
14364        final int privateFlags2 = mPrivateFlags2;
14365        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14366        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14367
14368        drawableState = VIEW_STATE_SETS[viewStateIndex];
14369
14370        //noinspection ConstantIfStatement
14371        if (false) {
14372            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14373            Log.i("View", toString()
14374                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14375                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14376                    + " fo=" + hasFocus()
14377                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14378                    + " wf=" + hasWindowFocus()
14379                    + ": " + Arrays.toString(drawableState));
14380        }
14381
14382        if (extraSpace == 0) {
14383            return drawableState;
14384        }
14385
14386        final int[] fullState;
14387        if (drawableState != null) {
14388            fullState = new int[drawableState.length + extraSpace];
14389            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14390        } else {
14391            fullState = new int[extraSpace];
14392        }
14393
14394        return fullState;
14395    }
14396
14397    /**
14398     * Merge your own state values in <var>additionalState</var> into the base
14399     * state values <var>baseState</var> that were returned by
14400     * {@link #onCreateDrawableState(int)}.
14401     *
14402     * @param baseState The base state values returned by
14403     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14404     * own additional state values.
14405     *
14406     * @param additionalState The additional state values you would like
14407     * added to <var>baseState</var>; this array is not modified.
14408     *
14409     * @return As a convenience, the <var>baseState</var> array you originally
14410     * passed into the function is returned.
14411     *
14412     * @see #onCreateDrawableState(int)
14413     */
14414    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14415        final int N = baseState.length;
14416        int i = N - 1;
14417        while (i >= 0 && baseState[i] == 0) {
14418            i--;
14419        }
14420        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14421        return baseState;
14422    }
14423
14424    /**
14425     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14426     * on all Drawable objects associated with this view.
14427     */
14428    public void jumpDrawablesToCurrentState() {
14429        if (mBackground != null) {
14430            mBackground.jumpToCurrentState();
14431        }
14432    }
14433
14434    /**
14435     * Sets the background color for this view.
14436     * @param color the color of the background
14437     */
14438    @RemotableViewMethod
14439    public void setBackgroundColor(int color) {
14440        if (mBackground instanceof ColorDrawable) {
14441            ((ColorDrawable) mBackground.mutate()).setColor(color);
14442            computeOpaqueFlags();
14443        } else {
14444            setBackground(new ColorDrawable(color));
14445        }
14446    }
14447
14448    /**
14449     * Set the background to a given resource. The resource should refer to
14450     * a Drawable object or 0 to remove the background.
14451     * @param resid The identifier of the resource.
14452     *
14453     * @attr ref android.R.styleable#View_background
14454     */
14455    @RemotableViewMethod
14456    public void setBackgroundResource(int resid) {
14457        if (resid != 0 && resid == mBackgroundResource) {
14458            return;
14459        }
14460
14461        Drawable d= null;
14462        if (resid != 0) {
14463            d = mResources.getDrawable(resid);
14464        }
14465        setBackground(d);
14466
14467        mBackgroundResource = resid;
14468    }
14469
14470    /**
14471     * Set the background to a given Drawable, or remove the background. If the
14472     * background has padding, this View's padding is set to the background's
14473     * padding. However, when a background is removed, this View's padding isn't
14474     * touched. If setting the padding is desired, please use
14475     * {@link #setPadding(int, int, int, int)}.
14476     *
14477     * @param background The Drawable to use as the background, or null to remove the
14478     *        background
14479     */
14480    public void setBackground(Drawable background) {
14481        //noinspection deprecation
14482        setBackgroundDrawable(background);
14483    }
14484
14485    /**
14486     * @deprecated use {@link #setBackground(Drawable)} instead
14487     */
14488    @Deprecated
14489    public void setBackgroundDrawable(Drawable background) {
14490        computeOpaqueFlags();
14491
14492        if (background == mBackground) {
14493            return;
14494        }
14495
14496        boolean requestLayout = false;
14497
14498        mBackgroundResource = 0;
14499
14500        /*
14501         * Regardless of whether we're setting a new background or not, we want
14502         * to clear the previous drawable.
14503         */
14504        if (mBackground != null) {
14505            mBackground.setCallback(null);
14506            unscheduleDrawable(mBackground);
14507        }
14508
14509        if (background != null) {
14510            Rect padding = sThreadLocal.get();
14511            if (padding == null) {
14512                padding = new Rect();
14513                sThreadLocal.set(padding);
14514            }
14515            resetResolvedDrawables();
14516            background.setLayoutDirection(getLayoutDirection());
14517            if (background.getPadding(padding)) {
14518                resetResolvedPadding();
14519                switch (background.getLayoutDirection()) {
14520                    case LAYOUT_DIRECTION_RTL:
14521                        mUserPaddingLeftInitial = padding.right;
14522                        mUserPaddingRightInitial = padding.left;
14523                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14524                        break;
14525                    case LAYOUT_DIRECTION_LTR:
14526                    default:
14527                        mUserPaddingLeftInitial = padding.left;
14528                        mUserPaddingRightInitial = padding.right;
14529                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14530                }
14531            }
14532
14533            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14534            // if it has a different minimum size, we should layout again
14535            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14536                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14537                requestLayout = true;
14538            }
14539
14540            background.setCallback(this);
14541            if (background.isStateful()) {
14542                background.setState(getDrawableState());
14543            }
14544            background.setVisible(getVisibility() == VISIBLE, false);
14545            mBackground = background;
14546
14547            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14548                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14549                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14550                requestLayout = true;
14551            }
14552        } else {
14553            /* Remove the background */
14554            mBackground = null;
14555
14556            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14557                /*
14558                 * This view ONLY drew the background before and we're removing
14559                 * the background, so now it won't draw anything
14560                 * (hence we SKIP_DRAW)
14561                 */
14562                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14563                mPrivateFlags |= PFLAG_SKIP_DRAW;
14564            }
14565
14566            /*
14567             * When the background is set, we try to apply its padding to this
14568             * View. When the background is removed, we don't touch this View's
14569             * padding. This is noted in the Javadocs. Hence, we don't need to
14570             * requestLayout(), the invalidate() below is sufficient.
14571             */
14572
14573            // The old background's minimum size could have affected this
14574            // View's layout, so let's requestLayout
14575            requestLayout = true;
14576        }
14577
14578        computeOpaqueFlags();
14579
14580        if (requestLayout) {
14581            requestLayout();
14582        }
14583
14584        mBackgroundSizeChanged = true;
14585        invalidate(true);
14586    }
14587
14588    /**
14589     * Gets the background drawable
14590     *
14591     * @return The drawable used as the background for this view, if any.
14592     *
14593     * @see #setBackground(Drawable)
14594     *
14595     * @attr ref android.R.styleable#View_background
14596     */
14597    public Drawable getBackground() {
14598        return mBackground;
14599    }
14600
14601    /**
14602     * Sets the padding. The view may add on the space required to display
14603     * the scrollbars, depending on the style and visibility of the scrollbars.
14604     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14605     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14606     * from the values set in this call.
14607     *
14608     * @attr ref android.R.styleable#View_padding
14609     * @attr ref android.R.styleable#View_paddingBottom
14610     * @attr ref android.R.styleable#View_paddingLeft
14611     * @attr ref android.R.styleable#View_paddingRight
14612     * @attr ref android.R.styleable#View_paddingTop
14613     * @param left the left padding in pixels
14614     * @param top the top padding in pixels
14615     * @param right the right padding in pixels
14616     * @param bottom the bottom padding in pixels
14617     */
14618    public void setPadding(int left, int top, int right, int bottom) {
14619        resetResolvedPadding();
14620
14621        mUserPaddingStart = UNDEFINED_PADDING;
14622        mUserPaddingEnd = UNDEFINED_PADDING;
14623
14624        mUserPaddingLeftInitial = left;
14625        mUserPaddingRightInitial = right;
14626
14627        internalSetPadding(left, top, right, bottom);
14628    }
14629
14630    /**
14631     * @hide
14632     */
14633    protected void internalSetPadding(int left, int top, int right, int bottom) {
14634        mUserPaddingLeft = left;
14635        mUserPaddingRight = right;
14636        mUserPaddingBottom = bottom;
14637
14638        final int viewFlags = mViewFlags;
14639        boolean changed = false;
14640
14641        // Common case is there are no scroll bars.
14642        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14643            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14644                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14645                        ? 0 : getVerticalScrollbarWidth();
14646                switch (mVerticalScrollbarPosition) {
14647                    case SCROLLBAR_POSITION_DEFAULT:
14648                        if (isLayoutRtl()) {
14649                            left += offset;
14650                        } else {
14651                            right += offset;
14652                        }
14653                        break;
14654                    case SCROLLBAR_POSITION_RIGHT:
14655                        right += offset;
14656                        break;
14657                    case SCROLLBAR_POSITION_LEFT:
14658                        left += offset;
14659                        break;
14660                }
14661            }
14662            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14663                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14664                        ? 0 : getHorizontalScrollbarHeight();
14665            }
14666        }
14667
14668        if (mPaddingLeft != left) {
14669            changed = true;
14670            mPaddingLeft = left;
14671        }
14672        if (mPaddingTop != top) {
14673            changed = true;
14674            mPaddingTop = top;
14675        }
14676        if (mPaddingRight != right) {
14677            changed = true;
14678            mPaddingRight = right;
14679        }
14680        if (mPaddingBottom != bottom) {
14681            changed = true;
14682            mPaddingBottom = bottom;
14683        }
14684
14685        if (changed) {
14686            requestLayout();
14687        }
14688    }
14689
14690    /**
14691     * Sets the relative padding. The view may add on the space required to display
14692     * the scrollbars, depending on the style and visibility of the scrollbars.
14693     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14694     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14695     * from the values set in this call.
14696     *
14697     * @attr ref android.R.styleable#View_padding
14698     * @attr ref android.R.styleable#View_paddingBottom
14699     * @attr ref android.R.styleable#View_paddingStart
14700     * @attr ref android.R.styleable#View_paddingEnd
14701     * @attr ref android.R.styleable#View_paddingTop
14702     * @param start the start padding in pixels
14703     * @param top the top padding in pixels
14704     * @param end the end padding in pixels
14705     * @param bottom the bottom padding in pixels
14706     */
14707    public void setPaddingRelative(int start, int top, int end, int bottom) {
14708        resetResolvedPadding();
14709
14710        mUserPaddingStart = start;
14711        mUserPaddingEnd = end;
14712
14713        switch(getLayoutDirection()) {
14714            case LAYOUT_DIRECTION_RTL:
14715                mUserPaddingLeftInitial = end;
14716                mUserPaddingRightInitial = start;
14717                internalSetPadding(end, top, start, bottom);
14718                break;
14719            case LAYOUT_DIRECTION_LTR:
14720            default:
14721                mUserPaddingLeftInitial = start;
14722                mUserPaddingRightInitial = end;
14723                internalSetPadding(start, top, end, bottom);
14724        }
14725    }
14726
14727    /**
14728     * Returns the top padding of this view.
14729     *
14730     * @return the top padding in pixels
14731     */
14732    public int getPaddingTop() {
14733        return mPaddingTop;
14734    }
14735
14736    /**
14737     * Returns the bottom padding of this view. If there are inset and enabled
14738     * scrollbars, this value may include the space required to display the
14739     * scrollbars as well.
14740     *
14741     * @return the bottom padding in pixels
14742     */
14743    public int getPaddingBottom() {
14744        return mPaddingBottom;
14745    }
14746
14747    /**
14748     * Returns the left padding of this view. If there are inset and enabled
14749     * scrollbars, this value may include the space required to display the
14750     * scrollbars as well.
14751     *
14752     * @return the left padding in pixels
14753     */
14754    public int getPaddingLeft() {
14755        if (!isPaddingResolved()) {
14756            resolvePadding();
14757        }
14758        return mPaddingLeft;
14759    }
14760
14761    /**
14762     * Returns the start padding of this view depending on its resolved layout direction.
14763     * If there are inset and enabled scrollbars, this value may include the space
14764     * required to display the scrollbars as well.
14765     *
14766     * @return the start padding in pixels
14767     */
14768    public int getPaddingStart() {
14769        if (!isPaddingResolved()) {
14770            resolvePadding();
14771        }
14772        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14773                mPaddingRight : mPaddingLeft;
14774    }
14775
14776    /**
14777     * Returns the right padding of this view. If there are inset and enabled
14778     * scrollbars, this value may include the space required to display the
14779     * scrollbars as well.
14780     *
14781     * @return the right padding in pixels
14782     */
14783    public int getPaddingRight() {
14784        if (!isPaddingResolved()) {
14785            resolvePadding();
14786        }
14787        return mPaddingRight;
14788    }
14789
14790    /**
14791     * Returns the end padding of this view depending on its resolved layout direction.
14792     * If there are inset and enabled scrollbars, this value may include the space
14793     * required to display the scrollbars as well.
14794     *
14795     * @return the end padding in pixels
14796     */
14797    public int getPaddingEnd() {
14798        if (!isPaddingResolved()) {
14799            resolvePadding();
14800        }
14801        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14802                mPaddingLeft : mPaddingRight;
14803    }
14804
14805    /**
14806     * Return if the padding as been set thru relative values
14807     * {@link #setPaddingRelative(int, int, int, int)} or thru
14808     * @attr ref android.R.styleable#View_paddingStart or
14809     * @attr ref android.R.styleable#View_paddingEnd
14810     *
14811     * @return true if the padding is relative or false if it is not.
14812     */
14813    public boolean isPaddingRelative() {
14814        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
14815    }
14816
14817    /**
14818     * @hide
14819     */
14820    public void resetPaddingToInitialValues() {
14821        if (isRtlCompatibilityMode()) {
14822            mPaddingLeft = mUserPaddingLeftInitial;
14823            mPaddingRight = mUserPaddingRightInitial;
14824            return;
14825        }
14826        if (isLayoutRtl()) {
14827            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
14828            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
14829        } else {
14830            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
14831            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
14832        }
14833    }
14834
14835    /**
14836     * @hide
14837     */
14838    public Insets getOpticalInsets() {
14839        if (mLayoutInsets == null) {
14840            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14841        }
14842        return mLayoutInsets;
14843    }
14844
14845    /**
14846     * @hide
14847     */
14848    public void setLayoutInsets(Insets layoutInsets) {
14849        mLayoutInsets = layoutInsets;
14850    }
14851
14852    /**
14853     * Changes the selection state of this view. A view can be selected or not.
14854     * Note that selection is not the same as focus. Views are typically
14855     * selected in the context of an AdapterView like ListView or GridView;
14856     * the selected view is the view that is highlighted.
14857     *
14858     * @param selected true if the view must be selected, false otherwise
14859     */
14860    public void setSelected(boolean selected) {
14861        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
14862            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
14863            if (!selected) resetPressedState();
14864            invalidate(true);
14865            refreshDrawableState();
14866            dispatchSetSelected(selected);
14867            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14868                notifyAccessibilityStateChanged();
14869            }
14870        }
14871    }
14872
14873    /**
14874     * Dispatch setSelected to all of this View's children.
14875     *
14876     * @see #setSelected(boolean)
14877     *
14878     * @param selected The new selected state
14879     */
14880    protected void dispatchSetSelected(boolean selected) {
14881    }
14882
14883    /**
14884     * Indicates the selection state of this view.
14885     *
14886     * @return true if the view is selected, false otherwise
14887     */
14888    @ViewDebug.ExportedProperty
14889    public boolean isSelected() {
14890        return (mPrivateFlags & PFLAG_SELECTED) != 0;
14891    }
14892
14893    /**
14894     * Changes the activated state of this view. A view can be activated or not.
14895     * Note that activation is not the same as selection.  Selection is
14896     * a transient property, representing the view (hierarchy) the user is
14897     * currently interacting with.  Activation is a longer-term state that the
14898     * user can move views in and out of.  For example, in a list view with
14899     * single or multiple selection enabled, the views in the current selection
14900     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14901     * here.)  The activated state is propagated down to children of the view it
14902     * is set on.
14903     *
14904     * @param activated true if the view must be activated, false otherwise
14905     */
14906    public void setActivated(boolean activated) {
14907        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
14908            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
14909            invalidate(true);
14910            refreshDrawableState();
14911            dispatchSetActivated(activated);
14912        }
14913    }
14914
14915    /**
14916     * Dispatch setActivated to all of this View's children.
14917     *
14918     * @see #setActivated(boolean)
14919     *
14920     * @param activated The new activated state
14921     */
14922    protected void dispatchSetActivated(boolean activated) {
14923    }
14924
14925    /**
14926     * Indicates the activation state of this view.
14927     *
14928     * @return true if the view is activated, false otherwise
14929     */
14930    @ViewDebug.ExportedProperty
14931    public boolean isActivated() {
14932        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
14933    }
14934
14935    /**
14936     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14937     * observer can be used to get notifications when global events, like
14938     * layout, happen.
14939     *
14940     * The returned ViewTreeObserver observer is not guaranteed to remain
14941     * valid for the lifetime of this View. If the caller of this method keeps
14942     * a long-lived reference to ViewTreeObserver, it should always check for
14943     * the return value of {@link ViewTreeObserver#isAlive()}.
14944     *
14945     * @return The ViewTreeObserver for this view's hierarchy.
14946     */
14947    public ViewTreeObserver getViewTreeObserver() {
14948        if (mAttachInfo != null) {
14949            return mAttachInfo.mTreeObserver;
14950        }
14951        if (mFloatingTreeObserver == null) {
14952            mFloatingTreeObserver = new ViewTreeObserver();
14953        }
14954        return mFloatingTreeObserver;
14955    }
14956
14957    /**
14958     * <p>Finds the topmost view in the current view hierarchy.</p>
14959     *
14960     * @return the topmost view containing this view
14961     */
14962    public View getRootView() {
14963        if (mAttachInfo != null) {
14964            final View v = mAttachInfo.mRootView;
14965            if (v != null) {
14966                return v;
14967            }
14968        }
14969
14970        View parent = this;
14971
14972        while (parent.mParent != null && parent.mParent instanceof View) {
14973            parent = (View) parent.mParent;
14974        }
14975
14976        return parent;
14977    }
14978
14979    /**
14980     * <p>Computes the coordinates of this view on the screen. The argument
14981     * must be an array of two integers. After the method returns, the array
14982     * contains the x and y location in that order.</p>
14983     *
14984     * @param location an array of two integers in which to hold the coordinates
14985     */
14986    public void getLocationOnScreen(int[] location) {
14987        getLocationInWindow(location);
14988
14989        final AttachInfo info = mAttachInfo;
14990        if (info != null) {
14991            location[0] += info.mWindowLeft;
14992            location[1] += info.mWindowTop;
14993        }
14994    }
14995
14996    /**
14997     * <p>Computes the coordinates of this view in its window. The argument
14998     * must be an array of two integers. After the method returns, the array
14999     * contains the x and y location in that order.</p>
15000     *
15001     * @param location an array of two integers in which to hold the coordinates
15002     */
15003    public void getLocationInWindow(int[] location) {
15004        if (location == null || location.length < 2) {
15005            throw new IllegalArgumentException("location must be an array of two integers");
15006        }
15007
15008        if (mAttachInfo == null) {
15009            // When the view is not attached to a window, this method does not make sense
15010            location[0] = location[1] = 0;
15011            return;
15012        }
15013
15014        float[] position = mAttachInfo.mTmpTransformLocation;
15015        position[0] = position[1] = 0.0f;
15016
15017        if (!hasIdentityMatrix()) {
15018            getMatrix().mapPoints(position);
15019        }
15020
15021        position[0] += mLeft;
15022        position[1] += mTop;
15023
15024        ViewParent viewParent = mParent;
15025        while (viewParent instanceof View) {
15026            final View view = (View) viewParent;
15027
15028            position[0] -= view.mScrollX;
15029            position[1] -= view.mScrollY;
15030
15031            if (!view.hasIdentityMatrix()) {
15032                view.getMatrix().mapPoints(position);
15033            }
15034
15035            position[0] += view.mLeft;
15036            position[1] += view.mTop;
15037
15038            viewParent = view.mParent;
15039         }
15040
15041        if (viewParent instanceof ViewRootImpl) {
15042            // *cough*
15043            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15044            position[1] -= vr.mCurScrollY;
15045        }
15046
15047        location[0] = (int) (position[0] + 0.5f);
15048        location[1] = (int) (position[1] + 0.5f);
15049    }
15050
15051    /**
15052     * {@hide}
15053     * @param id the id of the view to be found
15054     * @return the view of the specified id, null if cannot be found
15055     */
15056    protected View findViewTraversal(int id) {
15057        if (id == mID) {
15058            return this;
15059        }
15060        return null;
15061    }
15062
15063    /**
15064     * {@hide}
15065     * @param tag the tag of the view to be found
15066     * @return the view of specified tag, null if cannot be found
15067     */
15068    protected View findViewWithTagTraversal(Object tag) {
15069        if (tag != null && tag.equals(mTag)) {
15070            return this;
15071        }
15072        return null;
15073    }
15074
15075    /**
15076     * {@hide}
15077     * @param predicate The predicate to evaluate.
15078     * @param childToSkip If not null, ignores this child during the recursive traversal.
15079     * @return The first view that matches the predicate or null.
15080     */
15081    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15082        if (predicate.apply(this)) {
15083            return this;
15084        }
15085        return null;
15086    }
15087
15088    /**
15089     * Look for a child view with the given id.  If this view has the given
15090     * id, return this view.
15091     *
15092     * @param id The id to search for.
15093     * @return The view that has the given id in the hierarchy or null
15094     */
15095    public final View findViewById(int id) {
15096        if (id < 0) {
15097            return null;
15098        }
15099        return findViewTraversal(id);
15100    }
15101
15102    /**
15103     * Finds a view by its unuque and stable accessibility id.
15104     *
15105     * @param accessibilityId The searched accessibility id.
15106     * @return The found view.
15107     */
15108    final View findViewByAccessibilityId(int accessibilityId) {
15109        if (accessibilityId < 0) {
15110            return null;
15111        }
15112        return findViewByAccessibilityIdTraversal(accessibilityId);
15113    }
15114
15115    /**
15116     * Performs the traversal to find a view by its unuque and stable accessibility id.
15117     *
15118     * <strong>Note:</strong>This method does not stop at the root namespace
15119     * boundary since the user can touch the screen at an arbitrary location
15120     * potentially crossing the root namespace bounday which will send an
15121     * accessibility event to accessibility services and they should be able
15122     * to obtain the event source. Also accessibility ids are guaranteed to be
15123     * unique in the window.
15124     *
15125     * @param accessibilityId The accessibility id.
15126     * @return The found view.
15127     */
15128    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15129        if (getAccessibilityViewId() == accessibilityId) {
15130            return this;
15131        }
15132        return null;
15133    }
15134
15135    /**
15136     * Look for a child view with the given tag.  If this view has the given
15137     * tag, return this view.
15138     *
15139     * @param tag The tag to search for, using "tag.equals(getTag())".
15140     * @return The View that has the given tag in the hierarchy or null
15141     */
15142    public final View findViewWithTag(Object tag) {
15143        if (tag == null) {
15144            return null;
15145        }
15146        return findViewWithTagTraversal(tag);
15147    }
15148
15149    /**
15150     * {@hide}
15151     * Look for a child view that matches the specified predicate.
15152     * If this view matches the predicate, return this view.
15153     *
15154     * @param predicate The predicate to evaluate.
15155     * @return The first view that matches the predicate or null.
15156     */
15157    public final View findViewByPredicate(Predicate<View> predicate) {
15158        return findViewByPredicateTraversal(predicate, null);
15159    }
15160
15161    /**
15162     * {@hide}
15163     * Look for a child view that matches the specified predicate,
15164     * starting with the specified view and its descendents and then
15165     * recusively searching the ancestors and siblings of that view
15166     * until this view is reached.
15167     *
15168     * This method is useful in cases where the predicate does not match
15169     * a single unique view (perhaps multiple views use the same id)
15170     * and we are trying to find the view that is "closest" in scope to the
15171     * starting view.
15172     *
15173     * @param start The view to start from.
15174     * @param predicate The predicate to evaluate.
15175     * @return The first view that matches the predicate or null.
15176     */
15177    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15178        View childToSkip = null;
15179        for (;;) {
15180            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15181            if (view != null || start == this) {
15182                return view;
15183            }
15184
15185            ViewParent parent = start.getParent();
15186            if (parent == null || !(parent instanceof View)) {
15187                return null;
15188            }
15189
15190            childToSkip = start;
15191            start = (View) parent;
15192        }
15193    }
15194
15195    /**
15196     * Sets the identifier for this view. The identifier does not have to be
15197     * unique in this view's hierarchy. The identifier should be a positive
15198     * number.
15199     *
15200     * @see #NO_ID
15201     * @see #getId()
15202     * @see #findViewById(int)
15203     *
15204     * @param id a number used to identify the view
15205     *
15206     * @attr ref android.R.styleable#View_id
15207     */
15208    public void setId(int id) {
15209        mID = id;
15210        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15211            mID = generateViewId();
15212        }
15213    }
15214
15215    /**
15216     * {@hide}
15217     *
15218     * @param isRoot true if the view belongs to the root namespace, false
15219     *        otherwise
15220     */
15221    public void setIsRootNamespace(boolean isRoot) {
15222        if (isRoot) {
15223            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15224        } else {
15225            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15226        }
15227    }
15228
15229    /**
15230     * {@hide}
15231     *
15232     * @return true if the view belongs to the root namespace, false otherwise
15233     */
15234    public boolean isRootNamespace() {
15235        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15236    }
15237
15238    /**
15239     * Returns this view's identifier.
15240     *
15241     * @return a positive integer used to identify the view or {@link #NO_ID}
15242     *         if the view has no ID
15243     *
15244     * @see #setId(int)
15245     * @see #findViewById(int)
15246     * @attr ref android.R.styleable#View_id
15247     */
15248    @ViewDebug.CapturedViewProperty
15249    public int getId() {
15250        return mID;
15251    }
15252
15253    /**
15254     * Returns this view's tag.
15255     *
15256     * @return the Object stored in this view as a tag
15257     *
15258     * @see #setTag(Object)
15259     * @see #getTag(int)
15260     */
15261    @ViewDebug.ExportedProperty
15262    public Object getTag() {
15263        return mTag;
15264    }
15265
15266    /**
15267     * Sets the tag associated with this view. A tag can be used to mark
15268     * a view in its hierarchy and does not have to be unique within the
15269     * hierarchy. Tags can also be used to store data within a view without
15270     * resorting to another data structure.
15271     *
15272     * @param tag an Object to tag the view with
15273     *
15274     * @see #getTag()
15275     * @see #setTag(int, Object)
15276     */
15277    public void setTag(final Object tag) {
15278        mTag = tag;
15279    }
15280
15281    /**
15282     * Returns the tag associated with this view and the specified key.
15283     *
15284     * @param key The key identifying the tag
15285     *
15286     * @return the Object stored in this view as a tag
15287     *
15288     * @see #setTag(int, Object)
15289     * @see #getTag()
15290     */
15291    public Object getTag(int key) {
15292        if (mKeyedTags != null) return mKeyedTags.get(key);
15293        return null;
15294    }
15295
15296    /**
15297     * Sets a tag associated with this view and a key. A tag can be used
15298     * to mark a view in its hierarchy and does not have to be unique within
15299     * the hierarchy. Tags can also be used to store data within a view
15300     * without resorting to another data structure.
15301     *
15302     * The specified key should be an id declared in the resources of the
15303     * application to ensure it is unique (see the <a
15304     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15305     * Keys identified as belonging to
15306     * the Android framework or not associated with any package will cause
15307     * an {@link IllegalArgumentException} to be thrown.
15308     *
15309     * @param key The key identifying the tag
15310     * @param tag An Object to tag the view with
15311     *
15312     * @throws IllegalArgumentException If they specified key is not valid
15313     *
15314     * @see #setTag(Object)
15315     * @see #getTag(int)
15316     */
15317    public void setTag(int key, final Object tag) {
15318        // If the package id is 0x00 or 0x01, it's either an undefined package
15319        // or a framework id
15320        if ((key >>> 24) < 2) {
15321            throw new IllegalArgumentException("The key must be an application-specific "
15322                    + "resource id.");
15323        }
15324
15325        setKeyedTag(key, tag);
15326    }
15327
15328    /**
15329     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15330     * framework id.
15331     *
15332     * @hide
15333     */
15334    public void setTagInternal(int key, Object tag) {
15335        if ((key >>> 24) != 0x1) {
15336            throw new IllegalArgumentException("The key must be a framework-specific "
15337                    + "resource id.");
15338        }
15339
15340        setKeyedTag(key, tag);
15341    }
15342
15343    private void setKeyedTag(int key, Object tag) {
15344        if (mKeyedTags == null) {
15345            mKeyedTags = new SparseArray<Object>();
15346        }
15347
15348        mKeyedTags.put(key, tag);
15349    }
15350
15351    /**
15352     * Prints information about this view in the log output, with the tag
15353     * {@link #VIEW_LOG_TAG}.
15354     *
15355     * @hide
15356     */
15357    public void debug() {
15358        debug(0);
15359    }
15360
15361    /**
15362     * Prints information about this view in the log output, with the tag
15363     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15364     * indentation defined by the <code>depth</code>.
15365     *
15366     * @param depth the indentation level
15367     *
15368     * @hide
15369     */
15370    protected void debug(int depth) {
15371        String output = debugIndent(depth - 1);
15372
15373        output += "+ " + this;
15374        int id = getId();
15375        if (id != -1) {
15376            output += " (id=" + id + ")";
15377        }
15378        Object tag = getTag();
15379        if (tag != null) {
15380            output += " (tag=" + tag + ")";
15381        }
15382        Log.d(VIEW_LOG_TAG, output);
15383
15384        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15385            output = debugIndent(depth) + " FOCUSED";
15386            Log.d(VIEW_LOG_TAG, output);
15387        }
15388
15389        output = debugIndent(depth);
15390        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15391                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15392                + "} ";
15393        Log.d(VIEW_LOG_TAG, output);
15394
15395        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15396                || mPaddingBottom != 0) {
15397            output = debugIndent(depth);
15398            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15399                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15400            Log.d(VIEW_LOG_TAG, output);
15401        }
15402
15403        output = debugIndent(depth);
15404        output += "mMeasureWidth=" + mMeasuredWidth +
15405                " mMeasureHeight=" + mMeasuredHeight;
15406        Log.d(VIEW_LOG_TAG, output);
15407
15408        output = debugIndent(depth);
15409        if (mLayoutParams == null) {
15410            output += "BAD! no layout params";
15411        } else {
15412            output = mLayoutParams.debug(output);
15413        }
15414        Log.d(VIEW_LOG_TAG, output);
15415
15416        output = debugIndent(depth);
15417        output += "flags={";
15418        output += View.printFlags(mViewFlags);
15419        output += "}";
15420        Log.d(VIEW_LOG_TAG, output);
15421
15422        output = debugIndent(depth);
15423        output += "privateFlags={";
15424        output += View.printPrivateFlags(mPrivateFlags);
15425        output += "}";
15426        Log.d(VIEW_LOG_TAG, output);
15427    }
15428
15429    /**
15430     * Creates a string of whitespaces used for indentation.
15431     *
15432     * @param depth the indentation level
15433     * @return a String containing (depth * 2 + 3) * 2 white spaces
15434     *
15435     * @hide
15436     */
15437    protected static String debugIndent(int depth) {
15438        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15439        for (int i = 0; i < (depth * 2) + 3; i++) {
15440            spaces.append(' ').append(' ');
15441        }
15442        return spaces.toString();
15443    }
15444
15445    /**
15446     * <p>Return the offset of the widget's text baseline from the widget's top
15447     * boundary. If this widget does not support baseline alignment, this
15448     * method returns -1. </p>
15449     *
15450     * @return the offset of the baseline within the widget's bounds or -1
15451     *         if baseline alignment is not supported
15452     */
15453    @ViewDebug.ExportedProperty(category = "layout")
15454    public int getBaseline() {
15455        return -1;
15456    }
15457
15458    /**
15459     * Call this when something has changed which has invalidated the
15460     * layout of this view. This will schedule a layout pass of the view
15461     * tree.
15462     */
15463    public void requestLayout() {
15464        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15465        mPrivateFlags |= PFLAG_INVALIDATED;
15466
15467        if (mParent != null && !mParent.isLayoutRequested()) {
15468            mParent.requestLayout();
15469        }
15470    }
15471
15472    /**
15473     * Forces this view to be laid out during the next layout pass.
15474     * This method does not call requestLayout() or forceLayout()
15475     * on the parent.
15476     */
15477    public void forceLayout() {
15478        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15479        mPrivateFlags |= PFLAG_INVALIDATED;
15480    }
15481
15482    /**
15483     * <p>
15484     * This is called to find out how big a view should be. The parent
15485     * supplies constraint information in the width and height parameters.
15486     * </p>
15487     *
15488     * <p>
15489     * The actual measurement work of a view is performed in
15490     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15491     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15492     * </p>
15493     *
15494     *
15495     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15496     *        parent
15497     * @param heightMeasureSpec Vertical space requirements as imposed by the
15498     *        parent
15499     *
15500     * @see #onMeasure(int, int)
15501     */
15502    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15503        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15504                widthMeasureSpec != mOldWidthMeasureSpec ||
15505                heightMeasureSpec != mOldHeightMeasureSpec) {
15506
15507            // first clears the measured dimension flag
15508            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15509
15510            resolveRtlPropertiesIfNeeded();
15511
15512            // measure ourselves, this should set the measured dimension flag back
15513            onMeasure(widthMeasureSpec, heightMeasureSpec);
15514
15515            // flag not set, setMeasuredDimension() was not invoked, we raise
15516            // an exception to warn the developer
15517            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15518                throw new IllegalStateException("onMeasure() did not set the"
15519                        + " measured dimension by calling"
15520                        + " setMeasuredDimension()");
15521            }
15522
15523            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15524        }
15525
15526        mOldWidthMeasureSpec = widthMeasureSpec;
15527        mOldHeightMeasureSpec = heightMeasureSpec;
15528    }
15529
15530    /**
15531     * <p>
15532     * Measure the view and its content to determine the measured width and the
15533     * measured height. This method is invoked by {@link #measure(int, int)} and
15534     * should be overriden by subclasses to provide accurate and efficient
15535     * measurement of their contents.
15536     * </p>
15537     *
15538     * <p>
15539     * <strong>CONTRACT:</strong> When overriding this method, you
15540     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15541     * measured width and height of this view. Failure to do so will trigger an
15542     * <code>IllegalStateException</code>, thrown by
15543     * {@link #measure(int, int)}. Calling the superclass'
15544     * {@link #onMeasure(int, int)} is a valid use.
15545     * </p>
15546     *
15547     * <p>
15548     * The base class implementation of measure defaults to the background size,
15549     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15550     * override {@link #onMeasure(int, int)} to provide better measurements of
15551     * their content.
15552     * </p>
15553     *
15554     * <p>
15555     * If this method is overridden, it is the subclass's responsibility to make
15556     * sure the measured height and width are at least the view's minimum height
15557     * and width ({@link #getSuggestedMinimumHeight()} and
15558     * {@link #getSuggestedMinimumWidth()}).
15559     * </p>
15560     *
15561     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15562     *                         The requirements are encoded with
15563     *                         {@link android.view.View.MeasureSpec}.
15564     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15565     *                         The requirements are encoded with
15566     *                         {@link android.view.View.MeasureSpec}.
15567     *
15568     * @see #getMeasuredWidth()
15569     * @see #getMeasuredHeight()
15570     * @see #setMeasuredDimension(int, int)
15571     * @see #getSuggestedMinimumHeight()
15572     * @see #getSuggestedMinimumWidth()
15573     * @see android.view.View.MeasureSpec#getMode(int)
15574     * @see android.view.View.MeasureSpec#getSize(int)
15575     */
15576    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15577        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15578                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15579    }
15580
15581    /**
15582     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15583     * measured width and measured height. Failing to do so will trigger an
15584     * exception at measurement time.</p>
15585     *
15586     * @param measuredWidth The measured width of this view.  May be a complex
15587     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15588     * {@link #MEASURED_STATE_TOO_SMALL}.
15589     * @param measuredHeight The measured height of this view.  May be a complex
15590     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15591     * {@link #MEASURED_STATE_TOO_SMALL}.
15592     */
15593    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
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;
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        /**
17286         * Returns a String representation of the specified measure
17287         * specification.
17288         *
17289         * @param measureSpec the measure specification to convert to a String
17290         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17291         */
17292        public static String toString(int measureSpec) {
17293            int mode = getMode(measureSpec);
17294            int size = getSize(measureSpec);
17295
17296            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17297
17298            if (mode == UNSPECIFIED)
17299                sb.append("UNSPECIFIED ");
17300            else if (mode == EXACTLY)
17301                sb.append("EXACTLY ");
17302            else if (mode == AT_MOST)
17303                sb.append("AT_MOST ");
17304            else
17305                sb.append(mode).append(" ");
17306
17307            sb.append(size);
17308            return sb.toString();
17309        }
17310    }
17311
17312    class CheckForLongPress implements Runnable {
17313
17314        private int mOriginalWindowAttachCount;
17315
17316        public void run() {
17317            if (isPressed() && (mParent != null)
17318                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17319                if (performLongClick()) {
17320                    mHasPerformedLongPress = true;
17321                }
17322            }
17323        }
17324
17325        public void rememberWindowAttachCount() {
17326            mOriginalWindowAttachCount = mWindowAttachCount;
17327        }
17328    }
17329
17330    private final class CheckForTap implements Runnable {
17331        public void run() {
17332            mPrivateFlags &= ~PFLAG_PREPRESSED;
17333            setPressed(true);
17334            checkForLongClick(ViewConfiguration.getTapTimeout());
17335        }
17336    }
17337
17338    private final class PerformClick implements Runnable {
17339        public void run() {
17340            performClick();
17341        }
17342    }
17343
17344    /** @hide */
17345    public void hackTurnOffWindowResizeAnim(boolean off) {
17346        mAttachInfo.mTurnOffWindowResizeAnim = off;
17347    }
17348
17349    /**
17350     * This method returns a ViewPropertyAnimator object, which can be used to animate
17351     * specific properties on this View.
17352     *
17353     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17354     */
17355    public ViewPropertyAnimator animate() {
17356        if (mAnimator == null) {
17357            mAnimator = new ViewPropertyAnimator(this);
17358        }
17359        return mAnimator;
17360    }
17361
17362    /**
17363     * Interface definition for a callback to be invoked when a hardware key event is
17364     * dispatched to this view. The callback will be invoked before the key event is
17365     * given to the view. This is only useful for hardware keyboards; a software input
17366     * method has no obligation to trigger this listener.
17367     */
17368    public interface OnKeyListener {
17369        /**
17370         * Called when a hardware key is dispatched to a view. This allows listeners to
17371         * get a chance to respond before the target view.
17372         * <p>Key presses in software keyboards will generally NOT trigger this method,
17373         * although some may elect to do so in some situations. Do not assume a
17374         * software input method has to be key-based; even if it is, it may use key presses
17375         * in a different way than you expect, so there is no way to reliably catch soft
17376         * input key presses.
17377         *
17378         * @param v The view the key has been dispatched to.
17379         * @param keyCode The code for the physical key that was pressed
17380         * @param event The KeyEvent object containing full information about
17381         *        the event.
17382         * @return True if the listener has consumed the event, false otherwise.
17383         */
17384        boolean onKey(View v, int keyCode, KeyEvent event);
17385    }
17386
17387    /**
17388     * Interface definition for a callback to be invoked when a touch event is
17389     * dispatched to this view. The callback will be invoked before the touch
17390     * event is given to the view.
17391     */
17392    public interface OnTouchListener {
17393        /**
17394         * Called when a touch event is dispatched to a view. This allows listeners to
17395         * get a chance to respond before the target view.
17396         *
17397         * @param v The view the touch event has been dispatched to.
17398         * @param event The MotionEvent object containing full information about
17399         *        the event.
17400         * @return True if the listener has consumed the event, false otherwise.
17401         */
17402        boolean onTouch(View v, MotionEvent event);
17403    }
17404
17405    /**
17406     * Interface definition for a callback to be invoked when a hover event is
17407     * dispatched to this view. The callback will be invoked before the hover
17408     * event is given to the view.
17409     */
17410    public interface OnHoverListener {
17411        /**
17412         * Called when a hover event is dispatched to a view. This allows listeners to
17413         * get a chance to respond before the target view.
17414         *
17415         * @param v The view the hover event has been dispatched to.
17416         * @param event The MotionEvent object containing full information about
17417         *        the event.
17418         * @return True if the listener has consumed the event, false otherwise.
17419         */
17420        boolean onHover(View v, MotionEvent event);
17421    }
17422
17423    /**
17424     * Interface definition for a callback to be invoked when a generic motion event is
17425     * dispatched to this view. The callback will be invoked before the generic motion
17426     * event is given to the view.
17427     */
17428    public interface OnGenericMotionListener {
17429        /**
17430         * Called when a generic motion event is dispatched to a view. This allows listeners to
17431         * get a chance to respond before the target view.
17432         *
17433         * @param v The view the generic motion event has been dispatched to.
17434         * @param event The MotionEvent object containing full information about
17435         *        the event.
17436         * @return True if the listener has consumed the event, false otherwise.
17437         */
17438        boolean onGenericMotion(View v, MotionEvent event);
17439    }
17440
17441    /**
17442     * Interface definition for a callback to be invoked when a view has been clicked and held.
17443     */
17444    public interface OnLongClickListener {
17445        /**
17446         * Called when a view has been clicked and held.
17447         *
17448         * @param v The view that was clicked and held.
17449         *
17450         * @return true if the callback consumed the long click, false otherwise.
17451         */
17452        boolean onLongClick(View v);
17453    }
17454
17455    /**
17456     * Interface definition for a callback to be invoked when a drag is being dispatched
17457     * to this view.  The callback will be invoked before the hosting view's own
17458     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17459     * onDrag(event) behavior, it should return 'false' from this callback.
17460     *
17461     * <div class="special reference">
17462     * <h3>Developer Guides</h3>
17463     * <p>For a guide to implementing drag and drop features, read the
17464     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17465     * </div>
17466     */
17467    public interface OnDragListener {
17468        /**
17469         * Called when a drag event is dispatched to a view. This allows listeners
17470         * to get a chance to override base View behavior.
17471         *
17472         * @param v The View that received the drag event.
17473         * @param event The {@link android.view.DragEvent} object for the drag event.
17474         * @return {@code true} if the drag event was handled successfully, or {@code false}
17475         * if the drag event was not handled. Note that {@code false} will trigger the View
17476         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17477         */
17478        boolean onDrag(View v, DragEvent event);
17479    }
17480
17481    /**
17482     * Interface definition for a callback to be invoked when the focus state of
17483     * a view changed.
17484     */
17485    public interface OnFocusChangeListener {
17486        /**
17487         * Called when the focus state of a view has changed.
17488         *
17489         * @param v The view whose state has changed.
17490         * @param hasFocus The new focus state of v.
17491         */
17492        void onFocusChange(View v, boolean hasFocus);
17493    }
17494
17495    /**
17496     * Interface definition for a callback to be invoked when a view is clicked.
17497     */
17498    public interface OnClickListener {
17499        /**
17500         * Called when a view has been clicked.
17501         *
17502         * @param v The view that was clicked.
17503         */
17504        void onClick(View v);
17505    }
17506
17507    /**
17508     * Interface definition for a callback to be invoked when the context menu
17509     * for this view is being built.
17510     */
17511    public interface OnCreateContextMenuListener {
17512        /**
17513         * Called when the context menu for this view is being built. It is not
17514         * safe to hold onto the menu after this method returns.
17515         *
17516         * @param menu The context menu that is being built
17517         * @param v The view for which the context menu is being built
17518         * @param menuInfo Extra information about the item for which the
17519         *            context menu should be shown. This information will vary
17520         *            depending on the class of v.
17521         */
17522        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17523    }
17524
17525    /**
17526     * Interface definition for a callback to be invoked when the status bar changes
17527     * visibility.  This reports <strong>global</strong> changes to the system UI
17528     * state, not what the application is requesting.
17529     *
17530     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17531     */
17532    public interface OnSystemUiVisibilityChangeListener {
17533        /**
17534         * Called when the status bar changes visibility because of a call to
17535         * {@link View#setSystemUiVisibility(int)}.
17536         *
17537         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17538         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17539         * This tells you the <strong>global</strong> state of these UI visibility
17540         * flags, not what your app is currently applying.
17541         */
17542        public void onSystemUiVisibilityChange(int visibility);
17543    }
17544
17545    /**
17546     * Interface definition for a callback to be invoked when this view is attached
17547     * or detached from its window.
17548     */
17549    public interface OnAttachStateChangeListener {
17550        /**
17551         * Called when the view is attached to a window.
17552         * @param v The view that was attached
17553         */
17554        public void onViewAttachedToWindow(View v);
17555        /**
17556         * Called when the view is detached from a window.
17557         * @param v The view that was detached
17558         */
17559        public void onViewDetachedFromWindow(View v);
17560    }
17561
17562    private final class UnsetPressedState implements Runnable {
17563        public void run() {
17564            setPressed(false);
17565        }
17566    }
17567
17568    /**
17569     * Base class for derived classes that want to save and restore their own
17570     * state in {@link android.view.View#onSaveInstanceState()}.
17571     */
17572    public static class BaseSavedState extends AbsSavedState {
17573        /**
17574         * Constructor used when reading from a parcel. Reads the state of the superclass.
17575         *
17576         * @param source
17577         */
17578        public BaseSavedState(Parcel source) {
17579            super(source);
17580        }
17581
17582        /**
17583         * Constructor called by derived classes when creating their SavedState objects
17584         *
17585         * @param superState The state of the superclass of this view
17586         */
17587        public BaseSavedState(Parcelable superState) {
17588            super(superState);
17589        }
17590
17591        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17592                new Parcelable.Creator<BaseSavedState>() {
17593            public BaseSavedState createFromParcel(Parcel in) {
17594                return new BaseSavedState(in);
17595            }
17596
17597            public BaseSavedState[] newArray(int size) {
17598                return new BaseSavedState[size];
17599            }
17600        };
17601    }
17602
17603    /**
17604     * A set of information given to a view when it is attached to its parent
17605     * window.
17606     */
17607    static class AttachInfo {
17608        interface Callbacks {
17609            void playSoundEffect(int effectId);
17610            boolean performHapticFeedback(int effectId, boolean always);
17611        }
17612
17613        /**
17614         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17615         * to a Handler. This class contains the target (View) to invalidate and
17616         * the coordinates of the dirty rectangle.
17617         *
17618         * For performance purposes, this class also implements a pool of up to
17619         * POOL_LIMIT objects that get reused. This reduces memory allocations
17620         * whenever possible.
17621         */
17622        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17623            private static final int POOL_LIMIT = 10;
17624            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17625                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17626                        public InvalidateInfo newInstance() {
17627                            return new InvalidateInfo();
17628                        }
17629
17630                        public void onAcquired(InvalidateInfo element) {
17631                        }
17632
17633                        public void onReleased(InvalidateInfo element) {
17634                            element.target = null;
17635                        }
17636                    }, POOL_LIMIT)
17637            );
17638
17639            private InvalidateInfo mNext;
17640            private boolean mIsPooled;
17641
17642            View target;
17643
17644            int left;
17645            int top;
17646            int right;
17647            int bottom;
17648
17649            public void setNextPoolable(InvalidateInfo element) {
17650                mNext = element;
17651            }
17652
17653            public InvalidateInfo getNextPoolable() {
17654                return mNext;
17655            }
17656
17657            static InvalidateInfo acquire() {
17658                return sPool.acquire();
17659            }
17660
17661            void release() {
17662                sPool.release(this);
17663            }
17664
17665            public boolean isPooled() {
17666                return mIsPooled;
17667            }
17668
17669            public void setPooled(boolean isPooled) {
17670                mIsPooled = isPooled;
17671            }
17672        }
17673
17674        final IWindowSession mSession;
17675
17676        final IWindow mWindow;
17677
17678        final IBinder mWindowToken;
17679
17680        final Display mDisplay;
17681
17682        final Callbacks mRootCallbacks;
17683
17684        HardwareCanvas mHardwareCanvas;
17685
17686        /**
17687         * The top view of the hierarchy.
17688         */
17689        View mRootView;
17690
17691        IBinder mPanelParentWindowToken;
17692        Surface mSurface;
17693
17694        boolean mHardwareAccelerated;
17695        boolean mHardwareAccelerationRequested;
17696        HardwareRenderer mHardwareRenderer;
17697
17698        boolean mScreenOn;
17699
17700        /**
17701         * Scale factor used by the compatibility mode
17702         */
17703        float mApplicationScale;
17704
17705        /**
17706         * Indicates whether the application is in compatibility mode
17707         */
17708        boolean mScalingRequired;
17709
17710        /**
17711         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
17712         */
17713        boolean mTurnOffWindowResizeAnim;
17714
17715        /**
17716         * Left position of this view's window
17717         */
17718        int mWindowLeft;
17719
17720        /**
17721         * Top position of this view's window
17722         */
17723        int mWindowTop;
17724
17725        /**
17726         * Indicates whether views need to use 32-bit drawing caches
17727         */
17728        boolean mUse32BitDrawingCache;
17729
17730        /**
17731         * For windows that are full-screen but using insets to layout inside
17732         * of the screen decorations, these are the current insets for the
17733         * content of the window.
17734         */
17735        final Rect mContentInsets = new Rect();
17736
17737        /**
17738         * For windows that are full-screen but using insets to layout inside
17739         * of the screen decorations, these are the current insets for the
17740         * actual visible parts of the window.
17741         */
17742        final Rect mVisibleInsets = new Rect();
17743
17744        /**
17745         * The internal insets given by this window.  This value is
17746         * supplied by the client (through
17747         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17748         * be given to the window manager when changed to be used in laying
17749         * out windows behind it.
17750         */
17751        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17752                = new ViewTreeObserver.InternalInsetsInfo();
17753
17754        /**
17755         * All views in the window's hierarchy that serve as scroll containers,
17756         * used to determine if the window can be resized or must be panned
17757         * to adjust for a soft input area.
17758         */
17759        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17760
17761        final KeyEvent.DispatcherState mKeyDispatchState
17762                = new KeyEvent.DispatcherState();
17763
17764        /**
17765         * Indicates whether the view's window currently has the focus.
17766         */
17767        boolean mHasWindowFocus;
17768
17769        /**
17770         * The current visibility of the window.
17771         */
17772        int mWindowVisibility;
17773
17774        /**
17775         * Indicates the time at which drawing started to occur.
17776         */
17777        long mDrawingTime;
17778
17779        /**
17780         * Indicates whether or not ignoring the DIRTY_MASK flags.
17781         */
17782        boolean mIgnoreDirtyState;
17783
17784        /**
17785         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17786         * to avoid clearing that flag prematurely.
17787         */
17788        boolean mSetIgnoreDirtyState = false;
17789
17790        /**
17791         * Indicates whether the view's window is currently in touch mode.
17792         */
17793        boolean mInTouchMode;
17794
17795        /**
17796         * Indicates that ViewAncestor should trigger a global layout change
17797         * the next time it performs a traversal
17798         */
17799        boolean mRecomputeGlobalAttributes;
17800
17801        /**
17802         * Always report new attributes at next traversal.
17803         */
17804        boolean mForceReportNewAttributes;
17805
17806        /**
17807         * Set during a traveral if any views want to keep the screen on.
17808         */
17809        boolean mKeepScreenOn;
17810
17811        /**
17812         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17813         */
17814        int mSystemUiVisibility;
17815
17816        /**
17817         * Hack to force certain system UI visibility flags to be cleared.
17818         */
17819        int mDisabledSystemUiVisibility;
17820
17821        /**
17822         * Last global system UI visibility reported by the window manager.
17823         */
17824        int mGlobalSystemUiVisibility;
17825
17826        /**
17827         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17828         * attached.
17829         */
17830        boolean mHasSystemUiListeners;
17831
17832        /**
17833         * Set if the visibility of any views has changed.
17834         */
17835        boolean mViewVisibilityChanged;
17836
17837        /**
17838         * Set to true if a view has been scrolled.
17839         */
17840        boolean mViewScrollChanged;
17841
17842        /**
17843         * Global to the view hierarchy used as a temporary for dealing with
17844         * x/y points in the transparent region computations.
17845         */
17846        final int[] mTransparentLocation = new int[2];
17847
17848        /**
17849         * Global to the view hierarchy used as a temporary for dealing with
17850         * x/y points in the ViewGroup.invalidateChild implementation.
17851         */
17852        final int[] mInvalidateChildLocation = new int[2];
17853
17854
17855        /**
17856         * Global to the view hierarchy used as a temporary for dealing with
17857         * x/y location when view is transformed.
17858         */
17859        final float[] mTmpTransformLocation = new float[2];
17860
17861        /**
17862         * The view tree observer used to dispatch global events like
17863         * layout, pre-draw, touch mode change, etc.
17864         */
17865        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17866
17867        /**
17868         * A Canvas used by the view hierarchy to perform bitmap caching.
17869         */
17870        Canvas mCanvas;
17871
17872        /**
17873         * The view root impl.
17874         */
17875        final ViewRootImpl mViewRootImpl;
17876
17877        /**
17878         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17879         * handler can be used to pump events in the UI events queue.
17880         */
17881        final Handler mHandler;
17882
17883        /**
17884         * Temporary for use in computing invalidate rectangles while
17885         * calling up the hierarchy.
17886         */
17887        final Rect mTmpInvalRect = new Rect();
17888
17889        /**
17890         * Temporary for use in computing hit areas with transformed views
17891         */
17892        final RectF mTmpTransformRect = new RectF();
17893
17894        /**
17895         * Temporary for use in transforming invalidation rect
17896         */
17897        final Matrix mTmpMatrix = new Matrix();
17898
17899        /**
17900         * Temporary for use in transforming invalidation rect
17901         */
17902        final Transformation mTmpTransformation = new Transformation();
17903
17904        /**
17905         * Temporary list for use in collecting focusable descendents of a view.
17906         */
17907        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17908
17909        /**
17910         * The id of the window for accessibility purposes.
17911         */
17912        int mAccessibilityWindowId = View.NO_ID;
17913
17914        /**
17915         * Whether to ingore not exposed for accessibility Views when
17916         * reporting the view tree to accessibility services.
17917         */
17918        boolean mIncludeNotImportantViews;
17919
17920        /**
17921         * The drawable for highlighting accessibility focus.
17922         */
17923        Drawable mAccessibilityFocusDrawable;
17924
17925        /**
17926         * Show where the margins, bounds and layout bounds are for each view.
17927         */
17928        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17929
17930        /**
17931         * Point used to compute visible regions.
17932         */
17933        final Point mPoint = new Point();
17934
17935        /**
17936         * Creates a new set of attachment information with the specified
17937         * events handler and thread.
17938         *
17939         * @param handler the events handler the view must use
17940         */
17941        AttachInfo(IWindowSession session, IWindow window, Display display,
17942                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17943            mSession = session;
17944            mWindow = window;
17945            mWindowToken = window.asBinder();
17946            mDisplay = display;
17947            mViewRootImpl = viewRootImpl;
17948            mHandler = handler;
17949            mRootCallbacks = effectPlayer;
17950        }
17951    }
17952
17953    /**
17954     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17955     * is supported. This avoids keeping too many unused fields in most
17956     * instances of View.</p>
17957     */
17958    private static class ScrollabilityCache implements Runnable {
17959
17960        /**
17961         * Scrollbars are not visible
17962         */
17963        public static final int OFF = 0;
17964
17965        /**
17966         * Scrollbars are visible
17967         */
17968        public static final int ON = 1;
17969
17970        /**
17971         * Scrollbars are fading away
17972         */
17973        public static final int FADING = 2;
17974
17975        public boolean fadeScrollBars;
17976
17977        public int fadingEdgeLength;
17978        public int scrollBarDefaultDelayBeforeFade;
17979        public int scrollBarFadeDuration;
17980
17981        public int scrollBarSize;
17982        public ScrollBarDrawable scrollBar;
17983        public float[] interpolatorValues;
17984        public View host;
17985
17986        public final Paint paint;
17987        public final Matrix matrix;
17988        public Shader shader;
17989
17990        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17991
17992        private static final float[] OPAQUE = { 255 };
17993        private static final float[] TRANSPARENT = { 0.0f };
17994
17995        /**
17996         * When fading should start. This time moves into the future every time
17997         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17998         */
17999        public long fadeStartTime;
18000
18001
18002        /**
18003         * The current state of the scrollbars: ON, OFF, or FADING
18004         */
18005        public int state = OFF;
18006
18007        private int mLastColor;
18008
18009        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18010            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18011            scrollBarSize = configuration.getScaledScrollBarSize();
18012            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18013            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18014
18015            paint = new Paint();
18016            matrix = new Matrix();
18017            // use use a height of 1, and then wack the matrix each time we
18018            // actually use it.
18019            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18020            paint.setShader(shader);
18021            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18022
18023            this.host = host;
18024        }
18025
18026        public void setFadeColor(int color) {
18027            if (color != mLastColor) {
18028                mLastColor = color;
18029
18030                if (color != 0) {
18031                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18032                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18033                    paint.setShader(shader);
18034                    // Restore the default transfer mode (src_over)
18035                    paint.setXfermode(null);
18036                } else {
18037                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18038                    paint.setShader(shader);
18039                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18040                }
18041            }
18042        }
18043
18044        public void run() {
18045            long now = AnimationUtils.currentAnimationTimeMillis();
18046            if (now >= fadeStartTime) {
18047
18048                // the animation fades the scrollbars out by changing
18049                // the opacity (alpha) from fully opaque to fully
18050                // transparent
18051                int nextFrame = (int) now;
18052                int framesCount = 0;
18053
18054                Interpolator interpolator = scrollBarInterpolator;
18055
18056                // Start opaque
18057                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18058
18059                // End transparent
18060                nextFrame += scrollBarFadeDuration;
18061                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18062
18063                state = FADING;
18064
18065                // Kick off the fade animation
18066                host.invalidate(true);
18067            }
18068        }
18069    }
18070
18071    /**
18072     * Resuable callback for sending
18073     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18074     */
18075    private class SendViewScrolledAccessibilityEvent implements Runnable {
18076        public volatile boolean mIsPending;
18077
18078        public void run() {
18079            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18080            mIsPending = false;
18081        }
18082    }
18083
18084    /**
18085     * <p>
18086     * This class represents a delegate that can be registered in a {@link View}
18087     * to enhance accessibility support via composition rather via inheritance.
18088     * It is specifically targeted to widget developers that extend basic View
18089     * classes i.e. classes in package android.view, that would like their
18090     * applications to be backwards compatible.
18091     * </p>
18092     * <div class="special reference">
18093     * <h3>Developer Guides</h3>
18094     * <p>For more information about making applications accessible, read the
18095     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18096     * developer guide.</p>
18097     * </div>
18098     * <p>
18099     * A scenario in which a developer would like to use an accessibility delegate
18100     * is overriding a method introduced in a later API version then the minimal API
18101     * version supported by the application. For example, the method
18102     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18103     * in API version 4 when the accessibility APIs were first introduced. If a
18104     * developer would like his application to run on API version 4 devices (assuming
18105     * all other APIs used by the application are version 4 or lower) and take advantage
18106     * of this method, instead of overriding the method which would break the application's
18107     * backwards compatibility, he can override the corresponding method in this
18108     * delegate and register the delegate in the target View if the API version of
18109     * the system is high enough i.e. the API version is same or higher to the API
18110     * version that introduced
18111     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18112     * </p>
18113     * <p>
18114     * Here is an example implementation:
18115     * </p>
18116     * <code><pre><p>
18117     * if (Build.VERSION.SDK_INT >= 14) {
18118     *     // If the API version is equal of higher than the version in
18119     *     // which onInitializeAccessibilityNodeInfo was introduced we
18120     *     // register a delegate with a customized implementation.
18121     *     View view = findViewById(R.id.view_id);
18122     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18123     *         public void onInitializeAccessibilityNodeInfo(View host,
18124     *                 AccessibilityNodeInfo info) {
18125     *             // Let the default implementation populate the info.
18126     *             super.onInitializeAccessibilityNodeInfo(host, info);
18127     *             // Set some other information.
18128     *             info.setEnabled(host.isEnabled());
18129     *         }
18130     *     });
18131     * }
18132     * </code></pre></p>
18133     * <p>
18134     * This delegate contains methods that correspond to the accessibility methods
18135     * in View. If a delegate has been specified the implementation in View hands
18136     * off handling to the corresponding method in this delegate. The default
18137     * implementation the delegate methods behaves exactly as the corresponding
18138     * method in View for the case of no accessibility delegate been set. Hence,
18139     * to customize the behavior of a View method, clients can override only the
18140     * corresponding delegate method without altering the behavior of the rest
18141     * accessibility related methods of the host view.
18142     * </p>
18143     */
18144    public static class AccessibilityDelegate {
18145
18146        /**
18147         * Sends an accessibility event of the given type. If accessibility is not
18148         * enabled this method has no effect.
18149         * <p>
18150         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18151         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18152         * been set.
18153         * </p>
18154         *
18155         * @param host The View hosting the delegate.
18156         * @param eventType The type of the event to send.
18157         *
18158         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18159         */
18160        public void sendAccessibilityEvent(View host, int eventType) {
18161            host.sendAccessibilityEventInternal(eventType);
18162        }
18163
18164        /**
18165         * Performs the specified accessibility action on the view. For
18166         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18167         * <p>
18168         * The default implementation behaves as
18169         * {@link View#performAccessibilityAction(int, Bundle)
18170         *  View#performAccessibilityAction(int, Bundle)} for the case of
18171         *  no accessibility delegate been set.
18172         * </p>
18173         *
18174         * @param action The action to perform.
18175         * @return Whether the action was performed.
18176         *
18177         * @see View#performAccessibilityAction(int, Bundle)
18178         *      View#performAccessibilityAction(int, Bundle)
18179         */
18180        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18181            return host.performAccessibilityActionInternal(action, args);
18182        }
18183
18184        /**
18185         * Sends an accessibility event. This method behaves exactly as
18186         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18187         * empty {@link AccessibilityEvent} and does not perform a check whether
18188         * accessibility is enabled.
18189         * <p>
18190         * The default implementation behaves as
18191         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18192         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18193         * the case of no accessibility delegate been set.
18194         * </p>
18195         *
18196         * @param host The View hosting the delegate.
18197         * @param event The event to send.
18198         *
18199         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18200         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18201         */
18202        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18203            host.sendAccessibilityEventUncheckedInternal(event);
18204        }
18205
18206        /**
18207         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18208         * to its children for adding their text content to the event.
18209         * <p>
18210         * The default implementation behaves as
18211         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18212         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18213         * the case of no accessibility delegate been set.
18214         * </p>
18215         *
18216         * @param host The View hosting the delegate.
18217         * @param event The event.
18218         * @return True if the event population was completed.
18219         *
18220         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18221         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18222         */
18223        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18224            return host.dispatchPopulateAccessibilityEventInternal(event);
18225        }
18226
18227        /**
18228         * Gives a chance to the host View to populate the accessibility event with its
18229         * text content.
18230         * <p>
18231         * The default implementation behaves as
18232         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18233         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18234         * the case of no accessibility delegate been set.
18235         * </p>
18236         *
18237         * @param host The View hosting the delegate.
18238         * @param event The accessibility event which to populate.
18239         *
18240         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18241         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18242         */
18243        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18244            host.onPopulateAccessibilityEventInternal(event);
18245        }
18246
18247        /**
18248         * Initializes an {@link AccessibilityEvent} with information about the
18249         * the host View which is the event source.
18250         * <p>
18251         * The default implementation behaves as
18252         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18253         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18254         * the case of no accessibility delegate been set.
18255         * </p>
18256         *
18257         * @param host The View hosting the delegate.
18258         * @param event The event to initialize.
18259         *
18260         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18261         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18262         */
18263        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18264            host.onInitializeAccessibilityEventInternal(event);
18265        }
18266
18267        /**
18268         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18269         * <p>
18270         * The default implementation behaves as
18271         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18272         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18273         * the case of no accessibility delegate been set.
18274         * </p>
18275         *
18276         * @param host The View hosting the delegate.
18277         * @param info The instance to initialize.
18278         *
18279         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18280         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18281         */
18282        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18283            host.onInitializeAccessibilityNodeInfoInternal(info);
18284        }
18285
18286        /**
18287         * Called when a child of the host View has requested sending an
18288         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18289         * to augment the event.
18290         * <p>
18291         * The default implementation behaves as
18292         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18293         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18294         * the case of no accessibility delegate been set.
18295         * </p>
18296         *
18297         * @param host The View hosting the delegate.
18298         * @param child The child which requests sending the event.
18299         * @param event The event to be sent.
18300         * @return True if the event should be sent
18301         *
18302         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18303         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18304         */
18305        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18306                AccessibilityEvent event) {
18307            return host.onRequestSendAccessibilityEventInternal(child, event);
18308        }
18309
18310        /**
18311         * Gets the provider for managing a virtual view hierarchy rooted at this View
18312         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18313         * that explore the window content.
18314         * <p>
18315         * The default implementation behaves as
18316         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18317         * the case of no accessibility delegate been set.
18318         * </p>
18319         *
18320         * @return The provider.
18321         *
18322         * @see AccessibilityNodeProvider
18323         */
18324        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18325            return null;
18326        }
18327    }
18328
18329    private class MatchIdPredicate implements Predicate<View> {
18330        public int mId;
18331
18332        @Override
18333        public boolean apply(View view) {
18334            return (view.mID == mId);
18335        }
18336    }
18337
18338    private class MatchLabelForPredicate implements Predicate<View> {
18339        private int mLabeledId;
18340
18341        @Override
18342        public boolean apply(View view) {
18343            return (view.mLabelForId == mLabeledId);
18344        }
18345    }
18346
18347    /**
18348     * Dump all private flags in readable format, useful for documentation and
18349     * sanity checking.
18350     */
18351    private static void dumpFlags() {
18352        final HashMap<String, String> found = Maps.newHashMap();
18353        try {
18354            for (Field field : View.class.getDeclaredFields()) {
18355                final int modifiers = field.getModifiers();
18356                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18357                    if (field.getType().equals(int.class)) {
18358                        final int value = field.getInt(null);
18359                        dumpFlag(found, field.getName(), value);
18360                    } else if (field.getType().equals(int[].class)) {
18361                        final int[] values = (int[]) field.get(null);
18362                        for (int i = 0; i < values.length; i++) {
18363                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18364                        }
18365                    }
18366                }
18367            }
18368        } catch (IllegalAccessException e) {
18369            throw new RuntimeException(e);
18370        }
18371
18372        final ArrayList<String> keys = Lists.newArrayList();
18373        keys.addAll(found.keySet());
18374        Collections.sort(keys);
18375        for (String key : keys) {
18376            Log.d(VIEW_LOG_TAG, found.get(key));
18377        }
18378    }
18379
18380    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18381        // Sort flags by prefix, then by bits, always keeping unique keys
18382        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18383        final int prefix = name.indexOf('_');
18384        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18385        final String output = bits + " " + name;
18386        found.put(key, output);
18387    }
18388}
18389