View.java revision dd671599bed9d3ca28e2c744e8c224e1e15bc914
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.Build;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Parcel;
48import android.os.Parcelable;
49import android.os.RemoteException;
50import android.os.SystemClock;
51import android.os.SystemProperties;
52import android.text.TextUtils;
53import android.util.AttributeSet;
54import android.util.FloatProperty;
55import android.util.Log;
56import android.util.Pools.SynchronizedPool;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.AccessibilityIterators.TextSegmentIterator;
62import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
63import android.view.AccessibilityIterators.WordTextSegmentIterator;
64import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
65import android.view.accessibility.AccessibilityEvent;
66import android.view.accessibility.AccessibilityEventSource;
67import android.view.accessibility.AccessibilityManager;
68import android.view.accessibility.AccessibilityNodeInfo;
69import android.view.accessibility.AccessibilityNodeProvider;
70import android.view.animation.Animation;
71import android.view.animation.AnimationUtils;
72import android.view.animation.Transformation;
73import android.view.inputmethod.EditorInfo;
74import android.view.inputmethod.InputConnection;
75import android.view.inputmethod.InputMethodManager;
76import android.widget.ScrollBarDrawable;
77
78import static android.os.Build.VERSION_CODES.*;
79import static java.lang.Math.max;
80
81import com.android.internal.R;
82import com.android.internal.util.Predicate;
83import com.android.internal.view.menu.MenuBuilder;
84import com.google.android.collect.Lists;
85import com.google.android.collect.Maps;
86
87import java.lang.ref.WeakReference;
88import java.lang.reflect.Field;
89import java.lang.reflect.InvocationTargetException;
90import java.lang.reflect.Method;
91import java.lang.reflect.Modifier;
92import java.util.ArrayList;
93import java.util.Arrays;
94import java.util.Collections;
95import java.util.HashMap;
96import java.util.Locale;
97import java.util.concurrent.CopyOnWriteArrayList;
98import java.util.concurrent.atomic.AtomicInteger;
99
100/**
101 * <p>
102 * This class represents the basic building block for user interface components. A View
103 * occupies a rectangular area on the screen and is responsible for drawing and
104 * event handling. View is the base class for <em>widgets</em>, which are
105 * used to create interactive UI components (buttons, text fields, etc.). The
106 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
107 * are invisible containers that hold other Views (or other ViewGroups) and define
108 * their layout properties.
109 * </p>
110 *
111 * <div class="special reference">
112 * <h3>Developer Guides</h3>
113 * <p>For information about using this class to develop your application's user interface,
114 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
115 * </div>
116 *
117 * <a name="Using"></a>
118 * <h3>Using Views</h3>
119 * <p>
120 * All of the views in a window are arranged in a single tree. You can add views
121 * either from code or by specifying a tree of views in one or more XML layout
122 * files. There are many specialized subclasses of views that act as controls or
123 * are capable of displaying text, images, or other content.
124 * </p>
125 * <p>
126 * Once you have created a tree of views, there are typically a few types of
127 * common operations you may wish to perform:
128 * <ul>
129 * <li><strong>Set properties:</strong> for example setting the text of a
130 * {@link android.widget.TextView}. The available properties and the methods
131 * that set them will vary among the different subclasses of views. Note that
132 * properties that are known at build time can be set in the XML layout
133 * files.</li>
134 * <li><strong>Set focus:</strong> The framework will handled moving focus in
135 * response to user input. To force focus to a specific view, call
136 * {@link #requestFocus}.</li>
137 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
138 * that will be notified when something interesting happens to the view. For
139 * example, all views will let you set a listener to be notified when the view
140 * gains or loses focus. You can register such a listener using
141 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
142 * Other view subclasses offer more specialized listeners. For example, a Button
143 * exposes a listener to notify clients when the button is clicked.</li>
144 * <li><strong>Set visibility:</strong> You can hide or show views using
145 * {@link #setVisibility(int)}.</li>
146 * </ul>
147 * </p>
148 * <p><em>
149 * Note: The Android framework is responsible for measuring, laying out and
150 * drawing views. You should not call methods that perform these actions on
151 * views yourself unless you are actually implementing a
152 * {@link android.view.ViewGroup}.
153 * </em></p>
154 *
155 * <a name="Lifecycle"></a>
156 * <h3>Implementing a Custom View</h3>
157 *
158 * <p>
159 * To implement a custom view, you will usually begin by providing overrides for
160 * some of the standard methods that the framework calls on all views. You do
161 * not need to override all of these methods. In fact, you can start by just
162 * overriding {@link #onDraw(android.graphics.Canvas)}.
163 * <table border="2" width="85%" align="center" cellpadding="5">
164 *     <thead>
165 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
166 *     </thead>
167 *
168 *     <tbody>
169 *     <tr>
170 *         <td rowspan="2">Creation</td>
171 *         <td>Constructors</td>
172 *         <td>There is a form of the constructor that are called when the view
173 *         is created from code and a form that is called when the view is
174 *         inflated from a layout file. The second form should parse and apply
175 *         any attributes defined in the layout file.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onFinishInflate()}</code></td>
180 *         <td>Called after a view and all of its children has been inflated
181 *         from XML.</td>
182 *     </tr>
183 *
184 *     <tr>
185 *         <td rowspan="3">Layout</td>
186 *         <td><code>{@link #onMeasure(int, int)}</code></td>
187 *         <td>Called to determine the size requirements for this view and all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
193 *         <td>Called when this view should assign a size and position to all
194 *         of its children.
195 *         </td>
196 *     </tr>
197 *     <tr>
198 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
199 *         <td>Called when the size of this view has changed.
200 *         </td>
201 *     </tr>
202 *
203 *     <tr>
204 *         <td>Drawing</td>
205 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
206 *         <td>Called when the view should render its content.
207 *         </td>
208 *     </tr>
209 *
210 *     <tr>
211 *         <td rowspan="4">Event processing</td>
212 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
213 *         <td>Called when a new hardware key event occurs.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
218 *         <td>Called when a hardware key up event occurs.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
223 *         <td>Called when a trackball motion event occurs.
224 *         </td>
225 *     </tr>
226 *     <tr>
227 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
228 *         <td>Called when a touch screen motion event occurs.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="2">Focus</td>
234 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
235 *         <td>Called when the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
241 *         <td>Called when the window containing the view gains or loses focus.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="3">Attaching</td>
247 *         <td><code>{@link #onAttachedToWindow()}</code></td>
248 *         <td>Called when the view is attached to a window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onDetachedFromWindow}</code></td>
254 *         <td>Called when the view is detached from its window.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
260 *         <td>Called when the visibility of the window containing the view
261 *         has changed.
262 *         </td>
263 *     </tr>
264 *     </tbody>
265 *
266 * </table>
267 * </p>
268 *
269 * <a name="IDs"></a>
270 * <h3>IDs</h3>
271 * Views may have an integer id associated with them. These ids are typically
272 * assigned in the layout XML files, and are used to find specific views within
273 * the view tree. A common pattern is to:
274 * <ul>
275 * <li>Define a Button in the layout file and assign it a unique ID.
276 * <pre>
277 * &lt;Button
278 *     android:id="@+id/my_button"
279 *     android:layout_width="wrap_content"
280 *     android:layout_height="wrap_content"
281 *     android:text="@string/my_button_text"/&gt;
282 * </pre></li>
283 * <li>From the onCreate method of an Activity, find the Button
284 * <pre class="prettyprint">
285 *      Button myButton = (Button) findViewById(R.id.my_button);
286 * </pre></li>
287 * </ul>
288 * <p>
289 * View IDs need not be unique throughout the tree, but it is good practice to
290 * ensure that they are at least unique within the part of the tree you are
291 * searching.
292 * </p>
293 *
294 * <a name="Position"></a>
295 * <h3>Position</h3>
296 * <p>
297 * The geometry of a view is that of a rectangle. A view has a location,
298 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
299 * two dimensions, expressed as a width and a height. The unit for location
300 * and dimensions is the pixel.
301 * </p>
302 *
303 * <p>
304 * It is possible to retrieve the location of a view by invoking the methods
305 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
306 * coordinate of the rectangle representing the view. The latter returns the
307 * top, or Y, coordinate of the rectangle representing the view. These methods
308 * both return the location of the view relative to its parent. For instance,
309 * when getLeft() returns 20, that means the view is located 20 pixels to the
310 * right of the left edge of its direct parent.
311 * </p>
312 *
313 * <p>
314 * In addition, several convenience methods are offered to avoid unnecessary
315 * computations, namely {@link #getRight()} and {@link #getBottom()}.
316 * These methods return the coordinates of the right and bottom edges of the
317 * rectangle representing the view. For instance, calling {@link #getRight()}
318 * is similar to the following computation: <code>getLeft() + getWidth()</code>
319 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
320 * </p>
321 *
322 * <a name="SizePaddingMargins"></a>
323 * <h3>Size, padding and margins</h3>
324 * <p>
325 * The size of a view is expressed with a width and a height. A view actually
326 * possess two pairs of width and height values.
327 * </p>
328 *
329 * <p>
330 * The first pair is known as <em>measured width</em> and
331 * <em>measured height</em>. These dimensions define how big a view wants to be
332 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
333 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
334 * and {@link #getMeasuredHeight()}.
335 * </p>
336 *
337 * <p>
338 * The second pair is simply known as <em>width</em> and <em>height</em>, or
339 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
340 * dimensions define the actual size of the view on screen, at drawing time and
341 * after layout. These values may, but do not have to, be different from the
342 * measured width and height. The width and height can be obtained by calling
343 * {@link #getWidth()} and {@link #getHeight()}.
344 * </p>
345 *
346 * <p>
347 * To measure its dimensions, a view takes into account its padding. The padding
348 * is expressed in pixels for the left, top, right and bottom parts of the view.
349 * Padding can be used to offset the content of the view by a specific amount of
350 * pixels. For instance, a left padding of 2 will push the view's content by
351 * 2 pixels to the right of the left edge. Padding can be set using the
352 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
353 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
354 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
355 * {@link #getPaddingEnd()}.
356 * </p>
357 *
358 * <p>
359 * Even though a view can define a padding, it does not provide any support for
360 * margins. However, view groups provide such a support. Refer to
361 * {@link android.view.ViewGroup} and
362 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
363 * </p>
364 *
365 * <a name="Layout"></a>
366 * <h3>Layout</h3>
367 * <p>
368 * Layout is a two pass process: a measure pass and a layout pass. The measuring
369 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
370 * of the view tree. Each view pushes dimension specifications down the tree
371 * during the recursion. At the end of the measure pass, every view has stored
372 * its measurements. The second pass happens in
373 * {@link #layout(int,int,int,int)} and is also top-down. During
374 * this pass each parent is responsible for positioning all of its children
375 * using the sizes computed in the measure pass.
376 * </p>
377 *
378 * <p>
379 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
380 * {@link #getMeasuredHeight()} values must be set, along with those for all of
381 * that view's descendants. A view's measured width and measured height values
382 * must respect the constraints imposed by the view's parents. This guarantees
383 * that at the end of the measure pass, all parents accept all of their
384 * children's measurements. A parent view may call measure() more than once on
385 * its children. For example, the parent may measure each child once with
386 * unspecified dimensions to find out how big they want to be, then call
387 * measure() on them again with actual numbers if the sum of all the children's
388 * unconstrained sizes is too big or too small.
389 * </p>
390 *
391 * <p>
392 * The measure pass uses two classes to communicate dimensions. The
393 * {@link MeasureSpec} class is used by views to tell their parents how they
394 * want to be measured and positioned. The base LayoutParams class just
395 * describes how big the view wants to be for both width and height. For each
396 * dimension, it can specify one of:
397 * <ul>
398 * <li> an exact number
399 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
400 * (minus padding)
401 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
402 * enclose its content (plus padding).
403 * </ul>
404 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
405 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
406 * an X and Y value.
407 * </p>
408 *
409 * <p>
410 * MeasureSpecs are used to push requirements down the tree from parent to
411 * child. A MeasureSpec can be in one of three modes:
412 * <ul>
413 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
414 * of a child view. For example, a LinearLayout may call measure() on its child
415 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
416 * tall the child view wants to be given a width of 240 pixels.
417 * <li>EXACTLY: This is used by the parent to impose an exact size on the
418 * child. The child must use this size, and guarantee that all of its
419 * descendants will fit within this size.
420 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
421 * child. The child must gurantee that it and all of its descendants will fit
422 * within this size.
423 * </ul>
424 * </p>
425 *
426 * <p>
427 * To intiate a layout, call {@link #requestLayout}. This method is typically
428 * called by a view on itself when it believes that is can no longer fit within
429 * its current bounds.
430 * </p>
431 *
432 * <a name="Drawing"></a>
433 * <h3>Drawing</h3>
434 * <p>
435 * Drawing is handled by walking the tree and rendering each view that
436 * intersects the invalid region. Because the tree is traversed in-order,
437 * this means that parents will draw before (i.e., behind) their children, with
438 * siblings drawn in the order they appear in the tree.
439 * If you set a background drawable for a View, then the View will draw it for you
440 * before calling back to its <code>onDraw()</code> method.
441 * </p>
442 *
443 * <p>
444 * Note that the framework will not draw views that are not in the invalid region.
445 * </p>
446 *
447 * <p>
448 * To force a view to draw, call {@link #invalidate()}.
449 * </p>
450 *
451 * <a name="EventHandlingThreading"></a>
452 * <h3>Event Handling and Threading</h3>
453 * <p>
454 * The basic cycle of a view is as follows:
455 * <ol>
456 * <li>An event comes in and is dispatched to the appropriate view. The view
457 * handles the event and notifies any listeners.</li>
458 * <li>If in the course of processing the event, the view's bounds may need
459 * to be changed, the view will call {@link #requestLayout()}.</li>
460 * <li>Similarly, if in the course of processing the event the view's appearance
461 * may need to be changed, the view will call {@link #invalidate()}.</li>
462 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
463 * the framework will take care of measuring, laying out, and drawing the tree
464 * as appropriate.</li>
465 * </ol>
466 * </p>
467 *
468 * <p><em>Note: The entire view tree is single threaded. You must always be on
469 * the UI thread when calling any method on any view.</em>
470 * If you are doing work on other threads and want to update the state of a view
471 * from that thread, you should use a {@link Handler}.
472 * </p>
473 *
474 * <a name="FocusHandling"></a>
475 * <h3>Focus Handling</h3>
476 * <p>
477 * The framework will handle routine focus movement in response to user input.
478 * This includes changing the focus as views are removed or hidden, or as new
479 * views become available. Views indicate their willingness to take focus
480 * through the {@link #isFocusable} method. To change whether a view can take
481 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
482 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
483 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
484 * </p>
485 * <p>
486 * Focus movement is based on an algorithm which finds the nearest neighbor in a
487 * given direction. In rare cases, the default algorithm may not match the
488 * intended behavior of the developer. In these situations, you can provide
489 * explicit overrides by using these XML attributes in the layout file:
490 * <pre>
491 * nextFocusDown
492 * nextFocusLeft
493 * nextFocusRight
494 * nextFocusUp
495 * </pre>
496 * </p>
497 *
498 *
499 * <p>
500 * To get a particular view to take focus, call {@link #requestFocus()}.
501 * </p>
502 *
503 * <a name="TouchMode"></a>
504 * <h3>Touch Mode</h3>
505 * <p>
506 * When a user is navigating a user interface via directional keys such as a D-pad, it is
507 * necessary to give focus to actionable items such as buttons so the user can see
508 * what will take input.  If the device has touch capabilities, however, and the user
509 * begins interacting with the interface by touching it, it is no longer necessary to
510 * always highlight, or give focus to, a particular view.  This motivates a mode
511 * for interaction named 'touch mode'.
512 * </p>
513 * <p>
514 * For a touch capable device, once the user touches the screen, the device
515 * will enter touch mode.  From this point onward, only views for which
516 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
517 * Other views that are touchable, like buttons, will not take focus when touched; they will
518 * only fire the on click listeners.
519 * </p>
520 * <p>
521 * Any time a user hits a directional key, such as a D-pad direction, the view device will
522 * exit touch mode, and find a view to take focus, so that the user may resume interacting
523 * with the user interface without touching the screen again.
524 * </p>
525 * <p>
526 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
527 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
528 * </p>
529 *
530 * <a name="Scrolling"></a>
531 * <h3>Scrolling</h3>
532 * <p>
533 * The framework provides basic support for views that wish to internally
534 * scroll their content. This includes keeping track of the X and Y scroll
535 * offset as well as mechanisms for drawing scrollbars. See
536 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
537 * {@link #awakenScrollBars()} for more details.
538 * </p>
539 *
540 * <a name="Tags"></a>
541 * <h3>Tags</h3>
542 * <p>
543 * Unlike IDs, tags are not used to identify views. Tags are essentially an
544 * extra piece of information that can be associated with a view. They are most
545 * often used as a convenience to store data related to views in the views
546 * themselves rather than by putting them in a separate structure.
547 * </p>
548 *
549 * <a name="Properties"></a>
550 * <h3>Properties</h3>
551 * <p>
552 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
553 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
554 * available both in the {@link Property} form as well as in similarly-named setter/getter
555 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
556 * be used to set persistent state associated with these rendering-related properties on the view.
557 * The properties and methods can also be used in conjunction with
558 * {@link android.animation.Animator Animator}-based animations, described more in the
559 * <a href="#Animation">Animation</a> section.
560 * </p>
561 *
562 * <a name="Animation"></a>
563 * <h3>Animation</h3>
564 * <p>
565 * Starting with Android 3.0, the preferred way of animating views is to use the
566 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
567 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
568 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
569 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
570 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
571 * makes animating these View properties particularly easy and efficient.
572 * </p>
573 * <p>
574 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
575 * You can attach an {@link Animation} object to a view using
576 * {@link #setAnimation(Animation)} or
577 * {@link #startAnimation(Animation)}. The animation can alter the scale,
578 * rotation, translation and alpha of a view over time. If the animation is
579 * attached to a view that has children, the animation will affect the entire
580 * subtree rooted by that node. When an animation is started, the framework will
581 * take care of redrawing the appropriate views until the animation completes.
582 * </p>
583 *
584 * <a name="Security"></a>
585 * <h3>Security</h3>
586 * <p>
587 * Sometimes it is essential that an application be able to verify that an action
588 * is being performed with the full knowledge and consent of the user, such as
589 * granting a permission request, making a purchase or clicking on an advertisement.
590 * Unfortunately, a malicious application could try to spoof the user into
591 * performing these actions, unaware, by concealing the intended purpose of the view.
592 * As a remedy, the framework offers a touch filtering mechanism that can be used to
593 * improve the security of views that provide access to sensitive functionality.
594 * </p><p>
595 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
596 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
597 * will discard touches that are received whenever the view's window is obscured by
598 * another visible window.  As a result, the view will not receive touches whenever a
599 * toast, dialog or other window appears above the view's window.
600 * </p><p>
601 * For more fine-grained control over security, consider overriding the
602 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
603 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
604 * </p>
605 *
606 * @attr ref android.R.styleable#View_alpha
607 * @attr ref android.R.styleable#View_background
608 * @attr ref android.R.styleable#View_clickable
609 * @attr ref android.R.styleable#View_contentDescription
610 * @attr ref android.R.styleable#View_drawingCacheQuality
611 * @attr ref android.R.styleable#View_duplicateParentState
612 * @attr ref android.R.styleable#View_id
613 * @attr ref android.R.styleable#View_requiresFadingEdge
614 * @attr ref android.R.styleable#View_fadeScrollbars
615 * @attr ref android.R.styleable#View_fadingEdgeLength
616 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
617 * @attr ref android.R.styleable#View_fitsSystemWindows
618 * @attr ref android.R.styleable#View_isScrollContainer
619 * @attr ref android.R.styleable#View_focusable
620 * @attr ref android.R.styleable#View_focusableInTouchMode
621 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
622 * @attr ref android.R.styleable#View_keepScreenOn
623 * @attr ref android.R.styleable#View_layerType
624 * @attr ref android.R.styleable#View_layoutDirection
625 * @attr ref android.R.styleable#View_longClickable
626 * @attr ref android.R.styleable#View_minHeight
627 * @attr ref android.R.styleable#View_minWidth
628 * @attr ref android.R.styleable#View_nextFocusDown
629 * @attr ref android.R.styleable#View_nextFocusLeft
630 * @attr ref android.R.styleable#View_nextFocusRight
631 * @attr ref android.R.styleable#View_nextFocusUp
632 * @attr ref android.R.styleable#View_onClick
633 * @attr ref android.R.styleable#View_padding
634 * @attr ref android.R.styleable#View_paddingBottom
635 * @attr ref android.R.styleable#View_paddingLeft
636 * @attr ref android.R.styleable#View_paddingRight
637 * @attr ref android.R.styleable#View_paddingTop
638 * @attr ref android.R.styleable#View_paddingStart
639 * @attr ref android.R.styleable#View_paddingEnd
640 * @attr ref android.R.styleable#View_saveEnabled
641 * @attr ref android.R.styleable#View_rotation
642 * @attr ref android.R.styleable#View_rotationX
643 * @attr ref android.R.styleable#View_rotationY
644 * @attr ref android.R.styleable#View_scaleX
645 * @attr ref android.R.styleable#View_scaleY
646 * @attr ref android.R.styleable#View_scrollX
647 * @attr ref android.R.styleable#View_scrollY
648 * @attr ref android.R.styleable#View_scrollbarSize
649 * @attr ref android.R.styleable#View_scrollbarStyle
650 * @attr ref android.R.styleable#View_scrollbars
651 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
652 * @attr ref android.R.styleable#View_scrollbarFadeDuration
653 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
654 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbVertical
656 * @attr ref android.R.styleable#View_scrollbarTrackVertical
657 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
659 * @attr ref android.R.styleable#View_soundEffectsEnabled
660 * @attr ref android.R.styleable#View_tag
661 * @attr ref android.R.styleable#View_textAlignment
662 * @attr ref android.R.styleable#View_textDirection
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    private static boolean sUseBrokenMakeMeasureSpec = false;
693
694    /**
695     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
696     * calling setFlags.
697     */
698    private static final int NOT_FOCUSABLE = 0x00000000;
699
700    /**
701     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
702     * setFlags.
703     */
704    private static final int FOCUSABLE = 0x00000001;
705
706    /**
707     * Mask for use with setFlags indicating bits used for focus.
708     */
709    private static final int FOCUSABLE_MASK = 0x00000001;
710
711    /**
712     * This view will adjust its padding to fit sytem windows (e.g. status bar)
713     */
714    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
715
716    /**
717     * This view is visible.
718     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int VISIBLE = 0x00000000;
722
723    /**
724     * This view is invisible, but it still takes up space for layout purposes.
725     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
726     * android:visibility}.
727     */
728    public static final int INVISIBLE = 0x00000004;
729
730    /**
731     * This view is invisible, and it doesn't take any space for layout
732     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
733     * android:visibility}.
734     */
735    public static final int GONE = 0x00000008;
736
737    /**
738     * Mask for use with setFlags indicating bits used for visibility.
739     * {@hide}
740     */
741    static final int VISIBILITY_MASK = 0x0000000C;
742
743    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
744
745    /**
746     * This view is enabled. Interpretation varies by subclass.
747     * Use with ENABLED_MASK when calling setFlags.
748     * {@hide}
749     */
750    static final int ENABLED = 0x00000000;
751
752    /**
753     * This view is disabled. Interpretation varies by subclass.
754     * Use with ENABLED_MASK when calling setFlags.
755     * {@hide}
756     */
757    static final int DISABLED = 0x00000020;
758
759   /**
760    * Mask for use with setFlags indicating bits used for indicating whether
761    * this view is enabled
762    * {@hide}
763    */
764    static final int ENABLED_MASK = 0x00000020;
765
766    /**
767     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
768     * called and further optimizations will be performed. It is okay to have
769     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
770     * {@hide}
771     */
772    static final int WILL_NOT_DRAW = 0x00000080;
773
774    /**
775     * Mask for use with setFlags indicating bits used for indicating whether
776     * this view is will draw
777     * {@hide}
778     */
779    static final int DRAW_MASK = 0x00000080;
780
781    /**
782     * <p>This view doesn't show scrollbars.</p>
783     * {@hide}
784     */
785    static final int SCROLLBARS_NONE = 0x00000000;
786
787    /**
788     * <p>This view shows horizontal scrollbars.</p>
789     * {@hide}
790     */
791    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
792
793    /**
794     * <p>This view shows vertical scrollbars.</p>
795     * {@hide}
796     */
797    static final int SCROLLBARS_VERTICAL = 0x00000200;
798
799    /**
800     * <p>Mask for use with setFlags indicating bits used for indicating which
801     * scrollbars are enabled.</p>
802     * {@hide}
803     */
804    static final int SCROLLBARS_MASK = 0x00000300;
805
806    /**
807     * Indicates that the view should filter touches when its window is obscured.
808     * Refer to the class comments for more information about this security feature.
809     * {@hide}
810     */
811    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
812
813    /**
814     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
815     * that they are optional and should be skipped if the window has
816     * requested system UI flags that ignore those insets for layout.
817     */
818    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
819
820    /**
821     * <p>This view doesn't show fading edges.</p>
822     * {@hide}
823     */
824    static final int FADING_EDGE_NONE = 0x00000000;
825
826    /**
827     * <p>This view shows horizontal fading edges.</p>
828     * {@hide}
829     */
830    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
831
832    /**
833     * <p>This view shows vertical fading edges.</p>
834     * {@hide}
835     */
836    static final int FADING_EDGE_VERTICAL = 0x00002000;
837
838    /**
839     * <p>Mask for use with setFlags indicating bits used for indicating which
840     * fading edges are enabled.</p>
841     * {@hide}
842     */
843    static final int FADING_EDGE_MASK = 0x00003000;
844
845    /**
846     * <p>Indicates this view can be clicked. When clickable, a View reacts
847     * to clicks by notifying the OnClickListener.<p>
848     * {@hide}
849     */
850    static final int CLICKABLE = 0x00004000;
851
852    /**
853     * <p>Indicates this view is caching its drawing into a bitmap.</p>
854     * {@hide}
855     */
856    static final int DRAWING_CACHE_ENABLED = 0x00008000;
857
858    /**
859     * <p>Indicates that no icicle should be saved for this view.<p>
860     * {@hide}
861     */
862    static final int SAVE_DISABLED = 0x000010000;
863
864    /**
865     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
866     * property.</p>
867     * {@hide}
868     */
869    static final int SAVE_DISABLED_MASK = 0x000010000;
870
871    /**
872     * <p>Indicates that no drawing cache should ever be created for this view.<p>
873     * {@hide}
874     */
875    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
876
877    /**
878     * <p>Indicates this view can take / keep focus when int touch mode.</p>
879     * {@hide}
880     */
881    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
882
883    /**
884     * <p>Enables low quality mode for the drawing cache.</p>
885     */
886    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
887
888    /**
889     * <p>Enables high quality mode for the drawing cache.</p>
890     */
891    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
892
893    /**
894     * <p>Enables automatic quality mode for the drawing cache.</p>
895     */
896    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
897
898    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
899            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
900    };
901
902    /**
903     * <p>Mask for use with setFlags indicating bits used for the cache
904     * quality property.</p>
905     * {@hide}
906     */
907    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
908
909    /**
910     * <p>
911     * Indicates this view can be long clicked. When long clickable, a View
912     * reacts to long clicks by notifying the OnLongClickListener or showing a
913     * context menu.
914     * </p>
915     * {@hide}
916     */
917    static final int LONG_CLICKABLE = 0x00200000;
918
919    /**
920     * <p>Indicates that this view gets its drawable states from its direct parent
921     * and ignores its original internal states.</p>
922     *
923     * @hide
924     */
925    static final int DUPLICATE_PARENT_STATE = 0x00400000;
926
927    /**
928     * The scrollbar style to display the scrollbars inside the content area,
929     * without increasing the padding. The scrollbars will be overlaid with
930     * translucency on the view's content.
931     */
932    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
933
934    /**
935     * The scrollbar style to display the scrollbars inside the padded area,
936     * increasing the padding of the view. The scrollbars will not overlap the
937     * content area of the view.
938     */
939    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
940
941    /**
942     * The scrollbar style to display the scrollbars at the edge of the view,
943     * without increasing the padding. The scrollbars will be overlaid with
944     * translucency.
945     */
946    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
947
948    /**
949     * The scrollbar style to display the scrollbars at the edge of the view,
950     * increasing the padding of the view. The scrollbars will only overlap the
951     * background, if any.
952     */
953    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
954
955    /**
956     * Mask to check if the scrollbar style is overlay or inset.
957     * {@hide}
958     */
959    static final int SCROLLBARS_INSET_MASK = 0x01000000;
960
961    /**
962     * Mask to check if the scrollbar style is inside or outside.
963     * {@hide}
964     */
965    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
966
967    /**
968     * Mask for scrollbar style.
969     * {@hide}
970     */
971    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
972
973    /**
974     * View flag indicating that the screen should remain on while the
975     * window containing this view is visible to the user.  This effectively
976     * takes care of automatically setting the WindowManager's
977     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
978     */
979    public static final int KEEP_SCREEN_ON = 0x04000000;
980
981    /**
982     * View flag indicating whether this view should have sound effects enabled
983     * for events such as clicking and touching.
984     */
985    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
986
987    /**
988     * View flag indicating whether this view should have haptic feedback
989     * enabled for events such as long presses.
990     */
991    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
992
993    /**
994     * <p>Indicates that the view hierarchy should stop saving state when
995     * it reaches this view.  If state saving is initiated immediately at
996     * the view, it will be allowed.
997     * {@hide}
998     */
999    static final int PARENT_SAVE_DISABLED = 0x20000000;
1000
1001    /**
1002     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1003     * {@hide}
1004     */
1005    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1006
1007    /**
1008     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1009     * should add all focusable Views regardless if they are focusable in touch mode.
1010     */
1011    public static final int FOCUSABLES_ALL = 0x00000000;
1012
1013    /**
1014     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1015     * should add only Views focusable in touch mode.
1016     */
1017    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1021     * item.
1022     */
1023    public static final int FOCUS_BACKWARD = 0x00000001;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1027     * item.
1028     */
1029    public static final int FOCUS_FORWARD = 0x00000002;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move focus to the left.
1033     */
1034    public static final int FOCUS_LEFT = 0x00000011;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus up.
1038     */
1039    public static final int FOCUS_UP = 0x00000021;
1040
1041    /**
1042     * Use with {@link #focusSearch(int)}. Move focus to the right.
1043     */
1044    public static final int FOCUS_RIGHT = 0x00000042;
1045
1046    /**
1047     * Use with {@link #focusSearch(int)}. Move focus down.
1048     */
1049    public static final int FOCUS_DOWN = 0x00000082;
1050
1051    /**
1052     * Bits of {@link #getMeasuredWidthAndState()} and
1053     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1054     */
1055    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1056
1057    /**
1058     * Bits of {@link #getMeasuredWidthAndState()} and
1059     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1060     */
1061    public static final int MEASURED_STATE_MASK = 0xff000000;
1062
1063    /**
1064     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1065     * for functions that combine both width and height into a single int,
1066     * such as {@link #getMeasuredState()} and the childState argument of
1067     * {@link #resolveSizeAndState(int, int, int)}.
1068     */
1069    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1070
1071    /**
1072     * Bit of {@link #getMeasuredWidthAndState()} and
1073     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1074     * is smaller that the space the view would like to have.
1075     */
1076    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1077
1078    /**
1079     * Base View state sets
1080     */
1081    // Singles
1082    /**
1083     * Indicates the view has no states set. States are used with
1084     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1085     * view depending on its state.
1086     *
1087     * @see android.graphics.drawable.Drawable
1088     * @see #getDrawableState()
1089     */
1090    protected static final int[] EMPTY_STATE_SET;
1091    /**
1092     * Indicates the view is enabled. States are used with
1093     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1094     * view depending on its state.
1095     *
1096     * @see android.graphics.drawable.Drawable
1097     * @see #getDrawableState()
1098     */
1099    protected static final int[] ENABLED_STATE_SET;
1100    /**
1101     * Indicates the view is focused. States are used with
1102     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1103     * view depending on its state.
1104     *
1105     * @see android.graphics.drawable.Drawable
1106     * @see #getDrawableState()
1107     */
1108    protected static final int[] FOCUSED_STATE_SET;
1109    /**
1110     * Indicates the view is selected. States are used with
1111     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1112     * view depending on its state.
1113     *
1114     * @see android.graphics.drawable.Drawable
1115     * @see #getDrawableState()
1116     */
1117    protected static final int[] SELECTED_STATE_SET;
1118    /**
1119     * Indicates the view is pressed. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     * @hide
1126     */
1127    protected static final int[] PRESSED_STATE_SET;
1128    /**
1129     * Indicates the view's window has focus. States are used with
1130     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1131     * view depending on its state.
1132     *
1133     * @see android.graphics.drawable.Drawable
1134     * @see #getDrawableState()
1135     */
1136    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1137    // Doubles
1138    /**
1139     * Indicates the view is enabled and has the focus.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #FOCUSED_STATE_SET
1143     */
1144    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is enabled and selected.
1147     *
1148     * @see #ENABLED_STATE_SET
1149     * @see #SELECTED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_SELECTED_STATE_SET;
1152    /**
1153     * Indicates the view is enabled and that its window has focus.
1154     *
1155     * @see #ENABLED_STATE_SET
1156     * @see #WINDOW_FOCUSED_STATE_SET
1157     */
1158    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1159    /**
1160     * Indicates the view is focused and selected.
1161     *
1162     * @see #FOCUSED_STATE_SET
1163     * @see #SELECTED_STATE_SET
1164     */
1165    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1166    /**
1167     * Indicates the view has the focus and that its window has the focus.
1168     *
1169     * @see #FOCUSED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1173    /**
1174     * Indicates the view is selected and that its window has the focus.
1175     *
1176     * @see #SELECTED_STATE_SET
1177     * @see #WINDOW_FOCUSED_STATE_SET
1178     */
1179    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1180    // Triples
1181    /**
1182     * Indicates the view is enabled, focused and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #FOCUSED_STATE_SET
1186     * @see #SELECTED_STATE_SET
1187     */
1188    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1189    /**
1190     * Indicates the view is enabled, focused and its window has the focus.
1191     *
1192     * @see #ENABLED_STATE_SET
1193     * @see #FOCUSED_STATE_SET
1194     * @see #WINDOW_FOCUSED_STATE_SET
1195     */
1196    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1197    /**
1198     * Indicates the view is enabled, selected and its window has the focus.
1199     *
1200     * @see #ENABLED_STATE_SET
1201     * @see #SELECTED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is focused, selected and its window has the focus.
1207     *
1208     * @see #FOCUSED_STATE_SET
1209     * @see #SELECTED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1213    /**
1214     * Indicates the view is enabled, focused, selected and its window
1215     * has the focus.
1216     *
1217     * @see #ENABLED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and its window has the focus.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed and selected.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] PRESSED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view is pressed, selected and its window has the focus.
1239     *
1240     * @see #PRESSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed and focused.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #FOCUSED_STATE_SET
1250     */
1251    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is pressed, focused and its window has the focus.
1254     *
1255     * @see #PRESSED_STATE_SET
1256     * @see #FOCUSED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is pressed, focused and selected.
1262     *
1263     * @see #PRESSED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, focused, selected and its window has the focus.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and enabled.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_ENABLED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, enabled and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #ENABLED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, enabled and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #ENABLED_STATE_SET
1297     * @see #SELECTED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, enabled, selected and its window has the
1302     * focus.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #ENABLED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed, enabled and focused.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #ENABLED_STATE_SET
1315     * @see #FOCUSED_STATE_SET
1316     */
1317    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1318    /**
1319     * Indicates the view is pressed, enabled, focused and its window has the
1320     * focus.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #ENABLED_STATE_SET
1324     * @see #FOCUSED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled, focused and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, enabled, focused, selected and its window
1339     * has the focus.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #ENABLED_STATE_SET
1343     * @see #SELECTED_STATE_SET
1344     * @see #FOCUSED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1348
1349    /**
1350     * The order here is very important to {@link #getDrawableState()}
1351     */
1352    private static final int[][] VIEW_STATE_SETS;
1353
1354    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1355    static final int VIEW_STATE_SELECTED = 1 << 1;
1356    static final int VIEW_STATE_FOCUSED = 1 << 2;
1357    static final int VIEW_STATE_ENABLED = 1 << 3;
1358    static final int VIEW_STATE_PRESSED = 1 << 4;
1359    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1360    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1361    static final int VIEW_STATE_HOVERED = 1 << 7;
1362    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1363    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1364
1365    static final int[] VIEW_STATE_IDS = new int[] {
1366        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1367        R.attr.state_selected,          VIEW_STATE_SELECTED,
1368        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1369        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1370        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1371        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1372        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1373        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1374        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1375        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1376    };
1377
1378    static {
1379        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1380            throw new IllegalStateException(
1381                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1382        }
1383        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1384        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1385            int viewState = R.styleable.ViewDrawableStates[i];
1386            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1387                if (VIEW_STATE_IDS[j] == viewState) {
1388                    orderedIds[i * 2] = viewState;
1389                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1390                }
1391            }
1392        }
1393        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1394        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1395        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1396            int numBits = Integer.bitCount(i);
1397            int[] set = new int[numBits];
1398            int pos = 0;
1399            for (int j = 0; j < orderedIds.length; j += 2) {
1400                if ((i & orderedIds[j+1]) != 0) {
1401                    set[pos++] = orderedIds[j];
1402                }
1403            }
1404            VIEW_STATE_SETS[i] = set;
1405        }
1406
1407        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1408        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1409        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1410        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1412        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1413        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1415        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1417        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1419                | VIEW_STATE_FOCUSED];
1420        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1421        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1423        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1425        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1427                | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1432                | VIEW_STATE_ENABLED];
1433        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1434                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1435                | VIEW_STATE_ENABLED];
1436        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1438                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1439
1440        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1441        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1443        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1445        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1447                | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1452                | VIEW_STATE_PRESSED];
1453        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1455                | VIEW_STATE_PRESSED];
1456        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1458                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1463                | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1472                | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1475                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1476        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1478                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1479        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1481                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1482                | VIEW_STATE_PRESSED];
1483    }
1484
1485    /**
1486     * Accessibility event types that are dispatched for text population.
1487     */
1488    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1489            AccessibilityEvent.TYPE_VIEW_CLICKED
1490            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_SELECTED
1492            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1493            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1494            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1496            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1499            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1500
1501    /**
1502     * Temporary Rect currently for use in setBackground().  This will probably
1503     * be extended in the future to hold our own class with more than just
1504     * a Rect. :)
1505     */
1506    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1507
1508    /**
1509     * Map used to store views' tags.
1510     */
1511    private SparseArray<Object> mKeyedTags;
1512
1513    /**
1514     * The next available accessibility id.
1515     */
1516    private static int sNextAccessibilityViewId;
1517
1518    /**
1519     * The animation currently associated with this view.
1520     * @hide
1521     */
1522    protected Animation mCurrentAnimation = null;
1523
1524    /**
1525     * Width as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredWidth;
1530
1531    /**
1532     * Height as measured during measure pass.
1533     * {@hide}
1534     */
1535    @ViewDebug.ExportedProperty(category = "measurement")
1536    int mMeasuredHeight;
1537
1538    /**
1539     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1540     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1541     * its display list. This flag, used only when hw accelerated, allows us to clear the
1542     * flag while retaining this information until it's needed (at getDisplayList() time and
1543     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1544     *
1545     * {@hide}
1546     */
1547    boolean mRecreateDisplayList = false;
1548
1549    /**
1550     * The view's identifier.
1551     * {@hide}
1552     *
1553     * @see #setId(int)
1554     * @see #getId()
1555     */
1556    @ViewDebug.ExportedProperty(resolveId = true)
1557    int mID = NO_ID;
1558
1559    /**
1560     * The stable ID of this view for accessibility purposes.
1561     */
1562    int mAccessibilityViewId = NO_ID;
1563
1564    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1565
1566    /**
1567     * The view's tag.
1568     * {@hide}
1569     *
1570     * @see #setTag(Object)
1571     * @see #getTag()
1572     */
1573    protected Object mTag;
1574
1575    // for mPrivateFlags:
1576    /** {@hide} */
1577    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1578    /** {@hide} */
1579    static final int PFLAG_FOCUSED                     = 0x00000002;
1580    /** {@hide} */
1581    static final int PFLAG_SELECTED                    = 0x00000004;
1582    /** {@hide} */
1583    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1584    /** {@hide} */
1585    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1586    /** {@hide} */
1587    static final int PFLAG_DRAWN                       = 0x00000020;
1588    /**
1589     * When this flag is set, this view is running an animation on behalf of its
1590     * children and should therefore not cancel invalidate requests, even if they
1591     * lie outside of this view's bounds.
1592     *
1593     * {@hide}
1594     */
1595    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1596    /** {@hide} */
1597    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1598    /** {@hide} */
1599    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1600    /** {@hide} */
1601    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1602    /** {@hide} */
1603    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1604    /** {@hide} */
1605    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1606    /** {@hide} */
1607    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1608    /** {@hide} */
1609    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1610
1611    private static final int PFLAG_PRESSED             = 0x00004000;
1612
1613    /** {@hide} */
1614    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1615    /**
1616     * Flag used to indicate that this view should be drawn once more (and only once
1617     * more) after its animation has completed.
1618     * {@hide}
1619     */
1620    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1621
1622    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1623
1624    /**
1625     * Indicates that the View returned true when onSetAlpha() was called and that
1626     * the alpha must be restored.
1627     * {@hide}
1628     */
1629    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1630
1631    /**
1632     * Set by {@link #setScrollContainer(boolean)}.
1633     */
1634    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1640
1641    /**
1642     * View flag indicating whether this view was invalidated (fully or partially.)
1643     *
1644     * @hide
1645     */
1646    static final int PFLAG_DIRTY                       = 0x00200000;
1647
1648    /**
1649     * View flag indicating whether this view was invalidated by an opaque
1650     * invalidate request.
1651     *
1652     * @hide
1653     */
1654    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1655
1656    /**
1657     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1658     *
1659     * @hide
1660     */
1661    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1662
1663    /**
1664     * Indicates whether the background is opaque.
1665     *
1666     * @hide
1667     */
1668    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1669
1670    /**
1671     * Indicates whether the scrollbars are opaque.
1672     *
1673     * @hide
1674     */
1675    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1676
1677    /**
1678     * Indicates whether the view is opaque.
1679     *
1680     * @hide
1681     */
1682    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1683
1684    /**
1685     * Indicates a prepressed state;
1686     * the short time between ACTION_DOWN and recognizing
1687     * a 'real' press. Prepressed is used to recognize quick taps
1688     * even when they are shorter than ViewConfiguration.getTapTimeout().
1689     *
1690     * @hide
1691     */
1692    private static final int PFLAG_PREPRESSED          = 0x02000000;
1693
1694    /**
1695     * Indicates whether the view is temporarily detached.
1696     *
1697     * @hide
1698     */
1699    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1700
1701    /**
1702     * Indicates that we should awaken scroll bars once attached
1703     *
1704     * @hide
1705     */
1706    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1707
1708    /**
1709     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1710     * @hide
1711     */
1712    private static final int PFLAG_HOVERED             = 0x10000000;
1713
1714    /**
1715     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1716     * for transform operations
1717     *
1718     * @hide
1719     */
1720    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1721
1722    /** {@hide} */
1723    static final int PFLAG_ACTIVATED                   = 0x40000000;
1724
1725    /**
1726     * Indicates that this view was specifically invalidated, not just dirtied because some
1727     * child view was invalidated. The flag is used to determine when we need to recreate
1728     * a view's display list (as opposed to just returning a reference to its existing
1729     * display list).
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_INVALIDATED                 = 0x80000000;
1734
1735    /**
1736     * Masks for mPrivateFlags2, as generated by dumpFlags():
1737     *
1738     * -------|-------|-------|-------|
1739     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1740     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1741     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1742     *                               1  PFLAG2_DRAG_HOVERED
1743     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1744     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1745     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1746     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1747     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1748     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1749     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1750     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1751     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1752     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1753     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1754     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1755     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1756     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1757     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1758     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1759     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1760     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1761     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1762     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1763     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1764     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1765     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1766     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1767     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1768     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1769     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1770     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1771     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1772     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1773     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1774     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1775     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1776     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1777     *   1                              PFLAG2_PADDING_RESOLVED
1778     * -------|-------|-------|-------|
1779     */
1780
1781    /**
1782     * Indicates that this view has reported that it can accept the current drag's content.
1783     * Cleared when the drag operation concludes.
1784     * @hide
1785     */
1786    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1787
1788    /**
1789     * Indicates that this view is currently directly under the drag location in a
1790     * drag-and-drop operation involving content that it can accept.  Cleared when
1791     * the drag exits the view, or when the drag operation concludes.
1792     * @hide
1793     */
1794    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1795
1796    /**
1797     * Horizontal layout direction of this view is from Left to Right.
1798     * Use with {@link #setLayoutDirection}.
1799     */
1800    public static final int LAYOUT_DIRECTION_LTR = 0;
1801
1802    /**
1803     * Horizontal layout direction of this view is from Right to Left.
1804     * Use with {@link #setLayoutDirection}.
1805     */
1806    public static final int LAYOUT_DIRECTION_RTL = 1;
1807
1808    /**
1809     * Horizontal layout direction of this view is inherited from its parent.
1810     * Use with {@link #setLayoutDirection}.
1811     */
1812    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1813
1814    /**
1815     * Horizontal layout direction of this view is from deduced from the default language
1816     * script for the locale. Use with {@link #setLayoutDirection}.
1817     */
1818    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1819
1820    /**
1821     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1822     * @hide
1823     */
1824    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1825
1826    /**
1827     * Mask for use with private flags indicating bits used for horizontal layout direction.
1828     * @hide
1829     */
1830    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1831
1832    /**
1833     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1834     * right-to-left direction.
1835     * @hide
1836     */
1837    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1838
1839    /**
1840     * Indicates whether the view horizontal layout direction has been resolved.
1841     * @hide
1842     */
1843    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1844
1845    /**
1846     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1847     * @hide
1848     */
1849    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1850            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1851
1852    /*
1853     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1854     * flag value.
1855     * @hide
1856     */
1857    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1858            LAYOUT_DIRECTION_LTR,
1859            LAYOUT_DIRECTION_RTL,
1860            LAYOUT_DIRECTION_INHERIT,
1861            LAYOUT_DIRECTION_LOCALE
1862    };
1863
1864    /**
1865     * Default horizontal layout direction.
1866     */
1867    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1868
1869    /**
1870     * Default horizontal layout direction.
1871     * @hide
1872     */
1873    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1874
1875    /**
1876     * Indicates that the view is tracking some sort of transient state
1877     * that the app should not need to be aware of, but that the framework
1878     * should take special care to preserve.
1879     *
1880     * @hide
1881     */
1882    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1883
1884    /**
1885     * Text direction is inherited thru {@link ViewGroup}
1886     */
1887    public static final int TEXT_DIRECTION_INHERIT = 0;
1888
1889    /**
1890     * Text direction is using "first strong algorithm". The first strong directional character
1891     * determines the paragraph direction. If there is no strong directional character, the
1892     * paragraph direction is the view's resolved layout direction.
1893     */
1894    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1895
1896    /**
1897     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1898     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1899     * If there are neither, the paragraph direction is the view's resolved layout direction.
1900     */
1901    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1902
1903    /**
1904     * Text direction is forced to LTR.
1905     */
1906    public static final int TEXT_DIRECTION_LTR = 3;
1907
1908    /**
1909     * Text direction is forced to RTL.
1910     */
1911    public static final int TEXT_DIRECTION_RTL = 4;
1912
1913    /**
1914     * Text direction is coming from the system Locale.
1915     */
1916    public static final int TEXT_DIRECTION_LOCALE = 5;
1917
1918    /**
1919     * Default text direction is inherited
1920     */
1921    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1922
1923    /**
1924     * Default resolved text direction
1925     * @hide
1926     */
1927    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1928
1929    /**
1930     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1931     * @hide
1932     */
1933    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1934
1935    /**
1936     * Mask for use with private flags indicating bits used for text direction.
1937     * @hide
1938     */
1939    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1940            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Array of text direction flags for mapping attribute "textDirection" to correct
1944     * flag value.
1945     * @hide
1946     */
1947    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1948            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1949            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1950            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1951            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1952            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1954    };
1955
1956    /**
1957     * Indicates whether the view text direction has been resolved.
1958     * @hide
1959     */
1960    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1961            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1962
1963    /**
1964     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1965     * @hide
1966     */
1967    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1968
1969    /**
1970     * Mask for use with private flags indicating bits used for resolved text direction.
1971     * @hide
1972     */
1973    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1974            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1975
1976    /**
1977     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1978     * @hide
1979     */
1980    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1981            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1982
1983    /*
1984     * Default text alignment. The text alignment of this View is inherited from its parent.
1985     * Use with {@link #setTextAlignment(int)}
1986     */
1987    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1988
1989    /**
1990     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1991     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1992     *
1993     * Use with {@link #setTextAlignment(int)}
1994     */
1995    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1996
1997    /**
1998     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1999     *
2000     * Use with {@link #setTextAlignment(int)}
2001     */
2002    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2003
2004    /**
2005     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2006     *
2007     * Use with {@link #setTextAlignment(int)}
2008     */
2009    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2010
2011    /**
2012     * Center the paragraph, e.g. ALIGN_CENTER.
2013     *
2014     * Use with {@link #setTextAlignment(int)}
2015     */
2016    public static final int TEXT_ALIGNMENT_CENTER = 4;
2017
2018    /**
2019     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2020     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2021     *
2022     * Use with {@link #setTextAlignment(int)}
2023     */
2024    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2025
2026    /**
2027     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2028     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2029     *
2030     * Use with {@link #setTextAlignment(int)}
2031     */
2032    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2033
2034    /**
2035     * Default text alignment is inherited
2036     */
2037    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2038
2039    /**
2040     * Default resolved text alignment
2041     * @hide
2042     */
2043    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2044
2045    /**
2046      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2047      * @hide
2048      */
2049    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2050
2051    /**
2052      * Mask for use with private flags indicating bits used for text alignment.
2053      * @hide
2054      */
2055    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2056
2057    /**
2058     * Array of text direction flags for mapping attribute "textAlignment" to correct
2059     * flag value.
2060     * @hide
2061     */
2062    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2063            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2064            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2065            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2066            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2067            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2070    };
2071
2072    /**
2073     * Indicates whether the view text alignment has been resolved.
2074     * @hide
2075     */
2076    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2077
2078    /**
2079     * Bit shift to get the resolved text alignment.
2080     * @hide
2081     */
2082    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2083
2084    /**
2085     * Mask for use with private flags indicating bits used for text alignment.
2086     * @hide
2087     */
2088    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2089            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2090
2091    /**
2092     * Indicates whether if the view text alignment has been resolved to gravity
2093     */
2094    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2095            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2096
2097    // Accessiblity constants for mPrivateFlags2
2098
2099    /**
2100     * Shift for the bits in {@link #mPrivateFlags2} related to the
2101     * "importantForAccessibility" attribute.
2102     */
2103    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2104
2105    /**
2106     * Automatically determine whether a view is important for accessibility.
2107     */
2108    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2109
2110    /**
2111     * The view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2114
2115    /**
2116     * The view is not important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2119
2120    /**
2121     * The default whether the view is important for accessibility.
2122     */
2123    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2124
2125    /**
2126     * Mask for obtainig the bits which specify how to determine
2127     * whether a view is important for accessibility.
2128     */
2129    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2130        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2131        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2132
2133    /**
2134     * Flag indicating whether a view has accessibility focus.
2135     */
2136    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view state for accessibility has changed.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2142            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2143
2144    /**
2145     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2146     * is used to check whether later changes to the view's transform should invalidate the
2147     * view to force the quickReject test to run again.
2148     */
2149    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2150
2151    /**
2152     * Flag indicating that start/end padding has been resolved into left/right padding
2153     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2154     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2155     * during measurement. In some special cases this is required such as when an adapter-based
2156     * view measures prospective children without attaching them to a window.
2157     */
2158    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2159
2160    /**
2161     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2162     */
2163    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2164
2165    /**
2166     * Group of bits indicating that RTL properties resolution is done.
2167     */
2168    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2169            PFLAG2_TEXT_DIRECTION_RESOLVED |
2170            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2171            PFLAG2_PADDING_RESOLVED |
2172            PFLAG2_DRAWABLE_RESOLVED;
2173
2174    // There are a couple of flags left in mPrivateFlags2
2175
2176    /* End of masks for mPrivateFlags2 */
2177
2178    /* Masks for mPrivateFlags3 */
2179
2180    /**
2181     * Flag indicating that view has a transform animation set on it. This is used to track whether
2182     * an animation is cleared between successive frames, in order to tell the associated
2183     * DisplayList to clear its animation matrix.
2184     */
2185    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2186
2187    /**
2188     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2189     * animation is cleared between successive frames, in order to tell the associated
2190     * DisplayList to restore its alpha value.
2191     */
2192    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2193
2194
2195    /* End of masks for mPrivateFlags3 */
2196
2197    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2198
2199    /**
2200     * Always allow a user to over-scroll this view, provided it is a
2201     * view that can scroll.
2202     *
2203     * @see #getOverScrollMode()
2204     * @see #setOverScrollMode(int)
2205     */
2206    public static final int OVER_SCROLL_ALWAYS = 0;
2207
2208    /**
2209     * Allow a user to over-scroll this view only if the content is large
2210     * enough to meaningfully scroll, provided it is a view that can scroll.
2211     *
2212     * @see #getOverScrollMode()
2213     * @see #setOverScrollMode(int)
2214     */
2215    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2216
2217    /**
2218     * Never allow a user to over-scroll this view.
2219     *
2220     * @see #getOverScrollMode()
2221     * @see #setOverScrollMode(int)
2222     */
2223    public static final int OVER_SCROLL_NEVER = 2;
2224
2225    /**
2226     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2227     * requested the system UI (status bar) to be visible (the default).
2228     *
2229     * @see #setSystemUiVisibility(int)
2230     */
2231    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2232
2233    /**
2234     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2235     * system UI to enter an unobtrusive "low profile" mode.
2236     *
2237     * <p>This is for use in games, book readers, video players, or any other
2238     * "immersive" application where the usual system chrome is deemed too distracting.
2239     *
2240     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2241     *
2242     * @see #setSystemUiVisibility(int)
2243     */
2244    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2245
2246    /**
2247     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2248     * system navigation be temporarily hidden.
2249     *
2250     * <p>This is an even less obtrusive state than that called for by
2251     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2252     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2253     * those to disappear. This is useful (in conjunction with the
2254     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2255     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2256     * window flags) for displaying content using every last pixel on the display.
2257     *
2258     * <p>There is a limitation: because navigation controls are so important, the least user
2259     * interaction will cause them to reappear immediately.  When this happens, both
2260     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2261     * so that both elements reappear at the same time.
2262     *
2263     * @see #setSystemUiVisibility(int)
2264     */
2265    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2266
2267    /**
2268     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2269     * into the normal fullscreen mode so that its content can take over the screen
2270     * while still allowing the user to interact with the application.
2271     *
2272     * <p>This has the same visual effect as
2273     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2274     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2275     * meaning that non-critical screen decorations (such as the status bar) will be
2276     * hidden while the user is in the View's window, focusing the experience on
2277     * that content.  Unlike the window flag, if you are using ActionBar in
2278     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2279     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2280     * hide the action bar.
2281     *
2282     * <p>This approach to going fullscreen is best used over the window flag when
2283     * it is a transient state -- that is, the application does this at certain
2284     * points in its user interaction where it wants to allow the user to focus
2285     * on content, but not as a continuous state.  For situations where the application
2286     * would like to simply stay full screen the entire time (such as a game that
2287     * wants to take over the screen), the
2288     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2289     * is usually a better approach.  The state set here will be removed by the system
2290     * in various situations (such as the user moving to another application) like
2291     * the other system UI states.
2292     *
2293     * <p>When using this flag, the application should provide some easy facility
2294     * for the user to go out of it.  A common example would be in an e-book
2295     * reader, where tapping on the screen brings back whatever screen and UI
2296     * decorations that had been hidden while the user was immersed in reading
2297     * the book.
2298     *
2299     * @see #setSystemUiVisibility(int)
2300     */
2301    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2302
2303    /**
2304     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2305     * flags, we would like a stable view of the content insets given to
2306     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2307     * will always represent the worst case that the application can expect
2308     * as a continuous state.  In the stock Android UI this is the space for
2309     * the system bar, nav bar, and status bar, but not more transient elements
2310     * such as an input method.
2311     *
2312     * The stable layout your UI sees is based on the system UI modes you can
2313     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2314     * then you will get a stable layout for changes of the
2315     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2316     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2317     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2318     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2319     * with a stable layout.  (Note that you should avoid using
2320     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2321     *
2322     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2323     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2324     * then a hidden status bar will be considered a "stable" state for purposes
2325     * here.  This allows your UI to continually hide the status bar, while still
2326     * using the system UI flags to hide the action bar while still retaining
2327     * a stable layout.  Note that changing the window fullscreen flag will never
2328     * provide a stable layout for a clean transition.
2329     *
2330     * <p>If you are using ActionBar in
2331     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2332     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2333     * insets it adds to those given to the application.
2334     */
2335    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2336
2337    /**
2338     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2339     * to be layed out as if it has requested
2340     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2341     * allows it to avoid artifacts when switching in and out of that mode, at
2342     * the expense that some of its user interface may be covered by screen
2343     * decorations when they are shown.  You can perform layout of your inner
2344     * UI elements to account for the navagation system UI through the
2345     * {@link #fitSystemWindows(Rect)} method.
2346     */
2347    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2348
2349    /**
2350     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2351     * to be layed out as if it has requested
2352     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2353     * allows it to avoid artifacts when switching in and out of that mode, at
2354     * the expense that some of its user interface may be covered by screen
2355     * decorations when they are shown.  You can perform layout of your inner
2356     * UI elements to account for non-fullscreen system UI through the
2357     * {@link #fitSystemWindows(Rect)} method.
2358     */
2359    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2360
2361    /**
2362     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2363     */
2364    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2365
2366    /**
2367     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2368     */
2369    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2370
2371    /**
2372     * @hide
2373     *
2374     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2375     * out of the public fields to keep the undefined bits out of the developer's way.
2376     *
2377     * Flag to make the status bar not expandable.  Unless you also
2378     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2379     */
2380    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2381
2382    /**
2383     * @hide
2384     *
2385     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2386     * out of the public fields to keep the undefined bits out of the developer's way.
2387     *
2388     * Flag to hide notification icons and scrolling ticker text.
2389     */
2390    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2391
2392    /**
2393     * @hide
2394     *
2395     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2396     * out of the public fields to keep the undefined bits out of the developer's way.
2397     *
2398     * Flag to disable incoming notification alerts.  This will not block
2399     * icons, but it will block sound, vibrating and other visual or aural notifications.
2400     */
2401    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2402
2403    /**
2404     * @hide
2405     *
2406     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2407     * out of the public fields to keep the undefined bits out of the developer's way.
2408     *
2409     * Flag to hide only the scrolling ticker.  Note that
2410     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2411     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2412     */
2413    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2414
2415    /**
2416     * @hide
2417     *
2418     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2419     * out of the public fields to keep the undefined bits out of the developer's way.
2420     *
2421     * Flag to hide the center system info area.
2422     */
2423    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide only the home button.  Don't use this
2432     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2433     */
2434    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2435
2436    /**
2437     * @hide
2438     *
2439     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2440     * out of the public fields to keep the undefined bits out of the developer's way.
2441     *
2442     * Flag to hide only the back button. Don't use this
2443     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2444     */
2445    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2446
2447    /**
2448     * @hide
2449     *
2450     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2451     * out of the public fields to keep the undefined bits out of the developer's way.
2452     *
2453     * Flag to hide only the clock.  You might use this if your activity has
2454     * its own clock making the status bar's clock redundant.
2455     */
2456    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide only the recent apps button. Don't use this
2465     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2466     */
2467    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2468
2469    /**
2470     * @hide
2471     *
2472     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2473     * out of the public fields to keep the undefined bits out of the developer's way.
2474     *
2475     * Flag to disable the global search gesture. Don't use this
2476     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2477     */
2478    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2479
2480    /**
2481     * @hide
2482     */
2483    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2484
2485    /**
2486     * These are the system UI flags that can be cleared by events outside
2487     * of an application.  Currently this is just the ability to tap on the
2488     * screen while hiding the navigation bar to have it return.
2489     * @hide
2490     */
2491    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2492            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2493            | SYSTEM_UI_FLAG_FULLSCREEN;
2494
2495    /**
2496     * Flags that can impact the layout in relation to system UI.
2497     */
2498    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2499            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2500            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2501
2502    /**
2503     * Find views that render the specified text.
2504     *
2505     * @see #findViewsWithText(ArrayList, CharSequence, int)
2506     */
2507    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2508
2509    /**
2510     * Find find views that contain the specified content description.
2511     *
2512     * @see #findViewsWithText(ArrayList, CharSequence, int)
2513     */
2514    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2515
2516    /**
2517     * Find views that contain {@link AccessibilityNodeProvider}. Such
2518     * a View is a root of virtual view hierarchy and may contain the searched
2519     * text. If this flag is set Views with providers are automatically
2520     * added and it is a responsibility of the client to call the APIs of
2521     * the provider to determine whether the virtual tree rooted at this View
2522     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2523     * represeting the virtual views with this text.
2524     *
2525     * @see #findViewsWithText(ArrayList, CharSequence, int)
2526     *
2527     * @hide
2528     */
2529    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2530
2531    /**
2532     * The undefined cursor position.
2533     *
2534     * @hide
2535     */
2536    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2537
2538    /**
2539     * Indicates that the screen has changed state and is now off.
2540     *
2541     * @see #onScreenStateChanged(int)
2542     */
2543    public static final int SCREEN_STATE_OFF = 0x0;
2544
2545    /**
2546     * Indicates that the screen has changed state and is now on.
2547     *
2548     * @see #onScreenStateChanged(int)
2549     */
2550    public static final int SCREEN_STATE_ON = 0x1;
2551
2552    /**
2553     * Controls the over-scroll mode for this view.
2554     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2555     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2556     * and {@link #OVER_SCROLL_NEVER}.
2557     */
2558    private int mOverScrollMode;
2559
2560    /**
2561     * The parent this view is attached to.
2562     * {@hide}
2563     *
2564     * @see #getParent()
2565     */
2566    protected ViewParent mParent;
2567
2568    /**
2569     * {@hide}
2570     */
2571    AttachInfo mAttachInfo;
2572
2573    /**
2574     * {@hide}
2575     */
2576    @ViewDebug.ExportedProperty(flagMapping = {
2577        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2578                name = "FORCE_LAYOUT"),
2579        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2580                name = "LAYOUT_REQUIRED"),
2581        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2582            name = "DRAWING_CACHE_INVALID", outputIf = false),
2583        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2584        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2585        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2586        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2587    })
2588    int mPrivateFlags;
2589    int mPrivateFlags2;
2590    int mPrivateFlags3;
2591
2592    /**
2593     * This view's request for the visibility of the status bar.
2594     * @hide
2595     */
2596    @ViewDebug.ExportedProperty(flagMapping = {
2597        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2598                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2599                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2600        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2601                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2602                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2603        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2604                                equals = SYSTEM_UI_FLAG_VISIBLE,
2605                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2606    })
2607    int mSystemUiVisibility;
2608
2609    /**
2610     * Reference count for transient state.
2611     * @see #setHasTransientState(boolean)
2612     */
2613    int mTransientStateCount = 0;
2614
2615    /**
2616     * Count of how many windows this view has been attached to.
2617     */
2618    int mWindowAttachCount;
2619
2620    /**
2621     * The layout parameters associated with this view and used by the parent
2622     * {@link android.view.ViewGroup} to determine how this view should be
2623     * laid out.
2624     * {@hide}
2625     */
2626    protected ViewGroup.LayoutParams mLayoutParams;
2627
2628    /**
2629     * The view flags hold various views states.
2630     * {@hide}
2631     */
2632    @ViewDebug.ExportedProperty
2633    int mViewFlags;
2634
2635    static class TransformationInfo {
2636        /**
2637         * The transform matrix for the View. This transform is calculated internally
2638         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2639         * is used by default. Do *not* use this variable directly; instead call
2640         * getMatrix(), which will automatically recalculate the matrix if necessary
2641         * to get the correct matrix based on the latest rotation and scale properties.
2642         */
2643        private final Matrix mMatrix = new Matrix();
2644
2645        /**
2646         * The transform matrix for the View. This transform is calculated internally
2647         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2648         * is used by default. Do *not* use this variable directly; instead call
2649         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2650         * to get the correct matrix based on the latest rotation and scale properties.
2651         */
2652        private Matrix mInverseMatrix;
2653
2654        /**
2655         * An internal variable that tracks whether we need to recalculate the
2656         * transform matrix, based on whether the rotation or scaleX/Y properties
2657         * have changed since the matrix was last calculated.
2658         */
2659        boolean mMatrixDirty = false;
2660
2661        /**
2662         * An internal variable that tracks whether we need to recalculate the
2663         * transform matrix, based on whether the rotation or scaleX/Y properties
2664         * have changed since the matrix was last calculated.
2665         */
2666        private boolean mInverseMatrixDirty = true;
2667
2668        /**
2669         * A variable that tracks whether we need to recalculate the
2670         * transform matrix, based on whether the rotation or scaleX/Y properties
2671         * have changed since the matrix was last calculated. This variable
2672         * is only valid after a call to updateMatrix() or to a function that
2673         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2674         */
2675        private boolean mMatrixIsIdentity = true;
2676
2677        /**
2678         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2679         */
2680        private Camera mCamera = null;
2681
2682        /**
2683         * This matrix is used when computing the matrix for 3D rotations.
2684         */
2685        private Matrix matrix3D = null;
2686
2687        /**
2688         * These prev values are used to recalculate a centered pivot point when necessary. The
2689         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2690         * set), so thes values are only used then as well.
2691         */
2692        private int mPrevWidth = -1;
2693        private int mPrevHeight = -1;
2694
2695        /**
2696         * The degrees rotation around the vertical axis through the pivot point.
2697         */
2698        @ViewDebug.ExportedProperty
2699        float mRotationY = 0f;
2700
2701        /**
2702         * The degrees rotation around the horizontal axis through the pivot point.
2703         */
2704        @ViewDebug.ExportedProperty
2705        float mRotationX = 0f;
2706
2707        /**
2708         * The degrees rotation around the pivot point.
2709         */
2710        @ViewDebug.ExportedProperty
2711        float mRotation = 0f;
2712
2713        /**
2714         * The amount of translation of the object away from its left property (post-layout).
2715         */
2716        @ViewDebug.ExportedProperty
2717        float mTranslationX = 0f;
2718
2719        /**
2720         * The amount of translation of the object away from its top property (post-layout).
2721         */
2722        @ViewDebug.ExportedProperty
2723        float mTranslationY = 0f;
2724
2725        /**
2726         * The amount of scale in the x direction around the pivot point. A
2727         * value of 1 means no scaling is applied.
2728         */
2729        @ViewDebug.ExportedProperty
2730        float mScaleX = 1f;
2731
2732        /**
2733         * The amount of scale in the y direction around the pivot point. A
2734         * value of 1 means no scaling is applied.
2735         */
2736        @ViewDebug.ExportedProperty
2737        float mScaleY = 1f;
2738
2739        /**
2740         * The x location of the point around which the view is rotated and scaled.
2741         */
2742        @ViewDebug.ExportedProperty
2743        float mPivotX = 0f;
2744
2745        /**
2746         * The y location of the point around which the view is rotated and scaled.
2747         */
2748        @ViewDebug.ExportedProperty
2749        float mPivotY = 0f;
2750
2751        /**
2752         * The opacity of the View. This is a value from 0 to 1, where 0 means
2753         * completely transparent and 1 means completely opaque.
2754         */
2755        @ViewDebug.ExportedProperty
2756        float mAlpha = 1f;
2757    }
2758
2759    TransformationInfo mTransformationInfo;
2760
2761    /**
2762     * Current clip bounds. to which all drawing of this view are constrained.
2763     */
2764    private Rect mClipBounds = null;
2765
2766    private boolean mLastIsOpaque;
2767
2768    /**
2769     * Convenience value to check for float values that are close enough to zero to be considered
2770     * zero.
2771     */
2772    private static final float NONZERO_EPSILON = .001f;
2773
2774    /**
2775     * The distance in pixels from the left edge of this view's parent
2776     * to the left edge of this view.
2777     * {@hide}
2778     */
2779    @ViewDebug.ExportedProperty(category = "layout")
2780    protected int mLeft;
2781    /**
2782     * The distance in pixels from the left edge of this view's parent
2783     * to the right edge of this view.
2784     * {@hide}
2785     */
2786    @ViewDebug.ExportedProperty(category = "layout")
2787    protected int mRight;
2788    /**
2789     * The distance in pixels from the top edge of this view's parent
2790     * to the top edge of this view.
2791     * {@hide}
2792     */
2793    @ViewDebug.ExportedProperty(category = "layout")
2794    protected int mTop;
2795    /**
2796     * The distance in pixels from the top edge of this view's parent
2797     * to the bottom edge of this view.
2798     * {@hide}
2799     */
2800    @ViewDebug.ExportedProperty(category = "layout")
2801    protected int mBottom;
2802
2803    /**
2804     * The offset, in pixels, by which the content of this view is scrolled
2805     * horizontally.
2806     * {@hide}
2807     */
2808    @ViewDebug.ExportedProperty(category = "scrolling")
2809    protected int mScrollX;
2810    /**
2811     * The offset, in pixels, by which the content of this view is scrolled
2812     * vertically.
2813     * {@hide}
2814     */
2815    @ViewDebug.ExportedProperty(category = "scrolling")
2816    protected int mScrollY;
2817
2818    /**
2819     * The left padding in pixels, that is the distance in pixels between the
2820     * left edge of this view and the left edge of its content.
2821     * {@hide}
2822     */
2823    @ViewDebug.ExportedProperty(category = "padding")
2824    protected int mPaddingLeft = 0;
2825    /**
2826     * The right padding in pixels, that is the distance in pixels between the
2827     * right edge of this view and the right edge of its content.
2828     * {@hide}
2829     */
2830    @ViewDebug.ExportedProperty(category = "padding")
2831    protected int mPaddingRight = 0;
2832    /**
2833     * The top padding in pixels, that is the distance in pixels between the
2834     * top edge of this view and the top edge of its content.
2835     * {@hide}
2836     */
2837    @ViewDebug.ExportedProperty(category = "padding")
2838    protected int mPaddingTop;
2839    /**
2840     * The bottom padding in pixels, that is the distance in pixels between the
2841     * bottom edge of this view and the bottom edge of its content.
2842     * {@hide}
2843     */
2844    @ViewDebug.ExportedProperty(category = "padding")
2845    protected int mPaddingBottom;
2846
2847    /**
2848     * The layout insets in pixels, that is the distance in pixels between the
2849     * visible edges of this view its bounds.
2850     */
2851    private Insets mLayoutInsets;
2852
2853    /**
2854     * Briefly describes the view and is primarily used for accessibility support.
2855     */
2856    private CharSequence mContentDescription;
2857
2858    /**
2859     * Specifies the id of a view for which this view serves as a label for
2860     * accessibility purposes.
2861     */
2862    private int mLabelForId = View.NO_ID;
2863
2864    /**
2865     * Predicate for matching labeled view id with its label for
2866     * accessibility purposes.
2867     */
2868    private MatchLabelForPredicate mMatchLabelForPredicate;
2869
2870    /**
2871     * Predicate for matching a view by its id.
2872     */
2873    private MatchIdPredicate mMatchIdPredicate;
2874
2875    /**
2876     * Cache the paddingRight set by the user to append to the scrollbar's size.
2877     *
2878     * @hide
2879     */
2880    @ViewDebug.ExportedProperty(category = "padding")
2881    protected int mUserPaddingRight;
2882
2883    /**
2884     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2885     *
2886     * @hide
2887     */
2888    @ViewDebug.ExportedProperty(category = "padding")
2889    protected int mUserPaddingBottom;
2890
2891    /**
2892     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2893     *
2894     * @hide
2895     */
2896    @ViewDebug.ExportedProperty(category = "padding")
2897    protected int mUserPaddingLeft;
2898
2899    /**
2900     * Cache the paddingStart set by the user to append to the scrollbar's size.
2901     *
2902     */
2903    @ViewDebug.ExportedProperty(category = "padding")
2904    int mUserPaddingStart;
2905
2906    /**
2907     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2908     *
2909     */
2910    @ViewDebug.ExportedProperty(category = "padding")
2911    int mUserPaddingEnd;
2912
2913    /**
2914     * Cache initial left padding.
2915     *
2916     * @hide
2917     */
2918    int mUserPaddingLeftInitial = 0;
2919
2920    /**
2921     * Cache initial right padding.
2922     *
2923     * @hide
2924     */
2925    int mUserPaddingRightInitial = 0;
2926
2927    /**
2928     * Default undefined padding
2929     */
2930    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2931
2932    /**
2933     * @hide
2934     */
2935    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2936    /**
2937     * @hide
2938     */
2939    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2940
2941    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2942    private Drawable mBackground;
2943
2944    private int mBackgroundResource;
2945    private boolean mBackgroundSizeChanged;
2946
2947    static class ListenerInfo {
2948        /**
2949         * Listener used to dispatch focus change events.
2950         * This field should be made private, so it is hidden from the SDK.
2951         * {@hide}
2952         */
2953        protected OnFocusChangeListener mOnFocusChangeListener;
2954
2955        /**
2956         * Listeners for layout change events.
2957         */
2958        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2959
2960        /**
2961         * Listeners for attach events.
2962         */
2963        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2964
2965        /**
2966         * Listener used to dispatch click events.
2967         * This field should be made private, so it is hidden from the SDK.
2968         * {@hide}
2969         */
2970        public OnClickListener mOnClickListener;
2971
2972        /**
2973         * Listener used to dispatch long click events.
2974         * This field should be made private, so it is hidden from the SDK.
2975         * {@hide}
2976         */
2977        protected OnLongClickListener mOnLongClickListener;
2978
2979        /**
2980         * Listener used to build the context menu.
2981         * This field should be made private, so it is hidden from the SDK.
2982         * {@hide}
2983         */
2984        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2985
2986        private OnKeyListener mOnKeyListener;
2987
2988        private OnTouchListener mOnTouchListener;
2989
2990        private OnHoverListener mOnHoverListener;
2991
2992        private OnGenericMotionListener mOnGenericMotionListener;
2993
2994        private OnDragListener mOnDragListener;
2995
2996        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2997    }
2998
2999    ListenerInfo mListenerInfo;
3000
3001    /**
3002     * The application environment this view lives in.
3003     * This field should be made private, so it is hidden from the SDK.
3004     * {@hide}
3005     */
3006    protected Context mContext;
3007
3008    private final Resources mResources;
3009
3010    private ScrollabilityCache mScrollCache;
3011
3012    private int[] mDrawableState = null;
3013
3014    /**
3015     * Set to true when drawing cache is enabled and cannot be created.
3016     *
3017     * @hide
3018     */
3019    public boolean mCachingFailed;
3020
3021    private Bitmap mDrawingCache;
3022    private Bitmap mUnscaledDrawingCache;
3023    private HardwareLayer mHardwareLayer;
3024    DisplayList mDisplayList;
3025
3026    /**
3027     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3028     * the user may specify which view to go to next.
3029     */
3030    private int mNextFocusLeftId = View.NO_ID;
3031
3032    /**
3033     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3034     * the user may specify which view to go to next.
3035     */
3036    private int mNextFocusRightId = View.NO_ID;
3037
3038    /**
3039     * When this view has focus and the next focus is {@link #FOCUS_UP},
3040     * the user may specify which view to go to next.
3041     */
3042    private int mNextFocusUpId = View.NO_ID;
3043
3044    /**
3045     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3046     * the user may specify which view to go to next.
3047     */
3048    private int mNextFocusDownId = View.NO_ID;
3049
3050    /**
3051     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3052     * the user may specify which view to go to next.
3053     */
3054    int mNextFocusForwardId = View.NO_ID;
3055
3056    private CheckForLongPress mPendingCheckForLongPress;
3057    private CheckForTap mPendingCheckForTap = null;
3058    private PerformClick mPerformClick;
3059    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3060
3061    private UnsetPressedState mUnsetPressedState;
3062
3063    /**
3064     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3065     * up event while a long press is invoked as soon as the long press duration is reached, so
3066     * a long press could be performed before the tap is checked, in which case the tap's action
3067     * should not be invoked.
3068     */
3069    private boolean mHasPerformedLongPress;
3070
3071    /**
3072     * The minimum height of the view. We'll try our best to have the height
3073     * of this view to at least this amount.
3074     */
3075    @ViewDebug.ExportedProperty(category = "measurement")
3076    private int mMinHeight;
3077
3078    /**
3079     * The minimum width of the view. We'll try our best to have the width
3080     * of this view to at least this amount.
3081     */
3082    @ViewDebug.ExportedProperty(category = "measurement")
3083    private int mMinWidth;
3084
3085    /**
3086     * The delegate to handle touch events that are physically in this view
3087     * but should be handled by another view.
3088     */
3089    private TouchDelegate mTouchDelegate = null;
3090
3091    /**
3092     * Solid color to use as a background when creating the drawing cache. Enables
3093     * the cache to use 16 bit bitmaps instead of 32 bit.
3094     */
3095    private int mDrawingCacheBackgroundColor = 0;
3096
3097    /**
3098     * Special tree observer used when mAttachInfo is null.
3099     */
3100    private ViewTreeObserver mFloatingTreeObserver;
3101
3102    /**
3103     * Cache the touch slop from the context that created the view.
3104     */
3105    private int mTouchSlop;
3106
3107    /**
3108     * Object that handles automatic animation of view properties.
3109     */
3110    private ViewPropertyAnimator mAnimator = null;
3111
3112    /**
3113     * Flag indicating that a drag can cross window boundaries.  When
3114     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3115     * with this flag set, all visible applications will be able to participate
3116     * in the drag operation and receive the dragged content.
3117     *
3118     * @hide
3119     */
3120    public static final int DRAG_FLAG_GLOBAL = 1;
3121
3122    /**
3123     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3124     */
3125    private float mVerticalScrollFactor;
3126
3127    /**
3128     * Position of the vertical scroll bar.
3129     */
3130    private int mVerticalScrollbarPosition;
3131
3132    /**
3133     * Position the scroll bar at the default position as determined by the system.
3134     */
3135    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3136
3137    /**
3138     * Position the scroll bar along the left edge.
3139     */
3140    public static final int SCROLLBAR_POSITION_LEFT = 1;
3141
3142    /**
3143     * Position the scroll bar along the right edge.
3144     */
3145    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3146
3147    /**
3148     * Indicates that the view does not have a layer.
3149     *
3150     * @see #getLayerType()
3151     * @see #setLayerType(int, android.graphics.Paint)
3152     * @see #LAYER_TYPE_SOFTWARE
3153     * @see #LAYER_TYPE_HARDWARE
3154     */
3155    public static final int LAYER_TYPE_NONE = 0;
3156
3157    /**
3158     * <p>Indicates that the view has a software layer. A software layer is backed
3159     * by a bitmap and causes the view to be rendered using Android's software
3160     * rendering pipeline, even if hardware acceleration is enabled.</p>
3161     *
3162     * <p>Software layers have various usages:</p>
3163     * <p>When the application is not using hardware acceleration, a software layer
3164     * is useful to apply a specific color filter and/or blending mode and/or
3165     * translucency to a view and all its children.</p>
3166     * <p>When the application is using hardware acceleration, a software layer
3167     * is useful to render drawing primitives not supported by the hardware
3168     * accelerated pipeline. It can also be used to cache a complex view tree
3169     * into a texture and reduce the complexity of drawing operations. For instance,
3170     * when animating a complex view tree with a translation, a software layer can
3171     * be used to render the view tree only once.</p>
3172     * <p>Software layers should be avoided when the affected view tree updates
3173     * often. Every update will require to re-render the software layer, which can
3174     * potentially be slow (particularly when hardware acceleration is turned on
3175     * since the layer will have to be uploaded into a hardware texture after every
3176     * update.)</p>
3177     *
3178     * @see #getLayerType()
3179     * @see #setLayerType(int, android.graphics.Paint)
3180     * @see #LAYER_TYPE_NONE
3181     * @see #LAYER_TYPE_HARDWARE
3182     */
3183    public static final int LAYER_TYPE_SOFTWARE = 1;
3184
3185    /**
3186     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3187     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3188     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3189     * rendering pipeline, but only if hardware acceleration is turned on for the
3190     * view hierarchy. When hardware acceleration is turned off, hardware layers
3191     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3192     *
3193     * <p>A hardware layer is useful to apply a specific color filter and/or
3194     * blending mode and/or translucency to a view and all its children.</p>
3195     * <p>A hardware layer can be used to cache a complex view tree into a
3196     * texture and reduce the complexity of drawing operations. For instance,
3197     * when animating a complex view tree with a translation, a hardware layer can
3198     * be used to render the view tree only once.</p>
3199     * <p>A hardware layer can also be used to increase the rendering quality when
3200     * rotation transformations are applied on a view. It can also be used to
3201     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3202     *
3203     * @see #getLayerType()
3204     * @see #setLayerType(int, android.graphics.Paint)
3205     * @see #LAYER_TYPE_NONE
3206     * @see #LAYER_TYPE_SOFTWARE
3207     */
3208    public static final int LAYER_TYPE_HARDWARE = 2;
3209
3210    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3211            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3212            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3213            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3214    })
3215    int mLayerType = LAYER_TYPE_NONE;
3216    Paint mLayerPaint;
3217    Rect mLocalDirtyRect;
3218
3219    /**
3220     * Set to true when the view is sending hover accessibility events because it
3221     * is the innermost hovered view.
3222     */
3223    private boolean mSendingHoverAccessibilityEvents;
3224
3225    /**
3226     * Delegate for injecting accessibility functionality.
3227     */
3228    AccessibilityDelegate mAccessibilityDelegate;
3229
3230    /**
3231     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3232     * and add/remove objects to/from the overlay directly through the Overlay methods.
3233     */
3234    ViewOverlay mOverlay;
3235
3236    /**
3237     * Consistency verifier for debugging purposes.
3238     * @hide
3239     */
3240    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3241            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3242                    new InputEventConsistencyVerifier(this, 0) : null;
3243
3244    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3245
3246    /**
3247     * Simple constructor to use when creating a view from code.
3248     *
3249     * @param context The Context the view is running in, through which it can
3250     *        access the current theme, resources, etc.
3251     */
3252    public View(Context context) {
3253        mContext = context;
3254        mResources = context != null ? context.getResources() : null;
3255        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3256        // Set some flags defaults
3257        mPrivateFlags2 =
3258                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3259                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3260                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3261                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3262                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3263                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3264        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3265        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3266        mUserPaddingStart = UNDEFINED_PADDING;
3267        mUserPaddingEnd = UNDEFINED_PADDING;
3268
3269        if (!sUseBrokenMakeMeasureSpec && context.getApplicationInfo().targetSdkVersion <=
3270                Build.VERSION_CODES.JELLY_BEAN_MR1 ) {
3271            // Older apps may need this compatibility hack for measurement.
3272            sUseBrokenMakeMeasureSpec = true;
3273        }
3274    }
3275
3276    /**
3277     * Constructor that is called when inflating a view from XML. This is called
3278     * when a view is being constructed from an XML file, supplying attributes
3279     * that were specified in the XML file. This version uses a default style of
3280     * 0, so the only attribute values applied are those in the Context's Theme
3281     * and the given AttributeSet.
3282     *
3283     * <p>
3284     * The method onFinishInflate() will be called after all children have been
3285     * added.
3286     *
3287     * @param context The Context the view is running in, through which it can
3288     *        access the current theme, resources, etc.
3289     * @param attrs The attributes of the XML tag that is inflating the view.
3290     * @see #View(Context, AttributeSet, int)
3291     */
3292    public View(Context context, AttributeSet attrs) {
3293        this(context, attrs, 0);
3294    }
3295
3296    /**
3297     * Perform inflation from XML and apply a class-specific base style. This
3298     * constructor of View allows subclasses to use their own base style when
3299     * they are inflating. For example, a Button class's constructor would call
3300     * this version of the super class constructor and supply
3301     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3302     * the theme's button style to modify all of the base view attributes (in
3303     * particular its background) as well as the Button class's attributes.
3304     *
3305     * @param context The Context the view is running in, through which it can
3306     *        access the current theme, resources, etc.
3307     * @param attrs The attributes of the XML tag that is inflating the view.
3308     * @param defStyle The default style to apply to this view. If 0, no style
3309     *        will be applied (beyond what is included in the theme). This may
3310     *        either be an attribute resource, whose value will be retrieved
3311     *        from the current theme, or an explicit style resource.
3312     * @see #View(Context, AttributeSet)
3313     */
3314    public View(Context context, AttributeSet attrs, int defStyle) {
3315        this(context);
3316
3317        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3318                defStyle, 0);
3319
3320        Drawable background = null;
3321
3322        int leftPadding = -1;
3323        int topPadding = -1;
3324        int rightPadding = -1;
3325        int bottomPadding = -1;
3326        int startPadding = UNDEFINED_PADDING;
3327        int endPadding = UNDEFINED_PADDING;
3328
3329        int padding = -1;
3330
3331        int viewFlagValues = 0;
3332        int viewFlagMasks = 0;
3333
3334        boolean setScrollContainer = false;
3335
3336        int x = 0;
3337        int y = 0;
3338
3339        float tx = 0;
3340        float ty = 0;
3341        float rotation = 0;
3342        float rotationX = 0;
3343        float rotationY = 0;
3344        float sx = 1f;
3345        float sy = 1f;
3346        boolean transformSet = false;
3347
3348        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3349        int overScrollMode = mOverScrollMode;
3350        boolean initializeScrollbars = false;
3351
3352        boolean leftPaddingDefined = false;
3353        boolean rightPaddingDefined = false;
3354        boolean startPaddingDefined = false;
3355        boolean endPaddingDefined = false;
3356
3357        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3358
3359        final int N = a.getIndexCount();
3360        for (int i = 0; i < N; i++) {
3361            int attr = a.getIndex(i);
3362            switch (attr) {
3363                case com.android.internal.R.styleable.View_background:
3364                    background = a.getDrawable(attr);
3365                    break;
3366                case com.android.internal.R.styleable.View_padding:
3367                    padding = a.getDimensionPixelSize(attr, -1);
3368                    mUserPaddingLeftInitial = padding;
3369                    mUserPaddingRightInitial = padding;
3370                    leftPaddingDefined = true;
3371                    rightPaddingDefined = true;
3372                    break;
3373                 case com.android.internal.R.styleable.View_paddingLeft:
3374                    leftPadding = a.getDimensionPixelSize(attr, -1);
3375                    mUserPaddingLeftInitial = leftPadding;
3376                    leftPaddingDefined = true;
3377                    break;
3378                case com.android.internal.R.styleable.View_paddingTop:
3379                    topPadding = a.getDimensionPixelSize(attr, -1);
3380                    break;
3381                case com.android.internal.R.styleable.View_paddingRight:
3382                    rightPadding = a.getDimensionPixelSize(attr, -1);
3383                    mUserPaddingRightInitial = rightPadding;
3384                    rightPaddingDefined = true;
3385                    break;
3386                case com.android.internal.R.styleable.View_paddingBottom:
3387                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3388                    break;
3389                case com.android.internal.R.styleable.View_paddingStart:
3390                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3391                    startPaddingDefined = true;
3392                    break;
3393                case com.android.internal.R.styleable.View_paddingEnd:
3394                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3395                    endPaddingDefined = true;
3396                    break;
3397                case com.android.internal.R.styleable.View_scrollX:
3398                    x = a.getDimensionPixelOffset(attr, 0);
3399                    break;
3400                case com.android.internal.R.styleable.View_scrollY:
3401                    y = a.getDimensionPixelOffset(attr, 0);
3402                    break;
3403                case com.android.internal.R.styleable.View_alpha:
3404                    setAlpha(a.getFloat(attr, 1f));
3405                    break;
3406                case com.android.internal.R.styleable.View_transformPivotX:
3407                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3408                    break;
3409                case com.android.internal.R.styleable.View_transformPivotY:
3410                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3411                    break;
3412                case com.android.internal.R.styleable.View_translationX:
3413                    tx = a.getDimensionPixelOffset(attr, 0);
3414                    transformSet = true;
3415                    break;
3416                case com.android.internal.R.styleable.View_translationY:
3417                    ty = a.getDimensionPixelOffset(attr, 0);
3418                    transformSet = true;
3419                    break;
3420                case com.android.internal.R.styleable.View_rotation:
3421                    rotation = a.getFloat(attr, 0);
3422                    transformSet = true;
3423                    break;
3424                case com.android.internal.R.styleable.View_rotationX:
3425                    rotationX = a.getFloat(attr, 0);
3426                    transformSet = true;
3427                    break;
3428                case com.android.internal.R.styleable.View_rotationY:
3429                    rotationY = a.getFloat(attr, 0);
3430                    transformSet = true;
3431                    break;
3432                case com.android.internal.R.styleable.View_scaleX:
3433                    sx = a.getFloat(attr, 1f);
3434                    transformSet = true;
3435                    break;
3436                case com.android.internal.R.styleable.View_scaleY:
3437                    sy = a.getFloat(attr, 1f);
3438                    transformSet = true;
3439                    break;
3440                case com.android.internal.R.styleable.View_id:
3441                    mID = a.getResourceId(attr, NO_ID);
3442                    break;
3443                case com.android.internal.R.styleable.View_tag:
3444                    mTag = a.getText(attr);
3445                    break;
3446                case com.android.internal.R.styleable.View_fitsSystemWindows:
3447                    if (a.getBoolean(attr, false)) {
3448                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3449                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3450                    }
3451                    break;
3452                case com.android.internal.R.styleable.View_focusable:
3453                    if (a.getBoolean(attr, false)) {
3454                        viewFlagValues |= FOCUSABLE;
3455                        viewFlagMasks |= FOCUSABLE_MASK;
3456                    }
3457                    break;
3458                case com.android.internal.R.styleable.View_focusableInTouchMode:
3459                    if (a.getBoolean(attr, false)) {
3460                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3461                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3462                    }
3463                    break;
3464                case com.android.internal.R.styleable.View_clickable:
3465                    if (a.getBoolean(attr, false)) {
3466                        viewFlagValues |= CLICKABLE;
3467                        viewFlagMasks |= CLICKABLE;
3468                    }
3469                    break;
3470                case com.android.internal.R.styleable.View_longClickable:
3471                    if (a.getBoolean(attr, false)) {
3472                        viewFlagValues |= LONG_CLICKABLE;
3473                        viewFlagMasks |= LONG_CLICKABLE;
3474                    }
3475                    break;
3476                case com.android.internal.R.styleable.View_saveEnabled:
3477                    if (!a.getBoolean(attr, true)) {
3478                        viewFlagValues |= SAVE_DISABLED;
3479                        viewFlagMasks |= SAVE_DISABLED_MASK;
3480                    }
3481                    break;
3482                case com.android.internal.R.styleable.View_duplicateParentState:
3483                    if (a.getBoolean(attr, false)) {
3484                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3485                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3486                    }
3487                    break;
3488                case com.android.internal.R.styleable.View_visibility:
3489                    final int visibility = a.getInt(attr, 0);
3490                    if (visibility != 0) {
3491                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3492                        viewFlagMasks |= VISIBILITY_MASK;
3493                    }
3494                    break;
3495                case com.android.internal.R.styleable.View_layoutDirection:
3496                    // Clear any layout direction flags (included resolved bits) already set
3497                    mPrivateFlags2 &=
3498                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3499                    // Set the layout direction flags depending on the value of the attribute
3500                    final int layoutDirection = a.getInt(attr, -1);
3501                    final int value = (layoutDirection != -1) ?
3502                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3503                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3504                    break;
3505                case com.android.internal.R.styleable.View_drawingCacheQuality:
3506                    final int cacheQuality = a.getInt(attr, 0);
3507                    if (cacheQuality != 0) {
3508                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3509                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3510                    }
3511                    break;
3512                case com.android.internal.R.styleable.View_contentDescription:
3513                    setContentDescription(a.getString(attr));
3514                    break;
3515                case com.android.internal.R.styleable.View_labelFor:
3516                    setLabelFor(a.getResourceId(attr, NO_ID));
3517                    break;
3518                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3519                    if (!a.getBoolean(attr, true)) {
3520                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3521                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3522                    }
3523                    break;
3524                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3525                    if (!a.getBoolean(attr, true)) {
3526                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3527                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3528                    }
3529                    break;
3530                case R.styleable.View_scrollbars:
3531                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3532                    if (scrollbars != SCROLLBARS_NONE) {
3533                        viewFlagValues |= scrollbars;
3534                        viewFlagMasks |= SCROLLBARS_MASK;
3535                        initializeScrollbars = true;
3536                    }
3537                    break;
3538                //noinspection deprecation
3539                case R.styleable.View_fadingEdge:
3540                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3541                        // Ignore the attribute starting with ICS
3542                        break;
3543                    }
3544                    // With builds < ICS, fall through and apply fading edges
3545                case R.styleable.View_requiresFadingEdge:
3546                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3547                    if (fadingEdge != FADING_EDGE_NONE) {
3548                        viewFlagValues |= fadingEdge;
3549                        viewFlagMasks |= FADING_EDGE_MASK;
3550                        initializeFadingEdge(a);
3551                    }
3552                    break;
3553                case R.styleable.View_scrollbarStyle:
3554                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3555                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3556                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3557                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3558                    }
3559                    break;
3560                case R.styleable.View_isScrollContainer:
3561                    setScrollContainer = true;
3562                    if (a.getBoolean(attr, false)) {
3563                        setScrollContainer(true);
3564                    }
3565                    break;
3566                case com.android.internal.R.styleable.View_keepScreenOn:
3567                    if (a.getBoolean(attr, false)) {
3568                        viewFlagValues |= KEEP_SCREEN_ON;
3569                        viewFlagMasks |= KEEP_SCREEN_ON;
3570                    }
3571                    break;
3572                case R.styleable.View_filterTouchesWhenObscured:
3573                    if (a.getBoolean(attr, false)) {
3574                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3575                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3576                    }
3577                    break;
3578                case R.styleable.View_nextFocusLeft:
3579                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3580                    break;
3581                case R.styleable.View_nextFocusRight:
3582                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3583                    break;
3584                case R.styleable.View_nextFocusUp:
3585                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3586                    break;
3587                case R.styleable.View_nextFocusDown:
3588                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3589                    break;
3590                case R.styleable.View_nextFocusForward:
3591                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3592                    break;
3593                case R.styleable.View_minWidth:
3594                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3595                    break;
3596                case R.styleable.View_minHeight:
3597                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3598                    break;
3599                case R.styleable.View_onClick:
3600                    if (context.isRestricted()) {
3601                        throw new IllegalStateException("The android:onClick attribute cannot "
3602                                + "be used within a restricted context");
3603                    }
3604
3605                    final String handlerName = a.getString(attr);
3606                    if (handlerName != null) {
3607                        setOnClickListener(new OnClickListener() {
3608                            private Method mHandler;
3609
3610                            public void onClick(View v) {
3611                                if (mHandler == null) {
3612                                    try {
3613                                        mHandler = getContext().getClass().getMethod(handlerName,
3614                                                View.class);
3615                                    } catch (NoSuchMethodException e) {
3616                                        int id = getId();
3617                                        String idText = id == NO_ID ? "" : " with id '"
3618                                                + getContext().getResources().getResourceEntryName(
3619                                                    id) + "'";
3620                                        throw new IllegalStateException("Could not find a method " +
3621                                                handlerName + "(View) in the activity "
3622                                                + getContext().getClass() + " for onClick handler"
3623                                                + " on view " + View.this.getClass() + idText, e);
3624                                    }
3625                                }
3626
3627                                try {
3628                                    mHandler.invoke(getContext(), View.this);
3629                                } catch (IllegalAccessException e) {
3630                                    throw new IllegalStateException("Could not execute non "
3631                                            + "public method of the activity", e);
3632                                } catch (InvocationTargetException e) {
3633                                    throw new IllegalStateException("Could not execute "
3634                                            + "method of the activity", e);
3635                                }
3636                            }
3637                        });
3638                    }
3639                    break;
3640                case R.styleable.View_overScrollMode:
3641                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3642                    break;
3643                case R.styleable.View_verticalScrollbarPosition:
3644                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3645                    break;
3646                case R.styleable.View_layerType:
3647                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3648                    break;
3649                case R.styleable.View_textDirection:
3650                    // Clear any text direction flag already set
3651                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3652                    // Set the text direction flags depending on the value of the attribute
3653                    final int textDirection = a.getInt(attr, -1);
3654                    if (textDirection != -1) {
3655                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3656                    }
3657                    break;
3658                case R.styleable.View_textAlignment:
3659                    // Clear any text alignment flag already set
3660                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3661                    // Set the text alignment flag depending on the value of the attribute
3662                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3663                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3664                    break;
3665                case R.styleable.View_importantForAccessibility:
3666                    setImportantForAccessibility(a.getInt(attr,
3667                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3668                    break;
3669            }
3670        }
3671
3672        setOverScrollMode(overScrollMode);
3673
3674        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3675        // the resolved layout direction). Those cached values will be used later during padding
3676        // resolution.
3677        mUserPaddingStart = startPadding;
3678        mUserPaddingEnd = endPadding;
3679
3680        if (background != null) {
3681            setBackground(background);
3682        }
3683
3684        if (padding >= 0) {
3685            leftPadding = padding;
3686            topPadding = padding;
3687            rightPadding = padding;
3688            bottomPadding = padding;
3689            mUserPaddingLeftInitial = padding;
3690            mUserPaddingRightInitial = padding;
3691        }
3692
3693        if (isRtlCompatibilityMode()) {
3694            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3695            // left / right padding are used if defined (meaning here nothing to do). If they are not
3696            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3697            // start / end and resolve them as left / right (layout direction is not taken into account).
3698            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3699            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3700            // defined.
3701            if (!leftPaddingDefined && startPaddingDefined) {
3702                leftPadding = startPadding;
3703            }
3704            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3705            if (!rightPaddingDefined && endPaddingDefined) {
3706                rightPadding = endPadding;
3707            }
3708            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3709        } else {
3710            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3711            // values defined. Otherwise, left /right values are used.
3712            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3713            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3714            // defined.
3715            if (leftPaddingDefined) {
3716                mUserPaddingLeftInitial = leftPadding;
3717            }
3718            if (rightPaddingDefined) {
3719                mUserPaddingRightInitial = rightPadding;
3720            }
3721        }
3722
3723        internalSetPadding(
3724                mUserPaddingLeftInitial,
3725                topPadding >= 0 ? topPadding : mPaddingTop,
3726                mUserPaddingRightInitial,
3727                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3728
3729        if (viewFlagMasks != 0) {
3730            setFlags(viewFlagValues, viewFlagMasks);
3731        }
3732
3733        if (initializeScrollbars) {
3734            initializeScrollbars(a);
3735        }
3736
3737        a.recycle();
3738
3739        // Needs to be called after mViewFlags is set
3740        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3741            recomputePadding();
3742        }
3743
3744        if (x != 0 || y != 0) {
3745            scrollTo(x, y);
3746        }
3747
3748        if (transformSet) {
3749            setTranslationX(tx);
3750            setTranslationY(ty);
3751            setRotation(rotation);
3752            setRotationX(rotationX);
3753            setRotationY(rotationY);
3754            setScaleX(sx);
3755            setScaleY(sy);
3756        }
3757
3758        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3759            setScrollContainer(true);
3760        }
3761
3762        computeOpaqueFlags();
3763    }
3764
3765    /**
3766     * Non-public constructor for use in testing
3767     */
3768    View() {
3769        mResources = null;
3770    }
3771
3772    public String toString() {
3773        StringBuilder out = new StringBuilder(128);
3774        out.append(getClass().getName());
3775        out.append('{');
3776        out.append(Integer.toHexString(System.identityHashCode(this)));
3777        out.append(' ');
3778        switch (mViewFlags&VISIBILITY_MASK) {
3779            case VISIBLE: out.append('V'); break;
3780            case INVISIBLE: out.append('I'); break;
3781            case GONE: out.append('G'); break;
3782            default: out.append('.'); break;
3783        }
3784        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3785        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3786        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3787        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3788        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3789        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3790        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3791        out.append(' ');
3792        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3793        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3794        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3795        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3796            out.append('p');
3797        } else {
3798            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3799        }
3800        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3801        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3802        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3803        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3804        out.append(' ');
3805        out.append(mLeft);
3806        out.append(',');
3807        out.append(mTop);
3808        out.append('-');
3809        out.append(mRight);
3810        out.append(',');
3811        out.append(mBottom);
3812        final int id = getId();
3813        if (id != NO_ID) {
3814            out.append(" #");
3815            out.append(Integer.toHexString(id));
3816            final Resources r = mResources;
3817            if (id != 0 && r != null) {
3818                try {
3819                    String pkgname;
3820                    switch (id&0xff000000) {
3821                        case 0x7f000000:
3822                            pkgname="app";
3823                            break;
3824                        case 0x01000000:
3825                            pkgname="android";
3826                            break;
3827                        default:
3828                            pkgname = r.getResourcePackageName(id);
3829                            break;
3830                    }
3831                    String typename = r.getResourceTypeName(id);
3832                    String entryname = r.getResourceEntryName(id);
3833                    out.append(" ");
3834                    out.append(pkgname);
3835                    out.append(":");
3836                    out.append(typename);
3837                    out.append("/");
3838                    out.append(entryname);
3839                } catch (Resources.NotFoundException e) {
3840                }
3841            }
3842        }
3843        out.append("}");
3844        return out.toString();
3845    }
3846
3847    /**
3848     * <p>
3849     * Initializes the fading edges from a given set of styled attributes. This
3850     * method should be called by subclasses that need fading edges and when an
3851     * instance of these subclasses is created programmatically rather than
3852     * being inflated from XML. This method is automatically called when the XML
3853     * is inflated.
3854     * </p>
3855     *
3856     * @param a the styled attributes set to initialize the fading edges from
3857     */
3858    protected void initializeFadingEdge(TypedArray a) {
3859        initScrollCache();
3860
3861        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3862                R.styleable.View_fadingEdgeLength,
3863                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3864    }
3865
3866    /**
3867     * Returns the size of the vertical faded edges used to indicate that more
3868     * content in this view is visible.
3869     *
3870     * @return The size in pixels of the vertical faded edge or 0 if vertical
3871     *         faded edges are not enabled for this view.
3872     * @attr ref android.R.styleable#View_fadingEdgeLength
3873     */
3874    public int getVerticalFadingEdgeLength() {
3875        if (isVerticalFadingEdgeEnabled()) {
3876            ScrollabilityCache cache = mScrollCache;
3877            if (cache != null) {
3878                return cache.fadingEdgeLength;
3879            }
3880        }
3881        return 0;
3882    }
3883
3884    /**
3885     * Set the size of the faded edge used to indicate that more content in this
3886     * view is available.  Will not change whether the fading edge is enabled; use
3887     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3888     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3889     * for the vertical or horizontal fading edges.
3890     *
3891     * @param length The size in pixels of the faded edge used to indicate that more
3892     *        content in this view is visible.
3893     */
3894    public void setFadingEdgeLength(int length) {
3895        initScrollCache();
3896        mScrollCache.fadingEdgeLength = length;
3897    }
3898
3899    /**
3900     * Returns the size of the horizontal faded edges used to indicate that more
3901     * content in this view is visible.
3902     *
3903     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3904     *         faded edges are not enabled for this view.
3905     * @attr ref android.R.styleable#View_fadingEdgeLength
3906     */
3907    public int getHorizontalFadingEdgeLength() {
3908        if (isHorizontalFadingEdgeEnabled()) {
3909            ScrollabilityCache cache = mScrollCache;
3910            if (cache != null) {
3911                return cache.fadingEdgeLength;
3912            }
3913        }
3914        return 0;
3915    }
3916
3917    /**
3918     * Returns the width of the vertical scrollbar.
3919     *
3920     * @return The width in pixels of the vertical scrollbar or 0 if there
3921     *         is no vertical scrollbar.
3922     */
3923    public int getVerticalScrollbarWidth() {
3924        ScrollabilityCache cache = mScrollCache;
3925        if (cache != null) {
3926            ScrollBarDrawable scrollBar = cache.scrollBar;
3927            if (scrollBar != null) {
3928                int size = scrollBar.getSize(true);
3929                if (size <= 0) {
3930                    size = cache.scrollBarSize;
3931                }
3932                return size;
3933            }
3934            return 0;
3935        }
3936        return 0;
3937    }
3938
3939    /**
3940     * Returns the height of the horizontal scrollbar.
3941     *
3942     * @return The height in pixels of the horizontal scrollbar or 0 if
3943     *         there is no horizontal scrollbar.
3944     */
3945    protected int getHorizontalScrollbarHeight() {
3946        ScrollabilityCache cache = mScrollCache;
3947        if (cache != null) {
3948            ScrollBarDrawable scrollBar = cache.scrollBar;
3949            if (scrollBar != null) {
3950                int size = scrollBar.getSize(false);
3951                if (size <= 0) {
3952                    size = cache.scrollBarSize;
3953                }
3954                return size;
3955            }
3956            return 0;
3957        }
3958        return 0;
3959    }
3960
3961    /**
3962     * <p>
3963     * Initializes the scrollbars from a given set of styled attributes. This
3964     * method should be called by subclasses that need scrollbars and when an
3965     * instance of these subclasses is created programmatically rather than
3966     * being inflated from XML. This method is automatically called when the XML
3967     * is inflated.
3968     * </p>
3969     *
3970     * @param a the styled attributes set to initialize the scrollbars from
3971     */
3972    protected void initializeScrollbars(TypedArray a) {
3973        initScrollCache();
3974
3975        final ScrollabilityCache scrollabilityCache = mScrollCache;
3976
3977        if (scrollabilityCache.scrollBar == null) {
3978            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3979        }
3980
3981        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3982
3983        if (!fadeScrollbars) {
3984            scrollabilityCache.state = ScrollabilityCache.ON;
3985        }
3986        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3987
3988
3989        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3990                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3991                        .getScrollBarFadeDuration());
3992        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3993                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3994                ViewConfiguration.getScrollDefaultDelay());
3995
3996
3997        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3998                com.android.internal.R.styleable.View_scrollbarSize,
3999                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4000
4001        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4002        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4003
4004        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4005        if (thumb != null) {
4006            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4007        }
4008
4009        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4010                false);
4011        if (alwaysDraw) {
4012            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4013        }
4014
4015        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4016        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4017
4018        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4019        if (thumb != null) {
4020            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4021        }
4022
4023        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4024                false);
4025        if (alwaysDraw) {
4026            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4027        }
4028
4029        // Apply layout direction to the new Drawables if needed
4030        final int layoutDirection = getLayoutDirection();
4031        if (track != null) {
4032            track.setLayoutDirection(layoutDirection);
4033        }
4034        if (thumb != null) {
4035            thumb.setLayoutDirection(layoutDirection);
4036        }
4037
4038        // Re-apply user/background padding so that scrollbar(s) get added
4039        resolvePadding();
4040    }
4041
4042    /**
4043     * <p>
4044     * Initalizes the scrollability cache if necessary.
4045     * </p>
4046     */
4047    private void initScrollCache() {
4048        if (mScrollCache == null) {
4049            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4050        }
4051    }
4052
4053    private ScrollabilityCache getScrollCache() {
4054        initScrollCache();
4055        return mScrollCache;
4056    }
4057
4058    /**
4059     * Set the position of the vertical scroll bar. Should be one of
4060     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4061     * {@link #SCROLLBAR_POSITION_RIGHT}.
4062     *
4063     * @param position Where the vertical scroll bar should be positioned.
4064     */
4065    public void setVerticalScrollbarPosition(int position) {
4066        if (mVerticalScrollbarPosition != position) {
4067            mVerticalScrollbarPosition = position;
4068            computeOpaqueFlags();
4069            resolvePadding();
4070        }
4071    }
4072
4073    /**
4074     * @return The position where the vertical scroll bar will show, if applicable.
4075     * @see #setVerticalScrollbarPosition(int)
4076     */
4077    public int getVerticalScrollbarPosition() {
4078        return mVerticalScrollbarPosition;
4079    }
4080
4081    ListenerInfo getListenerInfo() {
4082        if (mListenerInfo != null) {
4083            return mListenerInfo;
4084        }
4085        mListenerInfo = new ListenerInfo();
4086        return mListenerInfo;
4087    }
4088
4089    /**
4090     * Register a callback to be invoked when focus of this view changed.
4091     *
4092     * @param l The callback that will run.
4093     */
4094    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4095        getListenerInfo().mOnFocusChangeListener = l;
4096    }
4097
4098    /**
4099     * Add a listener that will be called when the bounds of the view change due to
4100     * layout processing.
4101     *
4102     * @param listener The listener that will be called when layout bounds change.
4103     */
4104    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4105        ListenerInfo li = getListenerInfo();
4106        if (li.mOnLayoutChangeListeners == null) {
4107            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4108        }
4109        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4110            li.mOnLayoutChangeListeners.add(listener);
4111        }
4112    }
4113
4114    /**
4115     * Remove a listener for layout changes.
4116     *
4117     * @param listener The listener for layout bounds change.
4118     */
4119    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4120        ListenerInfo li = mListenerInfo;
4121        if (li == null || li.mOnLayoutChangeListeners == null) {
4122            return;
4123        }
4124        li.mOnLayoutChangeListeners.remove(listener);
4125    }
4126
4127    /**
4128     * Add a listener for attach state changes.
4129     *
4130     * This listener will be called whenever this view is attached or detached
4131     * from a window. Remove the listener using
4132     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4133     *
4134     * @param listener Listener to attach
4135     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4136     */
4137    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4138        ListenerInfo li = getListenerInfo();
4139        if (li.mOnAttachStateChangeListeners == null) {
4140            li.mOnAttachStateChangeListeners
4141                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4142        }
4143        li.mOnAttachStateChangeListeners.add(listener);
4144    }
4145
4146    /**
4147     * Remove a listener for attach state changes. The listener will receive no further
4148     * notification of window attach/detach events.
4149     *
4150     * @param listener Listener to remove
4151     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4152     */
4153    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4154        ListenerInfo li = mListenerInfo;
4155        if (li == null || li.mOnAttachStateChangeListeners == null) {
4156            return;
4157        }
4158        li.mOnAttachStateChangeListeners.remove(listener);
4159    }
4160
4161    /**
4162     * Returns the focus-change callback registered for this view.
4163     *
4164     * @return The callback, or null if one is not registered.
4165     */
4166    public OnFocusChangeListener getOnFocusChangeListener() {
4167        ListenerInfo li = mListenerInfo;
4168        return li != null ? li.mOnFocusChangeListener : null;
4169    }
4170
4171    /**
4172     * Register a callback to be invoked when this view is clicked. If this view is not
4173     * clickable, it becomes clickable.
4174     *
4175     * @param l The callback that will run
4176     *
4177     * @see #setClickable(boolean)
4178     */
4179    public void setOnClickListener(OnClickListener l) {
4180        if (!isClickable()) {
4181            setClickable(true);
4182        }
4183        getListenerInfo().mOnClickListener = l;
4184    }
4185
4186    /**
4187     * Return whether this view has an attached OnClickListener.  Returns
4188     * true if there is a listener, false if there is none.
4189     */
4190    public boolean hasOnClickListeners() {
4191        ListenerInfo li = mListenerInfo;
4192        return (li != null && li.mOnClickListener != null);
4193    }
4194
4195    /**
4196     * Register a callback to be invoked when this view is clicked and held. If this view is not
4197     * long clickable, it becomes long clickable.
4198     *
4199     * @param l The callback that will run
4200     *
4201     * @see #setLongClickable(boolean)
4202     */
4203    public void setOnLongClickListener(OnLongClickListener l) {
4204        if (!isLongClickable()) {
4205            setLongClickable(true);
4206        }
4207        getListenerInfo().mOnLongClickListener = l;
4208    }
4209
4210    /**
4211     * Register a callback to be invoked when the context menu for this view is
4212     * being built. If this view is not long clickable, it becomes long clickable.
4213     *
4214     * @param l The callback that will run
4215     *
4216     */
4217    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4218        if (!isLongClickable()) {
4219            setLongClickable(true);
4220        }
4221        getListenerInfo().mOnCreateContextMenuListener = l;
4222    }
4223
4224    /**
4225     * Call this view's OnClickListener, if it is defined.  Performs all normal
4226     * actions associated with clicking: reporting accessibility event, playing
4227     * a sound, etc.
4228     *
4229     * @return True there was an assigned OnClickListener that was called, false
4230     *         otherwise is returned.
4231     */
4232    public boolean performClick() {
4233        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4234
4235        ListenerInfo li = mListenerInfo;
4236        if (li != null && li.mOnClickListener != null) {
4237            playSoundEffect(SoundEffectConstants.CLICK);
4238            li.mOnClickListener.onClick(this);
4239            return true;
4240        }
4241
4242        return false;
4243    }
4244
4245    /**
4246     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4247     * this only calls the listener, and does not do any associated clicking
4248     * actions like reporting an accessibility event.
4249     *
4250     * @return True there was an assigned OnClickListener that was called, false
4251     *         otherwise is returned.
4252     */
4253    public boolean callOnClick() {
4254        ListenerInfo li = mListenerInfo;
4255        if (li != null && li.mOnClickListener != null) {
4256            li.mOnClickListener.onClick(this);
4257            return true;
4258        }
4259        return false;
4260    }
4261
4262    /**
4263     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4264     * OnLongClickListener did not consume the event.
4265     *
4266     * @return True if one of the above receivers consumed the event, false otherwise.
4267     */
4268    public boolean performLongClick() {
4269        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4270
4271        boolean handled = false;
4272        ListenerInfo li = mListenerInfo;
4273        if (li != null && li.mOnLongClickListener != null) {
4274            handled = li.mOnLongClickListener.onLongClick(View.this);
4275        }
4276        if (!handled) {
4277            handled = showContextMenu();
4278        }
4279        if (handled) {
4280            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4281        }
4282        return handled;
4283    }
4284
4285    /**
4286     * Performs button-related actions during a touch down event.
4287     *
4288     * @param event The event.
4289     * @return True if the down was consumed.
4290     *
4291     * @hide
4292     */
4293    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4294        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4295            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4296                return true;
4297            }
4298        }
4299        return false;
4300    }
4301
4302    /**
4303     * Bring up the context menu for this view.
4304     *
4305     * @return Whether a context menu was displayed.
4306     */
4307    public boolean showContextMenu() {
4308        return getParent().showContextMenuForChild(this);
4309    }
4310
4311    /**
4312     * Bring up the context menu for this view, referring to the item under the specified point.
4313     *
4314     * @param x The referenced x coordinate.
4315     * @param y The referenced y coordinate.
4316     * @param metaState The keyboard modifiers that were pressed.
4317     * @return Whether a context menu was displayed.
4318     *
4319     * @hide
4320     */
4321    public boolean showContextMenu(float x, float y, int metaState) {
4322        return showContextMenu();
4323    }
4324
4325    /**
4326     * Start an action mode.
4327     *
4328     * @param callback Callback that will control the lifecycle of the action mode
4329     * @return The new action mode if it is started, null otherwise
4330     *
4331     * @see ActionMode
4332     */
4333    public ActionMode startActionMode(ActionMode.Callback callback) {
4334        ViewParent parent = getParent();
4335        if (parent == null) return null;
4336        return parent.startActionModeForChild(this, callback);
4337    }
4338
4339    /**
4340     * Register a callback to be invoked when a hardware key is pressed in this view.
4341     * Key presses in software input methods will generally not trigger the methods of
4342     * this listener.
4343     * @param l the key listener to attach to this view
4344     */
4345    public void setOnKeyListener(OnKeyListener l) {
4346        getListenerInfo().mOnKeyListener = l;
4347    }
4348
4349    /**
4350     * Register a callback to be invoked when a touch event is sent to this view.
4351     * @param l the touch listener to attach to this view
4352     */
4353    public void setOnTouchListener(OnTouchListener l) {
4354        getListenerInfo().mOnTouchListener = l;
4355    }
4356
4357    /**
4358     * Register a callback to be invoked when a generic motion event is sent to this view.
4359     * @param l the generic motion listener to attach to this view
4360     */
4361    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4362        getListenerInfo().mOnGenericMotionListener = l;
4363    }
4364
4365    /**
4366     * Register a callback to be invoked when a hover event is sent to this view.
4367     * @param l the hover listener to attach to this view
4368     */
4369    public void setOnHoverListener(OnHoverListener l) {
4370        getListenerInfo().mOnHoverListener = l;
4371    }
4372
4373    /**
4374     * Register a drag event listener callback object for this View. The parameter is
4375     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4376     * View, the system calls the
4377     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4378     * @param l An implementation of {@link android.view.View.OnDragListener}.
4379     */
4380    public void setOnDragListener(OnDragListener l) {
4381        getListenerInfo().mOnDragListener = l;
4382    }
4383
4384    /**
4385     * Give this view focus. This will cause
4386     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4387     *
4388     * Note: this does not check whether this {@link View} should get focus, it just
4389     * gives it focus no matter what.  It should only be called internally by framework
4390     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4391     *
4392     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4393     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4394     *        focus moved when requestFocus() is called. It may not always
4395     *        apply, in which case use the default View.FOCUS_DOWN.
4396     * @param previouslyFocusedRect The rectangle of the view that had focus
4397     *        prior in this View's coordinate system.
4398     */
4399    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4400        if (DBG) {
4401            System.out.println(this + " requestFocus()");
4402        }
4403
4404        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4405            mPrivateFlags |= PFLAG_FOCUSED;
4406
4407            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4408
4409            if (mParent != null) {
4410                mParent.requestChildFocus(this, this);
4411            }
4412
4413            if (mAttachInfo != null) {
4414                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4415            }
4416
4417            onFocusChanged(true, direction, previouslyFocusedRect);
4418            refreshDrawableState();
4419
4420            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4421                notifyAccessibilityStateChanged();
4422            }
4423        }
4424    }
4425
4426    /**
4427     * Request that a rectangle of this view be visible on the screen,
4428     * scrolling if necessary just enough.
4429     *
4430     * <p>A View should call this if it maintains some notion of which part
4431     * of its content is interesting.  For example, a text editing view
4432     * should call this when its cursor moves.
4433     *
4434     * @param rectangle The rectangle.
4435     * @return Whether any parent scrolled.
4436     */
4437    public boolean requestRectangleOnScreen(Rect rectangle) {
4438        return requestRectangleOnScreen(rectangle, false);
4439    }
4440
4441    /**
4442     * Request that a rectangle of this view be visible on the screen,
4443     * scrolling if necessary just enough.
4444     *
4445     * <p>A View should call this if it maintains some notion of which part
4446     * of its content is interesting.  For example, a text editing view
4447     * should call this when its cursor moves.
4448     *
4449     * <p>When <code>immediate</code> is set to true, scrolling will not be
4450     * animated.
4451     *
4452     * @param rectangle The rectangle.
4453     * @param immediate True to forbid animated scrolling, false otherwise
4454     * @return Whether any parent scrolled.
4455     */
4456    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4457        if (mParent == null) {
4458            return false;
4459        }
4460
4461        View child = this;
4462
4463        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4464        position.set(rectangle);
4465
4466        ViewParent parent = mParent;
4467        boolean scrolled = false;
4468        while (parent != null) {
4469            rectangle.set((int) position.left, (int) position.top,
4470                    (int) position.right, (int) position.bottom);
4471
4472            scrolled |= parent.requestChildRectangleOnScreen(child,
4473                    rectangle, immediate);
4474
4475            if (!child.hasIdentityMatrix()) {
4476                child.getMatrix().mapRect(position);
4477            }
4478
4479            position.offset(child.mLeft, child.mTop);
4480
4481            if (!(parent instanceof View)) {
4482                break;
4483            }
4484
4485            View parentView = (View) parent;
4486
4487            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4488
4489            child = parentView;
4490            parent = child.getParent();
4491        }
4492
4493        return scrolled;
4494    }
4495
4496    /**
4497     * Called when this view wants to give up focus. If focus is cleared
4498     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4499     * <p>
4500     * <strong>Note:</strong> When a View clears focus the framework is trying
4501     * to give focus to the first focusable View from the top. Hence, if this
4502     * View is the first from the top that can take focus, then all callbacks
4503     * related to clearing focus will be invoked after wich the framework will
4504     * give focus to this view.
4505     * </p>
4506     */
4507    public void clearFocus() {
4508        if (DBG) {
4509            System.out.println(this + " clearFocus()");
4510        }
4511
4512        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4513            mPrivateFlags &= ~PFLAG_FOCUSED;
4514
4515            if (mParent != null) {
4516                mParent.clearChildFocus(this);
4517            }
4518
4519            onFocusChanged(false, 0, null);
4520
4521            refreshDrawableState();
4522
4523            if (!rootViewRequestFocus()) {
4524                notifyGlobalFocusCleared(this);
4525            }
4526
4527            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4528                notifyAccessibilityStateChanged();
4529            }
4530        }
4531    }
4532
4533    void notifyGlobalFocusCleared(View oldFocus) {
4534        if (oldFocus != null && mAttachInfo != null) {
4535            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4536        }
4537    }
4538
4539    boolean rootViewRequestFocus() {
4540        View root = getRootView();
4541        if (root != null) {
4542            return root.requestFocus();
4543        }
4544        return false;
4545    }
4546
4547    /**
4548     * Called internally by the view system when a new view is getting focus.
4549     * This is what clears the old focus.
4550     */
4551    void unFocus() {
4552        if (DBG) {
4553            System.out.println(this + " unFocus()");
4554        }
4555
4556        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4557            mPrivateFlags &= ~PFLAG_FOCUSED;
4558
4559            onFocusChanged(false, 0, null);
4560            refreshDrawableState();
4561
4562            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4563                notifyAccessibilityStateChanged();
4564            }
4565        }
4566    }
4567
4568    /**
4569     * Returns true if this view has focus iteself, or is the ancestor of the
4570     * view that has focus.
4571     *
4572     * @return True if this view has or contains focus, false otherwise.
4573     */
4574    @ViewDebug.ExportedProperty(category = "focus")
4575    public boolean hasFocus() {
4576        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4577    }
4578
4579    /**
4580     * Returns true if this view is focusable or if it contains a reachable View
4581     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4582     * is a View whose parents do not block descendants focus.
4583     *
4584     * Only {@link #VISIBLE} views are considered focusable.
4585     *
4586     * @return True if the view is focusable or if the view contains a focusable
4587     *         View, false otherwise.
4588     *
4589     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4590     */
4591    public boolean hasFocusable() {
4592        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4593    }
4594
4595    /**
4596     * Called by the view system when the focus state of this view changes.
4597     * When the focus change event is caused by directional navigation, direction
4598     * and previouslyFocusedRect provide insight into where the focus is coming from.
4599     * When overriding, be sure to call up through to the super class so that
4600     * the standard focus handling will occur.
4601     *
4602     * @param gainFocus True if the View has focus; false otherwise.
4603     * @param direction The direction focus has moved when requestFocus()
4604     *                  is called to give this view focus. Values are
4605     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4606     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4607     *                  It may not always apply, in which case use the default.
4608     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4609     *        system, of the previously focused view.  If applicable, this will be
4610     *        passed in as finer grained information about where the focus is coming
4611     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4612     */
4613    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4614        if (gainFocus) {
4615            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4616                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4617            }
4618        }
4619
4620        InputMethodManager imm = InputMethodManager.peekInstance();
4621        if (!gainFocus) {
4622            if (isPressed()) {
4623                setPressed(false);
4624            }
4625            if (imm != null && mAttachInfo != null
4626                    && mAttachInfo.mHasWindowFocus) {
4627                imm.focusOut(this);
4628            }
4629            onFocusLost();
4630        } else if (imm != null && mAttachInfo != null
4631                && mAttachInfo.mHasWindowFocus) {
4632            imm.focusIn(this);
4633        }
4634
4635        invalidate(true);
4636        ListenerInfo li = mListenerInfo;
4637        if (li != null && li.mOnFocusChangeListener != null) {
4638            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4639        }
4640
4641        if (mAttachInfo != null) {
4642            mAttachInfo.mKeyDispatchState.reset(this);
4643        }
4644    }
4645
4646    /**
4647     * Sends an accessibility event of the given type. If accessibility is
4648     * not enabled this method has no effect. The default implementation calls
4649     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4650     * to populate information about the event source (this View), then calls
4651     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4652     * populate the text content of the event source including its descendants,
4653     * and last calls
4654     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4655     * on its parent to resuest sending of the event to interested parties.
4656     * <p>
4657     * If an {@link AccessibilityDelegate} has been specified via calling
4658     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4659     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4660     * responsible for handling this call.
4661     * </p>
4662     *
4663     * @param eventType The type of the event to send, as defined by several types from
4664     * {@link android.view.accessibility.AccessibilityEvent}, such as
4665     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4666     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4667     *
4668     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4669     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4670     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4671     * @see AccessibilityDelegate
4672     */
4673    public void sendAccessibilityEvent(int eventType) {
4674        if (mAccessibilityDelegate != null) {
4675            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4676        } else {
4677            sendAccessibilityEventInternal(eventType);
4678        }
4679    }
4680
4681    /**
4682     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4683     * {@link AccessibilityEvent} to make an announcement which is related to some
4684     * sort of a context change for which none of the events representing UI transitions
4685     * is a good fit. For example, announcing a new page in a book. If accessibility
4686     * is not enabled this method does nothing.
4687     *
4688     * @param text The announcement text.
4689     */
4690    public void announceForAccessibility(CharSequence text) {
4691        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4692            AccessibilityEvent event = AccessibilityEvent.obtain(
4693                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4694            onInitializeAccessibilityEvent(event);
4695            event.getText().add(text);
4696            event.setContentDescription(null);
4697            mParent.requestSendAccessibilityEvent(this, event);
4698        }
4699    }
4700
4701    /**
4702     * @see #sendAccessibilityEvent(int)
4703     *
4704     * Note: Called from the default {@link AccessibilityDelegate}.
4705     */
4706    void sendAccessibilityEventInternal(int eventType) {
4707        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4708            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4709        }
4710    }
4711
4712    /**
4713     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4714     * takes as an argument an empty {@link AccessibilityEvent} and does not
4715     * perform a check whether accessibility is enabled.
4716     * <p>
4717     * If an {@link AccessibilityDelegate} has been specified via calling
4718     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4719     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4720     * is responsible for handling this call.
4721     * </p>
4722     *
4723     * @param event The event to send.
4724     *
4725     * @see #sendAccessibilityEvent(int)
4726     */
4727    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4728        if (mAccessibilityDelegate != null) {
4729            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4730        } else {
4731            sendAccessibilityEventUncheckedInternal(event);
4732        }
4733    }
4734
4735    /**
4736     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4737     *
4738     * Note: Called from the default {@link AccessibilityDelegate}.
4739     */
4740    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4741        if (!isShown()) {
4742            return;
4743        }
4744        onInitializeAccessibilityEvent(event);
4745        // Only a subset of accessibility events populates text content.
4746        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4747            dispatchPopulateAccessibilityEvent(event);
4748        }
4749        // In the beginning we called #isShown(), so we know that getParent() is not null.
4750        getParent().requestSendAccessibilityEvent(this, event);
4751    }
4752
4753    /**
4754     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4755     * to its children for adding their text content to the event. Note that the
4756     * event text is populated in a separate dispatch path since we add to the
4757     * event not only the text of the source but also the text of all its descendants.
4758     * A typical implementation will call
4759     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4760     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4761     * on each child. Override this method if custom population of the event text
4762     * content is required.
4763     * <p>
4764     * If an {@link AccessibilityDelegate} has been specified via calling
4765     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4766     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4767     * is responsible for handling this call.
4768     * </p>
4769     * <p>
4770     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4771     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4772     * </p>
4773     *
4774     * @param event The event.
4775     *
4776     * @return True if the event population was completed.
4777     */
4778    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4779        if (mAccessibilityDelegate != null) {
4780            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4781        } else {
4782            return dispatchPopulateAccessibilityEventInternal(event);
4783        }
4784    }
4785
4786    /**
4787     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4788     *
4789     * Note: Called from the default {@link AccessibilityDelegate}.
4790     */
4791    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4792        onPopulateAccessibilityEvent(event);
4793        return false;
4794    }
4795
4796    /**
4797     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4798     * giving a chance to this View to populate the accessibility event with its
4799     * text content. While this method is free to modify event
4800     * attributes other than text content, doing so should normally be performed in
4801     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4802     * <p>
4803     * Example: Adding formatted date string to an accessibility event in addition
4804     *          to the text added by the super implementation:
4805     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4806     *     super.onPopulateAccessibilityEvent(event);
4807     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4808     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4809     *         mCurrentDate.getTimeInMillis(), flags);
4810     *     event.getText().add(selectedDateUtterance);
4811     * }</pre>
4812     * <p>
4813     * If an {@link AccessibilityDelegate} has been specified via calling
4814     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4815     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4816     * is responsible for handling this call.
4817     * </p>
4818     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4819     * information to the event, in case the default implementation has basic information to add.
4820     * </p>
4821     *
4822     * @param event The accessibility event which to populate.
4823     *
4824     * @see #sendAccessibilityEvent(int)
4825     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4826     */
4827    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4828        if (mAccessibilityDelegate != null) {
4829            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4830        } else {
4831            onPopulateAccessibilityEventInternal(event);
4832        }
4833    }
4834
4835    /**
4836     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4837     *
4838     * Note: Called from the default {@link AccessibilityDelegate}.
4839     */
4840    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4841
4842    }
4843
4844    /**
4845     * Initializes an {@link AccessibilityEvent} with information about
4846     * this View which is the event source. In other words, the source of
4847     * an accessibility event is the view whose state change triggered firing
4848     * the event.
4849     * <p>
4850     * Example: Setting the password property of an event in addition
4851     *          to properties set by the super implementation:
4852     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4853     *     super.onInitializeAccessibilityEvent(event);
4854     *     event.setPassword(true);
4855     * }</pre>
4856     * <p>
4857     * If an {@link AccessibilityDelegate} has been specified via calling
4858     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4859     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4860     * is responsible for handling this call.
4861     * </p>
4862     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4863     * information to the event, in case the default implementation has basic information to add.
4864     * </p>
4865     * @param event The event to initialize.
4866     *
4867     * @see #sendAccessibilityEvent(int)
4868     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4869     */
4870    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4871        if (mAccessibilityDelegate != null) {
4872            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4873        } else {
4874            onInitializeAccessibilityEventInternal(event);
4875        }
4876    }
4877
4878    /**
4879     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4880     *
4881     * Note: Called from the default {@link AccessibilityDelegate}.
4882     */
4883    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4884        event.setSource(this);
4885        event.setClassName(View.class.getName());
4886        event.setPackageName(getContext().getPackageName());
4887        event.setEnabled(isEnabled());
4888        event.setContentDescription(mContentDescription);
4889
4890        switch (event.getEventType()) {
4891            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4892                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4893                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4894                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4895                event.setItemCount(focusablesTempList.size());
4896                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4897                if (mAttachInfo != null) {
4898                    focusablesTempList.clear();
4899                }
4900            } break;
4901            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4902                CharSequence text = getIterableTextForAccessibility();
4903                if (text != null && text.length() > 0) {
4904                    event.setFromIndex(getAccessibilitySelectionStart());
4905                    event.setToIndex(getAccessibilitySelectionEnd());
4906                    event.setItemCount(text.length());
4907                }
4908            } break;
4909        }
4910    }
4911
4912    /**
4913     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4914     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4915     * This method is responsible for obtaining an accessibility node info from a
4916     * pool of reusable instances and calling
4917     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4918     * initialize the former.
4919     * <p>
4920     * Note: The client is responsible for recycling the obtained instance by calling
4921     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4922     * </p>
4923     *
4924     * @return A populated {@link AccessibilityNodeInfo}.
4925     *
4926     * @see AccessibilityNodeInfo
4927     */
4928    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4929        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4930        if (provider != null) {
4931            return provider.createAccessibilityNodeInfo(View.NO_ID);
4932        } else {
4933            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4934            onInitializeAccessibilityNodeInfo(info);
4935            return info;
4936        }
4937    }
4938
4939    /**
4940     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4941     * The base implementation sets:
4942     * <ul>
4943     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4944     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4945     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4946     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4947     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4948     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4949     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4950     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4951     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4952     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4953     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4954     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4955     * </ul>
4956     * <p>
4957     * Subclasses should override this method, call the super implementation,
4958     * and set additional attributes.
4959     * </p>
4960     * <p>
4961     * If an {@link AccessibilityDelegate} has been specified via calling
4962     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4963     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4964     * is responsible for handling this call.
4965     * </p>
4966     *
4967     * @param info The instance to initialize.
4968     */
4969    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4970        if (mAccessibilityDelegate != null) {
4971            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4972        } else {
4973            onInitializeAccessibilityNodeInfoInternal(info);
4974        }
4975    }
4976
4977    /**
4978     * Gets the location of this view in screen coordintates.
4979     *
4980     * @param outRect The output location
4981     */
4982    void getBoundsOnScreen(Rect outRect) {
4983        if (mAttachInfo == null) {
4984            return;
4985        }
4986
4987        RectF position = mAttachInfo.mTmpTransformRect;
4988        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4989
4990        if (!hasIdentityMatrix()) {
4991            getMatrix().mapRect(position);
4992        }
4993
4994        position.offset(mLeft, mTop);
4995
4996        ViewParent parent = mParent;
4997        while (parent instanceof View) {
4998            View parentView = (View) parent;
4999
5000            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5001
5002            if (!parentView.hasIdentityMatrix()) {
5003                parentView.getMatrix().mapRect(position);
5004            }
5005
5006            position.offset(parentView.mLeft, parentView.mTop);
5007
5008            parent = parentView.mParent;
5009        }
5010
5011        if (parent instanceof ViewRootImpl) {
5012            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5013            position.offset(0, -viewRootImpl.mCurScrollY);
5014        }
5015
5016        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5017
5018        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5019                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5020    }
5021
5022    /**
5023     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5024     *
5025     * Note: Called from the default {@link AccessibilityDelegate}.
5026     */
5027    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5028        Rect bounds = mAttachInfo.mTmpInvalRect;
5029
5030        getDrawingRect(bounds);
5031        info.setBoundsInParent(bounds);
5032
5033        getBoundsOnScreen(bounds);
5034        info.setBoundsInScreen(bounds);
5035
5036        ViewParent parent = getParentForAccessibility();
5037        if (parent instanceof View) {
5038            info.setParent((View) parent);
5039        }
5040
5041        if (mID != View.NO_ID) {
5042            View rootView = getRootView();
5043            if (rootView == null) {
5044                rootView = this;
5045            }
5046            View label = rootView.findLabelForView(this, mID);
5047            if (label != null) {
5048                info.setLabeledBy(label);
5049            }
5050
5051            if ((mAttachInfo.mAccessibilityFetchFlags
5052                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5053                    && Resources.resourceHasPackage(mID)) {
5054                try {
5055                    String viewId = getResources().getResourceName(mID);
5056                    info.setViewIdResourceName(viewId);
5057                } catch (Resources.NotFoundException nfe) {
5058                    /* ignore */
5059                }
5060            }
5061        }
5062
5063        if (mLabelForId != View.NO_ID) {
5064            View rootView = getRootView();
5065            if (rootView == null) {
5066                rootView = this;
5067            }
5068            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5069            if (labeled != null) {
5070                info.setLabelFor(labeled);
5071            }
5072        }
5073
5074        info.setVisibleToUser(isVisibleToUser());
5075
5076        info.setPackageName(mContext.getPackageName());
5077        info.setClassName(View.class.getName());
5078        info.setContentDescription(getContentDescription());
5079
5080        info.setEnabled(isEnabled());
5081        info.setClickable(isClickable());
5082        info.setFocusable(isFocusable());
5083        info.setFocused(isFocused());
5084        info.setAccessibilityFocused(isAccessibilityFocused());
5085        info.setSelected(isSelected());
5086        info.setLongClickable(isLongClickable());
5087
5088        // TODO: These make sense only if we are in an AdapterView but all
5089        // views can be selected. Maybe from accessibility perspective
5090        // we should report as selectable view in an AdapterView.
5091        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5092        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5093
5094        if (isFocusable()) {
5095            if (isFocused()) {
5096                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5097            } else {
5098                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5099            }
5100        }
5101
5102        if (!isAccessibilityFocused()) {
5103            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5104        } else {
5105            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5106        }
5107
5108        if (isClickable() && isEnabled()) {
5109            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5110        }
5111
5112        if (isLongClickable() && isEnabled()) {
5113            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5114        }
5115
5116        CharSequence text = getIterableTextForAccessibility();
5117        if (text != null && text.length() > 0) {
5118            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5119
5120            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5121            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5122            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5123            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5124                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5125                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5126        }
5127    }
5128
5129    private View findLabelForView(View view, int labeledId) {
5130        if (mMatchLabelForPredicate == null) {
5131            mMatchLabelForPredicate = new MatchLabelForPredicate();
5132        }
5133        mMatchLabelForPredicate.mLabeledId = labeledId;
5134        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5135    }
5136
5137    /**
5138     * Computes whether this view is visible to the user. Such a view is
5139     * attached, visible, all its predecessors are visible, it is not clipped
5140     * entirely by its predecessors, and has an alpha greater than zero.
5141     *
5142     * @return Whether the view is visible on the screen.
5143     *
5144     * @hide
5145     */
5146    protected boolean isVisibleToUser() {
5147        return isVisibleToUser(null);
5148    }
5149
5150    /**
5151     * Computes whether the given portion of this view is visible to the user.
5152     * Such a view is attached, visible, all its predecessors are visible,
5153     * has an alpha greater than zero, and the specified portion is not
5154     * clipped entirely by its predecessors.
5155     *
5156     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5157     *                    <code>null</code>, and the entire view will be tested in this case.
5158     *                    When <code>true</code> is returned by the function, the actual visible
5159     *                    region will be stored in this parameter; that is, if boundInView is fully
5160     *                    contained within the view, no modification will be made, otherwise regions
5161     *                    outside of the visible area of the view will be clipped.
5162     *
5163     * @return Whether the specified portion of the view is visible on the screen.
5164     *
5165     * @hide
5166     */
5167    protected boolean isVisibleToUser(Rect boundInView) {
5168        if (mAttachInfo != null) {
5169            // Attached to invisible window means this view is not visible.
5170            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5171                return false;
5172            }
5173            // An invisible predecessor or one with alpha zero means
5174            // that this view is not visible to the user.
5175            Object current = this;
5176            while (current instanceof View) {
5177                View view = (View) current;
5178                // We have attach info so this view is attached and there is no
5179                // need to check whether we reach to ViewRootImpl on the way up.
5180                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5181                    return false;
5182                }
5183                current = view.mParent;
5184            }
5185            // Check if the view is entirely covered by its predecessors.
5186            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5187            Point offset = mAttachInfo.mPoint;
5188            if (!getGlobalVisibleRect(visibleRect, offset)) {
5189                return false;
5190            }
5191            // Check if the visible portion intersects the rectangle of interest.
5192            if (boundInView != null) {
5193                visibleRect.offset(-offset.x, -offset.y);
5194                return boundInView.intersect(visibleRect);
5195            }
5196            return true;
5197        }
5198        return false;
5199    }
5200
5201    /**
5202     * Returns the delegate for implementing accessibility support via
5203     * composition. For more details see {@link AccessibilityDelegate}.
5204     *
5205     * @return The delegate, or null if none set.
5206     *
5207     * @hide
5208     */
5209    public AccessibilityDelegate getAccessibilityDelegate() {
5210        return mAccessibilityDelegate;
5211    }
5212
5213    /**
5214     * Sets a delegate for implementing accessibility support via composition as
5215     * opposed to inheritance. The delegate's primary use is for implementing
5216     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5217     *
5218     * @param delegate The delegate instance.
5219     *
5220     * @see AccessibilityDelegate
5221     */
5222    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5223        mAccessibilityDelegate = delegate;
5224    }
5225
5226    /**
5227     * Gets the provider for managing a virtual view hierarchy rooted at this View
5228     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5229     * that explore the window content.
5230     * <p>
5231     * If this method returns an instance, this instance is responsible for managing
5232     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5233     * View including the one representing the View itself. Similarly the returned
5234     * instance is responsible for performing accessibility actions on any virtual
5235     * view or the root view itself.
5236     * </p>
5237     * <p>
5238     * If an {@link AccessibilityDelegate} has been specified via calling
5239     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5240     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5241     * is responsible for handling this call.
5242     * </p>
5243     *
5244     * @return The provider.
5245     *
5246     * @see AccessibilityNodeProvider
5247     */
5248    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5249        if (mAccessibilityDelegate != null) {
5250            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5251        } else {
5252            return null;
5253        }
5254    }
5255
5256    /**
5257     * Gets the unique identifier of this view on the screen for accessibility purposes.
5258     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5259     *
5260     * @return The view accessibility id.
5261     *
5262     * @hide
5263     */
5264    public int getAccessibilityViewId() {
5265        if (mAccessibilityViewId == NO_ID) {
5266            mAccessibilityViewId = sNextAccessibilityViewId++;
5267        }
5268        return mAccessibilityViewId;
5269    }
5270
5271    /**
5272     * Gets the unique identifier of the window in which this View reseides.
5273     *
5274     * @return The window accessibility id.
5275     *
5276     * @hide
5277     */
5278    public int getAccessibilityWindowId() {
5279        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5280    }
5281
5282    /**
5283     * Gets the {@link View} description. It briefly describes the view and is
5284     * primarily used for accessibility support. Set this property to enable
5285     * better accessibility support for your application. This is especially
5286     * true for views that do not have textual representation (For example,
5287     * ImageButton).
5288     *
5289     * @return The content description.
5290     *
5291     * @attr ref android.R.styleable#View_contentDescription
5292     */
5293    @ViewDebug.ExportedProperty(category = "accessibility")
5294    public CharSequence getContentDescription() {
5295        return mContentDescription;
5296    }
5297
5298    /**
5299     * Sets the {@link View} description. It briefly describes the view and is
5300     * primarily used for accessibility support. Set this property to enable
5301     * better accessibility support for your application. This is especially
5302     * true for views that do not have textual representation (For example,
5303     * ImageButton).
5304     *
5305     * @param contentDescription The content description.
5306     *
5307     * @attr ref android.R.styleable#View_contentDescription
5308     */
5309    @RemotableViewMethod
5310    public void setContentDescription(CharSequence contentDescription) {
5311        if (mContentDescription == null) {
5312            if (contentDescription == null) {
5313                return;
5314            }
5315        } else if (mContentDescription.equals(contentDescription)) {
5316            return;
5317        }
5318        mContentDescription = contentDescription;
5319        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5320        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5321             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5322        }
5323        notifyAccessibilityStateChanged();
5324    }
5325
5326    /**
5327     * Gets the id of a view for which this view serves as a label for
5328     * accessibility purposes.
5329     *
5330     * @return The labeled view id.
5331     */
5332    @ViewDebug.ExportedProperty(category = "accessibility")
5333    public int getLabelFor() {
5334        return mLabelForId;
5335    }
5336
5337    /**
5338     * Sets the id of a view for which this view serves as a label for
5339     * accessibility purposes.
5340     *
5341     * @param id The labeled view id.
5342     */
5343    @RemotableViewMethod
5344    public void setLabelFor(int id) {
5345        mLabelForId = id;
5346        if (mLabelForId != View.NO_ID
5347                && mID == View.NO_ID) {
5348            mID = generateViewId();
5349        }
5350    }
5351
5352    /**
5353     * Invoked whenever this view loses focus, either by losing window focus or by losing
5354     * focus within its window. This method can be used to clear any state tied to the
5355     * focus. For instance, if a button is held pressed with the trackball and the window
5356     * loses focus, this method can be used to cancel the press.
5357     *
5358     * Subclasses of View overriding this method should always call super.onFocusLost().
5359     *
5360     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5361     * @see #onWindowFocusChanged(boolean)
5362     *
5363     * @hide pending API council approval
5364     */
5365    protected void onFocusLost() {
5366        resetPressedState();
5367    }
5368
5369    private void resetPressedState() {
5370        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5371            return;
5372        }
5373
5374        if (isPressed()) {
5375            setPressed(false);
5376
5377            if (!mHasPerformedLongPress) {
5378                removeLongPressCallback();
5379            }
5380        }
5381    }
5382
5383    /**
5384     * Returns true if this view has focus
5385     *
5386     * @return True if this view has focus, false otherwise.
5387     */
5388    @ViewDebug.ExportedProperty(category = "focus")
5389    public boolean isFocused() {
5390        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5391    }
5392
5393    /**
5394     * Find the view in the hierarchy rooted at this view that currently has
5395     * focus.
5396     *
5397     * @return The view that currently has focus, or null if no focused view can
5398     *         be found.
5399     */
5400    public View findFocus() {
5401        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5402    }
5403
5404    /**
5405     * Indicates whether this view is one of the set of scrollable containers in
5406     * its window.
5407     *
5408     * @return whether this view is one of the set of scrollable containers in
5409     * its window
5410     *
5411     * @attr ref android.R.styleable#View_isScrollContainer
5412     */
5413    public boolean isScrollContainer() {
5414        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5415    }
5416
5417    /**
5418     * Change whether this view is one of the set of scrollable containers in
5419     * its window.  This will be used to determine whether the window can
5420     * resize or must pan when a soft input area is open -- scrollable
5421     * containers allow the window to use resize mode since the container
5422     * will appropriately shrink.
5423     *
5424     * @attr ref android.R.styleable#View_isScrollContainer
5425     */
5426    public void setScrollContainer(boolean isScrollContainer) {
5427        if (isScrollContainer) {
5428            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5429                mAttachInfo.mScrollContainers.add(this);
5430                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5431            }
5432            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5433        } else {
5434            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5435                mAttachInfo.mScrollContainers.remove(this);
5436            }
5437            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5438        }
5439    }
5440
5441    /**
5442     * Returns the quality of the drawing cache.
5443     *
5444     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5445     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5446     *
5447     * @see #setDrawingCacheQuality(int)
5448     * @see #setDrawingCacheEnabled(boolean)
5449     * @see #isDrawingCacheEnabled()
5450     *
5451     * @attr ref android.R.styleable#View_drawingCacheQuality
5452     */
5453    public int getDrawingCacheQuality() {
5454        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5455    }
5456
5457    /**
5458     * Set the drawing cache quality of this view. This value is used only when the
5459     * drawing cache is enabled
5460     *
5461     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5462     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5463     *
5464     * @see #getDrawingCacheQuality()
5465     * @see #setDrawingCacheEnabled(boolean)
5466     * @see #isDrawingCacheEnabled()
5467     *
5468     * @attr ref android.R.styleable#View_drawingCacheQuality
5469     */
5470    public void setDrawingCacheQuality(int quality) {
5471        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5472    }
5473
5474    /**
5475     * Returns whether the screen should remain on, corresponding to the current
5476     * value of {@link #KEEP_SCREEN_ON}.
5477     *
5478     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5479     *
5480     * @see #setKeepScreenOn(boolean)
5481     *
5482     * @attr ref android.R.styleable#View_keepScreenOn
5483     */
5484    public boolean getKeepScreenOn() {
5485        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5486    }
5487
5488    /**
5489     * Controls whether the screen should remain on, modifying the
5490     * value of {@link #KEEP_SCREEN_ON}.
5491     *
5492     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5493     *
5494     * @see #getKeepScreenOn()
5495     *
5496     * @attr ref android.R.styleable#View_keepScreenOn
5497     */
5498    public void setKeepScreenOn(boolean keepScreenOn) {
5499        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5500    }
5501
5502    /**
5503     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5504     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5505     *
5506     * @attr ref android.R.styleable#View_nextFocusLeft
5507     */
5508    public int getNextFocusLeftId() {
5509        return mNextFocusLeftId;
5510    }
5511
5512    /**
5513     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5514     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5515     * decide automatically.
5516     *
5517     * @attr ref android.R.styleable#View_nextFocusLeft
5518     */
5519    public void setNextFocusLeftId(int nextFocusLeftId) {
5520        mNextFocusLeftId = nextFocusLeftId;
5521    }
5522
5523    /**
5524     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5525     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5526     *
5527     * @attr ref android.R.styleable#View_nextFocusRight
5528     */
5529    public int getNextFocusRightId() {
5530        return mNextFocusRightId;
5531    }
5532
5533    /**
5534     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5535     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5536     * decide automatically.
5537     *
5538     * @attr ref android.R.styleable#View_nextFocusRight
5539     */
5540    public void setNextFocusRightId(int nextFocusRightId) {
5541        mNextFocusRightId = nextFocusRightId;
5542    }
5543
5544    /**
5545     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5546     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5547     *
5548     * @attr ref android.R.styleable#View_nextFocusUp
5549     */
5550    public int getNextFocusUpId() {
5551        return mNextFocusUpId;
5552    }
5553
5554    /**
5555     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5556     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5557     * decide automatically.
5558     *
5559     * @attr ref android.R.styleable#View_nextFocusUp
5560     */
5561    public void setNextFocusUpId(int nextFocusUpId) {
5562        mNextFocusUpId = nextFocusUpId;
5563    }
5564
5565    /**
5566     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5567     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5568     *
5569     * @attr ref android.R.styleable#View_nextFocusDown
5570     */
5571    public int getNextFocusDownId() {
5572        return mNextFocusDownId;
5573    }
5574
5575    /**
5576     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5577     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5578     * decide automatically.
5579     *
5580     * @attr ref android.R.styleable#View_nextFocusDown
5581     */
5582    public void setNextFocusDownId(int nextFocusDownId) {
5583        mNextFocusDownId = nextFocusDownId;
5584    }
5585
5586    /**
5587     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5588     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5589     *
5590     * @attr ref android.R.styleable#View_nextFocusForward
5591     */
5592    public int getNextFocusForwardId() {
5593        return mNextFocusForwardId;
5594    }
5595
5596    /**
5597     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5598     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5599     * decide automatically.
5600     *
5601     * @attr ref android.R.styleable#View_nextFocusForward
5602     */
5603    public void setNextFocusForwardId(int nextFocusForwardId) {
5604        mNextFocusForwardId = nextFocusForwardId;
5605    }
5606
5607    /**
5608     * Returns the visibility of this view and all of its ancestors
5609     *
5610     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5611     */
5612    public boolean isShown() {
5613        View current = this;
5614        //noinspection ConstantConditions
5615        do {
5616            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5617                return false;
5618            }
5619            ViewParent parent = current.mParent;
5620            if (parent == null) {
5621                return false; // We are not attached to the view root
5622            }
5623            if (!(parent instanceof View)) {
5624                return true;
5625            }
5626            current = (View) parent;
5627        } while (current != null);
5628
5629        return false;
5630    }
5631
5632    /**
5633     * Called by the view hierarchy when the content insets for a window have
5634     * changed, to allow it to adjust its content to fit within those windows.
5635     * The content insets tell you the space that the status bar, input method,
5636     * and other system windows infringe on the application's window.
5637     *
5638     * <p>You do not normally need to deal with this function, since the default
5639     * window decoration given to applications takes care of applying it to the
5640     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5641     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5642     * and your content can be placed under those system elements.  You can then
5643     * use this method within your view hierarchy if you have parts of your UI
5644     * which you would like to ensure are not being covered.
5645     *
5646     * <p>The default implementation of this method simply applies the content
5647     * inset's to the view's padding, consuming that content (modifying the
5648     * insets to be 0), and returning true.  This behavior is off by default, but can
5649     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5650     *
5651     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5652     * insets object is propagated down the hierarchy, so any changes made to it will
5653     * be seen by all following views (including potentially ones above in
5654     * the hierarchy since this is a depth-first traversal).  The first view
5655     * that returns true will abort the entire traversal.
5656     *
5657     * <p>The default implementation works well for a situation where it is
5658     * used with a container that covers the entire window, allowing it to
5659     * apply the appropriate insets to its content on all edges.  If you need
5660     * a more complicated layout (such as two different views fitting system
5661     * windows, one on the top of the window, and one on the bottom),
5662     * you can override the method and handle the insets however you would like.
5663     * Note that the insets provided by the framework are always relative to the
5664     * far edges of the window, not accounting for the location of the called view
5665     * within that window.  (In fact when this method is called you do not yet know
5666     * where the layout will place the view, as it is done before layout happens.)
5667     *
5668     * <p>Note: unlike many View methods, there is no dispatch phase to this
5669     * call.  If you are overriding it in a ViewGroup and want to allow the
5670     * call to continue to your children, you must be sure to call the super
5671     * implementation.
5672     *
5673     * <p>Here is a sample layout that makes use of fitting system windows
5674     * to have controls for a video view placed inside of the window decorations
5675     * that it hides and shows.  This can be used with code like the second
5676     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5677     *
5678     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5679     *
5680     * @param insets Current content insets of the window.  Prior to
5681     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5682     * the insets or else you and Android will be unhappy.
5683     *
5684     * @return Return true if this view applied the insets and it should not
5685     * continue propagating further down the hierarchy, false otherwise.
5686     * @see #getFitsSystemWindows()
5687     * @see #setFitsSystemWindows(boolean)
5688     * @see #setSystemUiVisibility(int)
5689     */
5690    protected boolean fitSystemWindows(Rect insets) {
5691        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5692            mUserPaddingStart = UNDEFINED_PADDING;
5693            mUserPaddingEnd = UNDEFINED_PADDING;
5694            Rect localInsets = sThreadLocal.get();
5695            if (localInsets == null) {
5696                localInsets = new Rect();
5697                sThreadLocal.set(localInsets);
5698            }
5699            boolean res = computeFitSystemWindows(insets, localInsets);
5700            internalSetPadding(localInsets.left, localInsets.top,
5701                    localInsets.right, localInsets.bottom);
5702            return res;
5703        }
5704        return false;
5705    }
5706
5707    /**
5708     * @hide Compute the insets that should be consumed by this view and the ones
5709     * that should propagate to those under it.
5710     */
5711    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5712        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5713                || mAttachInfo == null
5714                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5715                        && !mAttachInfo.mOverscanRequested)) {
5716            outLocalInsets.set(inoutInsets);
5717            inoutInsets.set(0, 0, 0, 0);
5718            return true;
5719        } else {
5720            // The application wants to take care of fitting system window for
5721            // the content...  however we still need to take care of any overscan here.
5722            final Rect overscan = mAttachInfo.mOverscanInsets;
5723            outLocalInsets.set(overscan);
5724            inoutInsets.left -= overscan.left;
5725            inoutInsets.top -= overscan.top;
5726            inoutInsets.right -= overscan.right;
5727            inoutInsets.bottom -= overscan.bottom;
5728            return false;
5729        }
5730    }
5731
5732    /**
5733     * Sets whether or not this view should account for system screen decorations
5734     * such as the status bar and inset its content; that is, controlling whether
5735     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5736     * executed.  See that method for more details.
5737     *
5738     * <p>Note that if you are providing your own implementation of
5739     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5740     * flag to true -- your implementation will be overriding the default
5741     * implementation that checks this flag.
5742     *
5743     * @param fitSystemWindows If true, then the default implementation of
5744     * {@link #fitSystemWindows(Rect)} will be executed.
5745     *
5746     * @attr ref android.R.styleable#View_fitsSystemWindows
5747     * @see #getFitsSystemWindows()
5748     * @see #fitSystemWindows(Rect)
5749     * @see #setSystemUiVisibility(int)
5750     */
5751    public void setFitsSystemWindows(boolean fitSystemWindows) {
5752        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5753    }
5754
5755    /**
5756     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5757     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5758     * will be executed.
5759     *
5760     * @return Returns true if the default implementation of
5761     * {@link #fitSystemWindows(Rect)} will be executed.
5762     *
5763     * @attr ref android.R.styleable#View_fitsSystemWindows
5764     * @see #setFitsSystemWindows()
5765     * @see #fitSystemWindows(Rect)
5766     * @see #setSystemUiVisibility(int)
5767     */
5768    public boolean getFitsSystemWindows() {
5769        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5770    }
5771
5772    /** @hide */
5773    public boolean fitsSystemWindows() {
5774        return getFitsSystemWindows();
5775    }
5776
5777    /**
5778     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5779     */
5780    public void requestFitSystemWindows() {
5781        if (mParent != null) {
5782            mParent.requestFitSystemWindows();
5783        }
5784    }
5785
5786    /**
5787     * For use by PhoneWindow to make its own system window fitting optional.
5788     * @hide
5789     */
5790    public void makeOptionalFitsSystemWindows() {
5791        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5792    }
5793
5794    /**
5795     * Returns the visibility status for this view.
5796     *
5797     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5798     * @attr ref android.R.styleable#View_visibility
5799     */
5800    @ViewDebug.ExportedProperty(mapping = {
5801        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5802        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5803        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5804    })
5805    public int getVisibility() {
5806        return mViewFlags & VISIBILITY_MASK;
5807    }
5808
5809    /**
5810     * Set the enabled state of this view.
5811     *
5812     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5813     * @attr ref android.R.styleable#View_visibility
5814     */
5815    @RemotableViewMethod
5816    public void setVisibility(int visibility) {
5817        setFlags(visibility, VISIBILITY_MASK);
5818        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5819    }
5820
5821    /**
5822     * Returns the enabled status for this view. The interpretation of the
5823     * enabled state varies by subclass.
5824     *
5825     * @return True if this view is enabled, false otherwise.
5826     */
5827    @ViewDebug.ExportedProperty
5828    public boolean isEnabled() {
5829        return (mViewFlags & ENABLED_MASK) == ENABLED;
5830    }
5831
5832    /**
5833     * Set the enabled state of this view. The interpretation of the enabled
5834     * state varies by subclass.
5835     *
5836     * @param enabled True if this view is enabled, false otherwise.
5837     */
5838    @RemotableViewMethod
5839    public void setEnabled(boolean enabled) {
5840        if (enabled == isEnabled()) return;
5841
5842        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5843
5844        /*
5845         * The View most likely has to change its appearance, so refresh
5846         * the drawable state.
5847         */
5848        refreshDrawableState();
5849
5850        // Invalidate too, since the default behavior for views is to be
5851        // be drawn at 50% alpha rather than to change the drawable.
5852        invalidate(true);
5853    }
5854
5855    /**
5856     * Set whether this view can receive the focus.
5857     *
5858     * Setting this to false will also ensure that this view is not focusable
5859     * in touch mode.
5860     *
5861     * @param focusable If true, this view can receive the focus.
5862     *
5863     * @see #setFocusableInTouchMode(boolean)
5864     * @attr ref android.R.styleable#View_focusable
5865     */
5866    public void setFocusable(boolean focusable) {
5867        if (!focusable) {
5868            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5869        }
5870        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5871    }
5872
5873    /**
5874     * Set whether this view can receive focus while in touch mode.
5875     *
5876     * Setting this to true will also ensure that this view is focusable.
5877     *
5878     * @param focusableInTouchMode If true, this view can receive the focus while
5879     *   in touch mode.
5880     *
5881     * @see #setFocusable(boolean)
5882     * @attr ref android.R.styleable#View_focusableInTouchMode
5883     */
5884    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5885        // Focusable in touch mode should always be set before the focusable flag
5886        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5887        // which, in touch mode, will not successfully request focus on this view
5888        // because the focusable in touch mode flag is not set
5889        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5890        if (focusableInTouchMode) {
5891            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5892        }
5893    }
5894
5895    /**
5896     * Set whether this view should have sound effects enabled for events such as
5897     * clicking and touching.
5898     *
5899     * <p>You may wish to disable sound effects for a view if you already play sounds,
5900     * for instance, a dial key that plays dtmf tones.
5901     *
5902     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5903     * @see #isSoundEffectsEnabled()
5904     * @see #playSoundEffect(int)
5905     * @attr ref android.R.styleable#View_soundEffectsEnabled
5906     */
5907    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5908        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5909    }
5910
5911    /**
5912     * @return whether this view should have sound effects enabled for events such as
5913     *     clicking and touching.
5914     *
5915     * @see #setSoundEffectsEnabled(boolean)
5916     * @see #playSoundEffect(int)
5917     * @attr ref android.R.styleable#View_soundEffectsEnabled
5918     */
5919    @ViewDebug.ExportedProperty
5920    public boolean isSoundEffectsEnabled() {
5921        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5922    }
5923
5924    /**
5925     * Set whether this view should have haptic feedback for events such as
5926     * long presses.
5927     *
5928     * <p>You may wish to disable haptic feedback if your view already controls
5929     * its own haptic feedback.
5930     *
5931     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5932     * @see #isHapticFeedbackEnabled()
5933     * @see #performHapticFeedback(int)
5934     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5935     */
5936    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5937        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5938    }
5939
5940    /**
5941     * @return whether this view should have haptic feedback enabled for events
5942     * long presses.
5943     *
5944     * @see #setHapticFeedbackEnabled(boolean)
5945     * @see #performHapticFeedback(int)
5946     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5947     */
5948    @ViewDebug.ExportedProperty
5949    public boolean isHapticFeedbackEnabled() {
5950        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5951    }
5952
5953    /**
5954     * Returns the layout direction for this view.
5955     *
5956     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5957     *   {@link #LAYOUT_DIRECTION_RTL},
5958     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5959     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5960     *
5961     * @attr ref android.R.styleable#View_layoutDirection
5962     *
5963     * @hide
5964     */
5965    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5966        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5967        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5968        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5969        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5970    })
5971    public int getRawLayoutDirection() {
5972        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5973    }
5974
5975    /**
5976     * Set the layout direction for this view. This will propagate a reset of layout direction
5977     * resolution to the view's children and resolve layout direction for this view.
5978     *
5979     * @param layoutDirection the layout direction to set. Should be one of:
5980     *
5981     * {@link #LAYOUT_DIRECTION_LTR},
5982     * {@link #LAYOUT_DIRECTION_RTL},
5983     * {@link #LAYOUT_DIRECTION_INHERIT},
5984     * {@link #LAYOUT_DIRECTION_LOCALE}.
5985     *
5986     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5987     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5988     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5989     *
5990     * @attr ref android.R.styleable#View_layoutDirection
5991     */
5992    @RemotableViewMethod
5993    public void setLayoutDirection(int layoutDirection) {
5994        if (getRawLayoutDirection() != layoutDirection) {
5995            // Reset the current layout direction and the resolved one
5996            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5997            resetRtlProperties();
5998            // Set the new layout direction (filtered)
5999            mPrivateFlags2 |=
6000                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6001            // We need to resolve all RTL properties as they all depend on layout direction
6002            resolveRtlPropertiesIfNeeded();
6003            requestLayout();
6004            invalidate(true);
6005        }
6006    }
6007
6008    /**
6009     * Returns the resolved layout direction for this view.
6010     *
6011     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6012     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6013     *
6014     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6015     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6016     *
6017     * @attr ref android.R.styleable#View_layoutDirection
6018     */
6019    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6020        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6021        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6022    })
6023    public int getLayoutDirection() {
6024        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6025        if (targetSdkVersion < JELLY_BEAN_MR1) {
6026            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6027            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6028        }
6029        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6030                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6031    }
6032
6033    /**
6034     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6035     * layout attribute and/or the inherited value from the parent
6036     *
6037     * @return true if the layout is right-to-left.
6038     *
6039     * @hide
6040     */
6041    @ViewDebug.ExportedProperty(category = "layout")
6042    public boolean isLayoutRtl() {
6043        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6044    }
6045
6046    /**
6047     * Indicates whether the view is currently tracking transient state that the
6048     * app should not need to concern itself with saving and restoring, but that
6049     * the framework should take special note to preserve when possible.
6050     *
6051     * <p>A view with transient state cannot be trivially rebound from an external
6052     * data source, such as an adapter binding item views in a list. This may be
6053     * because the view is performing an animation, tracking user selection
6054     * of content, or similar.</p>
6055     *
6056     * @return true if the view has transient state
6057     */
6058    @ViewDebug.ExportedProperty(category = "layout")
6059    public boolean hasTransientState() {
6060        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6061    }
6062
6063    /**
6064     * Set whether this view is currently tracking transient state that the
6065     * framework should attempt to preserve when possible. This flag is reference counted,
6066     * so every call to setHasTransientState(true) should be paired with a later call
6067     * to setHasTransientState(false).
6068     *
6069     * <p>A view with transient state cannot be trivially rebound from an external
6070     * data source, such as an adapter binding item views in a list. This may be
6071     * because the view is performing an animation, tracking user selection
6072     * of content, or similar.</p>
6073     *
6074     * @param hasTransientState true if this view has transient state
6075     */
6076    public void setHasTransientState(boolean hasTransientState) {
6077        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6078                mTransientStateCount - 1;
6079        if (mTransientStateCount < 0) {
6080            mTransientStateCount = 0;
6081            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6082                    "unmatched pair of setHasTransientState calls");
6083        } else if ((hasTransientState && mTransientStateCount == 1) ||
6084                (!hasTransientState && mTransientStateCount == 0)) {
6085            // update flag if we've just incremented up from 0 or decremented down to 0
6086            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6087                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6088            if (mParent != null) {
6089                try {
6090                    mParent.childHasTransientStateChanged(this, hasTransientState);
6091                } catch (AbstractMethodError e) {
6092                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6093                            " does not fully implement ViewParent", e);
6094                }
6095            }
6096        }
6097    }
6098
6099    /**
6100     * If this view doesn't do any drawing on its own, set this flag to
6101     * allow further optimizations. By default, this flag is not set on
6102     * View, but could be set on some View subclasses such as ViewGroup.
6103     *
6104     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6105     * you should clear this flag.
6106     *
6107     * @param willNotDraw whether or not this View draw on its own
6108     */
6109    public void setWillNotDraw(boolean willNotDraw) {
6110        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6111    }
6112
6113    /**
6114     * Returns whether or not this View draws on its own.
6115     *
6116     * @return true if this view has nothing to draw, false otherwise
6117     */
6118    @ViewDebug.ExportedProperty(category = "drawing")
6119    public boolean willNotDraw() {
6120        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6121    }
6122
6123    /**
6124     * When a View's drawing cache is enabled, drawing is redirected to an
6125     * offscreen bitmap. Some views, like an ImageView, must be able to
6126     * bypass this mechanism if they already draw a single bitmap, to avoid
6127     * unnecessary usage of the memory.
6128     *
6129     * @param willNotCacheDrawing true if this view does not cache its
6130     *        drawing, false otherwise
6131     */
6132    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6133        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6134    }
6135
6136    /**
6137     * Returns whether or not this View can cache its drawing or not.
6138     *
6139     * @return true if this view does not cache its drawing, false otherwise
6140     */
6141    @ViewDebug.ExportedProperty(category = "drawing")
6142    public boolean willNotCacheDrawing() {
6143        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6144    }
6145
6146    /**
6147     * Indicates whether this view reacts to click events or not.
6148     *
6149     * @return true if the view is clickable, false otherwise
6150     *
6151     * @see #setClickable(boolean)
6152     * @attr ref android.R.styleable#View_clickable
6153     */
6154    @ViewDebug.ExportedProperty
6155    public boolean isClickable() {
6156        return (mViewFlags & CLICKABLE) == CLICKABLE;
6157    }
6158
6159    /**
6160     * Enables or disables click events for this view. When a view
6161     * is clickable it will change its state to "pressed" on every click.
6162     * Subclasses should set the view clickable to visually react to
6163     * user's clicks.
6164     *
6165     * @param clickable true to make the view clickable, false otherwise
6166     *
6167     * @see #isClickable()
6168     * @attr ref android.R.styleable#View_clickable
6169     */
6170    public void setClickable(boolean clickable) {
6171        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6172    }
6173
6174    /**
6175     * Indicates whether this view reacts to long click events or not.
6176     *
6177     * @return true if the view is long clickable, false otherwise
6178     *
6179     * @see #setLongClickable(boolean)
6180     * @attr ref android.R.styleable#View_longClickable
6181     */
6182    public boolean isLongClickable() {
6183        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6184    }
6185
6186    /**
6187     * Enables or disables long click events for this view. When a view is long
6188     * clickable it reacts to the user holding down the button for a longer
6189     * duration than a tap. This event can either launch the listener or a
6190     * context menu.
6191     *
6192     * @param longClickable true to make the view long clickable, false otherwise
6193     * @see #isLongClickable()
6194     * @attr ref android.R.styleable#View_longClickable
6195     */
6196    public void setLongClickable(boolean longClickable) {
6197        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6198    }
6199
6200    /**
6201     * Sets the pressed state for this view.
6202     *
6203     * @see #isClickable()
6204     * @see #setClickable(boolean)
6205     *
6206     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6207     *        the View's internal state from a previously set "pressed" state.
6208     */
6209    public void setPressed(boolean pressed) {
6210        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6211
6212        if (pressed) {
6213            mPrivateFlags |= PFLAG_PRESSED;
6214        } else {
6215            mPrivateFlags &= ~PFLAG_PRESSED;
6216        }
6217
6218        if (needsRefresh) {
6219            refreshDrawableState();
6220        }
6221        dispatchSetPressed(pressed);
6222    }
6223
6224    /**
6225     * Dispatch setPressed to all of this View's children.
6226     *
6227     * @see #setPressed(boolean)
6228     *
6229     * @param pressed The new pressed state
6230     */
6231    protected void dispatchSetPressed(boolean pressed) {
6232    }
6233
6234    /**
6235     * Indicates whether the view is currently in pressed state. Unless
6236     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6237     * the pressed state.
6238     *
6239     * @see #setPressed(boolean)
6240     * @see #isClickable()
6241     * @see #setClickable(boolean)
6242     *
6243     * @return true if the view is currently pressed, false otherwise
6244     */
6245    public boolean isPressed() {
6246        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6247    }
6248
6249    /**
6250     * Indicates whether this view will save its state (that is,
6251     * whether its {@link #onSaveInstanceState} method will be called).
6252     *
6253     * @return Returns true if the view state saving is enabled, else false.
6254     *
6255     * @see #setSaveEnabled(boolean)
6256     * @attr ref android.R.styleable#View_saveEnabled
6257     */
6258    public boolean isSaveEnabled() {
6259        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6260    }
6261
6262    /**
6263     * Controls whether the saving of this view's state is
6264     * enabled (that is, whether its {@link #onSaveInstanceState} method
6265     * will be called).  Note that even if freezing is enabled, the
6266     * view still must have an id assigned to it (via {@link #setId(int)})
6267     * for its state to be saved.  This flag can only disable the
6268     * saving of this view; any child views may still have their state saved.
6269     *
6270     * @param enabled Set to false to <em>disable</em> state saving, or true
6271     * (the default) to allow it.
6272     *
6273     * @see #isSaveEnabled()
6274     * @see #setId(int)
6275     * @see #onSaveInstanceState()
6276     * @attr ref android.R.styleable#View_saveEnabled
6277     */
6278    public void setSaveEnabled(boolean enabled) {
6279        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6280    }
6281
6282    /**
6283     * Gets whether the framework should discard touches when the view's
6284     * window is obscured by another visible window.
6285     * Refer to the {@link View} security documentation for more details.
6286     *
6287     * @return True if touch filtering is enabled.
6288     *
6289     * @see #setFilterTouchesWhenObscured(boolean)
6290     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6291     */
6292    @ViewDebug.ExportedProperty
6293    public boolean getFilterTouchesWhenObscured() {
6294        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6295    }
6296
6297    /**
6298     * Sets whether the framework should discard touches when the view's
6299     * window is obscured by another visible window.
6300     * Refer to the {@link View} security documentation for more details.
6301     *
6302     * @param enabled True if touch filtering should be enabled.
6303     *
6304     * @see #getFilterTouchesWhenObscured
6305     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6306     */
6307    public void setFilterTouchesWhenObscured(boolean enabled) {
6308        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6309                FILTER_TOUCHES_WHEN_OBSCURED);
6310    }
6311
6312    /**
6313     * Indicates whether the entire hierarchy under this view will save its
6314     * state when a state saving traversal occurs from its parent.  The default
6315     * is true; if false, these views will not be saved unless
6316     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6317     *
6318     * @return Returns true if the view state saving from parent is enabled, else false.
6319     *
6320     * @see #setSaveFromParentEnabled(boolean)
6321     */
6322    public boolean isSaveFromParentEnabled() {
6323        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6324    }
6325
6326    /**
6327     * Controls whether the entire hierarchy under this view will save its
6328     * state when a state saving traversal occurs from its parent.  The default
6329     * is true; if false, these views will not be saved unless
6330     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6331     *
6332     * @param enabled Set to false to <em>disable</em> state saving, or true
6333     * (the default) to allow it.
6334     *
6335     * @see #isSaveFromParentEnabled()
6336     * @see #setId(int)
6337     * @see #onSaveInstanceState()
6338     */
6339    public void setSaveFromParentEnabled(boolean enabled) {
6340        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6341    }
6342
6343
6344    /**
6345     * Returns whether this View is able to take focus.
6346     *
6347     * @return True if this view can take focus, or false otherwise.
6348     * @attr ref android.R.styleable#View_focusable
6349     */
6350    @ViewDebug.ExportedProperty(category = "focus")
6351    public final boolean isFocusable() {
6352        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6353    }
6354
6355    /**
6356     * When a view is focusable, it may not want to take focus when in touch mode.
6357     * For example, a button would like focus when the user is navigating via a D-pad
6358     * so that the user can click on it, but once the user starts touching the screen,
6359     * the button shouldn't take focus
6360     * @return Whether the view is focusable in touch mode.
6361     * @attr ref android.R.styleable#View_focusableInTouchMode
6362     */
6363    @ViewDebug.ExportedProperty
6364    public final boolean isFocusableInTouchMode() {
6365        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6366    }
6367
6368    /**
6369     * Find the nearest view in the specified direction that can take focus.
6370     * This does not actually give focus to that view.
6371     *
6372     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6373     *
6374     * @return The nearest focusable in the specified direction, or null if none
6375     *         can be found.
6376     */
6377    public View focusSearch(int direction) {
6378        if (mParent != null) {
6379            return mParent.focusSearch(this, direction);
6380        } else {
6381            return null;
6382        }
6383    }
6384
6385    /**
6386     * This method is the last chance for the focused view and its ancestors to
6387     * respond to an arrow key. This is called when the focused view did not
6388     * consume the key internally, nor could the view system find a new view in
6389     * the requested direction to give focus to.
6390     *
6391     * @param focused The currently focused view.
6392     * @param direction The direction focus wants to move. One of FOCUS_UP,
6393     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6394     * @return True if the this view consumed this unhandled move.
6395     */
6396    public boolean dispatchUnhandledMove(View focused, int direction) {
6397        return false;
6398    }
6399
6400    /**
6401     * If a user manually specified the next view id for a particular direction,
6402     * use the root to look up the view.
6403     * @param root The root view of the hierarchy containing this view.
6404     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6405     * or FOCUS_BACKWARD.
6406     * @return The user specified next view, or null if there is none.
6407     */
6408    View findUserSetNextFocus(View root, int direction) {
6409        switch (direction) {
6410            case FOCUS_LEFT:
6411                if (mNextFocusLeftId == View.NO_ID) return null;
6412                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6413            case FOCUS_RIGHT:
6414                if (mNextFocusRightId == View.NO_ID) return null;
6415                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6416            case FOCUS_UP:
6417                if (mNextFocusUpId == View.NO_ID) return null;
6418                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6419            case FOCUS_DOWN:
6420                if (mNextFocusDownId == View.NO_ID) return null;
6421                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6422            case FOCUS_FORWARD:
6423                if (mNextFocusForwardId == View.NO_ID) return null;
6424                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6425            case FOCUS_BACKWARD: {
6426                if (mID == View.NO_ID) return null;
6427                final int id = mID;
6428                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6429                    @Override
6430                    public boolean apply(View t) {
6431                        return t.mNextFocusForwardId == id;
6432                    }
6433                });
6434            }
6435        }
6436        return null;
6437    }
6438
6439    private View findViewInsideOutShouldExist(View root, int id) {
6440        if (mMatchIdPredicate == null) {
6441            mMatchIdPredicate = new MatchIdPredicate();
6442        }
6443        mMatchIdPredicate.mId = id;
6444        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6445        if (result == null) {
6446            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6447        }
6448        return result;
6449    }
6450
6451    /**
6452     * Find and return all focusable views that are descendants of this view,
6453     * possibly including this view if it is focusable itself.
6454     *
6455     * @param direction The direction of the focus
6456     * @return A list of focusable views
6457     */
6458    public ArrayList<View> getFocusables(int direction) {
6459        ArrayList<View> result = new ArrayList<View>(24);
6460        addFocusables(result, direction);
6461        return result;
6462    }
6463
6464    /**
6465     * Add any focusable views that are descendants of this view (possibly
6466     * including this view if it is focusable itself) to views.  If we are in touch mode,
6467     * only add views that are also focusable in touch mode.
6468     *
6469     * @param views Focusable views found so far
6470     * @param direction The direction of the focus
6471     */
6472    public void addFocusables(ArrayList<View> views, int direction) {
6473        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6474    }
6475
6476    /**
6477     * Adds any focusable views that are descendants of this view (possibly
6478     * including this view if it is focusable itself) to views. This method
6479     * adds all focusable views regardless if we are in touch mode or
6480     * only views focusable in touch mode if we are in touch mode or
6481     * only views that can take accessibility focus if accessibility is enabeld
6482     * depending on the focusable mode paramater.
6483     *
6484     * @param views Focusable views found so far or null if all we are interested is
6485     *        the number of focusables.
6486     * @param direction The direction of the focus.
6487     * @param focusableMode The type of focusables to be added.
6488     *
6489     * @see #FOCUSABLES_ALL
6490     * @see #FOCUSABLES_TOUCH_MODE
6491     */
6492    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6493        if (views == null) {
6494            return;
6495        }
6496        if (!isFocusable()) {
6497            return;
6498        }
6499        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6500                && isInTouchMode() && !isFocusableInTouchMode()) {
6501            return;
6502        }
6503        views.add(this);
6504    }
6505
6506    /**
6507     * Finds the Views that contain given text. The containment is case insensitive.
6508     * The search is performed by either the text that the View renders or the content
6509     * description that describes the view for accessibility purposes and the view does
6510     * not render or both. Clients can specify how the search is to be performed via
6511     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6512     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6513     *
6514     * @param outViews The output list of matching Views.
6515     * @param searched The text to match against.
6516     *
6517     * @see #FIND_VIEWS_WITH_TEXT
6518     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6519     * @see #setContentDescription(CharSequence)
6520     */
6521    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6522        if (getAccessibilityNodeProvider() != null) {
6523            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6524                outViews.add(this);
6525            }
6526        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6527                && (searched != null && searched.length() > 0)
6528                && (mContentDescription != null && mContentDescription.length() > 0)) {
6529            String searchedLowerCase = searched.toString().toLowerCase();
6530            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6531            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6532                outViews.add(this);
6533            }
6534        }
6535    }
6536
6537    /**
6538     * Find and return all touchable views that are descendants of this view,
6539     * possibly including this view if it is touchable itself.
6540     *
6541     * @return A list of touchable views
6542     */
6543    public ArrayList<View> getTouchables() {
6544        ArrayList<View> result = new ArrayList<View>();
6545        addTouchables(result);
6546        return result;
6547    }
6548
6549    /**
6550     * Add any touchable views that are descendants of this view (possibly
6551     * including this view if it is touchable itself) to views.
6552     *
6553     * @param views Touchable views found so far
6554     */
6555    public void addTouchables(ArrayList<View> views) {
6556        final int viewFlags = mViewFlags;
6557
6558        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6559                && (viewFlags & ENABLED_MASK) == ENABLED) {
6560            views.add(this);
6561        }
6562    }
6563
6564    /**
6565     * Returns whether this View is accessibility focused.
6566     *
6567     * @return True if this View is accessibility focused.
6568     */
6569    boolean isAccessibilityFocused() {
6570        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6571    }
6572
6573    /**
6574     * Call this to try to give accessibility focus to this view.
6575     *
6576     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6577     * returns false or the view is no visible or the view already has accessibility
6578     * focus.
6579     *
6580     * See also {@link #focusSearch(int)}, which is what you call to say that you
6581     * have focus, and you want your parent to look for the next one.
6582     *
6583     * @return Whether this view actually took accessibility focus.
6584     *
6585     * @hide
6586     */
6587    public boolean requestAccessibilityFocus() {
6588        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6589        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6590            return false;
6591        }
6592        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6593            return false;
6594        }
6595        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6596            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6597            ViewRootImpl viewRootImpl = getViewRootImpl();
6598            if (viewRootImpl != null) {
6599                viewRootImpl.setAccessibilityFocus(this, null);
6600            }
6601            invalidate();
6602            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6603            notifyAccessibilityStateChanged();
6604            return true;
6605        }
6606        return false;
6607    }
6608
6609    /**
6610     * Call this to try to clear accessibility focus of this view.
6611     *
6612     * See also {@link #focusSearch(int)}, which is what you call to say that you
6613     * have focus, and you want your parent to look for the next one.
6614     *
6615     * @hide
6616     */
6617    public void clearAccessibilityFocus() {
6618        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6619            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6620            invalidate();
6621            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6622            notifyAccessibilityStateChanged();
6623        }
6624        // Clear the global reference of accessibility focus if this
6625        // view or any of its descendants had accessibility focus.
6626        ViewRootImpl viewRootImpl = getViewRootImpl();
6627        if (viewRootImpl != null) {
6628            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6629            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6630                viewRootImpl.setAccessibilityFocus(null, null);
6631            }
6632        }
6633    }
6634
6635    private void sendAccessibilityHoverEvent(int eventType) {
6636        // Since we are not delivering to a client accessibility events from not
6637        // important views (unless the clinet request that) we need to fire the
6638        // event from the deepest view exposed to the client. As a consequence if
6639        // the user crosses a not exposed view the client will see enter and exit
6640        // of the exposed predecessor followed by and enter and exit of that same
6641        // predecessor when entering and exiting the not exposed descendant. This
6642        // is fine since the client has a clear idea which view is hovered at the
6643        // price of a couple more events being sent. This is a simple and
6644        // working solution.
6645        View source = this;
6646        while (true) {
6647            if (source.includeForAccessibility()) {
6648                source.sendAccessibilityEvent(eventType);
6649                return;
6650            }
6651            ViewParent parent = source.getParent();
6652            if (parent instanceof View) {
6653                source = (View) parent;
6654            } else {
6655                return;
6656            }
6657        }
6658    }
6659
6660    /**
6661     * Clears accessibility focus without calling any callback methods
6662     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6663     * is used for clearing accessibility focus when giving this focus to
6664     * another view.
6665     */
6666    void clearAccessibilityFocusNoCallbacks() {
6667        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6668            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6669            invalidate();
6670        }
6671    }
6672
6673    /**
6674     * Call this to try to give focus to a specific view or to one of its
6675     * descendants.
6676     *
6677     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6678     * false), or if it is focusable and it is not focusable in touch mode
6679     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6680     *
6681     * See also {@link #focusSearch(int)}, which is what you call to say that you
6682     * have focus, and you want your parent to look for the next one.
6683     *
6684     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6685     * {@link #FOCUS_DOWN} and <code>null</code>.
6686     *
6687     * @return Whether this view or one of its descendants actually took focus.
6688     */
6689    public final boolean requestFocus() {
6690        return requestFocus(View.FOCUS_DOWN);
6691    }
6692
6693    /**
6694     * Call this to try to give focus to a specific view or to one of its
6695     * descendants and give it a hint about what direction focus is heading.
6696     *
6697     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6698     * false), or if it is focusable and it is not focusable in touch mode
6699     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6700     *
6701     * See also {@link #focusSearch(int)}, which is what you call to say that you
6702     * have focus, and you want your parent to look for the next one.
6703     *
6704     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6705     * <code>null</code> set for the previously focused rectangle.
6706     *
6707     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6708     * @return Whether this view or one of its descendants actually took focus.
6709     */
6710    public final boolean requestFocus(int direction) {
6711        return requestFocus(direction, null);
6712    }
6713
6714    /**
6715     * Call this to try to give focus to a specific view or to one of its descendants
6716     * and give it hints about the direction and a specific rectangle that the focus
6717     * is coming from.  The rectangle can help give larger views a finer grained hint
6718     * about where focus is coming from, and therefore, where to show selection, or
6719     * forward focus change internally.
6720     *
6721     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6722     * false), or if it is focusable and it is not focusable in touch mode
6723     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6724     *
6725     * A View will not take focus if it is not visible.
6726     *
6727     * A View will not take focus if one of its parents has
6728     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6729     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6730     *
6731     * See also {@link #focusSearch(int)}, which is what you call to say that you
6732     * have focus, and you want your parent to look for the next one.
6733     *
6734     * You may wish to override this method if your custom {@link View} has an internal
6735     * {@link View} that it wishes to forward the request to.
6736     *
6737     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6738     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6739     *        to give a finer grained hint about where focus is coming from.  May be null
6740     *        if there is no hint.
6741     * @return Whether this view or one of its descendants actually took focus.
6742     */
6743    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6744        return requestFocusNoSearch(direction, previouslyFocusedRect);
6745    }
6746
6747    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6748        // need to be focusable
6749        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6750                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6751            return false;
6752        }
6753
6754        // need to be focusable in touch mode if in touch mode
6755        if (isInTouchMode() &&
6756            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6757               return false;
6758        }
6759
6760        // need to not have any parents blocking us
6761        if (hasAncestorThatBlocksDescendantFocus()) {
6762            return false;
6763        }
6764
6765        handleFocusGainInternal(direction, previouslyFocusedRect);
6766        return true;
6767    }
6768
6769    /**
6770     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6771     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6772     * touch mode to request focus when they are touched.
6773     *
6774     * @return Whether this view or one of its descendants actually took focus.
6775     *
6776     * @see #isInTouchMode()
6777     *
6778     */
6779    public final boolean requestFocusFromTouch() {
6780        // Leave touch mode if we need to
6781        if (isInTouchMode()) {
6782            ViewRootImpl viewRoot = getViewRootImpl();
6783            if (viewRoot != null) {
6784                viewRoot.ensureTouchMode(false);
6785            }
6786        }
6787        return requestFocus(View.FOCUS_DOWN);
6788    }
6789
6790    /**
6791     * @return Whether any ancestor of this view blocks descendant focus.
6792     */
6793    private boolean hasAncestorThatBlocksDescendantFocus() {
6794        ViewParent ancestor = mParent;
6795        while (ancestor instanceof ViewGroup) {
6796            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6797            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6798                return true;
6799            } else {
6800                ancestor = vgAncestor.getParent();
6801            }
6802        }
6803        return false;
6804    }
6805
6806    /**
6807     * Gets the mode for determining whether this View is important for accessibility
6808     * which is if it fires accessibility events and if it is reported to
6809     * accessibility services that query the screen.
6810     *
6811     * @return The mode for determining whether a View is important for accessibility.
6812     *
6813     * @attr ref android.R.styleable#View_importantForAccessibility
6814     *
6815     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6816     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6817     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6818     */
6819    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6820            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6821            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6822            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6823        })
6824    public int getImportantForAccessibility() {
6825        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6826                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6827    }
6828
6829    /**
6830     * Sets how to determine whether this view is important for accessibility
6831     * which is if it fires accessibility events and if it is reported to
6832     * accessibility services that query the screen.
6833     *
6834     * @param mode How to determine whether this view is important for accessibility.
6835     *
6836     * @attr ref android.R.styleable#View_importantForAccessibility
6837     *
6838     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6839     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6840     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6841     */
6842    public void setImportantForAccessibility(int mode) {
6843        if (mode != getImportantForAccessibility()) {
6844            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6845            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6846                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6847            notifyAccessibilityStateChanged();
6848        }
6849    }
6850
6851    /**
6852     * Gets whether this view should be exposed for accessibility.
6853     *
6854     * @return Whether the view is exposed for accessibility.
6855     *
6856     * @hide
6857     */
6858    public boolean isImportantForAccessibility() {
6859        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6860                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6861        switch (mode) {
6862            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6863                return true;
6864            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6865                return false;
6866            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6867                return isActionableForAccessibility() || hasListenersForAccessibility()
6868                        || getAccessibilityNodeProvider() != null;
6869            default:
6870                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6871                        + mode);
6872        }
6873    }
6874
6875    /**
6876     * Gets the parent for accessibility purposes. Note that the parent for
6877     * accessibility is not necessary the immediate parent. It is the first
6878     * predecessor that is important for accessibility.
6879     *
6880     * @return The parent for accessibility purposes.
6881     */
6882    public ViewParent getParentForAccessibility() {
6883        if (mParent instanceof View) {
6884            View parentView = (View) mParent;
6885            if (parentView.includeForAccessibility()) {
6886                return mParent;
6887            } else {
6888                return mParent.getParentForAccessibility();
6889            }
6890        }
6891        return null;
6892    }
6893
6894    /**
6895     * Adds the children of a given View for accessibility. Since some Views are
6896     * not important for accessibility the children for accessibility are not
6897     * necessarily direct children of the view, rather they are the first level of
6898     * descendants important for accessibility.
6899     *
6900     * @param children The list of children for accessibility.
6901     */
6902    public void addChildrenForAccessibility(ArrayList<View> children) {
6903        if (includeForAccessibility()) {
6904            children.add(this);
6905        }
6906    }
6907
6908    /**
6909     * Whether to regard this view for accessibility. A view is regarded for
6910     * accessibility if it is important for accessibility or the querying
6911     * accessibility service has explicitly requested that view not
6912     * important for accessibility are regarded.
6913     *
6914     * @return Whether to regard the view for accessibility.
6915     *
6916     * @hide
6917     */
6918    public boolean includeForAccessibility() {
6919        if (mAttachInfo != null) {
6920            return (mAttachInfo.mAccessibilityFetchFlags
6921                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6922                    || isImportantForAccessibility();
6923        }
6924        return false;
6925    }
6926
6927    /**
6928     * Returns whether the View is considered actionable from
6929     * accessibility perspective. Such view are important for
6930     * accessibility.
6931     *
6932     * @return True if the view is actionable for accessibility.
6933     *
6934     * @hide
6935     */
6936    public boolean isActionableForAccessibility() {
6937        return (isClickable() || isLongClickable() || isFocusable());
6938    }
6939
6940    /**
6941     * Returns whether the View has registered callbacks wich makes it
6942     * important for accessibility.
6943     *
6944     * @return True if the view is actionable for accessibility.
6945     */
6946    private boolean hasListenersForAccessibility() {
6947        ListenerInfo info = getListenerInfo();
6948        return mTouchDelegate != null || info.mOnKeyListener != null
6949                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6950                || info.mOnHoverListener != null || info.mOnDragListener != null;
6951    }
6952
6953    /**
6954     * Notifies accessibility services that some view's important for
6955     * accessibility state has changed. Note that such notifications
6956     * are made at most once every
6957     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6958     * to avoid unnecessary load to the system. Also once a view has
6959     * made a notifucation this method is a NOP until the notification has
6960     * been sent to clients.
6961     *
6962     * @hide
6963     *
6964     * TODO: Makse sure this method is called for any view state change
6965     *       that is interesting for accessilility purposes.
6966     */
6967    public void notifyAccessibilityStateChanged() {
6968        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6969            return;
6970        }
6971        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6972            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6973            if (mParent != null) {
6974                mParent.childAccessibilityStateChanged(this);
6975            }
6976        }
6977    }
6978
6979    /**
6980     * Reset the state indicating the this view has requested clients
6981     * interested in its accessibility state to be notified.
6982     *
6983     * @hide
6984     */
6985    public void resetAccessibilityStateChanged() {
6986        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6987    }
6988
6989    /**
6990     * Performs the specified accessibility action on the view. For
6991     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6992     * <p>
6993     * If an {@link AccessibilityDelegate} has been specified via calling
6994     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6995     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6996     * is responsible for handling this call.
6997     * </p>
6998     *
6999     * @param action The action to perform.
7000     * @param arguments Optional action arguments.
7001     * @return Whether the action was performed.
7002     */
7003    public boolean performAccessibilityAction(int action, Bundle arguments) {
7004      if (mAccessibilityDelegate != null) {
7005          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7006      } else {
7007          return performAccessibilityActionInternal(action, arguments);
7008      }
7009    }
7010
7011   /**
7012    * @see #performAccessibilityAction(int, Bundle)
7013    *
7014    * Note: Called from the default {@link AccessibilityDelegate}.
7015    */
7016    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7017        switch (action) {
7018            case AccessibilityNodeInfo.ACTION_CLICK: {
7019                if (isClickable()) {
7020                    performClick();
7021                    return true;
7022                }
7023            } break;
7024            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7025                if (isLongClickable()) {
7026                    performLongClick();
7027                    return true;
7028                }
7029            } break;
7030            case AccessibilityNodeInfo.ACTION_FOCUS: {
7031                if (!hasFocus()) {
7032                    // Get out of touch mode since accessibility
7033                    // wants to move focus around.
7034                    getViewRootImpl().ensureTouchMode(false);
7035                    return requestFocus();
7036                }
7037            } break;
7038            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7039                if (hasFocus()) {
7040                    clearFocus();
7041                    return !isFocused();
7042                }
7043            } break;
7044            case AccessibilityNodeInfo.ACTION_SELECT: {
7045                if (!isSelected()) {
7046                    setSelected(true);
7047                    return isSelected();
7048                }
7049            } break;
7050            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7051                if (isSelected()) {
7052                    setSelected(false);
7053                    return !isSelected();
7054                }
7055            } break;
7056            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7057                if (!isAccessibilityFocused()) {
7058                    return requestAccessibilityFocus();
7059                }
7060            } break;
7061            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7062                if (isAccessibilityFocused()) {
7063                    clearAccessibilityFocus();
7064                    return true;
7065                }
7066            } break;
7067            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7068                if (arguments != null) {
7069                    final int granularity = arguments.getInt(
7070                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7071                    final boolean extendSelection = arguments.getBoolean(
7072                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7073                    return nextAtGranularity(granularity, extendSelection);
7074                }
7075            } break;
7076            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7077                if (arguments != null) {
7078                    final int granularity = arguments.getInt(
7079                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7080                    final boolean extendSelection = arguments.getBoolean(
7081                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7082                    return previousAtGranularity(granularity, extendSelection);
7083                }
7084            } break;
7085            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7086                CharSequence text = getIterableTextForAccessibility();
7087                if (text == null) {
7088                    return false;
7089                }
7090                final int start = (arguments != null) ? arguments.getInt(
7091                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7092                final int end = (arguments != null) ? arguments.getInt(
7093                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7094                // Only cursor position can be specified (selection length == 0)
7095                if ((getAccessibilitySelectionStart() != start
7096                        || getAccessibilitySelectionEnd() != end)
7097                        && (start == end)) {
7098                    setAccessibilitySelection(start, end);
7099                    notifyAccessibilityStateChanged();
7100                    return true;
7101                }
7102            } break;
7103        }
7104        return false;
7105    }
7106
7107    private boolean nextAtGranularity(int granularity, boolean extendSelection) {
7108        CharSequence text = getIterableTextForAccessibility();
7109        if (text == null || text.length() == 0) {
7110            return false;
7111        }
7112        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7113        if (iterator == null) {
7114            return false;
7115        }
7116        int current = getAccessibilitySelectionEnd();
7117        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7118            current = 0;
7119        }
7120        final int[] range = iterator.following(current);
7121        if (range == null) {
7122            return false;
7123        }
7124        final int start = range[0];
7125        final int end = range[1];
7126        if (extendSelection && isAccessibilitySelectionExtendable()) {
7127            int selectionStart = getAccessibilitySelectionStart();
7128            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7129                selectionStart = start;
7130            }
7131            setAccessibilitySelection(selectionStart, end);
7132        } else {
7133            setAccessibilitySelection(end, end);
7134        }
7135        sendViewTextTraversedAtGranularityEvent(
7136                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
7137                granularity, start, end);
7138        return true;
7139    }
7140
7141    private boolean previousAtGranularity(int granularity, boolean extendSelection) {
7142        CharSequence text = getIterableTextForAccessibility();
7143        if (text == null || text.length() == 0) {
7144            return false;
7145        }
7146        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7147        if (iterator == null) {
7148            return false;
7149        }
7150        int current = getAccessibilitySelectionStart();
7151        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7152            current = text.length();
7153        }
7154        final int[] range = iterator.preceding(current);
7155        if (range == null) {
7156            return false;
7157        }
7158        final int start = range[0];
7159        final int end = range[1];
7160        if (extendSelection && isAccessibilitySelectionExtendable()) {
7161            int selectionEnd = getAccessibilitySelectionEnd();
7162            if (selectionEnd == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7163                selectionEnd = end;
7164            }
7165            setAccessibilitySelection(start, selectionEnd);
7166        } else {
7167            setAccessibilitySelection(start, start);
7168        }
7169        sendViewTextTraversedAtGranularityEvent(
7170                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
7171                granularity, start, end);
7172        return true;
7173    }
7174
7175    /**
7176     * Gets the text reported for accessibility purposes.
7177     *
7178     * @return The accessibility text.
7179     *
7180     * @hide
7181     */
7182    public CharSequence getIterableTextForAccessibility() {
7183        return getContentDescription();
7184    }
7185
7186    /**
7187     * Gets whether accessibility selection can be extended.
7188     *
7189     * @return If selection is extensible.
7190     *
7191     * @hide
7192     */
7193    public boolean isAccessibilitySelectionExtendable() {
7194        return false;
7195    }
7196
7197    /**
7198     * @hide
7199     */
7200    public int getAccessibilitySelectionStart() {
7201        return mAccessibilityCursorPosition;
7202    }
7203
7204    /**
7205     * @hide
7206     */
7207    public int getAccessibilitySelectionEnd() {
7208        return getAccessibilitySelectionStart();
7209    }
7210
7211    /**
7212     * @hide
7213     */
7214    public void setAccessibilitySelection(int start, int end) {
7215        if (start ==  end && end == mAccessibilityCursorPosition) {
7216            return;
7217        }
7218        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7219            mAccessibilityCursorPosition = start;
7220        } else {
7221            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7222        }
7223        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7224    }
7225
7226    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7227            int fromIndex, int toIndex) {
7228        if (mParent == null) {
7229            return;
7230        }
7231        AccessibilityEvent event = AccessibilityEvent.obtain(
7232                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7233        onInitializeAccessibilityEvent(event);
7234        onPopulateAccessibilityEvent(event);
7235        event.setFromIndex(fromIndex);
7236        event.setToIndex(toIndex);
7237        event.setAction(action);
7238        event.setMovementGranularity(granularity);
7239        mParent.requestSendAccessibilityEvent(this, event);
7240    }
7241
7242    /**
7243     * @hide
7244     */
7245    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7246        switch (granularity) {
7247            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7248                CharSequence text = getIterableTextForAccessibility();
7249                if (text != null && text.length() > 0) {
7250                    CharacterTextSegmentIterator iterator =
7251                        CharacterTextSegmentIterator.getInstance(
7252                                mContext.getResources().getConfiguration().locale);
7253                    iterator.initialize(text.toString());
7254                    return iterator;
7255                }
7256            } break;
7257            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7258                CharSequence text = getIterableTextForAccessibility();
7259                if (text != null && text.length() > 0) {
7260                    WordTextSegmentIterator iterator =
7261                        WordTextSegmentIterator.getInstance(
7262                                mContext.getResources().getConfiguration().locale);
7263                    iterator.initialize(text.toString());
7264                    return iterator;
7265                }
7266            } break;
7267            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7268                CharSequence text = getIterableTextForAccessibility();
7269                if (text != null && text.length() > 0) {
7270                    ParagraphTextSegmentIterator iterator =
7271                        ParagraphTextSegmentIterator.getInstance();
7272                    iterator.initialize(text.toString());
7273                    return iterator;
7274                }
7275            } break;
7276        }
7277        return null;
7278    }
7279
7280    /**
7281     * @hide
7282     */
7283    public void dispatchStartTemporaryDetach() {
7284        clearAccessibilityFocus();
7285        clearDisplayList();
7286
7287        onStartTemporaryDetach();
7288    }
7289
7290    /**
7291     * This is called when a container is going to temporarily detach a child, with
7292     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7293     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7294     * {@link #onDetachedFromWindow()} when the container is done.
7295     */
7296    public void onStartTemporaryDetach() {
7297        removeUnsetPressCallback();
7298        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7299    }
7300
7301    /**
7302     * @hide
7303     */
7304    public void dispatchFinishTemporaryDetach() {
7305        onFinishTemporaryDetach();
7306    }
7307
7308    /**
7309     * Called after {@link #onStartTemporaryDetach} when the container is done
7310     * changing the view.
7311     */
7312    public void onFinishTemporaryDetach() {
7313    }
7314
7315    /**
7316     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7317     * for this view's window.  Returns null if the view is not currently attached
7318     * to the window.  Normally you will not need to use this directly, but
7319     * just use the standard high-level event callbacks like
7320     * {@link #onKeyDown(int, KeyEvent)}.
7321     */
7322    public KeyEvent.DispatcherState getKeyDispatcherState() {
7323        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7324    }
7325
7326    /**
7327     * Dispatch a key event before it is processed by any input method
7328     * associated with the view hierarchy.  This can be used to intercept
7329     * key events in special situations before the IME consumes them; a
7330     * typical example would be handling the BACK key to update the application's
7331     * UI instead of allowing the IME to see it and close itself.
7332     *
7333     * @param event The key event to be dispatched.
7334     * @return True if the event was handled, false otherwise.
7335     */
7336    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7337        return onKeyPreIme(event.getKeyCode(), event);
7338    }
7339
7340    /**
7341     * Dispatch a key event to the next view on the focus path. This path runs
7342     * from the top of the view tree down to the currently focused view. If this
7343     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7344     * the next node down the focus path. This method also fires any key
7345     * listeners.
7346     *
7347     * @param event The key event to be dispatched.
7348     * @return True if the event was handled, false otherwise.
7349     */
7350    public boolean dispatchKeyEvent(KeyEvent event) {
7351        if (mInputEventConsistencyVerifier != null) {
7352            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7353        }
7354
7355        // Give any attached key listener a first crack at the event.
7356        //noinspection SimplifiableIfStatement
7357        ListenerInfo li = mListenerInfo;
7358        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7359                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7360            return true;
7361        }
7362
7363        if (event.dispatch(this, mAttachInfo != null
7364                ? mAttachInfo.mKeyDispatchState : null, this)) {
7365            return true;
7366        }
7367
7368        if (mInputEventConsistencyVerifier != null) {
7369            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7370        }
7371        return false;
7372    }
7373
7374    /**
7375     * Dispatches a key shortcut event.
7376     *
7377     * @param event The key event to be dispatched.
7378     * @return True if the event was handled by the view, false otherwise.
7379     */
7380    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7381        return onKeyShortcut(event.getKeyCode(), event);
7382    }
7383
7384    /**
7385     * Pass the touch screen motion event down to the target view, or this
7386     * view if it is the target.
7387     *
7388     * @param event The motion event to be dispatched.
7389     * @return True if the event was handled by the view, false otherwise.
7390     */
7391    public boolean dispatchTouchEvent(MotionEvent event) {
7392        if (mInputEventConsistencyVerifier != null) {
7393            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7394        }
7395
7396        if (onFilterTouchEventForSecurity(event)) {
7397            //noinspection SimplifiableIfStatement
7398            ListenerInfo li = mListenerInfo;
7399            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7400                    && li.mOnTouchListener.onTouch(this, event)) {
7401                return true;
7402            }
7403
7404            if (onTouchEvent(event)) {
7405                return true;
7406            }
7407        }
7408
7409        if (mInputEventConsistencyVerifier != null) {
7410            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7411        }
7412        return false;
7413    }
7414
7415    /**
7416     * Filter the touch event to apply security policies.
7417     *
7418     * @param event The motion event to be filtered.
7419     * @return True if the event should be dispatched, false if the event should be dropped.
7420     *
7421     * @see #getFilterTouchesWhenObscured
7422     */
7423    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7424        //noinspection RedundantIfStatement
7425        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7426                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7427            // Window is obscured, drop this touch.
7428            return false;
7429        }
7430        return true;
7431    }
7432
7433    /**
7434     * Pass a trackball motion event down to the focused view.
7435     *
7436     * @param event The motion event to be dispatched.
7437     * @return True if the event was handled by the view, false otherwise.
7438     */
7439    public boolean dispatchTrackballEvent(MotionEvent event) {
7440        if (mInputEventConsistencyVerifier != null) {
7441            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7442        }
7443
7444        return onTrackballEvent(event);
7445    }
7446
7447    /**
7448     * Dispatch a generic motion event.
7449     * <p>
7450     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7451     * are delivered to the view under the pointer.  All other generic motion events are
7452     * delivered to the focused view.  Hover events are handled specially and are delivered
7453     * to {@link #onHoverEvent(MotionEvent)}.
7454     * </p>
7455     *
7456     * @param event The motion event to be dispatched.
7457     * @return True if the event was handled by the view, false otherwise.
7458     */
7459    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7460        if (mInputEventConsistencyVerifier != null) {
7461            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7462        }
7463
7464        final int source = event.getSource();
7465        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7466            final int action = event.getAction();
7467            if (action == MotionEvent.ACTION_HOVER_ENTER
7468                    || action == MotionEvent.ACTION_HOVER_MOVE
7469                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7470                if (dispatchHoverEvent(event)) {
7471                    return true;
7472                }
7473            } else if (dispatchGenericPointerEvent(event)) {
7474                return true;
7475            }
7476        } else if (dispatchGenericFocusedEvent(event)) {
7477            return true;
7478        }
7479
7480        if (dispatchGenericMotionEventInternal(event)) {
7481            return true;
7482        }
7483
7484        if (mInputEventConsistencyVerifier != null) {
7485            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7486        }
7487        return false;
7488    }
7489
7490    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7491        //noinspection SimplifiableIfStatement
7492        ListenerInfo li = mListenerInfo;
7493        if (li != null && li.mOnGenericMotionListener != null
7494                && (mViewFlags & ENABLED_MASK) == ENABLED
7495                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7496            return true;
7497        }
7498
7499        if (onGenericMotionEvent(event)) {
7500            return true;
7501        }
7502
7503        if (mInputEventConsistencyVerifier != null) {
7504            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7505        }
7506        return false;
7507    }
7508
7509    /**
7510     * Dispatch a hover event.
7511     * <p>
7512     * Do not call this method directly.
7513     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7514     * </p>
7515     *
7516     * @param event The motion event to be dispatched.
7517     * @return True if the event was handled by the view, false otherwise.
7518     */
7519    protected boolean dispatchHoverEvent(MotionEvent event) {
7520        //noinspection SimplifiableIfStatement
7521        ListenerInfo li = mListenerInfo;
7522        if (li != null && li.mOnHoverListener != null
7523                && (mViewFlags & ENABLED_MASK) == ENABLED
7524                && li.mOnHoverListener.onHover(this, event)) {
7525            return true;
7526        }
7527
7528        return onHoverEvent(event);
7529    }
7530
7531    /**
7532     * Returns true if the view has a child to which it has recently sent
7533     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7534     * it does not have a hovered child, then it must be the innermost hovered view.
7535     * @hide
7536     */
7537    protected boolean hasHoveredChild() {
7538        return false;
7539    }
7540
7541    /**
7542     * Dispatch a generic motion event to the view under the first pointer.
7543     * <p>
7544     * Do not call this method directly.
7545     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7546     * </p>
7547     *
7548     * @param event The motion event to be dispatched.
7549     * @return True if the event was handled by the view, false otherwise.
7550     */
7551    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7552        return false;
7553    }
7554
7555    /**
7556     * Dispatch a generic motion event to the currently focused view.
7557     * <p>
7558     * Do not call this method directly.
7559     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7560     * </p>
7561     *
7562     * @param event The motion event to be dispatched.
7563     * @return True if the event was handled by the view, false otherwise.
7564     */
7565    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7566        return false;
7567    }
7568
7569    /**
7570     * Dispatch a pointer event.
7571     * <p>
7572     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7573     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7574     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7575     * and should not be expected to handle other pointing device features.
7576     * </p>
7577     *
7578     * @param event The motion event to be dispatched.
7579     * @return True if the event was handled by the view, false otherwise.
7580     * @hide
7581     */
7582    public final boolean dispatchPointerEvent(MotionEvent event) {
7583        if (event.isTouchEvent()) {
7584            return dispatchTouchEvent(event);
7585        } else {
7586            return dispatchGenericMotionEvent(event);
7587        }
7588    }
7589
7590    /**
7591     * Called when the window containing this view gains or loses window focus.
7592     * ViewGroups should override to route to their children.
7593     *
7594     * @param hasFocus True if the window containing this view now has focus,
7595     *        false otherwise.
7596     */
7597    public void dispatchWindowFocusChanged(boolean hasFocus) {
7598        onWindowFocusChanged(hasFocus);
7599    }
7600
7601    /**
7602     * Called when the window containing this view gains or loses focus.  Note
7603     * that this is separate from view focus: to receive key events, both
7604     * your view and its window must have focus.  If a window is displayed
7605     * on top of yours that takes input focus, then your own window will lose
7606     * focus but the view focus will remain unchanged.
7607     *
7608     * @param hasWindowFocus True if the window containing this view now has
7609     *        focus, false otherwise.
7610     */
7611    public void onWindowFocusChanged(boolean hasWindowFocus) {
7612        InputMethodManager imm = InputMethodManager.peekInstance();
7613        if (!hasWindowFocus) {
7614            if (isPressed()) {
7615                setPressed(false);
7616            }
7617            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7618                imm.focusOut(this);
7619            }
7620            removeLongPressCallback();
7621            removeTapCallback();
7622            onFocusLost();
7623        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7624            imm.focusIn(this);
7625        }
7626        refreshDrawableState();
7627    }
7628
7629    /**
7630     * Returns true if this view is in a window that currently has window focus.
7631     * Note that this is not the same as the view itself having focus.
7632     *
7633     * @return True if this view is in a window that currently has window focus.
7634     */
7635    public boolean hasWindowFocus() {
7636        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7637    }
7638
7639    /**
7640     * Dispatch a view visibility change down the view hierarchy.
7641     * ViewGroups should override to route to their children.
7642     * @param changedView The view whose visibility changed. Could be 'this' or
7643     * an ancestor view.
7644     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7645     * {@link #INVISIBLE} or {@link #GONE}.
7646     */
7647    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7648        onVisibilityChanged(changedView, visibility);
7649    }
7650
7651    /**
7652     * Called when the visibility of the view or an ancestor of the view is changed.
7653     * @param changedView The view whose visibility changed. Could be 'this' or
7654     * an ancestor view.
7655     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7656     * {@link #INVISIBLE} or {@link #GONE}.
7657     */
7658    protected void onVisibilityChanged(View changedView, int visibility) {
7659        if (visibility == VISIBLE) {
7660            if (mAttachInfo != null) {
7661                initialAwakenScrollBars();
7662            } else {
7663                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7664            }
7665        }
7666    }
7667
7668    /**
7669     * Dispatch a hint about whether this view is displayed. For instance, when
7670     * a View moves out of the screen, it might receives a display hint indicating
7671     * the view is not displayed. Applications should not <em>rely</em> on this hint
7672     * as there is no guarantee that they will receive one.
7673     *
7674     * @param hint A hint about whether or not this view is displayed:
7675     * {@link #VISIBLE} or {@link #INVISIBLE}.
7676     */
7677    public void dispatchDisplayHint(int hint) {
7678        onDisplayHint(hint);
7679    }
7680
7681    /**
7682     * Gives this view a hint about whether is displayed or not. For instance, when
7683     * a View moves out of the screen, it might receives a display hint indicating
7684     * the view is not displayed. Applications should not <em>rely</em> on this hint
7685     * as there is no guarantee that they will receive one.
7686     *
7687     * @param hint A hint about whether or not this view is displayed:
7688     * {@link #VISIBLE} or {@link #INVISIBLE}.
7689     */
7690    protected void onDisplayHint(int hint) {
7691    }
7692
7693    /**
7694     * Dispatch a window visibility change down the view hierarchy.
7695     * ViewGroups should override to route to their children.
7696     *
7697     * @param visibility The new visibility of the window.
7698     *
7699     * @see #onWindowVisibilityChanged(int)
7700     */
7701    public void dispatchWindowVisibilityChanged(int visibility) {
7702        onWindowVisibilityChanged(visibility);
7703    }
7704
7705    /**
7706     * Called when the window containing has change its visibility
7707     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7708     * that this tells you whether or not your window is being made visible
7709     * to the window manager; this does <em>not</em> tell you whether or not
7710     * your window is obscured by other windows on the screen, even if it
7711     * is itself visible.
7712     *
7713     * @param visibility The new visibility of the window.
7714     */
7715    protected void onWindowVisibilityChanged(int visibility) {
7716        if (visibility == VISIBLE) {
7717            initialAwakenScrollBars();
7718        }
7719    }
7720
7721    /**
7722     * Returns the current visibility of the window this view is attached to
7723     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7724     *
7725     * @return Returns the current visibility of the view's window.
7726     */
7727    public int getWindowVisibility() {
7728        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7729    }
7730
7731    /**
7732     * Retrieve the overall visible display size in which the window this view is
7733     * attached to has been positioned in.  This takes into account screen
7734     * decorations above the window, for both cases where the window itself
7735     * is being position inside of them or the window is being placed under
7736     * then and covered insets are used for the window to position its content
7737     * inside.  In effect, this tells you the available area where content can
7738     * be placed and remain visible to users.
7739     *
7740     * <p>This function requires an IPC back to the window manager to retrieve
7741     * the requested information, so should not be used in performance critical
7742     * code like drawing.
7743     *
7744     * @param outRect Filled in with the visible display frame.  If the view
7745     * is not attached to a window, this is simply the raw display size.
7746     */
7747    public void getWindowVisibleDisplayFrame(Rect outRect) {
7748        if (mAttachInfo != null) {
7749            try {
7750                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7751            } catch (RemoteException e) {
7752                return;
7753            }
7754            // XXX This is really broken, and probably all needs to be done
7755            // in the window manager, and we need to know more about whether
7756            // we want the area behind or in front of the IME.
7757            final Rect insets = mAttachInfo.mVisibleInsets;
7758            outRect.left += insets.left;
7759            outRect.top += insets.top;
7760            outRect.right -= insets.right;
7761            outRect.bottom -= insets.bottom;
7762            return;
7763        }
7764        // The view is not attached to a display so we don't have a context.
7765        // Make a best guess about the display size.
7766        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7767        d.getRectSize(outRect);
7768    }
7769
7770    /**
7771     * Dispatch a notification about a resource configuration change down
7772     * the view hierarchy.
7773     * ViewGroups should override to route to their children.
7774     *
7775     * @param newConfig The new resource configuration.
7776     *
7777     * @see #onConfigurationChanged(android.content.res.Configuration)
7778     */
7779    public void dispatchConfigurationChanged(Configuration newConfig) {
7780        onConfigurationChanged(newConfig);
7781    }
7782
7783    /**
7784     * Called when the current configuration of the resources being used
7785     * by the application have changed.  You can use this to decide when
7786     * to reload resources that can changed based on orientation and other
7787     * configuration characterstics.  You only need to use this if you are
7788     * not relying on the normal {@link android.app.Activity} mechanism of
7789     * recreating the activity instance upon a configuration change.
7790     *
7791     * @param newConfig The new resource configuration.
7792     */
7793    protected void onConfigurationChanged(Configuration newConfig) {
7794    }
7795
7796    /**
7797     * Private function to aggregate all per-view attributes in to the view
7798     * root.
7799     */
7800    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7801        performCollectViewAttributes(attachInfo, visibility);
7802    }
7803
7804    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7805        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7806            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7807                attachInfo.mKeepScreenOn = true;
7808            }
7809            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7810            ListenerInfo li = mListenerInfo;
7811            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7812                attachInfo.mHasSystemUiListeners = true;
7813            }
7814        }
7815    }
7816
7817    void needGlobalAttributesUpdate(boolean force) {
7818        final AttachInfo ai = mAttachInfo;
7819        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7820            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7821                    || ai.mHasSystemUiListeners) {
7822                ai.mRecomputeGlobalAttributes = true;
7823            }
7824        }
7825    }
7826
7827    /**
7828     * Returns whether the device is currently in touch mode.  Touch mode is entered
7829     * once the user begins interacting with the device by touch, and affects various
7830     * things like whether focus is always visible to the user.
7831     *
7832     * @return Whether the device is in touch mode.
7833     */
7834    @ViewDebug.ExportedProperty
7835    public boolean isInTouchMode() {
7836        if (mAttachInfo != null) {
7837            return mAttachInfo.mInTouchMode;
7838        } else {
7839            return ViewRootImpl.isInTouchMode();
7840        }
7841    }
7842
7843    /**
7844     * Returns the context the view is running in, through which it can
7845     * access the current theme, resources, etc.
7846     *
7847     * @return The view's Context.
7848     */
7849    @ViewDebug.CapturedViewProperty
7850    public final Context getContext() {
7851        return mContext;
7852    }
7853
7854    /**
7855     * Handle a key event before it is processed by any input method
7856     * associated with the view hierarchy.  This can be used to intercept
7857     * key events in special situations before the IME consumes them; a
7858     * typical example would be handling the BACK key to update the application's
7859     * UI instead of allowing the IME to see it and close itself.
7860     *
7861     * @param keyCode The value in event.getKeyCode().
7862     * @param event Description of the key event.
7863     * @return If you handled the event, return true. If you want to allow the
7864     *         event to be handled by the next receiver, return false.
7865     */
7866    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7867        return false;
7868    }
7869
7870    /**
7871     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7872     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7873     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7874     * is released, if the view is enabled and clickable.
7875     *
7876     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7877     * although some may elect to do so in some situations. Do not rely on this to
7878     * catch software key presses.
7879     *
7880     * @param keyCode A key code that represents the button pressed, from
7881     *                {@link android.view.KeyEvent}.
7882     * @param event   The KeyEvent object that defines the button action.
7883     */
7884    public boolean onKeyDown(int keyCode, KeyEvent event) {
7885        boolean result = false;
7886
7887        switch (keyCode) {
7888            case KeyEvent.KEYCODE_DPAD_CENTER:
7889            case KeyEvent.KEYCODE_ENTER: {
7890                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7891                    return true;
7892                }
7893                // Long clickable items don't necessarily have to be clickable
7894                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7895                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7896                        (event.getRepeatCount() == 0)) {
7897                    setPressed(true);
7898                    checkForLongClick(0);
7899                    return true;
7900                }
7901                break;
7902            }
7903        }
7904        return result;
7905    }
7906
7907    /**
7908     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7909     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7910     * the event).
7911     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7912     * although some may elect to do so in some situations. Do not rely on this to
7913     * catch software key presses.
7914     */
7915    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7916        return false;
7917    }
7918
7919    /**
7920     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7921     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7922     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7923     * {@link KeyEvent#KEYCODE_ENTER} is released.
7924     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7925     * although some may elect to do so in some situations. Do not rely on this to
7926     * catch software key presses.
7927     *
7928     * @param keyCode A key code that represents the button pressed, from
7929     *                {@link android.view.KeyEvent}.
7930     * @param event   The KeyEvent object that defines the button action.
7931     */
7932    public boolean onKeyUp(int keyCode, KeyEvent event) {
7933        boolean result = false;
7934
7935        switch (keyCode) {
7936            case KeyEvent.KEYCODE_DPAD_CENTER:
7937            case KeyEvent.KEYCODE_ENTER: {
7938                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7939                    return true;
7940                }
7941                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7942                    setPressed(false);
7943
7944                    if (!mHasPerformedLongPress) {
7945                        // This is a tap, so remove the longpress check
7946                        removeLongPressCallback();
7947
7948                        result = performClick();
7949                    }
7950                }
7951                break;
7952            }
7953        }
7954        return result;
7955    }
7956
7957    /**
7958     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7959     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7960     * the event).
7961     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7962     * although some may elect to do so in some situations. Do not rely on this to
7963     * catch software key presses.
7964     *
7965     * @param keyCode     A key code that represents the button pressed, from
7966     *                    {@link android.view.KeyEvent}.
7967     * @param repeatCount The number of times the action was made.
7968     * @param event       The KeyEvent object that defines the button action.
7969     */
7970    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7971        return false;
7972    }
7973
7974    /**
7975     * Called on the focused view when a key shortcut event is not handled.
7976     * Override this method to implement local key shortcuts for the View.
7977     * Key shortcuts can also be implemented by setting the
7978     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7979     *
7980     * @param keyCode The value in event.getKeyCode().
7981     * @param event Description of the key event.
7982     * @return If you handled the event, return true. If you want to allow the
7983     *         event to be handled by the next receiver, return false.
7984     */
7985    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7986        return false;
7987    }
7988
7989    /**
7990     * Check whether the called view is a text editor, in which case it
7991     * would make sense to automatically display a soft input window for
7992     * it.  Subclasses should override this if they implement
7993     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7994     * a call on that method would return a non-null InputConnection, and
7995     * they are really a first-class editor that the user would normally
7996     * start typing on when the go into a window containing your view.
7997     *
7998     * <p>The default implementation always returns false.  This does
7999     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8000     * will not be called or the user can not otherwise perform edits on your
8001     * view; it is just a hint to the system that this is not the primary
8002     * purpose of this view.
8003     *
8004     * @return Returns true if this view is a text editor, else false.
8005     */
8006    public boolean onCheckIsTextEditor() {
8007        return false;
8008    }
8009
8010    /**
8011     * Create a new InputConnection for an InputMethod to interact
8012     * with the view.  The default implementation returns null, since it doesn't
8013     * support input methods.  You can override this to implement such support.
8014     * This is only needed for views that take focus and text input.
8015     *
8016     * <p>When implementing this, you probably also want to implement
8017     * {@link #onCheckIsTextEditor()} to indicate you will return a
8018     * non-null InputConnection.
8019     *
8020     * @param outAttrs Fill in with attribute information about the connection.
8021     */
8022    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8023        return null;
8024    }
8025
8026    /**
8027     * Called by the {@link android.view.inputmethod.InputMethodManager}
8028     * when a view who is not the current
8029     * input connection target is trying to make a call on the manager.  The
8030     * default implementation returns false; you can override this to return
8031     * true for certain views if you are performing InputConnection proxying
8032     * to them.
8033     * @param view The View that is making the InputMethodManager call.
8034     * @return Return true to allow the call, false to reject.
8035     */
8036    public boolean checkInputConnectionProxy(View view) {
8037        return false;
8038    }
8039
8040    /**
8041     * Show the context menu for this view. It is not safe to hold on to the
8042     * menu after returning from this method.
8043     *
8044     * You should normally not overload this method. Overload
8045     * {@link #onCreateContextMenu(ContextMenu)} or define an
8046     * {@link OnCreateContextMenuListener} to add items to the context menu.
8047     *
8048     * @param menu The context menu to populate
8049     */
8050    public void createContextMenu(ContextMenu menu) {
8051        ContextMenuInfo menuInfo = getContextMenuInfo();
8052
8053        // Sets the current menu info so all items added to menu will have
8054        // my extra info set.
8055        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8056
8057        onCreateContextMenu(menu);
8058        ListenerInfo li = mListenerInfo;
8059        if (li != null && li.mOnCreateContextMenuListener != null) {
8060            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8061        }
8062
8063        // Clear the extra information so subsequent items that aren't mine don't
8064        // have my extra info.
8065        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8066
8067        if (mParent != null) {
8068            mParent.createContextMenu(menu);
8069        }
8070    }
8071
8072    /**
8073     * Views should implement this if they have extra information to associate
8074     * with the context menu. The return result is supplied as a parameter to
8075     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8076     * callback.
8077     *
8078     * @return Extra information about the item for which the context menu
8079     *         should be shown. This information will vary across different
8080     *         subclasses of View.
8081     */
8082    protected ContextMenuInfo getContextMenuInfo() {
8083        return null;
8084    }
8085
8086    /**
8087     * Views should implement this if the view itself is going to add items to
8088     * the context menu.
8089     *
8090     * @param menu the context menu to populate
8091     */
8092    protected void onCreateContextMenu(ContextMenu menu) {
8093    }
8094
8095    /**
8096     * Implement this method to handle trackball motion events.  The
8097     * <em>relative</em> movement of the trackball since the last event
8098     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8099     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8100     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8101     * they will often be fractional values, representing the more fine-grained
8102     * movement information available from a trackball).
8103     *
8104     * @param event The motion event.
8105     * @return True if the event was handled, false otherwise.
8106     */
8107    public boolean onTrackballEvent(MotionEvent event) {
8108        return false;
8109    }
8110
8111    /**
8112     * Implement this method to handle generic motion events.
8113     * <p>
8114     * Generic motion events describe joystick movements, mouse hovers, track pad
8115     * touches, scroll wheel movements and other input events.  The
8116     * {@link MotionEvent#getSource() source} of the motion event specifies
8117     * the class of input that was received.  Implementations of this method
8118     * must examine the bits in the source before processing the event.
8119     * The following code example shows how this is done.
8120     * </p><p>
8121     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8122     * are delivered to the view under the pointer.  All other generic motion events are
8123     * delivered to the focused view.
8124     * </p>
8125     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8126     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8127     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8128     *             // process the joystick movement...
8129     *             return true;
8130     *         }
8131     *     }
8132     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8133     *         switch (event.getAction()) {
8134     *             case MotionEvent.ACTION_HOVER_MOVE:
8135     *                 // process the mouse hover movement...
8136     *                 return true;
8137     *             case MotionEvent.ACTION_SCROLL:
8138     *                 // process the scroll wheel movement...
8139     *                 return true;
8140     *         }
8141     *     }
8142     *     return super.onGenericMotionEvent(event);
8143     * }</pre>
8144     *
8145     * @param event The generic motion event being processed.
8146     * @return True if the event was handled, false otherwise.
8147     */
8148    public boolean onGenericMotionEvent(MotionEvent event) {
8149        return false;
8150    }
8151
8152    /**
8153     * Implement this method to handle hover events.
8154     * <p>
8155     * This method is called whenever a pointer is hovering into, over, or out of the
8156     * bounds of a view and the view is not currently being touched.
8157     * Hover events are represented as pointer events with action
8158     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8159     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8160     * </p>
8161     * <ul>
8162     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8163     * when the pointer enters the bounds of the view.</li>
8164     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8165     * when the pointer has already entered the bounds of the view and has moved.</li>
8166     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8167     * when the pointer has exited the bounds of the view or when the pointer is
8168     * about to go down due to a button click, tap, or similar user action that
8169     * causes the view to be touched.</li>
8170     * </ul>
8171     * <p>
8172     * The view should implement this method to return true to indicate that it is
8173     * handling the hover event, such as by changing its drawable state.
8174     * </p><p>
8175     * The default implementation calls {@link #setHovered} to update the hovered state
8176     * of the view when a hover enter or hover exit event is received, if the view
8177     * is enabled and is clickable.  The default implementation also sends hover
8178     * accessibility events.
8179     * </p>
8180     *
8181     * @param event The motion event that describes the hover.
8182     * @return True if the view handled the hover event.
8183     *
8184     * @see #isHovered
8185     * @see #setHovered
8186     * @see #onHoverChanged
8187     */
8188    public boolean onHoverEvent(MotionEvent event) {
8189        // The root view may receive hover (or touch) events that are outside the bounds of
8190        // the window.  This code ensures that we only send accessibility events for
8191        // hovers that are actually within the bounds of the root view.
8192        final int action = event.getActionMasked();
8193        if (!mSendingHoverAccessibilityEvents) {
8194            if ((action == MotionEvent.ACTION_HOVER_ENTER
8195                    || action == MotionEvent.ACTION_HOVER_MOVE)
8196                    && !hasHoveredChild()
8197                    && pointInView(event.getX(), event.getY())) {
8198                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8199                mSendingHoverAccessibilityEvents = true;
8200            }
8201        } else {
8202            if (action == MotionEvent.ACTION_HOVER_EXIT
8203                    || (action == MotionEvent.ACTION_MOVE
8204                            && !pointInView(event.getX(), event.getY()))) {
8205                mSendingHoverAccessibilityEvents = false;
8206                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8207                // If the window does not have input focus we take away accessibility
8208                // focus as soon as the user stop hovering over the view.
8209                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8210                    getViewRootImpl().setAccessibilityFocus(null, null);
8211                }
8212            }
8213        }
8214
8215        if (isHoverable()) {
8216            switch (action) {
8217                case MotionEvent.ACTION_HOVER_ENTER:
8218                    setHovered(true);
8219                    break;
8220                case MotionEvent.ACTION_HOVER_EXIT:
8221                    setHovered(false);
8222                    break;
8223            }
8224
8225            // Dispatch the event to onGenericMotionEvent before returning true.
8226            // This is to provide compatibility with existing applications that
8227            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8228            // break because of the new default handling for hoverable views
8229            // in onHoverEvent.
8230            // Note that onGenericMotionEvent will be called by default when
8231            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8232            return dispatchGenericMotionEventInternal(event);
8233        }
8234
8235        return false;
8236    }
8237
8238    /**
8239     * Returns true if the view should handle {@link #onHoverEvent}
8240     * by calling {@link #setHovered} to change its hovered state.
8241     *
8242     * @return True if the view is hoverable.
8243     */
8244    private boolean isHoverable() {
8245        final int viewFlags = mViewFlags;
8246        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8247            return false;
8248        }
8249
8250        return (viewFlags & CLICKABLE) == CLICKABLE
8251                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8252    }
8253
8254    /**
8255     * Returns true if the view is currently hovered.
8256     *
8257     * @return True if the view is currently hovered.
8258     *
8259     * @see #setHovered
8260     * @see #onHoverChanged
8261     */
8262    @ViewDebug.ExportedProperty
8263    public boolean isHovered() {
8264        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8265    }
8266
8267    /**
8268     * Sets whether the view is currently hovered.
8269     * <p>
8270     * Calling this method also changes the drawable state of the view.  This
8271     * enables the view to react to hover by using different drawable resources
8272     * to change its appearance.
8273     * </p><p>
8274     * The {@link #onHoverChanged} method is called when the hovered state changes.
8275     * </p>
8276     *
8277     * @param hovered True if the view is hovered.
8278     *
8279     * @see #isHovered
8280     * @see #onHoverChanged
8281     */
8282    public void setHovered(boolean hovered) {
8283        if (hovered) {
8284            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8285                mPrivateFlags |= PFLAG_HOVERED;
8286                refreshDrawableState();
8287                onHoverChanged(true);
8288            }
8289        } else {
8290            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8291                mPrivateFlags &= ~PFLAG_HOVERED;
8292                refreshDrawableState();
8293                onHoverChanged(false);
8294            }
8295        }
8296    }
8297
8298    /**
8299     * Implement this method to handle hover state changes.
8300     * <p>
8301     * This method is called whenever the hover state changes as a result of a
8302     * call to {@link #setHovered}.
8303     * </p>
8304     *
8305     * @param hovered The current hover state, as returned by {@link #isHovered}.
8306     *
8307     * @see #isHovered
8308     * @see #setHovered
8309     */
8310    public void onHoverChanged(boolean hovered) {
8311    }
8312
8313    /**
8314     * Implement this method to handle touch screen motion events.
8315     *
8316     * @param event The motion event.
8317     * @return True if the event was handled, false otherwise.
8318     */
8319    public boolean onTouchEvent(MotionEvent event) {
8320        final int viewFlags = mViewFlags;
8321
8322        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8323            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8324                setPressed(false);
8325            }
8326            // A disabled view that is clickable still consumes the touch
8327            // events, it just doesn't respond to them.
8328            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8329                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8330        }
8331
8332        if (mTouchDelegate != null) {
8333            if (mTouchDelegate.onTouchEvent(event)) {
8334                return true;
8335            }
8336        }
8337
8338        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8339                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8340            switch (event.getAction()) {
8341                case MotionEvent.ACTION_UP:
8342                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8343                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8344                        // take focus if we don't have it already and we should in
8345                        // touch mode.
8346                        boolean focusTaken = false;
8347                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8348                            focusTaken = requestFocus();
8349                        }
8350
8351                        if (prepressed) {
8352                            // The button is being released before we actually
8353                            // showed it as pressed.  Make it show the pressed
8354                            // state now (before scheduling the click) to ensure
8355                            // the user sees it.
8356                            setPressed(true);
8357                       }
8358
8359                        if (!mHasPerformedLongPress) {
8360                            // This is a tap, so remove the longpress check
8361                            removeLongPressCallback();
8362
8363                            // Only perform take click actions if we were in the pressed state
8364                            if (!focusTaken) {
8365                                // Use a Runnable and post this rather than calling
8366                                // performClick directly. This lets other visual state
8367                                // of the view update before click actions start.
8368                                if (mPerformClick == null) {
8369                                    mPerformClick = new PerformClick();
8370                                }
8371                                if (!post(mPerformClick)) {
8372                                    performClick();
8373                                }
8374                            }
8375                        }
8376
8377                        if (mUnsetPressedState == null) {
8378                            mUnsetPressedState = new UnsetPressedState();
8379                        }
8380
8381                        if (prepressed) {
8382                            postDelayed(mUnsetPressedState,
8383                                    ViewConfiguration.getPressedStateDuration());
8384                        } else if (!post(mUnsetPressedState)) {
8385                            // If the post failed, unpress right now
8386                            mUnsetPressedState.run();
8387                        }
8388                        removeTapCallback();
8389                    }
8390                    break;
8391
8392                case MotionEvent.ACTION_DOWN:
8393                    mHasPerformedLongPress = false;
8394
8395                    if (performButtonActionOnTouchDown(event)) {
8396                        break;
8397                    }
8398
8399                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8400                    boolean isInScrollingContainer = isInScrollingContainer();
8401
8402                    // For views inside a scrolling container, delay the pressed feedback for
8403                    // a short period in case this is a scroll.
8404                    if (isInScrollingContainer) {
8405                        mPrivateFlags |= PFLAG_PREPRESSED;
8406                        if (mPendingCheckForTap == null) {
8407                            mPendingCheckForTap = new CheckForTap();
8408                        }
8409                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8410                    } else {
8411                        // Not inside a scrolling container, so show the feedback right away
8412                        setPressed(true);
8413                        checkForLongClick(0);
8414                    }
8415                    break;
8416
8417                case MotionEvent.ACTION_CANCEL:
8418                    setPressed(false);
8419                    removeTapCallback();
8420                    removeLongPressCallback();
8421                    break;
8422
8423                case MotionEvent.ACTION_MOVE:
8424                    final int x = (int) event.getX();
8425                    final int y = (int) event.getY();
8426
8427                    // Be lenient about moving outside of buttons
8428                    if (!pointInView(x, y, mTouchSlop)) {
8429                        // Outside button
8430                        removeTapCallback();
8431                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8432                            // Remove any future long press/tap checks
8433                            removeLongPressCallback();
8434
8435                            setPressed(false);
8436                        }
8437                    }
8438                    break;
8439            }
8440            return true;
8441        }
8442
8443        return false;
8444    }
8445
8446    /**
8447     * @hide
8448     */
8449    public boolean isInScrollingContainer() {
8450        ViewParent p = getParent();
8451        while (p != null && p instanceof ViewGroup) {
8452            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8453                return true;
8454            }
8455            p = p.getParent();
8456        }
8457        return false;
8458    }
8459
8460    /**
8461     * Remove the longpress detection timer.
8462     */
8463    private void removeLongPressCallback() {
8464        if (mPendingCheckForLongPress != null) {
8465          removeCallbacks(mPendingCheckForLongPress);
8466        }
8467    }
8468
8469    /**
8470     * Remove the pending click action
8471     */
8472    private void removePerformClickCallback() {
8473        if (mPerformClick != null) {
8474            removeCallbacks(mPerformClick);
8475        }
8476    }
8477
8478    /**
8479     * Remove the prepress detection timer.
8480     */
8481    private void removeUnsetPressCallback() {
8482        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8483            setPressed(false);
8484            removeCallbacks(mUnsetPressedState);
8485        }
8486    }
8487
8488    /**
8489     * Remove the tap detection timer.
8490     */
8491    private void removeTapCallback() {
8492        if (mPendingCheckForTap != null) {
8493            mPrivateFlags &= ~PFLAG_PREPRESSED;
8494            removeCallbacks(mPendingCheckForTap);
8495        }
8496    }
8497
8498    /**
8499     * Cancels a pending long press.  Your subclass can use this if you
8500     * want the context menu to come up if the user presses and holds
8501     * at the same place, but you don't want it to come up if they press
8502     * and then move around enough to cause scrolling.
8503     */
8504    public void cancelLongPress() {
8505        removeLongPressCallback();
8506
8507        /*
8508         * The prepressed state handled by the tap callback is a display
8509         * construct, but the tap callback will post a long press callback
8510         * less its own timeout. Remove it here.
8511         */
8512        removeTapCallback();
8513    }
8514
8515    /**
8516     * Remove the pending callback for sending a
8517     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8518     */
8519    private void removeSendViewScrolledAccessibilityEventCallback() {
8520        if (mSendViewScrolledAccessibilityEvent != null) {
8521            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8522            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8523        }
8524    }
8525
8526    /**
8527     * Sets the TouchDelegate for this View.
8528     */
8529    public void setTouchDelegate(TouchDelegate delegate) {
8530        mTouchDelegate = delegate;
8531    }
8532
8533    /**
8534     * Gets the TouchDelegate for this View.
8535     */
8536    public TouchDelegate getTouchDelegate() {
8537        return mTouchDelegate;
8538    }
8539
8540    /**
8541     * Set flags controlling behavior of this view.
8542     *
8543     * @param flags Constant indicating the value which should be set
8544     * @param mask Constant indicating the bit range that should be changed
8545     */
8546    void setFlags(int flags, int mask) {
8547        int old = mViewFlags;
8548        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8549
8550        int changed = mViewFlags ^ old;
8551        if (changed == 0) {
8552            return;
8553        }
8554        int privateFlags = mPrivateFlags;
8555
8556        /* Check if the FOCUSABLE bit has changed */
8557        if (((changed & FOCUSABLE_MASK) != 0) &&
8558                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8559            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8560                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8561                /* Give up focus if we are no longer focusable */
8562                clearFocus();
8563            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8564                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8565                /*
8566                 * Tell the view system that we are now available to take focus
8567                 * if no one else already has it.
8568                 */
8569                if (mParent != null) mParent.focusableViewAvailable(this);
8570            }
8571            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8572                notifyAccessibilityStateChanged();
8573            }
8574        }
8575
8576        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8577            if ((changed & VISIBILITY_MASK) != 0) {
8578                /*
8579                 * If this view is becoming visible, invalidate it in case it changed while
8580                 * it was not visible. Marking it drawn ensures that the invalidation will
8581                 * go through.
8582                 */
8583                mPrivateFlags |= PFLAG_DRAWN;
8584                invalidate(true);
8585
8586                needGlobalAttributesUpdate(true);
8587
8588                // a view becoming visible is worth notifying the parent
8589                // about in case nothing has focus.  even if this specific view
8590                // isn't focusable, it may contain something that is, so let
8591                // the root view try to give this focus if nothing else does.
8592                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8593                    mParent.focusableViewAvailable(this);
8594                }
8595            }
8596        }
8597
8598        /* Check if the GONE bit has changed */
8599        if ((changed & GONE) != 0) {
8600            needGlobalAttributesUpdate(false);
8601            requestLayout();
8602
8603            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8604                if (hasFocus()) clearFocus();
8605                clearAccessibilityFocus();
8606                destroyDrawingCache();
8607                if (mParent instanceof View) {
8608                    // GONE views noop invalidation, so invalidate the parent
8609                    ((View) mParent).invalidate(true);
8610                }
8611                // Mark the view drawn to ensure that it gets invalidated properly the next
8612                // time it is visible and gets invalidated
8613                mPrivateFlags |= PFLAG_DRAWN;
8614            }
8615            if (mAttachInfo != null) {
8616                mAttachInfo.mViewVisibilityChanged = true;
8617            }
8618        }
8619
8620        /* Check if the VISIBLE bit has changed */
8621        if ((changed & INVISIBLE) != 0) {
8622            needGlobalAttributesUpdate(false);
8623            /*
8624             * If this view is becoming invisible, set the DRAWN flag so that
8625             * the next invalidate() will not be skipped.
8626             */
8627            mPrivateFlags |= PFLAG_DRAWN;
8628
8629            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8630                // root view becoming invisible shouldn't clear focus and accessibility focus
8631                if (getRootView() != this) {
8632                    clearFocus();
8633                    clearAccessibilityFocus();
8634                }
8635            }
8636            if (mAttachInfo != null) {
8637                mAttachInfo.mViewVisibilityChanged = true;
8638            }
8639        }
8640
8641        if ((changed & VISIBILITY_MASK) != 0) {
8642            if (mParent instanceof ViewGroup) {
8643                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8644                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8645                ((View) mParent).invalidate(true);
8646            } else if (mParent != null) {
8647                mParent.invalidateChild(this, null);
8648            }
8649            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8650        }
8651
8652        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8653            destroyDrawingCache();
8654        }
8655
8656        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8657            destroyDrawingCache();
8658            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8659            invalidateParentCaches();
8660        }
8661
8662        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8663            destroyDrawingCache();
8664            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8665        }
8666
8667        if ((changed & DRAW_MASK) != 0) {
8668            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8669                if (mBackground != null) {
8670                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8671                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8672                } else {
8673                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8674                }
8675            } else {
8676                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8677            }
8678            requestLayout();
8679            invalidate(true);
8680        }
8681
8682        if ((changed & KEEP_SCREEN_ON) != 0) {
8683            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8684                mParent.recomputeViewAttributes(this);
8685            }
8686        }
8687
8688        if (AccessibilityManager.getInstance(mContext).isEnabled()
8689                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8690                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8691            notifyAccessibilityStateChanged();
8692        }
8693    }
8694
8695    /**
8696     * Change the view's z order in the tree, so it's on top of other sibling
8697     * views
8698     */
8699    public void bringToFront() {
8700        if (mParent != null) {
8701            mParent.bringChildToFront(this);
8702        }
8703    }
8704
8705    /**
8706     * This is called in response to an internal scroll in this view (i.e., the
8707     * view scrolled its own contents). This is typically as a result of
8708     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8709     * called.
8710     *
8711     * @param l Current horizontal scroll origin.
8712     * @param t Current vertical scroll origin.
8713     * @param oldl Previous horizontal scroll origin.
8714     * @param oldt Previous vertical scroll origin.
8715     */
8716    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8717        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8718            postSendViewScrolledAccessibilityEventCallback();
8719        }
8720
8721        mBackgroundSizeChanged = true;
8722
8723        final AttachInfo ai = mAttachInfo;
8724        if (ai != null) {
8725            ai.mViewScrollChanged = true;
8726        }
8727    }
8728
8729    /**
8730     * Interface definition for a callback to be invoked when the layout bounds of a view
8731     * changes due to layout processing.
8732     */
8733    public interface OnLayoutChangeListener {
8734        /**
8735         * Called when the focus state of a view has changed.
8736         *
8737         * @param v The view whose state has changed.
8738         * @param left The new value of the view's left property.
8739         * @param top The new value of the view's top property.
8740         * @param right The new value of the view's right property.
8741         * @param bottom The new value of the view's bottom property.
8742         * @param oldLeft The previous value of the view's left property.
8743         * @param oldTop The previous value of the view's top property.
8744         * @param oldRight The previous value of the view's right property.
8745         * @param oldBottom The previous value of the view's bottom property.
8746         */
8747        void onLayoutChange(View v, int left, int top, int right, int bottom,
8748            int oldLeft, int oldTop, int oldRight, int oldBottom);
8749    }
8750
8751    /**
8752     * This is called during layout when the size of this view has changed. If
8753     * you were just added to the view hierarchy, you're called with the old
8754     * values of 0.
8755     *
8756     * @param w Current width of this view.
8757     * @param h Current height of this view.
8758     * @param oldw Old width of this view.
8759     * @param oldh Old height of this view.
8760     */
8761    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8762    }
8763
8764    /**
8765     * Called by draw to draw the child views. This may be overridden
8766     * by derived classes to gain control just before its children are drawn
8767     * (but after its own view has been drawn).
8768     * @param canvas the canvas on which to draw the view
8769     */
8770    protected void dispatchDraw(Canvas canvas) {
8771
8772    }
8773
8774    /**
8775     * Gets the parent of this view. Note that the parent is a
8776     * ViewParent and not necessarily a View.
8777     *
8778     * @return Parent of this view.
8779     */
8780    public final ViewParent getParent() {
8781        return mParent;
8782    }
8783
8784    /**
8785     * Set the horizontal scrolled position of your view. This will cause a call to
8786     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8787     * invalidated.
8788     * @param value the x position to scroll to
8789     */
8790    public void setScrollX(int value) {
8791        scrollTo(value, mScrollY);
8792    }
8793
8794    /**
8795     * Set the vertical scrolled position of your view. This will cause a call to
8796     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8797     * invalidated.
8798     * @param value the y position to scroll to
8799     */
8800    public void setScrollY(int value) {
8801        scrollTo(mScrollX, value);
8802    }
8803
8804    /**
8805     * Return the scrolled left position of this view. This is the left edge of
8806     * the displayed part of your view. You do not need to draw any pixels
8807     * farther left, since those are outside of the frame of your view on
8808     * screen.
8809     *
8810     * @return The left edge of the displayed part of your view, in pixels.
8811     */
8812    public final int getScrollX() {
8813        return mScrollX;
8814    }
8815
8816    /**
8817     * Return the scrolled top position of this view. This is the top edge of
8818     * the displayed part of your view. You do not need to draw any pixels above
8819     * it, since those are outside of the frame of your view on screen.
8820     *
8821     * @return The top edge of the displayed part of your view, in pixels.
8822     */
8823    public final int getScrollY() {
8824        return mScrollY;
8825    }
8826
8827    /**
8828     * Return the width of the your view.
8829     *
8830     * @return The width of your view, in pixels.
8831     */
8832    @ViewDebug.ExportedProperty(category = "layout")
8833    public final int getWidth() {
8834        return mRight - mLeft;
8835    }
8836
8837    /**
8838     * Return the height of your view.
8839     *
8840     * @return The height of your view, in pixels.
8841     */
8842    @ViewDebug.ExportedProperty(category = "layout")
8843    public final int getHeight() {
8844        return mBottom - mTop;
8845    }
8846
8847    /**
8848     * Return the visible drawing bounds of your view. Fills in the output
8849     * rectangle with the values from getScrollX(), getScrollY(),
8850     * getWidth(), and getHeight(). These bounds do not account for any
8851     * transformation properties currently set on the view, such as
8852     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8853     *
8854     * @param outRect The (scrolled) drawing bounds of the view.
8855     */
8856    public void getDrawingRect(Rect outRect) {
8857        outRect.left = mScrollX;
8858        outRect.top = mScrollY;
8859        outRect.right = mScrollX + (mRight - mLeft);
8860        outRect.bottom = mScrollY + (mBottom - mTop);
8861    }
8862
8863    /**
8864     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8865     * raw width component (that is the result is masked by
8866     * {@link #MEASURED_SIZE_MASK}).
8867     *
8868     * @return The raw measured width of this view.
8869     */
8870    public final int getMeasuredWidth() {
8871        return mMeasuredWidth & MEASURED_SIZE_MASK;
8872    }
8873
8874    /**
8875     * Return the full width measurement information for this view as computed
8876     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8877     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8878     * This should be used during measurement and layout calculations only. Use
8879     * {@link #getWidth()} to see how wide a view is after layout.
8880     *
8881     * @return The measured width of this view as a bit mask.
8882     */
8883    public final int getMeasuredWidthAndState() {
8884        return mMeasuredWidth;
8885    }
8886
8887    /**
8888     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8889     * raw width component (that is the result is masked by
8890     * {@link #MEASURED_SIZE_MASK}).
8891     *
8892     * @return The raw measured height of this view.
8893     */
8894    public final int getMeasuredHeight() {
8895        return mMeasuredHeight & MEASURED_SIZE_MASK;
8896    }
8897
8898    /**
8899     * Return the full height measurement information for this view as computed
8900     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8901     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8902     * This should be used during measurement and layout calculations only. Use
8903     * {@link #getHeight()} to see how wide a view is after layout.
8904     *
8905     * @return The measured width of this view as a bit mask.
8906     */
8907    public final int getMeasuredHeightAndState() {
8908        return mMeasuredHeight;
8909    }
8910
8911    /**
8912     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8913     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8914     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8915     * and the height component is at the shifted bits
8916     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8917     */
8918    public final int getMeasuredState() {
8919        return (mMeasuredWidth&MEASURED_STATE_MASK)
8920                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8921                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8922    }
8923
8924    /**
8925     * The transform matrix of this view, which is calculated based on the current
8926     * roation, scale, and pivot properties.
8927     *
8928     * @see #getRotation()
8929     * @see #getScaleX()
8930     * @see #getScaleY()
8931     * @see #getPivotX()
8932     * @see #getPivotY()
8933     * @return The current transform matrix for the view
8934     */
8935    public Matrix getMatrix() {
8936        if (mTransformationInfo != null) {
8937            updateMatrix();
8938            return mTransformationInfo.mMatrix;
8939        }
8940        return Matrix.IDENTITY_MATRIX;
8941    }
8942
8943    /**
8944     * Utility function to determine if the value is far enough away from zero to be
8945     * considered non-zero.
8946     * @param value A floating point value to check for zero-ness
8947     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8948     */
8949    private static boolean nonzero(float value) {
8950        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8951    }
8952
8953    /**
8954     * Returns true if the transform matrix is the identity matrix.
8955     * Recomputes the matrix if necessary.
8956     *
8957     * @return True if the transform matrix is the identity matrix, false otherwise.
8958     */
8959    final boolean hasIdentityMatrix() {
8960        if (mTransformationInfo != null) {
8961            updateMatrix();
8962            return mTransformationInfo.mMatrixIsIdentity;
8963        }
8964        return true;
8965    }
8966
8967    void ensureTransformationInfo() {
8968        if (mTransformationInfo == null) {
8969            mTransformationInfo = new TransformationInfo();
8970        }
8971    }
8972
8973    /**
8974     * Recomputes the transform matrix if necessary.
8975     */
8976    private void updateMatrix() {
8977        final TransformationInfo info = mTransformationInfo;
8978        if (info == null) {
8979            return;
8980        }
8981        if (info.mMatrixDirty) {
8982            // transform-related properties have changed since the last time someone
8983            // asked for the matrix; recalculate it with the current values
8984
8985            // Figure out if we need to update the pivot point
8986            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8987                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8988                    info.mPrevWidth = mRight - mLeft;
8989                    info.mPrevHeight = mBottom - mTop;
8990                    info.mPivotX = info.mPrevWidth / 2f;
8991                    info.mPivotY = info.mPrevHeight / 2f;
8992                }
8993            }
8994            info.mMatrix.reset();
8995            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8996                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8997                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8998                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8999            } else {
9000                if (info.mCamera == null) {
9001                    info.mCamera = new Camera();
9002                    info.matrix3D = new Matrix();
9003                }
9004                info.mCamera.save();
9005                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9006                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9007                info.mCamera.getMatrix(info.matrix3D);
9008                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9009                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9010                        info.mPivotY + info.mTranslationY);
9011                info.mMatrix.postConcat(info.matrix3D);
9012                info.mCamera.restore();
9013            }
9014            info.mMatrixDirty = false;
9015            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9016            info.mInverseMatrixDirty = true;
9017        }
9018    }
9019
9020   /**
9021     * Utility method to retrieve the inverse of the current mMatrix property.
9022     * We cache the matrix to avoid recalculating it when transform properties
9023     * have not changed.
9024     *
9025     * @return The inverse of the current matrix of this view.
9026     */
9027    final Matrix getInverseMatrix() {
9028        final TransformationInfo info = mTransformationInfo;
9029        if (info != null) {
9030            updateMatrix();
9031            if (info.mInverseMatrixDirty) {
9032                if (info.mInverseMatrix == null) {
9033                    info.mInverseMatrix = new Matrix();
9034                }
9035                info.mMatrix.invert(info.mInverseMatrix);
9036                info.mInverseMatrixDirty = false;
9037            }
9038            return info.mInverseMatrix;
9039        }
9040        return Matrix.IDENTITY_MATRIX;
9041    }
9042
9043    /**
9044     * Gets the distance along the Z axis from the camera to this view.
9045     *
9046     * @see #setCameraDistance(float)
9047     *
9048     * @return The distance along the Z axis.
9049     */
9050    public float getCameraDistance() {
9051        ensureTransformationInfo();
9052        final float dpi = mResources.getDisplayMetrics().densityDpi;
9053        final TransformationInfo info = mTransformationInfo;
9054        if (info.mCamera == null) {
9055            info.mCamera = new Camera();
9056            info.matrix3D = new Matrix();
9057        }
9058        return -(info.mCamera.getLocationZ() * dpi);
9059    }
9060
9061    /**
9062     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9063     * views are drawn) from the camera to this view. The camera's distance
9064     * affects 3D transformations, for instance rotations around the X and Y
9065     * axis. If the rotationX or rotationY properties are changed and this view is
9066     * large (more than half the size of the screen), it is recommended to always
9067     * use a camera distance that's greater than the height (X axis rotation) or
9068     * the width (Y axis rotation) of this view.</p>
9069     *
9070     * <p>The distance of the camera from the view plane can have an affect on the
9071     * perspective distortion of the view when it is rotated around the x or y axis.
9072     * For example, a large distance will result in a large viewing angle, and there
9073     * will not be much perspective distortion of the view as it rotates. A short
9074     * distance may cause much more perspective distortion upon rotation, and can
9075     * also result in some drawing artifacts if the rotated view ends up partially
9076     * behind the camera (which is why the recommendation is to use a distance at
9077     * least as far as the size of the view, if the view is to be rotated.)</p>
9078     *
9079     * <p>The distance is expressed in "depth pixels." The default distance depends
9080     * on the screen density. For instance, on a medium density display, the
9081     * default distance is 1280. On a high density display, the default distance
9082     * is 1920.</p>
9083     *
9084     * <p>If you want to specify a distance that leads to visually consistent
9085     * results across various densities, use the following formula:</p>
9086     * <pre>
9087     * float scale = context.getResources().getDisplayMetrics().density;
9088     * view.setCameraDistance(distance * scale);
9089     * </pre>
9090     *
9091     * <p>The density scale factor of a high density display is 1.5,
9092     * and 1920 = 1280 * 1.5.</p>
9093     *
9094     * @param distance The distance in "depth pixels", if negative the opposite
9095     *        value is used
9096     *
9097     * @see #setRotationX(float)
9098     * @see #setRotationY(float)
9099     */
9100    public void setCameraDistance(float distance) {
9101        invalidateViewProperty(true, false);
9102
9103        ensureTransformationInfo();
9104        final float dpi = mResources.getDisplayMetrics().densityDpi;
9105        final TransformationInfo info = mTransformationInfo;
9106        if (info.mCamera == null) {
9107            info.mCamera = new Camera();
9108            info.matrix3D = new Matrix();
9109        }
9110
9111        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9112        info.mMatrixDirty = true;
9113
9114        invalidateViewProperty(false, false);
9115        if (mDisplayList != null) {
9116            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9117        }
9118        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9119            // View was rejected last time it was drawn by its parent; this may have changed
9120            invalidateParentIfNeeded();
9121        }
9122    }
9123
9124    /**
9125     * The degrees that the view is rotated around the pivot point.
9126     *
9127     * @see #setRotation(float)
9128     * @see #getPivotX()
9129     * @see #getPivotY()
9130     *
9131     * @return The degrees of rotation.
9132     */
9133    @ViewDebug.ExportedProperty(category = "drawing")
9134    public float getRotation() {
9135        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9136    }
9137
9138    /**
9139     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9140     * result in clockwise rotation.
9141     *
9142     * @param rotation The degrees of rotation.
9143     *
9144     * @see #getRotation()
9145     * @see #getPivotX()
9146     * @see #getPivotY()
9147     * @see #setRotationX(float)
9148     * @see #setRotationY(float)
9149     *
9150     * @attr ref android.R.styleable#View_rotation
9151     */
9152    public void setRotation(float rotation) {
9153        ensureTransformationInfo();
9154        final TransformationInfo info = mTransformationInfo;
9155        if (info.mRotation != rotation) {
9156            // Double-invalidation is necessary to capture view's old and new areas
9157            invalidateViewProperty(true, false);
9158            info.mRotation = rotation;
9159            info.mMatrixDirty = true;
9160            invalidateViewProperty(false, true);
9161            if (mDisplayList != null) {
9162                mDisplayList.setRotation(rotation);
9163            }
9164            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9165                // View was rejected last time it was drawn by its parent; this may have changed
9166                invalidateParentIfNeeded();
9167            }
9168        }
9169    }
9170
9171    /**
9172     * The degrees that the view is rotated around the vertical axis through the pivot point.
9173     *
9174     * @see #getPivotX()
9175     * @see #getPivotY()
9176     * @see #setRotationY(float)
9177     *
9178     * @return The degrees of Y rotation.
9179     */
9180    @ViewDebug.ExportedProperty(category = "drawing")
9181    public float getRotationY() {
9182        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9183    }
9184
9185    /**
9186     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9187     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9188     * down the y axis.
9189     *
9190     * When rotating large views, it is recommended to adjust the camera distance
9191     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9192     *
9193     * @param rotationY The degrees of Y rotation.
9194     *
9195     * @see #getRotationY()
9196     * @see #getPivotX()
9197     * @see #getPivotY()
9198     * @see #setRotation(float)
9199     * @see #setRotationX(float)
9200     * @see #setCameraDistance(float)
9201     *
9202     * @attr ref android.R.styleable#View_rotationY
9203     */
9204    public void setRotationY(float rotationY) {
9205        ensureTransformationInfo();
9206        final TransformationInfo info = mTransformationInfo;
9207        if (info.mRotationY != rotationY) {
9208            invalidateViewProperty(true, false);
9209            info.mRotationY = rotationY;
9210            info.mMatrixDirty = true;
9211            invalidateViewProperty(false, true);
9212            if (mDisplayList != null) {
9213                mDisplayList.setRotationY(rotationY);
9214            }
9215            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9216                // View was rejected last time it was drawn by its parent; this may have changed
9217                invalidateParentIfNeeded();
9218            }
9219        }
9220    }
9221
9222    /**
9223     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9224     *
9225     * @see #getPivotX()
9226     * @see #getPivotY()
9227     * @see #setRotationX(float)
9228     *
9229     * @return The degrees of X rotation.
9230     */
9231    @ViewDebug.ExportedProperty(category = "drawing")
9232    public float getRotationX() {
9233        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9234    }
9235
9236    /**
9237     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9238     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9239     * x axis.
9240     *
9241     * When rotating large views, it is recommended to adjust the camera distance
9242     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9243     *
9244     * @param rotationX The degrees of X rotation.
9245     *
9246     * @see #getRotationX()
9247     * @see #getPivotX()
9248     * @see #getPivotY()
9249     * @see #setRotation(float)
9250     * @see #setRotationY(float)
9251     * @see #setCameraDistance(float)
9252     *
9253     * @attr ref android.R.styleable#View_rotationX
9254     */
9255    public void setRotationX(float rotationX) {
9256        ensureTransformationInfo();
9257        final TransformationInfo info = mTransformationInfo;
9258        if (info.mRotationX != rotationX) {
9259            invalidateViewProperty(true, false);
9260            info.mRotationX = rotationX;
9261            info.mMatrixDirty = true;
9262            invalidateViewProperty(false, true);
9263            if (mDisplayList != null) {
9264                mDisplayList.setRotationX(rotationX);
9265            }
9266            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9267                // View was rejected last time it was drawn by its parent; this may have changed
9268                invalidateParentIfNeeded();
9269            }
9270        }
9271    }
9272
9273    /**
9274     * The amount that the view is scaled in x around the pivot point, as a proportion of
9275     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9276     *
9277     * <p>By default, this is 1.0f.
9278     *
9279     * @see #getPivotX()
9280     * @see #getPivotY()
9281     * @return The scaling factor.
9282     */
9283    @ViewDebug.ExportedProperty(category = "drawing")
9284    public float getScaleX() {
9285        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9286    }
9287
9288    /**
9289     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9290     * the view's unscaled width. A value of 1 means that no scaling is applied.
9291     *
9292     * @param scaleX The scaling factor.
9293     * @see #getPivotX()
9294     * @see #getPivotY()
9295     *
9296     * @attr ref android.R.styleable#View_scaleX
9297     */
9298    public void setScaleX(float scaleX) {
9299        ensureTransformationInfo();
9300        final TransformationInfo info = mTransformationInfo;
9301        if (info.mScaleX != scaleX) {
9302            invalidateViewProperty(true, false);
9303            info.mScaleX = scaleX;
9304            info.mMatrixDirty = true;
9305            invalidateViewProperty(false, true);
9306            if (mDisplayList != null) {
9307                mDisplayList.setScaleX(scaleX);
9308            }
9309            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9310                // View was rejected last time it was drawn by its parent; this may have changed
9311                invalidateParentIfNeeded();
9312            }
9313        }
9314    }
9315
9316    /**
9317     * The amount that the view is scaled in y around the pivot point, as a proportion of
9318     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9319     *
9320     * <p>By default, this is 1.0f.
9321     *
9322     * @see #getPivotX()
9323     * @see #getPivotY()
9324     * @return The scaling factor.
9325     */
9326    @ViewDebug.ExportedProperty(category = "drawing")
9327    public float getScaleY() {
9328        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9329    }
9330
9331    /**
9332     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9333     * the view's unscaled width. A value of 1 means that no scaling is applied.
9334     *
9335     * @param scaleY The scaling factor.
9336     * @see #getPivotX()
9337     * @see #getPivotY()
9338     *
9339     * @attr ref android.R.styleable#View_scaleY
9340     */
9341    public void setScaleY(float scaleY) {
9342        ensureTransformationInfo();
9343        final TransformationInfo info = mTransformationInfo;
9344        if (info.mScaleY != scaleY) {
9345            invalidateViewProperty(true, false);
9346            info.mScaleY = scaleY;
9347            info.mMatrixDirty = true;
9348            invalidateViewProperty(false, true);
9349            if (mDisplayList != null) {
9350                mDisplayList.setScaleY(scaleY);
9351            }
9352            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9353                // View was rejected last time it was drawn by its parent; this may have changed
9354                invalidateParentIfNeeded();
9355            }
9356        }
9357    }
9358
9359    /**
9360     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9361     * and {@link #setScaleX(float) scaled}.
9362     *
9363     * @see #getRotation()
9364     * @see #getScaleX()
9365     * @see #getScaleY()
9366     * @see #getPivotY()
9367     * @return The x location of the pivot point.
9368     *
9369     * @attr ref android.R.styleable#View_transformPivotX
9370     */
9371    @ViewDebug.ExportedProperty(category = "drawing")
9372    public float getPivotX() {
9373        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9374    }
9375
9376    /**
9377     * Sets the x location of the point around which the view is
9378     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9379     * By default, the pivot point is centered on the object.
9380     * Setting this property disables this behavior and causes the view to use only the
9381     * explicitly set pivotX and pivotY values.
9382     *
9383     * @param pivotX The x location of the pivot point.
9384     * @see #getRotation()
9385     * @see #getScaleX()
9386     * @see #getScaleY()
9387     * @see #getPivotY()
9388     *
9389     * @attr ref android.R.styleable#View_transformPivotX
9390     */
9391    public void setPivotX(float pivotX) {
9392        ensureTransformationInfo();
9393        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9394        final TransformationInfo info = mTransformationInfo;
9395        if (info.mPivotX != pivotX) {
9396            invalidateViewProperty(true, false);
9397            info.mPivotX = pivotX;
9398            info.mMatrixDirty = true;
9399            invalidateViewProperty(false, true);
9400            if (mDisplayList != null) {
9401                mDisplayList.setPivotX(pivotX);
9402            }
9403            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9404                // View was rejected last time it was drawn by its parent; this may have changed
9405                invalidateParentIfNeeded();
9406            }
9407        }
9408    }
9409
9410    /**
9411     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9412     * and {@link #setScaleY(float) scaled}.
9413     *
9414     * @see #getRotation()
9415     * @see #getScaleX()
9416     * @see #getScaleY()
9417     * @see #getPivotY()
9418     * @return The y location of the pivot point.
9419     *
9420     * @attr ref android.R.styleable#View_transformPivotY
9421     */
9422    @ViewDebug.ExportedProperty(category = "drawing")
9423    public float getPivotY() {
9424        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9425    }
9426
9427    /**
9428     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9429     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9430     * Setting this property disables this behavior and causes the view to use only the
9431     * explicitly set pivotX and pivotY values.
9432     *
9433     * @param pivotY The y location of the pivot point.
9434     * @see #getRotation()
9435     * @see #getScaleX()
9436     * @see #getScaleY()
9437     * @see #getPivotY()
9438     *
9439     * @attr ref android.R.styleable#View_transformPivotY
9440     */
9441    public void setPivotY(float pivotY) {
9442        ensureTransformationInfo();
9443        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9444        final TransformationInfo info = mTransformationInfo;
9445        if (info.mPivotY != pivotY) {
9446            invalidateViewProperty(true, false);
9447            info.mPivotY = pivotY;
9448            info.mMatrixDirty = true;
9449            invalidateViewProperty(false, true);
9450            if (mDisplayList != null) {
9451                mDisplayList.setPivotY(pivotY);
9452            }
9453            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9454                // View was rejected last time it was drawn by its parent; this may have changed
9455                invalidateParentIfNeeded();
9456            }
9457        }
9458    }
9459
9460    /**
9461     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9462     * completely transparent and 1 means the view is completely opaque.
9463     *
9464     * <p>By default this is 1.0f.
9465     * @return The opacity of the view.
9466     */
9467    @ViewDebug.ExportedProperty(category = "drawing")
9468    public float getAlpha() {
9469        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9470    }
9471
9472    /**
9473     * Returns whether this View has content which overlaps. This function, intended to be
9474     * overridden by specific View types, is an optimization when alpha is set on a view. If
9475     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9476     * and then composited it into place, which can be expensive. If the view has no overlapping
9477     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9478     * An example of overlapping rendering is a TextView with a background image, such as a
9479     * Button. An example of non-overlapping rendering is a TextView with no background, or
9480     * an ImageView with only the foreground image. The default implementation returns true;
9481     * subclasses should override if they have cases which can be optimized.
9482     *
9483     * @return true if the content in this view might overlap, false otherwise.
9484     */
9485    public boolean hasOverlappingRendering() {
9486        return true;
9487    }
9488
9489    /**
9490     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9491     * completely transparent and 1 means the view is completely opaque.</p>
9492     *
9493     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9494     * performance implications, especially for large views. It is best to use the alpha property
9495     * sparingly and transiently, as in the case of fading animations.</p>
9496     *
9497     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9498     * strongly recommended for performance reasons to either override
9499     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9500     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9501     *
9502     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9503     * responsible for applying the opacity itself.</p>
9504     *
9505     * <p>Note that if the view is backed by a
9506     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9507     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9508     * 1.0 will supercede the alpha of the layer paint.</p>
9509     *
9510     * @param alpha The opacity of the view.
9511     *
9512     * @see #hasOverlappingRendering()
9513     * @see #setLayerType(int, android.graphics.Paint)
9514     *
9515     * @attr ref android.R.styleable#View_alpha
9516     */
9517    public void setAlpha(float alpha) {
9518        ensureTransformationInfo();
9519        if (mTransformationInfo.mAlpha != alpha) {
9520            mTransformationInfo.mAlpha = alpha;
9521            if (onSetAlpha((int) (alpha * 255))) {
9522                mPrivateFlags |= PFLAG_ALPHA_SET;
9523                // subclass is handling alpha - don't optimize rendering cache invalidation
9524                invalidateParentCaches();
9525                invalidate(true);
9526            } else {
9527                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9528                invalidateViewProperty(true, false);
9529                if (mDisplayList != null) {
9530                    mDisplayList.setAlpha(alpha);
9531                }
9532            }
9533        }
9534    }
9535
9536    /**
9537     * Faster version of setAlpha() which performs the same steps except there are
9538     * no calls to invalidate(). The caller of this function should perform proper invalidation
9539     * on the parent and this object. The return value indicates whether the subclass handles
9540     * alpha (the return value for onSetAlpha()).
9541     *
9542     * @param alpha The new value for the alpha property
9543     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9544     *         the new value for the alpha property is different from the old value
9545     */
9546    boolean setAlphaNoInvalidation(float alpha) {
9547        ensureTransformationInfo();
9548        if (mTransformationInfo.mAlpha != alpha) {
9549            mTransformationInfo.mAlpha = alpha;
9550            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9551            if (subclassHandlesAlpha) {
9552                mPrivateFlags |= PFLAG_ALPHA_SET;
9553                return true;
9554            } else {
9555                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9556                if (mDisplayList != null) {
9557                    mDisplayList.setAlpha(alpha);
9558                }
9559            }
9560        }
9561        return false;
9562    }
9563
9564    /**
9565     * Top position of this view relative to its parent.
9566     *
9567     * @return The top of this view, in pixels.
9568     */
9569    @ViewDebug.CapturedViewProperty
9570    public final int getTop() {
9571        return mTop;
9572    }
9573
9574    /**
9575     * Sets the top position of this view relative to its parent. This method is meant to be called
9576     * by the layout system and should not generally be called otherwise, because the property
9577     * may be changed at any time by the layout.
9578     *
9579     * @param top The top of this view, in pixels.
9580     */
9581    public final void setTop(int top) {
9582        if (top != mTop) {
9583            updateMatrix();
9584            final boolean matrixIsIdentity = mTransformationInfo == null
9585                    || mTransformationInfo.mMatrixIsIdentity;
9586            if (matrixIsIdentity) {
9587                if (mAttachInfo != null) {
9588                    int minTop;
9589                    int yLoc;
9590                    if (top < mTop) {
9591                        minTop = top;
9592                        yLoc = top - mTop;
9593                    } else {
9594                        minTop = mTop;
9595                        yLoc = 0;
9596                    }
9597                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9598                }
9599            } else {
9600                // Double-invalidation is necessary to capture view's old and new areas
9601                invalidate(true);
9602            }
9603
9604            int width = mRight - mLeft;
9605            int oldHeight = mBottom - mTop;
9606
9607            mTop = top;
9608            if (mDisplayList != null) {
9609                mDisplayList.setTop(mTop);
9610            }
9611
9612            sizeChange(width, mBottom - mTop, width, oldHeight);
9613
9614            if (!matrixIsIdentity) {
9615                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9616                    // A change in dimension means an auto-centered pivot point changes, too
9617                    mTransformationInfo.mMatrixDirty = true;
9618                }
9619                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9620                invalidate(true);
9621            }
9622            mBackgroundSizeChanged = true;
9623            invalidateParentIfNeeded();
9624            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9625                // View was rejected last time it was drawn by its parent; this may have changed
9626                invalidateParentIfNeeded();
9627            }
9628        }
9629    }
9630
9631    /**
9632     * Bottom position of this view relative to its parent.
9633     *
9634     * @return The bottom of this view, in pixels.
9635     */
9636    @ViewDebug.CapturedViewProperty
9637    public final int getBottom() {
9638        return mBottom;
9639    }
9640
9641    /**
9642     * True if this view has changed since the last time being drawn.
9643     *
9644     * @return The dirty state of this view.
9645     */
9646    public boolean isDirty() {
9647        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9648    }
9649
9650    /**
9651     * Sets the bottom position of this view relative to its parent. This method is meant to be
9652     * called by the layout system and should not generally be called otherwise, because the
9653     * property may be changed at any time by the layout.
9654     *
9655     * @param bottom The bottom of this view, in pixels.
9656     */
9657    public final void setBottom(int bottom) {
9658        if (bottom != mBottom) {
9659            updateMatrix();
9660            final boolean matrixIsIdentity = mTransformationInfo == null
9661                    || mTransformationInfo.mMatrixIsIdentity;
9662            if (matrixIsIdentity) {
9663                if (mAttachInfo != null) {
9664                    int maxBottom;
9665                    if (bottom < mBottom) {
9666                        maxBottom = mBottom;
9667                    } else {
9668                        maxBottom = bottom;
9669                    }
9670                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9671                }
9672            } else {
9673                // Double-invalidation is necessary to capture view's old and new areas
9674                invalidate(true);
9675            }
9676
9677            int width = mRight - mLeft;
9678            int oldHeight = mBottom - mTop;
9679
9680            mBottom = bottom;
9681            if (mDisplayList != null) {
9682                mDisplayList.setBottom(mBottom);
9683            }
9684
9685            sizeChange(width, mBottom - mTop, width, oldHeight);
9686
9687            if (!matrixIsIdentity) {
9688                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9689                    // A change in dimension means an auto-centered pivot point changes, too
9690                    mTransformationInfo.mMatrixDirty = true;
9691                }
9692                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9693                invalidate(true);
9694            }
9695            mBackgroundSizeChanged = true;
9696            invalidateParentIfNeeded();
9697            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9698                // View was rejected last time it was drawn by its parent; this may have changed
9699                invalidateParentIfNeeded();
9700            }
9701        }
9702    }
9703
9704    /**
9705     * Left position of this view relative to its parent.
9706     *
9707     * @return The left edge of this view, in pixels.
9708     */
9709    @ViewDebug.CapturedViewProperty
9710    public final int getLeft() {
9711        return mLeft;
9712    }
9713
9714    /**
9715     * Sets the left position of this view relative to its parent. This method is meant to be called
9716     * by the layout system and should not generally be called otherwise, because the property
9717     * may be changed at any time by the layout.
9718     *
9719     * @param left The bottom of this view, in pixels.
9720     */
9721    public final void setLeft(int left) {
9722        if (left != mLeft) {
9723            updateMatrix();
9724            final boolean matrixIsIdentity = mTransformationInfo == null
9725                    || mTransformationInfo.mMatrixIsIdentity;
9726            if (matrixIsIdentity) {
9727                if (mAttachInfo != null) {
9728                    int minLeft;
9729                    int xLoc;
9730                    if (left < mLeft) {
9731                        minLeft = left;
9732                        xLoc = left - mLeft;
9733                    } else {
9734                        minLeft = mLeft;
9735                        xLoc = 0;
9736                    }
9737                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9738                }
9739            } else {
9740                // Double-invalidation is necessary to capture view's old and new areas
9741                invalidate(true);
9742            }
9743
9744            int oldWidth = mRight - mLeft;
9745            int height = mBottom - mTop;
9746
9747            mLeft = left;
9748            if (mDisplayList != null) {
9749                mDisplayList.setLeft(left);
9750            }
9751
9752            sizeChange(mRight - mLeft, height, oldWidth, height);
9753
9754            if (!matrixIsIdentity) {
9755                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9756                    // A change in dimension means an auto-centered pivot point changes, too
9757                    mTransformationInfo.mMatrixDirty = true;
9758                }
9759                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9760                invalidate(true);
9761            }
9762            mBackgroundSizeChanged = true;
9763            invalidateParentIfNeeded();
9764            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9765                // View was rejected last time it was drawn by its parent; this may have changed
9766                invalidateParentIfNeeded();
9767            }
9768        }
9769    }
9770
9771    /**
9772     * Right position of this view relative to its parent.
9773     *
9774     * @return The right edge of this view, in pixels.
9775     */
9776    @ViewDebug.CapturedViewProperty
9777    public final int getRight() {
9778        return mRight;
9779    }
9780
9781    /**
9782     * Sets the right position of this view relative to its parent. This method is meant to be called
9783     * by the layout system and should not generally be called otherwise, because the property
9784     * may be changed at any time by the layout.
9785     *
9786     * @param right The bottom of this view, in pixels.
9787     */
9788    public final void setRight(int right) {
9789        if (right != mRight) {
9790            updateMatrix();
9791            final boolean matrixIsIdentity = mTransformationInfo == null
9792                    || mTransformationInfo.mMatrixIsIdentity;
9793            if (matrixIsIdentity) {
9794                if (mAttachInfo != null) {
9795                    int maxRight;
9796                    if (right < mRight) {
9797                        maxRight = mRight;
9798                    } else {
9799                        maxRight = right;
9800                    }
9801                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9802                }
9803            } else {
9804                // Double-invalidation is necessary to capture view's old and new areas
9805                invalidate(true);
9806            }
9807
9808            int oldWidth = mRight - mLeft;
9809            int height = mBottom - mTop;
9810
9811            mRight = right;
9812            if (mDisplayList != null) {
9813                mDisplayList.setRight(mRight);
9814            }
9815
9816            sizeChange(mRight - mLeft, height, oldWidth, height);
9817
9818            if (!matrixIsIdentity) {
9819                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9820                    // A change in dimension means an auto-centered pivot point changes, too
9821                    mTransformationInfo.mMatrixDirty = true;
9822                }
9823                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9824                invalidate(true);
9825            }
9826            mBackgroundSizeChanged = true;
9827            invalidateParentIfNeeded();
9828            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9829                // View was rejected last time it was drawn by its parent; this may have changed
9830                invalidateParentIfNeeded();
9831            }
9832        }
9833    }
9834
9835    /**
9836     * The visual x position of this view, in pixels. This is equivalent to the
9837     * {@link #setTranslationX(float) translationX} property plus the current
9838     * {@link #getLeft() left} property.
9839     *
9840     * @return The visual x position of this view, in pixels.
9841     */
9842    @ViewDebug.ExportedProperty(category = "drawing")
9843    public float getX() {
9844        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9845    }
9846
9847    /**
9848     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9849     * {@link #setTranslationX(float) translationX} property to be the difference between
9850     * the x value passed in and the current {@link #getLeft() left} property.
9851     *
9852     * @param x The visual x position of this view, in pixels.
9853     */
9854    public void setX(float x) {
9855        setTranslationX(x - mLeft);
9856    }
9857
9858    /**
9859     * The visual y position of this view, in pixels. This is equivalent to the
9860     * {@link #setTranslationY(float) translationY} property plus the current
9861     * {@link #getTop() top} property.
9862     *
9863     * @return The visual y position of this view, in pixels.
9864     */
9865    @ViewDebug.ExportedProperty(category = "drawing")
9866    public float getY() {
9867        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9868    }
9869
9870    /**
9871     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9872     * {@link #setTranslationY(float) translationY} property to be the difference between
9873     * the y value passed in and the current {@link #getTop() top} property.
9874     *
9875     * @param y The visual y position of this view, in pixels.
9876     */
9877    public void setY(float y) {
9878        setTranslationY(y - mTop);
9879    }
9880
9881
9882    /**
9883     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9884     * This position is post-layout, in addition to wherever the object's
9885     * layout placed it.
9886     *
9887     * @return The horizontal position of this view relative to its left position, in pixels.
9888     */
9889    @ViewDebug.ExportedProperty(category = "drawing")
9890    public float getTranslationX() {
9891        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9892    }
9893
9894    /**
9895     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9896     * This effectively positions the object post-layout, in addition to wherever the object's
9897     * layout placed it.
9898     *
9899     * @param translationX The horizontal position of this view relative to its left position,
9900     * in pixels.
9901     *
9902     * @attr ref android.R.styleable#View_translationX
9903     */
9904    public void setTranslationX(float translationX) {
9905        ensureTransformationInfo();
9906        final TransformationInfo info = mTransformationInfo;
9907        if (info.mTranslationX != translationX) {
9908            // Double-invalidation is necessary to capture view's old and new areas
9909            invalidateViewProperty(true, false);
9910            info.mTranslationX = translationX;
9911            info.mMatrixDirty = true;
9912            invalidateViewProperty(false, true);
9913            if (mDisplayList != null) {
9914                mDisplayList.setTranslationX(translationX);
9915            }
9916            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9917                // View was rejected last time it was drawn by its parent; this may have changed
9918                invalidateParentIfNeeded();
9919            }
9920        }
9921    }
9922
9923    /**
9924     * The horizontal location of this view relative to its {@link #getTop() top} position.
9925     * This position is post-layout, in addition to wherever the object's
9926     * layout placed it.
9927     *
9928     * @return The vertical position of this view relative to its top position,
9929     * in pixels.
9930     */
9931    @ViewDebug.ExportedProperty(category = "drawing")
9932    public float getTranslationY() {
9933        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9934    }
9935
9936    /**
9937     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9938     * This effectively positions the object post-layout, in addition to wherever the object's
9939     * layout placed it.
9940     *
9941     * @param translationY The vertical position of this view relative to its top position,
9942     * in pixels.
9943     *
9944     * @attr ref android.R.styleable#View_translationY
9945     */
9946    public void setTranslationY(float translationY) {
9947        ensureTransformationInfo();
9948        final TransformationInfo info = mTransformationInfo;
9949        if (info.mTranslationY != translationY) {
9950            invalidateViewProperty(true, false);
9951            info.mTranslationY = translationY;
9952            info.mMatrixDirty = true;
9953            invalidateViewProperty(false, true);
9954            if (mDisplayList != null) {
9955                mDisplayList.setTranslationY(translationY);
9956            }
9957            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9958                // View was rejected last time it was drawn by its parent; this may have changed
9959                invalidateParentIfNeeded();
9960            }
9961        }
9962    }
9963
9964    /**
9965     * Hit rectangle in parent's coordinates
9966     *
9967     * @param outRect The hit rectangle of the view.
9968     */
9969    public void getHitRect(Rect outRect) {
9970        updateMatrix();
9971        final TransformationInfo info = mTransformationInfo;
9972        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9973            outRect.set(mLeft, mTop, mRight, mBottom);
9974        } else {
9975            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9976            tmpRect.set(0, 0, getWidth(), getHeight());
9977            info.mMatrix.mapRect(tmpRect);
9978            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9979                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9980        }
9981    }
9982
9983    /**
9984     * Determines whether the given point, in local coordinates is inside the view.
9985     */
9986    /*package*/ final boolean pointInView(float localX, float localY) {
9987        return localX >= 0 && localX < (mRight - mLeft)
9988                && localY >= 0 && localY < (mBottom - mTop);
9989    }
9990
9991    /**
9992     * Utility method to determine whether the given point, in local coordinates,
9993     * is inside the view, where the area of the view is expanded by the slop factor.
9994     * This method is called while processing touch-move events to determine if the event
9995     * is still within the view.
9996     */
9997    private boolean pointInView(float localX, float localY, float slop) {
9998        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9999                localY < ((mBottom - mTop) + slop);
10000    }
10001
10002    /**
10003     * When a view has focus and the user navigates away from it, the next view is searched for
10004     * starting from the rectangle filled in by this method.
10005     *
10006     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10007     * of the view.  However, if your view maintains some idea of internal selection,
10008     * such as a cursor, or a selected row or column, you should override this method and
10009     * fill in a more specific rectangle.
10010     *
10011     * @param r The rectangle to fill in, in this view's coordinates.
10012     */
10013    public void getFocusedRect(Rect r) {
10014        getDrawingRect(r);
10015    }
10016
10017    /**
10018     * If some part of this view is not clipped by any of its parents, then
10019     * return that area in r in global (root) coordinates. To convert r to local
10020     * coordinates (without taking possible View rotations into account), offset
10021     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10022     * If the view is completely clipped or translated out, return false.
10023     *
10024     * @param r If true is returned, r holds the global coordinates of the
10025     *        visible portion of this view.
10026     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10027     *        between this view and its root. globalOffet may be null.
10028     * @return true if r is non-empty (i.e. part of the view is visible at the
10029     *         root level.
10030     */
10031    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10032        int width = mRight - mLeft;
10033        int height = mBottom - mTop;
10034        if (width > 0 && height > 0) {
10035            r.set(0, 0, width, height);
10036            if (globalOffset != null) {
10037                globalOffset.set(-mScrollX, -mScrollY);
10038            }
10039            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10040        }
10041        return false;
10042    }
10043
10044    public final boolean getGlobalVisibleRect(Rect r) {
10045        return getGlobalVisibleRect(r, null);
10046    }
10047
10048    public final boolean getLocalVisibleRect(Rect r) {
10049        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10050        if (getGlobalVisibleRect(r, offset)) {
10051            r.offset(-offset.x, -offset.y); // make r local
10052            return true;
10053        }
10054        return false;
10055    }
10056
10057    /**
10058     * Offset this view's vertical location by the specified number of pixels.
10059     *
10060     * @param offset the number of pixels to offset the view by
10061     */
10062    public void offsetTopAndBottom(int offset) {
10063        if (offset != 0) {
10064            updateMatrix();
10065            final boolean matrixIsIdentity = mTransformationInfo == null
10066                    || mTransformationInfo.mMatrixIsIdentity;
10067            if (matrixIsIdentity) {
10068                if (mDisplayList != null) {
10069                    invalidateViewProperty(false, false);
10070                } else {
10071                    final ViewParent p = mParent;
10072                    if (p != null && mAttachInfo != null) {
10073                        final Rect r = mAttachInfo.mTmpInvalRect;
10074                        int minTop;
10075                        int maxBottom;
10076                        int yLoc;
10077                        if (offset < 0) {
10078                            minTop = mTop + offset;
10079                            maxBottom = mBottom;
10080                            yLoc = offset;
10081                        } else {
10082                            minTop = mTop;
10083                            maxBottom = mBottom + offset;
10084                            yLoc = 0;
10085                        }
10086                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10087                        p.invalidateChild(this, r);
10088                    }
10089                }
10090            } else {
10091                invalidateViewProperty(false, false);
10092            }
10093
10094            mTop += offset;
10095            mBottom += offset;
10096            if (mDisplayList != null) {
10097                mDisplayList.offsetTopAndBottom(offset);
10098                invalidateViewProperty(false, false);
10099            } else {
10100                if (!matrixIsIdentity) {
10101                    invalidateViewProperty(false, true);
10102                }
10103                invalidateParentIfNeeded();
10104            }
10105        }
10106    }
10107
10108    /**
10109     * Offset this view's horizontal location by the specified amount of pixels.
10110     *
10111     * @param offset the number of pixels to offset the view by
10112     */
10113    public void offsetLeftAndRight(int offset) {
10114        if (offset != 0) {
10115            updateMatrix();
10116            final boolean matrixIsIdentity = mTransformationInfo == null
10117                    || mTransformationInfo.mMatrixIsIdentity;
10118            if (matrixIsIdentity) {
10119                if (mDisplayList != null) {
10120                    invalidateViewProperty(false, false);
10121                } else {
10122                    final ViewParent p = mParent;
10123                    if (p != null && mAttachInfo != null) {
10124                        final Rect r = mAttachInfo.mTmpInvalRect;
10125                        int minLeft;
10126                        int maxRight;
10127                        if (offset < 0) {
10128                            minLeft = mLeft + offset;
10129                            maxRight = mRight;
10130                        } else {
10131                            minLeft = mLeft;
10132                            maxRight = mRight + offset;
10133                        }
10134                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10135                        p.invalidateChild(this, r);
10136                    }
10137                }
10138            } else {
10139                invalidateViewProperty(false, false);
10140            }
10141
10142            mLeft += offset;
10143            mRight += offset;
10144            if (mDisplayList != null) {
10145                mDisplayList.offsetLeftAndRight(offset);
10146                invalidateViewProperty(false, false);
10147            } else {
10148                if (!matrixIsIdentity) {
10149                    invalidateViewProperty(false, true);
10150                }
10151                invalidateParentIfNeeded();
10152            }
10153        }
10154    }
10155
10156    /**
10157     * Get the LayoutParams associated with this view. All views should have
10158     * layout parameters. These supply parameters to the <i>parent</i> of this
10159     * view specifying how it should be arranged. There are many subclasses of
10160     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10161     * of ViewGroup that are responsible for arranging their children.
10162     *
10163     * This method may return null if this View is not attached to a parent
10164     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10165     * was not invoked successfully. When a View is attached to a parent
10166     * ViewGroup, this method must not return null.
10167     *
10168     * @return The LayoutParams associated with this view, or null if no
10169     *         parameters have been set yet
10170     */
10171    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10172    public ViewGroup.LayoutParams getLayoutParams() {
10173        return mLayoutParams;
10174    }
10175
10176    /**
10177     * Set the layout parameters associated with this view. These supply
10178     * parameters to the <i>parent</i> of this view specifying how it should be
10179     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10180     * correspond to the different subclasses of ViewGroup that are responsible
10181     * for arranging their children.
10182     *
10183     * @param params The layout parameters for this view, cannot be null
10184     */
10185    public void setLayoutParams(ViewGroup.LayoutParams params) {
10186        if (params == null) {
10187            throw new NullPointerException("Layout parameters cannot be null");
10188        }
10189        mLayoutParams = params;
10190        resolveLayoutParams();
10191        if (mParent instanceof ViewGroup) {
10192            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10193        }
10194        requestLayout();
10195    }
10196
10197    /**
10198     * Resolve the layout parameters depending on the resolved layout direction
10199     *
10200     * @hide
10201     */
10202    public void resolveLayoutParams() {
10203        if (mLayoutParams != null) {
10204            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10205        }
10206    }
10207
10208    /**
10209     * Set the scrolled position of your view. This will cause a call to
10210     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10211     * invalidated.
10212     * @param x the x position to scroll to
10213     * @param y the y position to scroll to
10214     */
10215    public void scrollTo(int x, int y) {
10216        if (mScrollX != x || mScrollY != y) {
10217            int oldX = mScrollX;
10218            int oldY = mScrollY;
10219            mScrollX = x;
10220            mScrollY = y;
10221            invalidateParentCaches();
10222            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10223            if (!awakenScrollBars()) {
10224                postInvalidateOnAnimation();
10225            }
10226        }
10227    }
10228
10229    /**
10230     * Move the scrolled position of your view. This will cause a call to
10231     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10232     * invalidated.
10233     * @param x the amount of pixels to scroll by horizontally
10234     * @param y the amount of pixels to scroll by vertically
10235     */
10236    public void scrollBy(int x, int y) {
10237        scrollTo(mScrollX + x, mScrollY + y);
10238    }
10239
10240    /**
10241     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10242     * animation to fade the scrollbars out after a default delay. If a subclass
10243     * provides animated scrolling, the start delay should equal the duration
10244     * of the scrolling animation.</p>
10245     *
10246     * <p>The animation starts only if at least one of the scrollbars is
10247     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10248     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10249     * this method returns true, and false otherwise. If the animation is
10250     * started, this method calls {@link #invalidate()}; in that case the
10251     * caller should not call {@link #invalidate()}.</p>
10252     *
10253     * <p>This method should be invoked every time a subclass directly updates
10254     * the scroll parameters.</p>
10255     *
10256     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10257     * and {@link #scrollTo(int, int)}.</p>
10258     *
10259     * @return true if the animation is played, false otherwise
10260     *
10261     * @see #awakenScrollBars(int)
10262     * @see #scrollBy(int, int)
10263     * @see #scrollTo(int, int)
10264     * @see #isHorizontalScrollBarEnabled()
10265     * @see #isVerticalScrollBarEnabled()
10266     * @see #setHorizontalScrollBarEnabled(boolean)
10267     * @see #setVerticalScrollBarEnabled(boolean)
10268     */
10269    protected boolean awakenScrollBars() {
10270        return mScrollCache != null &&
10271                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10272    }
10273
10274    /**
10275     * Trigger the scrollbars to draw.
10276     * This method differs from awakenScrollBars() only in its default duration.
10277     * initialAwakenScrollBars() will show the scroll bars for longer than
10278     * usual to give the user more of a chance to notice them.
10279     *
10280     * @return true if the animation is played, false otherwise.
10281     */
10282    private boolean initialAwakenScrollBars() {
10283        return mScrollCache != null &&
10284                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10285    }
10286
10287    /**
10288     * <p>
10289     * Trigger the scrollbars to draw. When invoked this method starts an
10290     * animation to fade the scrollbars out after a fixed delay. If a subclass
10291     * provides animated scrolling, the start delay should equal the duration of
10292     * the scrolling animation.
10293     * </p>
10294     *
10295     * <p>
10296     * The animation starts only if at least one of the scrollbars is enabled,
10297     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10298     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10299     * this method returns true, and false otherwise. If the animation is
10300     * started, this method calls {@link #invalidate()}; in that case the caller
10301     * should not call {@link #invalidate()}.
10302     * </p>
10303     *
10304     * <p>
10305     * This method should be invoked everytime a subclass directly updates the
10306     * scroll parameters.
10307     * </p>
10308     *
10309     * @param startDelay the delay, in milliseconds, after which the animation
10310     *        should start; when the delay is 0, the animation starts
10311     *        immediately
10312     * @return true if the animation is played, false otherwise
10313     *
10314     * @see #scrollBy(int, int)
10315     * @see #scrollTo(int, int)
10316     * @see #isHorizontalScrollBarEnabled()
10317     * @see #isVerticalScrollBarEnabled()
10318     * @see #setHorizontalScrollBarEnabled(boolean)
10319     * @see #setVerticalScrollBarEnabled(boolean)
10320     */
10321    protected boolean awakenScrollBars(int startDelay) {
10322        return awakenScrollBars(startDelay, true);
10323    }
10324
10325    /**
10326     * <p>
10327     * Trigger the scrollbars to draw. When invoked this method starts an
10328     * animation to fade the scrollbars out after a fixed delay. If a subclass
10329     * provides animated scrolling, the start delay should equal the duration of
10330     * the scrolling animation.
10331     * </p>
10332     *
10333     * <p>
10334     * The animation starts only if at least one of the scrollbars is enabled,
10335     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10336     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10337     * this method returns true, and false otherwise. If the animation is
10338     * started, this method calls {@link #invalidate()} if the invalidate parameter
10339     * is set to true; in that case the caller
10340     * should not call {@link #invalidate()}.
10341     * </p>
10342     *
10343     * <p>
10344     * This method should be invoked everytime a subclass directly updates the
10345     * scroll parameters.
10346     * </p>
10347     *
10348     * @param startDelay the delay, in milliseconds, after which the animation
10349     *        should start; when the delay is 0, the animation starts
10350     *        immediately
10351     *
10352     * @param invalidate Wheter this method should call invalidate
10353     *
10354     * @return true if the animation is played, false otherwise
10355     *
10356     * @see #scrollBy(int, int)
10357     * @see #scrollTo(int, int)
10358     * @see #isHorizontalScrollBarEnabled()
10359     * @see #isVerticalScrollBarEnabled()
10360     * @see #setHorizontalScrollBarEnabled(boolean)
10361     * @see #setVerticalScrollBarEnabled(boolean)
10362     */
10363    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10364        final ScrollabilityCache scrollCache = mScrollCache;
10365
10366        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10367            return false;
10368        }
10369
10370        if (scrollCache.scrollBar == null) {
10371            scrollCache.scrollBar = new ScrollBarDrawable();
10372        }
10373
10374        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10375
10376            if (invalidate) {
10377                // Invalidate to show the scrollbars
10378                postInvalidateOnAnimation();
10379            }
10380
10381            if (scrollCache.state == ScrollabilityCache.OFF) {
10382                // FIXME: this is copied from WindowManagerService.
10383                // We should get this value from the system when it
10384                // is possible to do so.
10385                final int KEY_REPEAT_FIRST_DELAY = 750;
10386                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10387            }
10388
10389            // Tell mScrollCache when we should start fading. This may
10390            // extend the fade start time if one was already scheduled
10391            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10392            scrollCache.fadeStartTime = fadeStartTime;
10393            scrollCache.state = ScrollabilityCache.ON;
10394
10395            // Schedule our fader to run, unscheduling any old ones first
10396            if (mAttachInfo != null) {
10397                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10398                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10399            }
10400
10401            return true;
10402        }
10403
10404        return false;
10405    }
10406
10407    /**
10408     * Do not invalidate views which are not visible and which are not running an animation. They
10409     * will not get drawn and they should not set dirty flags as if they will be drawn
10410     */
10411    private boolean skipInvalidate() {
10412        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10413                (!(mParent instanceof ViewGroup) ||
10414                        !((ViewGroup) mParent).isViewTransitioning(this));
10415    }
10416    /**
10417     * Mark the area defined by dirty as needing to be drawn. If the view is
10418     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10419     * in the future. This must be called from a UI thread. To call from a non-UI
10420     * thread, call {@link #postInvalidate()}.
10421     *
10422     * WARNING: This method is destructive to dirty.
10423     * @param dirty the rectangle representing the bounds of the dirty region
10424     */
10425    public void invalidate(Rect dirty) {
10426        if (skipInvalidate()) {
10427            return;
10428        }
10429        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10430                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10431                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10432            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10433            mPrivateFlags |= PFLAG_INVALIDATED;
10434            mPrivateFlags |= PFLAG_DIRTY;
10435            final ViewParent p = mParent;
10436            final AttachInfo ai = mAttachInfo;
10437            //noinspection PointlessBooleanExpression,ConstantConditions
10438            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10439                if (p != null && ai != null && ai.mHardwareAccelerated) {
10440                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10441                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10442                    p.invalidateChild(this, null);
10443                    return;
10444                }
10445            }
10446            if (p != null && ai != null) {
10447                final int scrollX = mScrollX;
10448                final int scrollY = mScrollY;
10449                final Rect r = ai.mTmpInvalRect;
10450                r.set(dirty.left - scrollX, dirty.top - scrollY,
10451                        dirty.right - scrollX, dirty.bottom - scrollY);
10452                mParent.invalidateChild(this, r);
10453            }
10454        }
10455    }
10456
10457    /**
10458     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10459     * The coordinates of the dirty rect are relative to the view.
10460     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10461     * will be called at some point in the future. This must be called from
10462     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10463     * @param l the left position of the dirty region
10464     * @param t the top position of the dirty region
10465     * @param r the right position of the dirty region
10466     * @param b the bottom position of the dirty region
10467     */
10468    public void invalidate(int l, int t, int r, int b) {
10469        if (skipInvalidate()) {
10470            return;
10471        }
10472        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10473                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10474                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10475            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10476            mPrivateFlags |= PFLAG_INVALIDATED;
10477            mPrivateFlags |= PFLAG_DIRTY;
10478            final ViewParent p = mParent;
10479            final AttachInfo ai = mAttachInfo;
10480            //noinspection PointlessBooleanExpression,ConstantConditions
10481            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10482                if (p != null && ai != null && ai.mHardwareAccelerated) {
10483                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10484                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10485                    p.invalidateChild(this, null);
10486                    return;
10487                }
10488            }
10489            if (p != null && ai != null && l < r && t < b) {
10490                final int scrollX = mScrollX;
10491                final int scrollY = mScrollY;
10492                final Rect tmpr = ai.mTmpInvalRect;
10493                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10494                p.invalidateChild(this, tmpr);
10495            }
10496        }
10497    }
10498
10499    /**
10500     * Invalidate the whole view. If the view is visible,
10501     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10502     * the future. This must be called from a UI thread. To call from a non-UI thread,
10503     * call {@link #postInvalidate()}.
10504     */
10505    public void invalidate() {
10506        invalidate(true);
10507    }
10508
10509    /**
10510     * This is where the invalidate() work actually happens. A full invalidate()
10511     * causes the drawing cache to be invalidated, but this function can be called with
10512     * invalidateCache set to false to skip that invalidation step for cases that do not
10513     * need it (for example, a component that remains at the same dimensions with the same
10514     * content).
10515     *
10516     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10517     * well. This is usually true for a full invalidate, but may be set to false if the
10518     * View's contents or dimensions have not changed.
10519     */
10520    void invalidate(boolean invalidateCache) {
10521        if (skipInvalidate()) {
10522            return;
10523        }
10524        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10525                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10526                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10527            mLastIsOpaque = isOpaque();
10528            mPrivateFlags &= ~PFLAG_DRAWN;
10529            mPrivateFlags |= PFLAG_DIRTY;
10530            if (invalidateCache) {
10531                mPrivateFlags |= PFLAG_INVALIDATED;
10532                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10533            }
10534            final AttachInfo ai = mAttachInfo;
10535            final ViewParent p = mParent;
10536            //noinspection PointlessBooleanExpression,ConstantConditions
10537            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10538                if (p != null && ai != null && ai.mHardwareAccelerated) {
10539                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10540                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10541                    p.invalidateChild(this, null);
10542                    return;
10543                }
10544            }
10545
10546            if (p != null && ai != null) {
10547                final Rect r = ai.mTmpInvalRect;
10548                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10549                // Don't call invalidate -- we don't want to internally scroll
10550                // our own bounds
10551                p.invalidateChild(this, r);
10552            }
10553        }
10554    }
10555
10556    /**
10557     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10558     * set any flags or handle all of the cases handled by the default invalidation methods.
10559     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10560     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10561     * walk up the hierarchy, transforming the dirty rect as necessary.
10562     *
10563     * The method also handles normal invalidation logic if display list properties are not
10564     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10565     * backup approach, to handle these cases used in the various property-setting methods.
10566     *
10567     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10568     * are not being used in this view
10569     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10570     * list properties are not being used in this view
10571     */
10572    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10573        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10574            if (invalidateParent) {
10575                invalidateParentCaches();
10576            }
10577            if (forceRedraw) {
10578                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10579            }
10580            invalidate(false);
10581        } else {
10582            final AttachInfo ai = mAttachInfo;
10583            final ViewParent p = mParent;
10584            if (p != null && ai != null) {
10585                final Rect r = ai.mTmpInvalRect;
10586                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10587                if (mParent instanceof ViewGroup) {
10588                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10589                } else {
10590                    mParent.invalidateChild(this, r);
10591                }
10592            }
10593        }
10594    }
10595
10596    /**
10597     * Utility method to transform a given Rect by the current matrix of this view.
10598     */
10599    void transformRect(final Rect rect) {
10600        if (!getMatrix().isIdentity()) {
10601            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10602            boundingRect.set(rect);
10603            getMatrix().mapRect(boundingRect);
10604            rect.set((int) (boundingRect.left - 0.5f),
10605                    (int) (boundingRect.top - 0.5f),
10606                    (int) (boundingRect.right + 0.5f),
10607                    (int) (boundingRect.bottom + 0.5f));
10608        }
10609    }
10610
10611    /**
10612     * Used to indicate that the parent of this view should clear its caches. This functionality
10613     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10614     * which is necessary when various parent-managed properties of the view change, such as
10615     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10616     * clears the parent caches and does not causes an invalidate event.
10617     *
10618     * @hide
10619     */
10620    protected void invalidateParentCaches() {
10621        if (mParent instanceof View) {
10622            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10623        }
10624    }
10625
10626    /**
10627     * Used to indicate that the parent of this view should be invalidated. This functionality
10628     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10629     * which is necessary when various parent-managed properties of the view change, such as
10630     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10631     * an invalidation event to the parent.
10632     *
10633     * @hide
10634     */
10635    protected void invalidateParentIfNeeded() {
10636        if (isHardwareAccelerated() && mParent instanceof View) {
10637            ((View) mParent).invalidate(true);
10638        }
10639    }
10640
10641    /**
10642     * Indicates whether this View is opaque. An opaque View guarantees that it will
10643     * draw all the pixels overlapping its bounds using a fully opaque color.
10644     *
10645     * Subclasses of View should override this method whenever possible to indicate
10646     * whether an instance is opaque. Opaque Views are treated in a special way by
10647     * the View hierarchy, possibly allowing it to perform optimizations during
10648     * invalidate/draw passes.
10649     *
10650     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10651     */
10652    @ViewDebug.ExportedProperty(category = "drawing")
10653    public boolean isOpaque() {
10654        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10655                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10656    }
10657
10658    /**
10659     * @hide
10660     */
10661    protected void computeOpaqueFlags() {
10662        // Opaque if:
10663        //   - Has a background
10664        //   - Background is opaque
10665        //   - Doesn't have scrollbars or scrollbars overlay
10666
10667        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10668            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10669        } else {
10670            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10671        }
10672
10673        final int flags = mViewFlags;
10674        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10675                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10676                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10677            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10678        } else {
10679            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10680        }
10681    }
10682
10683    /**
10684     * @hide
10685     */
10686    protected boolean hasOpaqueScrollbars() {
10687        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10688    }
10689
10690    /**
10691     * @return A handler associated with the thread running the View. This
10692     * handler can be used to pump events in the UI events queue.
10693     */
10694    public Handler getHandler() {
10695        if (mAttachInfo != null) {
10696            return mAttachInfo.mHandler;
10697        }
10698        return null;
10699    }
10700
10701    /**
10702     * Gets the view root associated with the View.
10703     * @return The view root, or null if none.
10704     * @hide
10705     */
10706    public ViewRootImpl getViewRootImpl() {
10707        if (mAttachInfo != null) {
10708            return mAttachInfo.mViewRootImpl;
10709        }
10710        return null;
10711    }
10712
10713    /**
10714     * <p>Causes the Runnable to be added to the message queue.
10715     * The runnable will be run on the user interface thread.</p>
10716     *
10717     * @param action The Runnable that will be executed.
10718     *
10719     * @return Returns true if the Runnable was successfully placed in to the
10720     *         message queue.  Returns false on failure, usually because the
10721     *         looper processing the message queue is exiting.
10722     *
10723     * @see #postDelayed
10724     * @see #removeCallbacks
10725     */
10726    public boolean post(Runnable action) {
10727        final AttachInfo attachInfo = mAttachInfo;
10728        if (attachInfo != null) {
10729            return attachInfo.mHandler.post(action);
10730        }
10731        // Assume that post will succeed later
10732        ViewRootImpl.getRunQueue().post(action);
10733        return true;
10734    }
10735
10736    /**
10737     * <p>Causes the Runnable to be added to the message queue, to be run
10738     * after the specified amount of time elapses.
10739     * The runnable will be run on the user interface thread.</p>
10740     *
10741     * @param action The Runnable that will be executed.
10742     * @param delayMillis The delay (in milliseconds) until the Runnable
10743     *        will be executed.
10744     *
10745     * @return true if the Runnable was successfully placed in to the
10746     *         message queue.  Returns false on failure, usually because the
10747     *         looper processing the message queue is exiting.  Note that a
10748     *         result of true does not mean the Runnable will be processed --
10749     *         if the looper is quit before the delivery time of the message
10750     *         occurs then the message will be dropped.
10751     *
10752     * @see #post
10753     * @see #removeCallbacks
10754     */
10755    public boolean postDelayed(Runnable action, long delayMillis) {
10756        final AttachInfo attachInfo = mAttachInfo;
10757        if (attachInfo != null) {
10758            return attachInfo.mHandler.postDelayed(action, delayMillis);
10759        }
10760        // Assume that post will succeed later
10761        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10762        return true;
10763    }
10764
10765    /**
10766     * <p>Causes the Runnable to execute on the next animation time step.
10767     * The runnable will be run on the user interface thread.</p>
10768     *
10769     * @param action The Runnable that will be executed.
10770     *
10771     * @see #postOnAnimationDelayed
10772     * @see #removeCallbacks
10773     */
10774    public void postOnAnimation(Runnable action) {
10775        final AttachInfo attachInfo = mAttachInfo;
10776        if (attachInfo != null) {
10777            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10778                    Choreographer.CALLBACK_ANIMATION, action, null);
10779        } else {
10780            // Assume that post will succeed later
10781            ViewRootImpl.getRunQueue().post(action);
10782        }
10783    }
10784
10785    /**
10786     * <p>Causes the Runnable to execute on the next animation time step,
10787     * after the specified amount of time elapses.
10788     * The runnable will be run on the user interface thread.</p>
10789     *
10790     * @param action The Runnable that will be executed.
10791     * @param delayMillis The delay (in milliseconds) until the Runnable
10792     *        will be executed.
10793     *
10794     * @see #postOnAnimation
10795     * @see #removeCallbacks
10796     */
10797    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10798        final AttachInfo attachInfo = mAttachInfo;
10799        if (attachInfo != null) {
10800            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10801                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10802        } else {
10803            // Assume that post will succeed later
10804            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10805        }
10806    }
10807
10808    /**
10809     * <p>Removes the specified Runnable from the message queue.</p>
10810     *
10811     * @param action The Runnable to remove from the message handling queue
10812     *
10813     * @return true if this view could ask the Handler to remove the Runnable,
10814     *         false otherwise. When the returned value is true, the Runnable
10815     *         may or may not have been actually removed from the message queue
10816     *         (for instance, if the Runnable was not in the queue already.)
10817     *
10818     * @see #post
10819     * @see #postDelayed
10820     * @see #postOnAnimation
10821     * @see #postOnAnimationDelayed
10822     */
10823    public boolean removeCallbacks(Runnable action) {
10824        if (action != null) {
10825            final AttachInfo attachInfo = mAttachInfo;
10826            if (attachInfo != null) {
10827                attachInfo.mHandler.removeCallbacks(action);
10828                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10829                        Choreographer.CALLBACK_ANIMATION, action, null);
10830            } else {
10831                // Assume that post will succeed later
10832                ViewRootImpl.getRunQueue().removeCallbacks(action);
10833            }
10834        }
10835        return true;
10836    }
10837
10838    /**
10839     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10840     * Use this to invalidate the View from a non-UI thread.</p>
10841     *
10842     * <p>This method can be invoked from outside of the UI thread
10843     * only when this View is attached to a window.</p>
10844     *
10845     * @see #invalidate()
10846     * @see #postInvalidateDelayed(long)
10847     */
10848    public void postInvalidate() {
10849        postInvalidateDelayed(0);
10850    }
10851
10852    /**
10853     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10854     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10855     *
10856     * <p>This method can be invoked from outside of the UI thread
10857     * only when this View is attached to a window.</p>
10858     *
10859     * @param left The left coordinate of the rectangle to invalidate.
10860     * @param top The top coordinate of the rectangle to invalidate.
10861     * @param right The right coordinate of the rectangle to invalidate.
10862     * @param bottom The bottom coordinate of the rectangle to invalidate.
10863     *
10864     * @see #invalidate(int, int, int, int)
10865     * @see #invalidate(Rect)
10866     * @see #postInvalidateDelayed(long, int, int, int, int)
10867     */
10868    public void postInvalidate(int left, int top, int right, int bottom) {
10869        postInvalidateDelayed(0, left, top, right, bottom);
10870    }
10871
10872    /**
10873     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10874     * loop. Waits for the specified amount of time.</p>
10875     *
10876     * <p>This method can be invoked from outside of the UI thread
10877     * only when this View is attached to a window.</p>
10878     *
10879     * @param delayMilliseconds the duration in milliseconds to delay the
10880     *         invalidation by
10881     *
10882     * @see #invalidate()
10883     * @see #postInvalidate()
10884     */
10885    public void postInvalidateDelayed(long delayMilliseconds) {
10886        // We try only with the AttachInfo because there's no point in invalidating
10887        // if we are not attached to our window
10888        final AttachInfo attachInfo = mAttachInfo;
10889        if (attachInfo != null) {
10890            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10891        }
10892    }
10893
10894    /**
10895     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10896     * through the event loop. Waits for the specified amount of time.</p>
10897     *
10898     * <p>This method can be invoked from outside of the UI thread
10899     * only when this View is attached to a window.</p>
10900     *
10901     * @param delayMilliseconds the duration in milliseconds to delay the
10902     *         invalidation by
10903     * @param left The left coordinate of the rectangle to invalidate.
10904     * @param top The top coordinate of the rectangle to invalidate.
10905     * @param right The right coordinate of the rectangle to invalidate.
10906     * @param bottom The bottom coordinate of the rectangle to invalidate.
10907     *
10908     * @see #invalidate(int, int, int, int)
10909     * @see #invalidate(Rect)
10910     * @see #postInvalidate(int, int, int, int)
10911     */
10912    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10913            int right, int bottom) {
10914
10915        // We try only with the AttachInfo because there's no point in invalidating
10916        // if we are not attached to our window
10917        final AttachInfo attachInfo = mAttachInfo;
10918        if (attachInfo != null) {
10919            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10920            info.target = this;
10921            info.left = left;
10922            info.top = top;
10923            info.right = right;
10924            info.bottom = bottom;
10925
10926            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10927        }
10928    }
10929
10930    /**
10931     * <p>Cause an invalidate to happen on the next animation time step, typically the
10932     * next display frame.</p>
10933     *
10934     * <p>This method can be invoked from outside of the UI thread
10935     * only when this View is attached to a window.</p>
10936     *
10937     * @see #invalidate()
10938     */
10939    public void postInvalidateOnAnimation() {
10940        // We try only with the AttachInfo because there's no point in invalidating
10941        // if we are not attached to our window
10942        final AttachInfo attachInfo = mAttachInfo;
10943        if (attachInfo != null) {
10944            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10945        }
10946    }
10947
10948    /**
10949     * <p>Cause an invalidate of the specified area to happen on the next animation
10950     * time step, typically the next display frame.</p>
10951     *
10952     * <p>This method can be invoked from outside of the UI thread
10953     * only when this View is attached to a window.</p>
10954     *
10955     * @param left The left coordinate of the rectangle to invalidate.
10956     * @param top The top coordinate of the rectangle to invalidate.
10957     * @param right The right coordinate of the rectangle to invalidate.
10958     * @param bottom The bottom coordinate of the rectangle to invalidate.
10959     *
10960     * @see #invalidate(int, int, int, int)
10961     * @see #invalidate(Rect)
10962     */
10963    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10964        // We try only with the AttachInfo because there's no point in invalidating
10965        // if we are not attached to our window
10966        final AttachInfo attachInfo = mAttachInfo;
10967        if (attachInfo != null) {
10968            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10969            info.target = this;
10970            info.left = left;
10971            info.top = top;
10972            info.right = right;
10973            info.bottom = bottom;
10974
10975            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10976        }
10977    }
10978
10979    /**
10980     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10981     * This event is sent at most once every
10982     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10983     */
10984    private void postSendViewScrolledAccessibilityEventCallback() {
10985        if (mSendViewScrolledAccessibilityEvent == null) {
10986            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10987        }
10988        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10989            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10990            postDelayed(mSendViewScrolledAccessibilityEvent,
10991                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10992        }
10993    }
10994
10995    /**
10996     * Called by a parent to request that a child update its values for mScrollX
10997     * and mScrollY if necessary. This will typically be done if the child is
10998     * animating a scroll using a {@link android.widget.Scroller Scroller}
10999     * object.
11000     */
11001    public void computeScroll() {
11002    }
11003
11004    /**
11005     * <p>Indicate whether the horizontal edges are faded when the view is
11006     * scrolled horizontally.</p>
11007     *
11008     * @return true if the horizontal edges should are faded on scroll, false
11009     *         otherwise
11010     *
11011     * @see #setHorizontalFadingEdgeEnabled(boolean)
11012     *
11013     * @attr ref android.R.styleable#View_requiresFadingEdge
11014     */
11015    public boolean isHorizontalFadingEdgeEnabled() {
11016        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11017    }
11018
11019    /**
11020     * <p>Define whether the horizontal edges should be faded when this view
11021     * is scrolled horizontally.</p>
11022     *
11023     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11024     *                                    be faded when the view is scrolled
11025     *                                    horizontally
11026     *
11027     * @see #isHorizontalFadingEdgeEnabled()
11028     *
11029     * @attr ref android.R.styleable#View_requiresFadingEdge
11030     */
11031    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11032        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11033            if (horizontalFadingEdgeEnabled) {
11034                initScrollCache();
11035            }
11036
11037            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11038        }
11039    }
11040
11041    /**
11042     * <p>Indicate whether the vertical edges are faded when the view is
11043     * scrolled horizontally.</p>
11044     *
11045     * @return true if the vertical edges should are faded on scroll, false
11046     *         otherwise
11047     *
11048     * @see #setVerticalFadingEdgeEnabled(boolean)
11049     *
11050     * @attr ref android.R.styleable#View_requiresFadingEdge
11051     */
11052    public boolean isVerticalFadingEdgeEnabled() {
11053        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11054    }
11055
11056    /**
11057     * <p>Define whether the vertical edges should be faded when this view
11058     * is scrolled vertically.</p>
11059     *
11060     * @param verticalFadingEdgeEnabled true if the vertical edges should
11061     *                                  be faded when the view is scrolled
11062     *                                  vertically
11063     *
11064     * @see #isVerticalFadingEdgeEnabled()
11065     *
11066     * @attr ref android.R.styleable#View_requiresFadingEdge
11067     */
11068    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11069        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11070            if (verticalFadingEdgeEnabled) {
11071                initScrollCache();
11072            }
11073
11074            mViewFlags ^= FADING_EDGE_VERTICAL;
11075        }
11076    }
11077
11078    /**
11079     * Returns the strength, or intensity, of the top faded edge. The strength is
11080     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11081     * returns 0.0 or 1.0 but no value in between.
11082     *
11083     * Subclasses should override this method to provide a smoother fade transition
11084     * when scrolling occurs.
11085     *
11086     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11087     */
11088    protected float getTopFadingEdgeStrength() {
11089        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11090    }
11091
11092    /**
11093     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11094     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11095     * returns 0.0 or 1.0 but no value in between.
11096     *
11097     * Subclasses should override this method to provide a smoother fade transition
11098     * when scrolling occurs.
11099     *
11100     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11101     */
11102    protected float getBottomFadingEdgeStrength() {
11103        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11104                computeVerticalScrollRange() ? 1.0f : 0.0f;
11105    }
11106
11107    /**
11108     * Returns the strength, or intensity, of the left faded edge. The strength is
11109     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11110     * returns 0.0 or 1.0 but no value in between.
11111     *
11112     * Subclasses should override this method to provide a smoother fade transition
11113     * when scrolling occurs.
11114     *
11115     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11116     */
11117    protected float getLeftFadingEdgeStrength() {
11118        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11119    }
11120
11121    /**
11122     * Returns the strength, or intensity, of the right faded edge. The strength is
11123     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11124     * returns 0.0 or 1.0 but no value in between.
11125     *
11126     * Subclasses should override this method to provide a smoother fade transition
11127     * when scrolling occurs.
11128     *
11129     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11130     */
11131    protected float getRightFadingEdgeStrength() {
11132        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11133                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11134    }
11135
11136    /**
11137     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11138     * scrollbar is not drawn by default.</p>
11139     *
11140     * @return true if the horizontal scrollbar should be painted, false
11141     *         otherwise
11142     *
11143     * @see #setHorizontalScrollBarEnabled(boolean)
11144     */
11145    public boolean isHorizontalScrollBarEnabled() {
11146        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11147    }
11148
11149    /**
11150     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11151     * scrollbar is not drawn by default.</p>
11152     *
11153     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11154     *                                   be painted
11155     *
11156     * @see #isHorizontalScrollBarEnabled()
11157     */
11158    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11159        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11160            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11161            computeOpaqueFlags();
11162            resolvePadding();
11163        }
11164    }
11165
11166    /**
11167     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11168     * scrollbar is not drawn by default.</p>
11169     *
11170     * @return true if the vertical scrollbar should be painted, false
11171     *         otherwise
11172     *
11173     * @see #setVerticalScrollBarEnabled(boolean)
11174     */
11175    public boolean isVerticalScrollBarEnabled() {
11176        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11177    }
11178
11179    /**
11180     * <p>Define whether the vertical scrollbar should be drawn or not. The
11181     * scrollbar is not drawn by default.</p>
11182     *
11183     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11184     *                                 be painted
11185     *
11186     * @see #isVerticalScrollBarEnabled()
11187     */
11188    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11189        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11190            mViewFlags ^= SCROLLBARS_VERTICAL;
11191            computeOpaqueFlags();
11192            resolvePadding();
11193        }
11194    }
11195
11196    /**
11197     * @hide
11198     */
11199    protected void recomputePadding() {
11200        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11201    }
11202
11203    /**
11204     * Define whether scrollbars will fade when the view is not scrolling.
11205     *
11206     * @param fadeScrollbars wheter to enable fading
11207     *
11208     * @attr ref android.R.styleable#View_fadeScrollbars
11209     */
11210    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11211        initScrollCache();
11212        final ScrollabilityCache scrollabilityCache = mScrollCache;
11213        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11214        if (fadeScrollbars) {
11215            scrollabilityCache.state = ScrollabilityCache.OFF;
11216        } else {
11217            scrollabilityCache.state = ScrollabilityCache.ON;
11218        }
11219    }
11220
11221    /**
11222     *
11223     * Returns true if scrollbars will fade when this view is not scrolling
11224     *
11225     * @return true if scrollbar fading is enabled
11226     *
11227     * @attr ref android.R.styleable#View_fadeScrollbars
11228     */
11229    public boolean isScrollbarFadingEnabled() {
11230        return mScrollCache != null && mScrollCache.fadeScrollBars;
11231    }
11232
11233    /**
11234     *
11235     * Returns the delay before scrollbars fade.
11236     *
11237     * @return the delay before scrollbars fade
11238     *
11239     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11240     */
11241    public int getScrollBarDefaultDelayBeforeFade() {
11242        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11243                mScrollCache.scrollBarDefaultDelayBeforeFade;
11244    }
11245
11246    /**
11247     * Define the delay before scrollbars fade.
11248     *
11249     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11250     *
11251     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11252     */
11253    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11254        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11255    }
11256
11257    /**
11258     *
11259     * Returns the scrollbar fade duration.
11260     *
11261     * @return the scrollbar fade duration
11262     *
11263     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11264     */
11265    public int getScrollBarFadeDuration() {
11266        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11267                mScrollCache.scrollBarFadeDuration;
11268    }
11269
11270    /**
11271     * Define the scrollbar fade duration.
11272     *
11273     * @param scrollBarFadeDuration - the scrollbar fade duration
11274     *
11275     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11276     */
11277    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11278        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11279    }
11280
11281    /**
11282     *
11283     * Returns the scrollbar size.
11284     *
11285     * @return the scrollbar size
11286     *
11287     * @attr ref android.R.styleable#View_scrollbarSize
11288     */
11289    public int getScrollBarSize() {
11290        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11291                mScrollCache.scrollBarSize;
11292    }
11293
11294    /**
11295     * Define the scrollbar size.
11296     *
11297     * @param scrollBarSize - the scrollbar size
11298     *
11299     * @attr ref android.R.styleable#View_scrollbarSize
11300     */
11301    public void setScrollBarSize(int scrollBarSize) {
11302        getScrollCache().scrollBarSize = scrollBarSize;
11303    }
11304
11305    /**
11306     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11307     * inset. When inset, they add to the padding of the view. And the scrollbars
11308     * can be drawn inside the padding area or on the edge of the view. For example,
11309     * if a view has a background drawable and you want to draw the scrollbars
11310     * inside the padding specified by the drawable, you can use
11311     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11312     * appear at the edge of the view, ignoring the padding, then you can use
11313     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11314     * @param style the style of the scrollbars. Should be one of
11315     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11316     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11317     * @see #SCROLLBARS_INSIDE_OVERLAY
11318     * @see #SCROLLBARS_INSIDE_INSET
11319     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11320     * @see #SCROLLBARS_OUTSIDE_INSET
11321     *
11322     * @attr ref android.R.styleable#View_scrollbarStyle
11323     */
11324    public void setScrollBarStyle(int style) {
11325        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11326            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11327            computeOpaqueFlags();
11328            resolvePadding();
11329        }
11330    }
11331
11332    /**
11333     * <p>Returns the current scrollbar style.</p>
11334     * @return the current scrollbar style
11335     * @see #SCROLLBARS_INSIDE_OVERLAY
11336     * @see #SCROLLBARS_INSIDE_INSET
11337     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11338     * @see #SCROLLBARS_OUTSIDE_INSET
11339     *
11340     * @attr ref android.R.styleable#View_scrollbarStyle
11341     */
11342    @ViewDebug.ExportedProperty(mapping = {
11343            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11344            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11345            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11346            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11347    })
11348    public int getScrollBarStyle() {
11349        return mViewFlags & SCROLLBARS_STYLE_MASK;
11350    }
11351
11352    /**
11353     * <p>Compute the horizontal range that the horizontal scrollbar
11354     * represents.</p>
11355     *
11356     * <p>The range is expressed in arbitrary units that must be the same as the
11357     * units used by {@link #computeHorizontalScrollExtent()} and
11358     * {@link #computeHorizontalScrollOffset()}.</p>
11359     *
11360     * <p>The default range is the drawing width of this view.</p>
11361     *
11362     * @return the total horizontal range represented by the horizontal
11363     *         scrollbar
11364     *
11365     * @see #computeHorizontalScrollExtent()
11366     * @see #computeHorizontalScrollOffset()
11367     * @see android.widget.ScrollBarDrawable
11368     */
11369    protected int computeHorizontalScrollRange() {
11370        return getWidth();
11371    }
11372
11373    /**
11374     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11375     * within the horizontal range. This value is used to compute the position
11376     * of the thumb within the scrollbar's track.</p>
11377     *
11378     * <p>The range is expressed in arbitrary units that must be the same as the
11379     * units used by {@link #computeHorizontalScrollRange()} and
11380     * {@link #computeHorizontalScrollExtent()}.</p>
11381     *
11382     * <p>The default offset is the scroll offset of this view.</p>
11383     *
11384     * @return the horizontal offset of the scrollbar's thumb
11385     *
11386     * @see #computeHorizontalScrollRange()
11387     * @see #computeHorizontalScrollExtent()
11388     * @see android.widget.ScrollBarDrawable
11389     */
11390    protected int computeHorizontalScrollOffset() {
11391        return mScrollX;
11392    }
11393
11394    /**
11395     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11396     * within the horizontal range. This value is used to compute the length
11397     * of the thumb within the scrollbar's track.</p>
11398     *
11399     * <p>The range is expressed in arbitrary units that must be the same as the
11400     * units used by {@link #computeHorizontalScrollRange()} and
11401     * {@link #computeHorizontalScrollOffset()}.</p>
11402     *
11403     * <p>The default extent is the drawing width of this view.</p>
11404     *
11405     * @return the horizontal extent of the scrollbar's thumb
11406     *
11407     * @see #computeHorizontalScrollRange()
11408     * @see #computeHorizontalScrollOffset()
11409     * @see android.widget.ScrollBarDrawable
11410     */
11411    protected int computeHorizontalScrollExtent() {
11412        return getWidth();
11413    }
11414
11415    /**
11416     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11417     *
11418     * <p>The range is expressed in arbitrary units that must be the same as the
11419     * units used by {@link #computeVerticalScrollExtent()} and
11420     * {@link #computeVerticalScrollOffset()}.</p>
11421     *
11422     * @return the total vertical range represented by the vertical scrollbar
11423     *
11424     * <p>The default range is the drawing height of this view.</p>
11425     *
11426     * @see #computeVerticalScrollExtent()
11427     * @see #computeVerticalScrollOffset()
11428     * @see android.widget.ScrollBarDrawable
11429     */
11430    protected int computeVerticalScrollRange() {
11431        return getHeight();
11432    }
11433
11434    /**
11435     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11436     * within the horizontal range. This value is used to compute the position
11437     * of the thumb within the scrollbar's track.</p>
11438     *
11439     * <p>The range is expressed in arbitrary units that must be the same as the
11440     * units used by {@link #computeVerticalScrollRange()} and
11441     * {@link #computeVerticalScrollExtent()}.</p>
11442     *
11443     * <p>The default offset is the scroll offset of this view.</p>
11444     *
11445     * @return the vertical offset of the scrollbar's thumb
11446     *
11447     * @see #computeVerticalScrollRange()
11448     * @see #computeVerticalScrollExtent()
11449     * @see android.widget.ScrollBarDrawable
11450     */
11451    protected int computeVerticalScrollOffset() {
11452        return mScrollY;
11453    }
11454
11455    /**
11456     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11457     * within the vertical range. This value is used to compute the length
11458     * of the thumb within the scrollbar's track.</p>
11459     *
11460     * <p>The range is expressed in arbitrary units that must be the same as the
11461     * units used by {@link #computeVerticalScrollRange()} and
11462     * {@link #computeVerticalScrollOffset()}.</p>
11463     *
11464     * <p>The default extent is the drawing height of this view.</p>
11465     *
11466     * @return the vertical extent of the scrollbar's thumb
11467     *
11468     * @see #computeVerticalScrollRange()
11469     * @see #computeVerticalScrollOffset()
11470     * @see android.widget.ScrollBarDrawable
11471     */
11472    protected int computeVerticalScrollExtent() {
11473        return getHeight();
11474    }
11475
11476    /**
11477     * Check if this view can be scrolled horizontally in a certain direction.
11478     *
11479     * @param direction Negative to check scrolling left, positive to check scrolling right.
11480     * @return true if this view can be scrolled in the specified direction, false otherwise.
11481     */
11482    public boolean canScrollHorizontally(int direction) {
11483        final int offset = computeHorizontalScrollOffset();
11484        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11485        if (range == 0) return false;
11486        if (direction < 0) {
11487            return offset > 0;
11488        } else {
11489            return offset < range - 1;
11490        }
11491    }
11492
11493    /**
11494     * Check if this view can be scrolled vertically in a certain direction.
11495     *
11496     * @param direction Negative to check scrolling up, positive to check scrolling down.
11497     * @return true if this view can be scrolled in the specified direction, false otherwise.
11498     */
11499    public boolean canScrollVertically(int direction) {
11500        final int offset = computeVerticalScrollOffset();
11501        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11502        if (range == 0) return false;
11503        if (direction < 0) {
11504            return offset > 0;
11505        } else {
11506            return offset < range - 1;
11507        }
11508    }
11509
11510    /**
11511     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11512     * scrollbars are painted only if they have been awakened first.</p>
11513     *
11514     * @param canvas the canvas on which to draw the scrollbars
11515     *
11516     * @see #awakenScrollBars(int)
11517     */
11518    protected final void onDrawScrollBars(Canvas canvas) {
11519        // scrollbars are drawn only when the animation is running
11520        final ScrollabilityCache cache = mScrollCache;
11521        if (cache != null) {
11522
11523            int state = cache.state;
11524
11525            if (state == ScrollabilityCache.OFF) {
11526                return;
11527            }
11528
11529            boolean invalidate = false;
11530
11531            if (state == ScrollabilityCache.FADING) {
11532                // We're fading -- get our fade interpolation
11533                if (cache.interpolatorValues == null) {
11534                    cache.interpolatorValues = new float[1];
11535                }
11536
11537                float[] values = cache.interpolatorValues;
11538
11539                // Stops the animation if we're done
11540                if (cache.scrollBarInterpolator.timeToValues(values) ==
11541                        Interpolator.Result.FREEZE_END) {
11542                    cache.state = ScrollabilityCache.OFF;
11543                } else {
11544                    cache.scrollBar.setAlpha(Math.round(values[0]));
11545                }
11546
11547                // This will make the scroll bars inval themselves after
11548                // drawing. We only want this when we're fading so that
11549                // we prevent excessive redraws
11550                invalidate = true;
11551            } else {
11552                // We're just on -- but we may have been fading before so
11553                // reset alpha
11554                cache.scrollBar.setAlpha(255);
11555            }
11556
11557
11558            final int viewFlags = mViewFlags;
11559
11560            final boolean drawHorizontalScrollBar =
11561                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11562            final boolean drawVerticalScrollBar =
11563                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11564                && !isVerticalScrollBarHidden();
11565
11566            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11567                final int width = mRight - mLeft;
11568                final int height = mBottom - mTop;
11569
11570                final ScrollBarDrawable scrollBar = cache.scrollBar;
11571
11572                final int scrollX = mScrollX;
11573                final int scrollY = mScrollY;
11574                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11575
11576                int left;
11577                int top;
11578                int right;
11579                int bottom;
11580
11581                if (drawHorizontalScrollBar) {
11582                    int size = scrollBar.getSize(false);
11583                    if (size <= 0) {
11584                        size = cache.scrollBarSize;
11585                    }
11586
11587                    scrollBar.setParameters(computeHorizontalScrollRange(),
11588                                            computeHorizontalScrollOffset(),
11589                                            computeHorizontalScrollExtent(), false);
11590                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11591                            getVerticalScrollbarWidth() : 0;
11592                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11593                    left = scrollX + (mPaddingLeft & inside);
11594                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11595                    bottom = top + size;
11596                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11597                    if (invalidate) {
11598                        invalidate(left, top, right, bottom);
11599                    }
11600                }
11601
11602                if (drawVerticalScrollBar) {
11603                    int size = scrollBar.getSize(true);
11604                    if (size <= 0) {
11605                        size = cache.scrollBarSize;
11606                    }
11607
11608                    scrollBar.setParameters(computeVerticalScrollRange(),
11609                                            computeVerticalScrollOffset(),
11610                                            computeVerticalScrollExtent(), true);
11611                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11612                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11613                        verticalScrollbarPosition = isLayoutRtl() ?
11614                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11615                    }
11616                    switch (verticalScrollbarPosition) {
11617                        default:
11618                        case SCROLLBAR_POSITION_RIGHT:
11619                            left = scrollX + width - size - (mUserPaddingRight & inside);
11620                            break;
11621                        case SCROLLBAR_POSITION_LEFT:
11622                            left = scrollX + (mUserPaddingLeft & inside);
11623                            break;
11624                    }
11625                    top = scrollY + (mPaddingTop & inside);
11626                    right = left + size;
11627                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11628                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11629                    if (invalidate) {
11630                        invalidate(left, top, right, bottom);
11631                    }
11632                }
11633            }
11634        }
11635    }
11636
11637    /**
11638     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11639     * FastScroller is visible.
11640     * @return whether to temporarily hide the vertical scrollbar
11641     * @hide
11642     */
11643    protected boolean isVerticalScrollBarHidden() {
11644        return false;
11645    }
11646
11647    /**
11648     * <p>Draw the horizontal scrollbar if
11649     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11650     *
11651     * @param canvas the canvas on which to draw the scrollbar
11652     * @param scrollBar the scrollbar's drawable
11653     *
11654     * @see #isHorizontalScrollBarEnabled()
11655     * @see #computeHorizontalScrollRange()
11656     * @see #computeHorizontalScrollExtent()
11657     * @see #computeHorizontalScrollOffset()
11658     * @see android.widget.ScrollBarDrawable
11659     * @hide
11660     */
11661    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11662            int l, int t, int r, int b) {
11663        scrollBar.setBounds(l, t, r, b);
11664        scrollBar.draw(canvas);
11665    }
11666
11667    /**
11668     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11669     * returns true.</p>
11670     *
11671     * @param canvas the canvas on which to draw the scrollbar
11672     * @param scrollBar the scrollbar's drawable
11673     *
11674     * @see #isVerticalScrollBarEnabled()
11675     * @see #computeVerticalScrollRange()
11676     * @see #computeVerticalScrollExtent()
11677     * @see #computeVerticalScrollOffset()
11678     * @see android.widget.ScrollBarDrawable
11679     * @hide
11680     */
11681    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11682            int l, int t, int r, int b) {
11683        scrollBar.setBounds(l, t, r, b);
11684        scrollBar.draw(canvas);
11685    }
11686
11687    /**
11688     * Implement this to do your drawing.
11689     *
11690     * @param canvas the canvas on which the background will be drawn
11691     */
11692    protected void onDraw(Canvas canvas) {
11693    }
11694
11695    /*
11696     * Caller is responsible for calling requestLayout if necessary.
11697     * (This allows addViewInLayout to not request a new layout.)
11698     */
11699    void assignParent(ViewParent parent) {
11700        if (mParent == null) {
11701            mParent = parent;
11702        } else if (parent == null) {
11703            mParent = null;
11704        } else {
11705            throw new RuntimeException("view " + this + " being added, but"
11706                    + " it already has a parent");
11707        }
11708    }
11709
11710    /**
11711     * This is called when the view is attached to a window.  At this point it
11712     * has a Surface and will start drawing.  Note that this function is
11713     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11714     * however it may be called any time before the first onDraw -- including
11715     * before or after {@link #onMeasure(int, int)}.
11716     *
11717     * @see #onDetachedFromWindow()
11718     */
11719    protected void onAttachedToWindow() {
11720        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11721            mParent.requestTransparentRegion(this);
11722        }
11723
11724        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11725            initialAwakenScrollBars();
11726            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11727        }
11728
11729        jumpDrawablesToCurrentState();
11730
11731        clearAccessibilityFocus();
11732        if (isFocused()) {
11733            InputMethodManager imm = InputMethodManager.peekInstance();
11734            imm.focusIn(this);
11735        }
11736
11737        if (mDisplayList != null) {
11738            mDisplayList.clearDirty();
11739        }
11740    }
11741
11742    /**
11743     * Resolve all RTL related properties.
11744     *
11745     * @hide
11746     */
11747    public void resolveRtlPropertiesIfNeeded() {
11748        if (!needRtlPropertiesResolution()) return;
11749
11750        // Order is important here: LayoutDirection MUST be resolved first
11751        if (!isLayoutDirectionResolved()) {
11752            resolveLayoutDirection();
11753            resolveLayoutParams();
11754        }
11755        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11756        if (!isTextDirectionResolved()) {
11757            resolveTextDirection();
11758        }
11759        if (!isTextAlignmentResolved()) {
11760            resolveTextAlignment();
11761        }
11762        if (!isPaddingResolved()) {
11763            resolvePadding();
11764        }
11765        if (!isDrawablesResolved()) {
11766            resolveDrawables();
11767        }
11768        onRtlPropertiesChanged(getLayoutDirection());
11769    }
11770
11771    /**
11772     * Reset resolution of all RTL related properties.
11773     *
11774     * @hide
11775     */
11776    public void resetRtlProperties() {
11777        resetResolvedLayoutDirection();
11778        resetResolvedTextDirection();
11779        resetResolvedTextAlignment();
11780        resetResolvedPadding();
11781        resetResolvedDrawables();
11782    }
11783
11784    /**
11785     * @see #onScreenStateChanged(int)
11786     */
11787    void dispatchScreenStateChanged(int screenState) {
11788        onScreenStateChanged(screenState);
11789    }
11790
11791    /**
11792     * This method is called whenever the state of the screen this view is
11793     * attached to changes. A state change will usually occurs when the screen
11794     * turns on or off (whether it happens automatically or the user does it
11795     * manually.)
11796     *
11797     * @param screenState The new state of the screen. Can be either
11798     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11799     */
11800    public void onScreenStateChanged(int screenState) {
11801    }
11802
11803    /**
11804     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11805     */
11806    private boolean hasRtlSupport() {
11807        return mContext.getApplicationInfo().hasRtlSupport();
11808    }
11809
11810    /**
11811     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11812     * RTL not supported)
11813     */
11814    private boolean isRtlCompatibilityMode() {
11815        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11816        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11817    }
11818
11819    /**
11820     * @return true if RTL properties need resolution.
11821     */
11822    private boolean needRtlPropertiesResolution() {
11823        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11824    }
11825
11826    /**
11827     * Called when any RTL property (layout direction or text direction or text alignment) has
11828     * been changed.
11829     *
11830     * Subclasses need to override this method to take care of cached information that depends on the
11831     * resolved layout direction, or to inform child views that inherit their layout direction.
11832     *
11833     * The default implementation does nothing.
11834     *
11835     * @param layoutDirection the direction of the layout
11836     *
11837     * @see #LAYOUT_DIRECTION_LTR
11838     * @see #LAYOUT_DIRECTION_RTL
11839     */
11840    public void onRtlPropertiesChanged(int layoutDirection) {
11841    }
11842
11843    /**
11844     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11845     * that the parent directionality can and will be resolved before its children.
11846     *
11847     * @return true if resolution has been done, false otherwise.
11848     *
11849     * @hide
11850     */
11851    public boolean resolveLayoutDirection() {
11852        // Clear any previous layout direction resolution
11853        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11854
11855        if (hasRtlSupport()) {
11856            // Set resolved depending on layout direction
11857            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11858                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11859                case LAYOUT_DIRECTION_INHERIT:
11860                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11861                    // later to get the correct resolved value
11862                    if (!canResolveLayoutDirection()) return false;
11863
11864                    // Parent has not yet resolved, LTR is still the default
11865                    if (!mParent.isLayoutDirectionResolved()) return false;
11866
11867                    if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11868                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11869                    }
11870                    break;
11871                case LAYOUT_DIRECTION_RTL:
11872                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11873                    break;
11874                case LAYOUT_DIRECTION_LOCALE:
11875                    if((LAYOUT_DIRECTION_RTL ==
11876                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11877                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11878                    }
11879                    break;
11880                default:
11881                    // Nothing to do, LTR by default
11882            }
11883        }
11884
11885        // Set to resolved
11886        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11887        return true;
11888    }
11889
11890    /**
11891     * Check if layout direction resolution can be done.
11892     *
11893     * @return true if layout direction resolution can be done otherwise return false.
11894     *
11895     * @hide
11896     */
11897    public boolean canResolveLayoutDirection() {
11898        switch (getRawLayoutDirection()) {
11899            case LAYOUT_DIRECTION_INHERIT:
11900                return (mParent != null) && mParent.canResolveLayoutDirection();
11901            default:
11902                return true;
11903        }
11904    }
11905
11906    /**
11907     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11908     * {@link #onMeasure(int, int)}.
11909     *
11910     * @hide
11911     */
11912    public void resetResolvedLayoutDirection() {
11913        // Reset the current resolved bits
11914        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11915    }
11916
11917    /**
11918     * @return true if the layout direction is inherited.
11919     *
11920     * @hide
11921     */
11922    public boolean isLayoutDirectionInherited() {
11923        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11924    }
11925
11926    /**
11927     * @return true if layout direction has been resolved.
11928     * @hide
11929     */
11930    public boolean isLayoutDirectionResolved() {
11931        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11932    }
11933
11934    /**
11935     * Return if padding has been resolved
11936     *
11937     * @hide
11938     */
11939    boolean isPaddingResolved() {
11940        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11941    }
11942
11943    /**
11944     * Resolve padding depending on layout direction.
11945     *
11946     * @hide
11947     */
11948    public void resolvePadding() {
11949        if (!isRtlCompatibilityMode()) {
11950            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11951            // If start / end padding are defined, they will be resolved (hence overriding) to
11952            // left / right or right / left depending on the resolved layout direction.
11953            // If start / end padding are not defined, use the left / right ones.
11954            int resolvedLayoutDirection = getLayoutDirection();
11955            // Set user padding to initial values ...
11956            mUserPaddingLeft = mUserPaddingLeftInitial;
11957            mUserPaddingRight = mUserPaddingRightInitial;
11958            // ... then resolve it.
11959            switch (resolvedLayoutDirection) {
11960                case LAYOUT_DIRECTION_RTL:
11961                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11962                        mUserPaddingRight = mUserPaddingStart;
11963                    }
11964                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11965                        mUserPaddingLeft = mUserPaddingEnd;
11966                    }
11967                    break;
11968                case LAYOUT_DIRECTION_LTR:
11969                default:
11970                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11971                        mUserPaddingLeft = mUserPaddingStart;
11972                    }
11973                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11974                        mUserPaddingRight = mUserPaddingEnd;
11975                    }
11976            }
11977
11978            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11979
11980            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11981                    mUserPaddingBottom);
11982            onRtlPropertiesChanged(resolvedLayoutDirection);
11983        }
11984
11985        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11986    }
11987
11988    /**
11989     * Reset the resolved layout direction.
11990     *
11991     * @hide
11992     */
11993    public void resetResolvedPadding() {
11994        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11995    }
11996
11997    /**
11998     * This is called when the view is detached from a window.  At this point it
11999     * no longer has a surface for drawing.
12000     *
12001     * @see #onAttachedToWindow()
12002     */
12003    protected void onDetachedFromWindow() {
12004        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12005
12006        removeUnsetPressCallback();
12007        removeLongPressCallback();
12008        removePerformClickCallback();
12009        removeSendViewScrolledAccessibilityEventCallback();
12010
12011        destroyDrawingCache();
12012
12013        destroyLayer(false);
12014
12015        if (mAttachInfo != null) {
12016            if (mDisplayList != null) {
12017                mDisplayList.markDirty();
12018                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12019            }
12020            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12021        } else {
12022            // Should never happen
12023            clearDisplayList();
12024        }
12025
12026        mCurrentAnimation = null;
12027
12028        resetAccessibilityStateChanged();
12029    }
12030
12031    /**
12032     * @return The number of times this view has been attached to a window
12033     */
12034    protected int getWindowAttachCount() {
12035        return mWindowAttachCount;
12036    }
12037
12038    /**
12039     * Retrieve a unique token identifying the window this view is attached to.
12040     * @return Return the window's token for use in
12041     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12042     */
12043    public IBinder getWindowToken() {
12044        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12045    }
12046
12047    /**
12048     * Retrieve the {@link WindowId} for the window this view is
12049     * currently attached to.
12050     */
12051    public WindowId getWindowId() {
12052        if (mAttachInfo == null) {
12053            return null;
12054        }
12055        if (mAttachInfo.mWindowId == null) {
12056            try {
12057                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12058                        mAttachInfo.mWindowToken);
12059                mAttachInfo.mWindowId = new WindowId(
12060                        mAttachInfo.mIWindowId);
12061            } catch (RemoteException e) {
12062            }
12063        }
12064        return mAttachInfo.mWindowId;
12065    }
12066
12067    /**
12068     * Retrieve a unique token identifying the top-level "real" window of
12069     * the window that this view is attached to.  That is, this is like
12070     * {@link #getWindowToken}, except if the window this view in is a panel
12071     * window (attached to another containing window), then the token of
12072     * the containing window is returned instead.
12073     *
12074     * @return Returns the associated window token, either
12075     * {@link #getWindowToken()} or the containing window's token.
12076     */
12077    public IBinder getApplicationWindowToken() {
12078        AttachInfo ai = mAttachInfo;
12079        if (ai != null) {
12080            IBinder appWindowToken = ai.mPanelParentWindowToken;
12081            if (appWindowToken == null) {
12082                appWindowToken = ai.mWindowToken;
12083            }
12084            return appWindowToken;
12085        }
12086        return null;
12087    }
12088
12089    /**
12090     * Gets the logical display to which the view's window has been attached.
12091     *
12092     * @return The logical display, or null if the view is not currently attached to a window.
12093     */
12094    public Display getDisplay() {
12095        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12096    }
12097
12098    /**
12099     * Retrieve private session object this view hierarchy is using to
12100     * communicate with the window manager.
12101     * @return the session object to communicate with the window manager
12102     */
12103    /*package*/ IWindowSession getWindowSession() {
12104        return mAttachInfo != null ? mAttachInfo.mSession : null;
12105    }
12106
12107    /**
12108     * @param info the {@link android.view.View.AttachInfo} to associated with
12109     *        this view
12110     */
12111    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12112        //System.out.println("Attached! " + this);
12113        mAttachInfo = info;
12114        if (mOverlay != null) {
12115            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12116        }
12117        mWindowAttachCount++;
12118        // We will need to evaluate the drawable state at least once.
12119        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12120        if (mFloatingTreeObserver != null) {
12121            info.mTreeObserver.merge(mFloatingTreeObserver);
12122            mFloatingTreeObserver = null;
12123        }
12124        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12125            mAttachInfo.mScrollContainers.add(this);
12126            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12127        }
12128        performCollectViewAttributes(mAttachInfo, visibility);
12129        onAttachedToWindow();
12130
12131        ListenerInfo li = mListenerInfo;
12132        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12133                li != null ? li.mOnAttachStateChangeListeners : null;
12134        if (listeners != null && listeners.size() > 0) {
12135            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12136            // perform the dispatching. The iterator is a safe guard against listeners that
12137            // could mutate the list by calling the various add/remove methods. This prevents
12138            // the array from being modified while we iterate it.
12139            for (OnAttachStateChangeListener listener : listeners) {
12140                listener.onViewAttachedToWindow(this);
12141            }
12142        }
12143
12144        int vis = info.mWindowVisibility;
12145        if (vis != GONE) {
12146            onWindowVisibilityChanged(vis);
12147        }
12148        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12149            // If nobody has evaluated the drawable state yet, then do it now.
12150            refreshDrawableState();
12151        }
12152        needGlobalAttributesUpdate(false);
12153    }
12154
12155    void dispatchDetachedFromWindow() {
12156        AttachInfo info = mAttachInfo;
12157        if (info != null) {
12158            int vis = info.mWindowVisibility;
12159            if (vis != GONE) {
12160                onWindowVisibilityChanged(GONE);
12161            }
12162        }
12163
12164        onDetachedFromWindow();
12165
12166        ListenerInfo li = mListenerInfo;
12167        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12168                li != null ? li.mOnAttachStateChangeListeners : null;
12169        if (listeners != null && listeners.size() > 0) {
12170            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12171            // perform the dispatching. The iterator is a safe guard against listeners that
12172            // could mutate the list by calling the various add/remove methods. This prevents
12173            // the array from being modified while we iterate it.
12174            for (OnAttachStateChangeListener listener : listeners) {
12175                listener.onViewDetachedFromWindow(this);
12176            }
12177        }
12178
12179        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12180            mAttachInfo.mScrollContainers.remove(this);
12181            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12182        }
12183
12184        mAttachInfo = null;
12185        if (mOverlay != null) {
12186            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12187        }
12188    }
12189
12190    /**
12191     * Store this view hierarchy's frozen state into the given container.
12192     *
12193     * @param container The SparseArray in which to save the view's state.
12194     *
12195     * @see #restoreHierarchyState(android.util.SparseArray)
12196     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12197     * @see #onSaveInstanceState()
12198     */
12199    public void saveHierarchyState(SparseArray<Parcelable> container) {
12200        dispatchSaveInstanceState(container);
12201    }
12202
12203    /**
12204     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12205     * this view and its children. May be overridden to modify how freezing happens to a
12206     * view's children; for example, some views may want to not store state for their children.
12207     *
12208     * @param container The SparseArray in which to save the view's state.
12209     *
12210     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12211     * @see #saveHierarchyState(android.util.SparseArray)
12212     * @see #onSaveInstanceState()
12213     */
12214    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12215        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12216            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12217            Parcelable state = onSaveInstanceState();
12218            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12219                throw new IllegalStateException(
12220                        "Derived class did not call super.onSaveInstanceState()");
12221            }
12222            if (state != null) {
12223                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12224                // + ": " + state);
12225                container.put(mID, state);
12226            }
12227        }
12228    }
12229
12230    /**
12231     * Hook allowing a view to generate a representation of its internal state
12232     * that can later be used to create a new instance with that same state.
12233     * This state should only contain information that is not persistent or can
12234     * not be reconstructed later. For example, you will never store your
12235     * current position on screen because that will be computed again when a
12236     * new instance of the view is placed in its view hierarchy.
12237     * <p>
12238     * Some examples of things you may store here: the current cursor position
12239     * in a text view (but usually not the text itself since that is stored in a
12240     * content provider or other persistent storage), the currently selected
12241     * item in a list view.
12242     *
12243     * @return Returns a Parcelable object containing the view's current dynamic
12244     *         state, or null if there is nothing interesting to save. The
12245     *         default implementation returns null.
12246     * @see #onRestoreInstanceState(android.os.Parcelable)
12247     * @see #saveHierarchyState(android.util.SparseArray)
12248     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12249     * @see #setSaveEnabled(boolean)
12250     */
12251    protected Parcelable onSaveInstanceState() {
12252        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12253        return BaseSavedState.EMPTY_STATE;
12254    }
12255
12256    /**
12257     * Restore this view hierarchy's frozen state from the given container.
12258     *
12259     * @param container The SparseArray which holds previously frozen states.
12260     *
12261     * @see #saveHierarchyState(android.util.SparseArray)
12262     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12263     * @see #onRestoreInstanceState(android.os.Parcelable)
12264     */
12265    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12266        dispatchRestoreInstanceState(container);
12267    }
12268
12269    /**
12270     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12271     * state for this view and its children. May be overridden to modify how restoring
12272     * happens to a view's children; for example, some views may want to not store state
12273     * for their children.
12274     *
12275     * @param container The SparseArray which holds previously saved state.
12276     *
12277     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12278     * @see #restoreHierarchyState(android.util.SparseArray)
12279     * @see #onRestoreInstanceState(android.os.Parcelable)
12280     */
12281    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12282        if (mID != NO_ID) {
12283            Parcelable state = container.get(mID);
12284            if (state != null) {
12285                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12286                // + ": " + state);
12287                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12288                onRestoreInstanceState(state);
12289                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12290                    throw new IllegalStateException(
12291                            "Derived class did not call super.onRestoreInstanceState()");
12292                }
12293            }
12294        }
12295    }
12296
12297    /**
12298     * Hook allowing a view to re-apply a representation of its internal state that had previously
12299     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12300     * null state.
12301     *
12302     * @param state The frozen state that had previously been returned by
12303     *        {@link #onSaveInstanceState}.
12304     *
12305     * @see #onSaveInstanceState()
12306     * @see #restoreHierarchyState(android.util.SparseArray)
12307     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12308     */
12309    protected void onRestoreInstanceState(Parcelable state) {
12310        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12311        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12312            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12313                    + "received " + state.getClass().toString() + " instead. This usually happens "
12314                    + "when two views of different type have the same id in the same hierarchy. "
12315                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12316                    + "other views do not use the same id.");
12317        }
12318    }
12319
12320    /**
12321     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12322     *
12323     * @return the drawing start time in milliseconds
12324     */
12325    public long getDrawingTime() {
12326        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12327    }
12328
12329    /**
12330     * <p>Enables or disables the duplication of the parent's state into this view. When
12331     * duplication is enabled, this view gets its drawable state from its parent rather
12332     * than from its own internal properties.</p>
12333     *
12334     * <p>Note: in the current implementation, setting this property to true after the
12335     * view was added to a ViewGroup might have no effect at all. This property should
12336     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12337     *
12338     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12339     * property is enabled, an exception will be thrown.</p>
12340     *
12341     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12342     * parent, these states should not be affected by this method.</p>
12343     *
12344     * @param enabled True to enable duplication of the parent's drawable state, false
12345     *                to disable it.
12346     *
12347     * @see #getDrawableState()
12348     * @see #isDuplicateParentStateEnabled()
12349     */
12350    public void setDuplicateParentStateEnabled(boolean enabled) {
12351        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12352    }
12353
12354    /**
12355     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12356     *
12357     * @return True if this view's drawable state is duplicated from the parent,
12358     *         false otherwise
12359     *
12360     * @see #getDrawableState()
12361     * @see #setDuplicateParentStateEnabled(boolean)
12362     */
12363    public boolean isDuplicateParentStateEnabled() {
12364        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12365    }
12366
12367    /**
12368     * <p>Specifies the type of layer backing this view. The layer can be
12369     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12370     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12371     *
12372     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12373     * instance that controls how the layer is composed on screen. The following
12374     * properties of the paint are taken into account when composing the layer:</p>
12375     * <ul>
12376     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12377     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12378     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12379     * </ul>
12380     *
12381     * <p>If this view has an alpha value set to < 1.0 by calling
12382     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12383     * by this view's alpha value.</p>
12384     *
12385     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12386     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12387     * for more information on when and how to use layers.</p>
12388     *
12389     * @param layerType The type of layer to use with this view, must be one of
12390     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12391     *        {@link #LAYER_TYPE_HARDWARE}
12392     * @param paint The paint used to compose the layer. This argument is optional
12393     *        and can be null. It is ignored when the layer type is
12394     *        {@link #LAYER_TYPE_NONE}
12395     *
12396     * @see #getLayerType()
12397     * @see #LAYER_TYPE_NONE
12398     * @see #LAYER_TYPE_SOFTWARE
12399     * @see #LAYER_TYPE_HARDWARE
12400     * @see #setAlpha(float)
12401     *
12402     * @attr ref android.R.styleable#View_layerType
12403     */
12404    public void setLayerType(int layerType, Paint paint) {
12405        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12406            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12407                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12408        }
12409
12410        if (layerType == mLayerType) {
12411            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12412                mLayerPaint = paint == null ? new Paint() : paint;
12413                invalidateParentCaches();
12414                invalidate(true);
12415            }
12416            return;
12417        }
12418
12419        // Destroy any previous software drawing cache if needed
12420        switch (mLayerType) {
12421            case LAYER_TYPE_HARDWARE:
12422                destroyLayer(false);
12423                // fall through - non-accelerated views may use software layer mechanism instead
12424            case LAYER_TYPE_SOFTWARE:
12425                destroyDrawingCache();
12426                break;
12427            default:
12428                break;
12429        }
12430
12431        mLayerType = layerType;
12432        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12433        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12434        mLocalDirtyRect = layerDisabled ? null : new Rect();
12435
12436        invalidateParentCaches();
12437        invalidate(true);
12438    }
12439
12440    /**
12441     * Updates the {@link Paint} object used with the current layer (used only if the current
12442     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12443     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12444     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12445     * ensure that the view gets redrawn immediately.
12446     *
12447     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12448     * instance that controls how the layer is composed on screen. The following
12449     * properties of the paint are taken into account when composing the layer:</p>
12450     * <ul>
12451     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12452     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12453     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12454     * </ul>
12455     *
12456     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12457     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12458     *
12459     * @param paint The paint used to compose the layer. This argument is optional
12460     *        and can be null. It is ignored when the layer type is
12461     *        {@link #LAYER_TYPE_NONE}
12462     *
12463     * @see #setLayerType(int, android.graphics.Paint)
12464     */
12465    public void setLayerPaint(Paint paint) {
12466        int layerType = getLayerType();
12467        if (layerType != LAYER_TYPE_NONE) {
12468            mLayerPaint = paint == null ? new Paint() : paint;
12469            if (layerType == LAYER_TYPE_HARDWARE) {
12470                HardwareLayer layer = getHardwareLayer();
12471                if (layer != null) {
12472                    layer.setLayerPaint(paint);
12473                }
12474                invalidateViewProperty(false, false);
12475            } else {
12476                invalidate();
12477            }
12478        }
12479    }
12480
12481    /**
12482     * Indicates whether this view has a static layer. A view with layer type
12483     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12484     * dynamic.
12485     */
12486    boolean hasStaticLayer() {
12487        return true;
12488    }
12489
12490    /**
12491     * Indicates what type of layer is currently associated with this view. By default
12492     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12493     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12494     * for more information on the different types of layers.
12495     *
12496     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12497     *         {@link #LAYER_TYPE_HARDWARE}
12498     *
12499     * @see #setLayerType(int, android.graphics.Paint)
12500     * @see #buildLayer()
12501     * @see #LAYER_TYPE_NONE
12502     * @see #LAYER_TYPE_SOFTWARE
12503     * @see #LAYER_TYPE_HARDWARE
12504     */
12505    public int getLayerType() {
12506        return mLayerType;
12507    }
12508
12509    /**
12510     * Forces this view's layer to be created and this view to be rendered
12511     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12512     * invoking this method will have no effect.
12513     *
12514     * This method can for instance be used to render a view into its layer before
12515     * starting an animation. If this view is complex, rendering into the layer
12516     * before starting the animation will avoid skipping frames.
12517     *
12518     * @throws IllegalStateException If this view is not attached to a window
12519     *
12520     * @see #setLayerType(int, android.graphics.Paint)
12521     */
12522    public void buildLayer() {
12523        if (mLayerType == LAYER_TYPE_NONE) return;
12524
12525        if (mAttachInfo == null) {
12526            throw new IllegalStateException("This view must be attached to a window first");
12527        }
12528
12529        switch (mLayerType) {
12530            case LAYER_TYPE_HARDWARE:
12531                if (mAttachInfo.mHardwareRenderer != null &&
12532                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12533                        mAttachInfo.mHardwareRenderer.validate()) {
12534                    getHardwareLayer();
12535                }
12536                break;
12537            case LAYER_TYPE_SOFTWARE:
12538                buildDrawingCache(true);
12539                break;
12540        }
12541    }
12542
12543    /**
12544     * <p>Returns a hardware layer that can be used to draw this view again
12545     * without executing its draw method.</p>
12546     *
12547     * @return A HardwareLayer ready to render, or null if an error occurred.
12548     */
12549    HardwareLayer getHardwareLayer() {
12550        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12551                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12552            return null;
12553        }
12554
12555        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12556
12557        final int width = mRight - mLeft;
12558        final int height = mBottom - mTop;
12559
12560        if (width == 0 || height == 0) {
12561            return null;
12562        }
12563
12564        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12565            if (mHardwareLayer == null) {
12566                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12567                        width, height, isOpaque());
12568                mLocalDirtyRect.set(0, 0, width, height);
12569            } else {
12570                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12571                    if (mHardwareLayer.resize(width, height)) {
12572                        mLocalDirtyRect.set(0, 0, width, height);
12573                    }
12574                }
12575
12576                // This should not be necessary but applications that change
12577                // the parameters of their background drawable without calling
12578                // this.setBackground(Drawable) can leave the view in a bad state
12579                // (for instance isOpaque() returns true, but the background is
12580                // not opaque.)
12581                computeOpaqueFlags();
12582
12583                final boolean opaque = isOpaque();
12584                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12585                    mHardwareLayer.setOpaque(opaque);
12586                    mLocalDirtyRect.set(0, 0, width, height);
12587                }
12588            }
12589
12590            // The layer is not valid if the underlying GPU resources cannot be allocated
12591            if (!mHardwareLayer.isValid()) {
12592                return null;
12593            }
12594
12595            mHardwareLayer.setLayerPaint(mLayerPaint);
12596            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12597            ViewRootImpl viewRoot = getViewRootImpl();
12598            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12599
12600            mLocalDirtyRect.setEmpty();
12601        }
12602
12603        return mHardwareLayer;
12604    }
12605
12606    /**
12607     * Destroys this View's hardware layer if possible.
12608     *
12609     * @return True if the layer was destroyed, false otherwise.
12610     *
12611     * @see #setLayerType(int, android.graphics.Paint)
12612     * @see #LAYER_TYPE_HARDWARE
12613     */
12614    boolean destroyLayer(boolean valid) {
12615        if (mHardwareLayer != null) {
12616            AttachInfo info = mAttachInfo;
12617            if (info != null && info.mHardwareRenderer != null &&
12618                    info.mHardwareRenderer.isEnabled() &&
12619                    (valid || info.mHardwareRenderer.validate())) {
12620                mHardwareLayer.destroy();
12621                mHardwareLayer = null;
12622
12623                if (mDisplayList != null) {
12624                    mDisplayList.reset();
12625                }
12626                invalidate(true);
12627                invalidateParentCaches();
12628            }
12629            return true;
12630        }
12631        return false;
12632    }
12633
12634    /**
12635     * Destroys all hardware rendering resources. This method is invoked
12636     * when the system needs to reclaim resources. Upon execution of this
12637     * method, you should free any OpenGL resources created by the view.
12638     *
12639     * Note: you <strong>must</strong> call
12640     * <code>super.destroyHardwareResources()</code> when overriding
12641     * this method.
12642     *
12643     * @hide
12644     */
12645    protected void destroyHardwareResources() {
12646        destroyLayer(true);
12647    }
12648
12649    /**
12650     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12651     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12652     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12653     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12654     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12655     * null.</p>
12656     *
12657     * <p>Enabling the drawing cache is similar to
12658     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12659     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12660     * drawing cache has no effect on rendering because the system uses a different mechanism
12661     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12662     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12663     * for information on how to enable software and hardware layers.</p>
12664     *
12665     * <p>This API can be used to manually generate
12666     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12667     * {@link #getDrawingCache()}.</p>
12668     *
12669     * @param enabled true to enable the drawing cache, false otherwise
12670     *
12671     * @see #isDrawingCacheEnabled()
12672     * @see #getDrawingCache()
12673     * @see #buildDrawingCache()
12674     * @see #setLayerType(int, android.graphics.Paint)
12675     */
12676    public void setDrawingCacheEnabled(boolean enabled) {
12677        mCachingFailed = false;
12678        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12679    }
12680
12681    /**
12682     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12683     *
12684     * @return true if the drawing cache is enabled
12685     *
12686     * @see #setDrawingCacheEnabled(boolean)
12687     * @see #getDrawingCache()
12688     */
12689    @ViewDebug.ExportedProperty(category = "drawing")
12690    public boolean isDrawingCacheEnabled() {
12691        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12692    }
12693
12694    /**
12695     * Debugging utility which recursively outputs the dirty state of a view and its
12696     * descendants.
12697     *
12698     * @hide
12699     */
12700    @SuppressWarnings({"UnusedDeclaration"})
12701    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12702        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12703                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12704                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12705                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12706        if (clear) {
12707            mPrivateFlags &= clearMask;
12708        }
12709        if (this instanceof ViewGroup) {
12710            ViewGroup parent = (ViewGroup) this;
12711            final int count = parent.getChildCount();
12712            for (int i = 0; i < count; i++) {
12713                final View child = parent.getChildAt(i);
12714                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12715            }
12716        }
12717    }
12718
12719    /**
12720     * This method is used by ViewGroup to cause its children to restore or recreate their
12721     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12722     * to recreate its own display list, which would happen if it went through the normal
12723     * draw/dispatchDraw mechanisms.
12724     *
12725     * @hide
12726     */
12727    protected void dispatchGetDisplayList() {}
12728
12729    /**
12730     * A view that is not attached or hardware accelerated cannot create a display list.
12731     * This method checks these conditions and returns the appropriate result.
12732     *
12733     * @return true if view has the ability to create a display list, false otherwise.
12734     *
12735     * @hide
12736     */
12737    public boolean canHaveDisplayList() {
12738        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12739    }
12740
12741    /**
12742     * @return The {@link HardwareRenderer} associated with that view or null if
12743     *         hardware rendering is not supported or this view is not attached
12744     *         to a window.
12745     *
12746     * @hide
12747     */
12748    public HardwareRenderer getHardwareRenderer() {
12749        if (mAttachInfo != null) {
12750            return mAttachInfo.mHardwareRenderer;
12751        }
12752        return null;
12753    }
12754
12755    /**
12756     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12757     * Otherwise, the same display list will be returned (after having been rendered into
12758     * along the way, depending on the invalidation state of the view).
12759     *
12760     * @param displayList The previous version of this displayList, could be null.
12761     * @param isLayer Whether the requester of the display list is a layer. If so,
12762     * the view will avoid creating a layer inside the resulting display list.
12763     * @return A new or reused DisplayList object.
12764     */
12765    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12766        if (!canHaveDisplayList()) {
12767            return null;
12768        }
12769
12770        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12771                displayList == null || !displayList.isValid() ||
12772                (!isLayer && mRecreateDisplayList))) {
12773            // Don't need to recreate the display list, just need to tell our
12774            // children to restore/recreate theirs
12775            if (displayList != null && displayList.isValid() &&
12776                    !isLayer && !mRecreateDisplayList) {
12777                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12778                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12779                dispatchGetDisplayList();
12780
12781                return displayList;
12782            }
12783
12784            if (!isLayer) {
12785                // If we got here, we're recreating it. Mark it as such to ensure that
12786                // we copy in child display lists into ours in drawChild()
12787                mRecreateDisplayList = true;
12788            }
12789            if (displayList == null) {
12790                final String name = getClass().getSimpleName();
12791                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12792                // If we're creating a new display list, make sure our parent gets invalidated
12793                // since they will need to recreate their display list to account for this
12794                // new child display list.
12795                invalidateParentCaches();
12796            }
12797
12798            boolean caching = false;
12799            int width = mRight - mLeft;
12800            int height = mBottom - mTop;
12801            int layerType = getLayerType();
12802
12803            final HardwareCanvas canvas = displayList.start(width, height);
12804
12805            try {
12806                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12807                    if (layerType == LAYER_TYPE_HARDWARE) {
12808                        final HardwareLayer layer = getHardwareLayer();
12809                        if (layer != null && layer.isValid()) {
12810                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12811                        } else {
12812                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12813                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12814                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12815                        }
12816                        caching = true;
12817                    } else {
12818                        buildDrawingCache(true);
12819                        Bitmap cache = getDrawingCache(true);
12820                        if (cache != null) {
12821                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12822                            caching = true;
12823                        }
12824                    }
12825                } else {
12826
12827                    computeScroll();
12828
12829                    canvas.translate(-mScrollX, -mScrollY);
12830                    if (!isLayer) {
12831                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12832                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12833                    }
12834
12835                    // Fast path for layouts with no backgrounds
12836                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12837                        dispatchDraw(canvas);
12838                        if (mOverlay != null && !mOverlay.isEmpty()) {
12839                            mOverlay.getOverlayView().draw(canvas);
12840                        }
12841                    } else {
12842                        draw(canvas);
12843                    }
12844                }
12845            } finally {
12846                displayList.end();
12847                displayList.setCaching(caching);
12848                if (isLayer) {
12849                    displayList.setLeftTopRightBottom(0, 0, width, height);
12850                } else {
12851                    setDisplayListProperties(displayList);
12852                }
12853            }
12854        } else if (!isLayer) {
12855            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12856            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12857        }
12858
12859        return displayList;
12860    }
12861
12862    /**
12863     * Get the DisplayList for the HardwareLayer
12864     *
12865     * @param layer The HardwareLayer whose DisplayList we want
12866     * @return A DisplayList fopr the specified HardwareLayer
12867     */
12868    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12869        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12870        layer.setDisplayList(displayList);
12871        return displayList;
12872    }
12873
12874
12875    /**
12876     * <p>Returns a display list that can be used to draw this view again
12877     * without executing its draw method.</p>
12878     *
12879     * @return A DisplayList ready to replay, or null if caching is not enabled.
12880     *
12881     * @hide
12882     */
12883    public DisplayList getDisplayList() {
12884        mDisplayList = getDisplayList(mDisplayList, false);
12885        return mDisplayList;
12886    }
12887
12888    private void clearDisplayList() {
12889        if (mDisplayList != null) {
12890            mDisplayList.clear();
12891        }
12892    }
12893
12894    /**
12895     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12896     *
12897     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12898     *
12899     * @see #getDrawingCache(boolean)
12900     */
12901    public Bitmap getDrawingCache() {
12902        return getDrawingCache(false);
12903    }
12904
12905    /**
12906     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12907     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12908     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12909     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12910     * request the drawing cache by calling this method and draw it on screen if the
12911     * returned bitmap is not null.</p>
12912     *
12913     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12914     * this method will create a bitmap of the same size as this view. Because this bitmap
12915     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12916     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12917     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12918     * size than the view. This implies that your application must be able to handle this
12919     * size.</p>
12920     *
12921     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12922     *        the current density of the screen when the application is in compatibility
12923     *        mode.
12924     *
12925     * @return A bitmap representing this view or null if cache is disabled.
12926     *
12927     * @see #setDrawingCacheEnabled(boolean)
12928     * @see #isDrawingCacheEnabled()
12929     * @see #buildDrawingCache(boolean)
12930     * @see #destroyDrawingCache()
12931     */
12932    public Bitmap getDrawingCache(boolean autoScale) {
12933        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12934            return null;
12935        }
12936        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12937            buildDrawingCache(autoScale);
12938        }
12939        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12940    }
12941
12942    /**
12943     * <p>Frees the resources used by the drawing cache. If you call
12944     * {@link #buildDrawingCache()} manually without calling
12945     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12946     * should cleanup the cache with this method afterwards.</p>
12947     *
12948     * @see #setDrawingCacheEnabled(boolean)
12949     * @see #buildDrawingCache()
12950     * @see #getDrawingCache()
12951     */
12952    public void destroyDrawingCache() {
12953        if (mDrawingCache != null) {
12954            mDrawingCache.recycle();
12955            mDrawingCache = null;
12956        }
12957        if (mUnscaledDrawingCache != null) {
12958            mUnscaledDrawingCache.recycle();
12959            mUnscaledDrawingCache = null;
12960        }
12961    }
12962
12963    /**
12964     * Setting a solid background color for the drawing cache's bitmaps will improve
12965     * performance and memory usage. Note, though that this should only be used if this
12966     * view will always be drawn on top of a solid color.
12967     *
12968     * @param color The background color to use for the drawing cache's bitmap
12969     *
12970     * @see #setDrawingCacheEnabled(boolean)
12971     * @see #buildDrawingCache()
12972     * @see #getDrawingCache()
12973     */
12974    public void setDrawingCacheBackgroundColor(int color) {
12975        if (color != mDrawingCacheBackgroundColor) {
12976            mDrawingCacheBackgroundColor = color;
12977            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12978        }
12979    }
12980
12981    /**
12982     * @see #setDrawingCacheBackgroundColor(int)
12983     *
12984     * @return The background color to used for the drawing cache's bitmap
12985     */
12986    public int getDrawingCacheBackgroundColor() {
12987        return mDrawingCacheBackgroundColor;
12988    }
12989
12990    /**
12991     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12992     *
12993     * @see #buildDrawingCache(boolean)
12994     */
12995    public void buildDrawingCache() {
12996        buildDrawingCache(false);
12997    }
12998
12999    /**
13000     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13001     *
13002     * <p>If you call {@link #buildDrawingCache()} manually without calling
13003     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13004     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13005     *
13006     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13007     * this method will create a bitmap of the same size as this view. Because this bitmap
13008     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13009     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13010     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13011     * size than the view. This implies that your application must be able to handle this
13012     * size.</p>
13013     *
13014     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13015     * you do not need the drawing cache bitmap, calling this method will increase memory
13016     * usage and cause the view to be rendered in software once, thus negatively impacting
13017     * performance.</p>
13018     *
13019     * @see #getDrawingCache()
13020     * @see #destroyDrawingCache()
13021     */
13022    public void buildDrawingCache(boolean autoScale) {
13023        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13024                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13025            mCachingFailed = false;
13026
13027            int width = mRight - mLeft;
13028            int height = mBottom - mTop;
13029
13030            final AttachInfo attachInfo = mAttachInfo;
13031            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13032
13033            if (autoScale && scalingRequired) {
13034                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13035                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13036            }
13037
13038            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13039            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13040            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13041
13042            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13043            final long drawingCacheSize =
13044                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13045            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13046                if (width > 0 && height > 0) {
13047                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13048                            + projectedBitmapSize + " bytes, only "
13049                            + drawingCacheSize + " available");
13050                }
13051                destroyDrawingCache();
13052                mCachingFailed = true;
13053                return;
13054            }
13055
13056            boolean clear = true;
13057            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13058
13059            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13060                Bitmap.Config quality;
13061                if (!opaque) {
13062                    // Never pick ARGB_4444 because it looks awful
13063                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13064                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13065                        case DRAWING_CACHE_QUALITY_AUTO:
13066                            quality = Bitmap.Config.ARGB_8888;
13067                            break;
13068                        case DRAWING_CACHE_QUALITY_LOW:
13069                            quality = Bitmap.Config.ARGB_8888;
13070                            break;
13071                        case DRAWING_CACHE_QUALITY_HIGH:
13072                            quality = Bitmap.Config.ARGB_8888;
13073                            break;
13074                        default:
13075                            quality = Bitmap.Config.ARGB_8888;
13076                            break;
13077                    }
13078                } else {
13079                    // Optimization for translucent windows
13080                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13081                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13082                }
13083
13084                // Try to cleanup memory
13085                if (bitmap != null) bitmap.recycle();
13086
13087                try {
13088                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13089                            width, height, quality);
13090                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13091                    if (autoScale) {
13092                        mDrawingCache = bitmap;
13093                    } else {
13094                        mUnscaledDrawingCache = bitmap;
13095                    }
13096                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13097                } catch (OutOfMemoryError e) {
13098                    // If there is not enough memory to create the bitmap cache, just
13099                    // ignore the issue as bitmap caches are not required to draw the
13100                    // view hierarchy
13101                    if (autoScale) {
13102                        mDrawingCache = null;
13103                    } else {
13104                        mUnscaledDrawingCache = null;
13105                    }
13106                    mCachingFailed = true;
13107                    return;
13108                }
13109
13110                clear = drawingCacheBackgroundColor != 0;
13111            }
13112
13113            Canvas canvas;
13114            if (attachInfo != null) {
13115                canvas = attachInfo.mCanvas;
13116                if (canvas == null) {
13117                    canvas = new Canvas();
13118                }
13119                canvas.setBitmap(bitmap);
13120                // Temporarily clobber the cached Canvas in case one of our children
13121                // is also using a drawing cache. Without this, the children would
13122                // steal the canvas by attaching their own bitmap to it and bad, bad
13123                // thing would happen (invisible views, corrupted drawings, etc.)
13124                attachInfo.mCanvas = null;
13125            } else {
13126                // This case should hopefully never or seldom happen
13127                canvas = new Canvas(bitmap);
13128            }
13129
13130            if (clear) {
13131                bitmap.eraseColor(drawingCacheBackgroundColor);
13132            }
13133
13134            computeScroll();
13135            final int restoreCount = canvas.save();
13136
13137            if (autoScale && scalingRequired) {
13138                final float scale = attachInfo.mApplicationScale;
13139                canvas.scale(scale, scale);
13140            }
13141
13142            canvas.translate(-mScrollX, -mScrollY);
13143
13144            mPrivateFlags |= PFLAG_DRAWN;
13145            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13146                    mLayerType != LAYER_TYPE_NONE) {
13147                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13148            }
13149
13150            // Fast path for layouts with no backgrounds
13151            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13152                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13153                dispatchDraw(canvas);
13154                if (mOverlay != null && !mOverlay.isEmpty()) {
13155                    mOverlay.getOverlayView().draw(canvas);
13156                }
13157            } else {
13158                draw(canvas);
13159            }
13160
13161            canvas.restoreToCount(restoreCount);
13162            canvas.setBitmap(null);
13163
13164            if (attachInfo != null) {
13165                // Restore the cached Canvas for our siblings
13166                attachInfo.mCanvas = canvas;
13167            }
13168        }
13169    }
13170
13171    /**
13172     * Create a snapshot of the view into a bitmap.  We should probably make
13173     * some form of this public, but should think about the API.
13174     */
13175    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13176        int width = mRight - mLeft;
13177        int height = mBottom - mTop;
13178
13179        final AttachInfo attachInfo = mAttachInfo;
13180        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13181        width = (int) ((width * scale) + 0.5f);
13182        height = (int) ((height * scale) + 0.5f);
13183
13184        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13185                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13186        if (bitmap == null) {
13187            throw new OutOfMemoryError();
13188        }
13189
13190        Resources resources = getResources();
13191        if (resources != null) {
13192            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13193        }
13194
13195        Canvas canvas;
13196        if (attachInfo != null) {
13197            canvas = attachInfo.mCanvas;
13198            if (canvas == null) {
13199                canvas = new Canvas();
13200            }
13201            canvas.setBitmap(bitmap);
13202            // Temporarily clobber the cached Canvas in case one of our children
13203            // is also using a drawing cache. Without this, the children would
13204            // steal the canvas by attaching their own bitmap to it and bad, bad
13205            // things would happen (invisible views, corrupted drawings, etc.)
13206            attachInfo.mCanvas = null;
13207        } else {
13208            // This case should hopefully never or seldom happen
13209            canvas = new Canvas(bitmap);
13210        }
13211
13212        if ((backgroundColor & 0xff000000) != 0) {
13213            bitmap.eraseColor(backgroundColor);
13214        }
13215
13216        computeScroll();
13217        final int restoreCount = canvas.save();
13218        canvas.scale(scale, scale);
13219        canvas.translate(-mScrollX, -mScrollY);
13220
13221        // Temporarily remove the dirty mask
13222        int flags = mPrivateFlags;
13223        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13224
13225        // Fast path for layouts with no backgrounds
13226        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13227            dispatchDraw(canvas);
13228        } else {
13229            draw(canvas);
13230        }
13231
13232        mPrivateFlags = flags;
13233
13234        canvas.restoreToCount(restoreCount);
13235        canvas.setBitmap(null);
13236
13237        if (attachInfo != null) {
13238            // Restore the cached Canvas for our siblings
13239            attachInfo.mCanvas = canvas;
13240        }
13241
13242        return bitmap;
13243    }
13244
13245    /**
13246     * Indicates whether this View is currently in edit mode. A View is usually
13247     * in edit mode when displayed within a developer tool. For instance, if
13248     * this View is being drawn by a visual user interface builder, this method
13249     * should return true.
13250     *
13251     * Subclasses should check the return value of this method to provide
13252     * different behaviors if their normal behavior might interfere with the
13253     * host environment. For instance: the class spawns a thread in its
13254     * constructor, the drawing code relies on device-specific features, etc.
13255     *
13256     * This method is usually checked in the drawing code of custom widgets.
13257     *
13258     * @return True if this View is in edit mode, false otherwise.
13259     */
13260    public boolean isInEditMode() {
13261        return false;
13262    }
13263
13264    /**
13265     * If the View draws content inside its padding and enables fading edges,
13266     * it needs to support padding offsets. Padding offsets are added to the
13267     * fading edges to extend the length of the fade so that it covers pixels
13268     * drawn inside the padding.
13269     *
13270     * Subclasses of this class should override this method if they need
13271     * to draw content inside the padding.
13272     *
13273     * @return True if padding offset must be applied, false otherwise.
13274     *
13275     * @see #getLeftPaddingOffset()
13276     * @see #getRightPaddingOffset()
13277     * @see #getTopPaddingOffset()
13278     * @see #getBottomPaddingOffset()
13279     *
13280     * @since CURRENT
13281     */
13282    protected boolean isPaddingOffsetRequired() {
13283        return false;
13284    }
13285
13286    /**
13287     * Amount by which to extend the left fading region. Called only when
13288     * {@link #isPaddingOffsetRequired()} returns true.
13289     *
13290     * @return The left padding offset in pixels.
13291     *
13292     * @see #isPaddingOffsetRequired()
13293     *
13294     * @since CURRENT
13295     */
13296    protected int getLeftPaddingOffset() {
13297        return 0;
13298    }
13299
13300    /**
13301     * Amount by which to extend the right fading region. Called only when
13302     * {@link #isPaddingOffsetRequired()} returns true.
13303     *
13304     * @return The right padding offset in pixels.
13305     *
13306     * @see #isPaddingOffsetRequired()
13307     *
13308     * @since CURRENT
13309     */
13310    protected int getRightPaddingOffset() {
13311        return 0;
13312    }
13313
13314    /**
13315     * Amount by which to extend the top fading region. Called only when
13316     * {@link #isPaddingOffsetRequired()} returns true.
13317     *
13318     * @return The top padding offset in pixels.
13319     *
13320     * @see #isPaddingOffsetRequired()
13321     *
13322     * @since CURRENT
13323     */
13324    protected int getTopPaddingOffset() {
13325        return 0;
13326    }
13327
13328    /**
13329     * Amount by which to extend the bottom fading region. Called only when
13330     * {@link #isPaddingOffsetRequired()} returns true.
13331     *
13332     * @return The bottom padding offset in pixels.
13333     *
13334     * @see #isPaddingOffsetRequired()
13335     *
13336     * @since CURRENT
13337     */
13338    protected int getBottomPaddingOffset() {
13339        return 0;
13340    }
13341
13342    /**
13343     * @hide
13344     * @param offsetRequired
13345     */
13346    protected int getFadeTop(boolean offsetRequired) {
13347        int top = mPaddingTop;
13348        if (offsetRequired) top += getTopPaddingOffset();
13349        return top;
13350    }
13351
13352    /**
13353     * @hide
13354     * @param offsetRequired
13355     */
13356    protected int getFadeHeight(boolean offsetRequired) {
13357        int padding = mPaddingTop;
13358        if (offsetRequired) padding += getTopPaddingOffset();
13359        return mBottom - mTop - mPaddingBottom - padding;
13360    }
13361
13362    /**
13363     * <p>Indicates whether this view is attached to a hardware accelerated
13364     * window or not.</p>
13365     *
13366     * <p>Even if this method returns true, it does not mean that every call
13367     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13368     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13369     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13370     * window is hardware accelerated,
13371     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13372     * return false, and this method will return true.</p>
13373     *
13374     * @return True if the view is attached to a window and the window is
13375     *         hardware accelerated; false in any other case.
13376     */
13377    public boolean isHardwareAccelerated() {
13378        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13379    }
13380
13381    /**
13382     * Sets a rectangular area on this view to which the view will be clipped
13383     * when it is drawn. Setting the value to null will remove the clip bounds
13384     * and the view will draw normally, using its full bounds.
13385     *
13386     * @param clipBounds The rectangular area, in the local coordinates of
13387     * this view, to which future drawing operations will be clipped.
13388     */
13389    public void setClipBounds(Rect clipBounds) {
13390        if (clipBounds != null) {
13391            if (clipBounds.equals(mClipBounds)) {
13392                return;
13393            }
13394            if (mClipBounds == null) {
13395                invalidate();
13396                mClipBounds = new Rect(clipBounds);
13397            } else {
13398                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13399                        Math.min(mClipBounds.top, clipBounds.top),
13400                        Math.max(mClipBounds.right, clipBounds.right),
13401                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13402                mClipBounds.set(clipBounds);
13403            }
13404        } else {
13405            if (mClipBounds != null) {
13406                invalidate();
13407                mClipBounds = null;
13408            }
13409        }
13410    }
13411
13412    /**
13413     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13414     *
13415     * @return A copy of the current clip bounds if clip bounds are set,
13416     * otherwise null.
13417     */
13418    public Rect getClipBounds() {
13419        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13420    }
13421
13422    /**
13423     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13424     * case of an active Animation being run on the view.
13425     */
13426    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13427            Animation a, boolean scalingRequired) {
13428        Transformation invalidationTransform;
13429        final int flags = parent.mGroupFlags;
13430        final boolean initialized = a.isInitialized();
13431        if (!initialized) {
13432            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13433            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13434            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13435            onAnimationStart();
13436        }
13437
13438        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13439        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13440            if (parent.mInvalidationTransformation == null) {
13441                parent.mInvalidationTransformation = new Transformation();
13442            }
13443            invalidationTransform = parent.mInvalidationTransformation;
13444            a.getTransformation(drawingTime, invalidationTransform, 1f);
13445        } else {
13446            invalidationTransform = parent.mChildTransformation;
13447        }
13448
13449        if (more) {
13450            if (!a.willChangeBounds()) {
13451                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13452                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13453                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13454                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13455                    // The child need to draw an animation, potentially offscreen, so
13456                    // make sure we do not cancel invalidate requests
13457                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13458                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13459                }
13460            } else {
13461                if (parent.mInvalidateRegion == null) {
13462                    parent.mInvalidateRegion = new RectF();
13463                }
13464                final RectF region = parent.mInvalidateRegion;
13465                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13466                        invalidationTransform);
13467
13468                // The child need to draw an animation, potentially offscreen, so
13469                // make sure we do not cancel invalidate requests
13470                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13471
13472                final int left = mLeft + (int) region.left;
13473                final int top = mTop + (int) region.top;
13474                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13475                        top + (int) (region.height() + .5f));
13476            }
13477        }
13478        return more;
13479    }
13480
13481    /**
13482     * This method is called by getDisplayList() when a display list is created or re-rendered.
13483     * It sets or resets the current value of all properties on that display list (resetting is
13484     * necessary when a display list is being re-created, because we need to make sure that
13485     * previously-set transform values
13486     */
13487    void setDisplayListProperties(DisplayList displayList) {
13488        if (displayList != null) {
13489            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13490            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13491            if (mParent instanceof ViewGroup) {
13492                displayList.setClipToBounds(
13493                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13494            }
13495            float alpha = 1;
13496            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13497                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13498                ViewGroup parentVG = (ViewGroup) mParent;
13499                final boolean hasTransform =
13500                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13501                if (hasTransform) {
13502                    Transformation transform = parentVG.mChildTransformation;
13503                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13504                    if (transformType != Transformation.TYPE_IDENTITY) {
13505                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13506                            alpha = transform.getAlpha();
13507                        }
13508                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13509                            displayList.setMatrix(transform.getMatrix());
13510                        }
13511                    }
13512                }
13513            }
13514            if (mTransformationInfo != null) {
13515                alpha *= mTransformationInfo.mAlpha;
13516                if (alpha < 1) {
13517                    final int multipliedAlpha = (int) (255 * alpha);
13518                    if (onSetAlpha(multipliedAlpha)) {
13519                        alpha = 1;
13520                    }
13521                }
13522                displayList.setTransformationInfo(alpha,
13523                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13524                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13525                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13526                        mTransformationInfo.mScaleY);
13527                if (mTransformationInfo.mCamera == null) {
13528                    mTransformationInfo.mCamera = new Camera();
13529                    mTransformationInfo.matrix3D = new Matrix();
13530                }
13531                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13532                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13533                    displayList.setPivotX(getPivotX());
13534                    displayList.setPivotY(getPivotY());
13535                }
13536            } else if (alpha < 1) {
13537                displayList.setAlpha(alpha);
13538            }
13539        }
13540    }
13541
13542    /**
13543     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13544     * This draw() method is an implementation detail and is not intended to be overridden or
13545     * to be called from anywhere else other than ViewGroup.drawChild().
13546     */
13547    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13548        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13549        boolean more = false;
13550        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13551        final int flags = parent.mGroupFlags;
13552
13553        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13554            parent.mChildTransformation.clear();
13555            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13556        }
13557
13558        Transformation transformToApply = null;
13559        boolean concatMatrix = false;
13560
13561        boolean scalingRequired = false;
13562        boolean caching;
13563        int layerType = getLayerType();
13564
13565        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13566        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13567                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13568            caching = true;
13569            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13570            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13571        } else {
13572            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13573        }
13574
13575        final Animation a = getAnimation();
13576        if (a != null) {
13577            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13578            concatMatrix = a.willChangeTransformationMatrix();
13579            if (concatMatrix) {
13580                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13581            }
13582            transformToApply = parent.mChildTransformation;
13583        } else {
13584            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13585                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13586                // No longer animating: clear out old animation matrix
13587                mDisplayList.setAnimationMatrix(null);
13588                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13589            }
13590            if (!useDisplayListProperties &&
13591                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13592                final boolean hasTransform =
13593                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13594                if (hasTransform) {
13595                    final int transformType = parent.mChildTransformation.getTransformationType();
13596                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13597                            parent.mChildTransformation : null;
13598                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13599                }
13600            }
13601        }
13602
13603        concatMatrix |= !childHasIdentityMatrix;
13604
13605        // Sets the flag as early as possible to allow draw() implementations
13606        // to call invalidate() successfully when doing animations
13607        mPrivateFlags |= PFLAG_DRAWN;
13608
13609        if (!concatMatrix &&
13610                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13611                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13612                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13613                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13614            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13615            return more;
13616        }
13617        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13618
13619        if (hardwareAccelerated) {
13620            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13621            // retain the flag's value temporarily in the mRecreateDisplayList flag
13622            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13623            mPrivateFlags &= ~PFLAG_INVALIDATED;
13624        }
13625
13626        DisplayList displayList = null;
13627        Bitmap cache = null;
13628        boolean hasDisplayList = false;
13629        if (caching) {
13630            if (!hardwareAccelerated) {
13631                if (layerType != LAYER_TYPE_NONE) {
13632                    layerType = LAYER_TYPE_SOFTWARE;
13633                    buildDrawingCache(true);
13634                }
13635                cache = getDrawingCache(true);
13636            } else {
13637                switch (layerType) {
13638                    case LAYER_TYPE_SOFTWARE:
13639                        if (useDisplayListProperties) {
13640                            hasDisplayList = canHaveDisplayList();
13641                        } else {
13642                            buildDrawingCache(true);
13643                            cache = getDrawingCache(true);
13644                        }
13645                        break;
13646                    case LAYER_TYPE_HARDWARE:
13647                        if (useDisplayListProperties) {
13648                            hasDisplayList = canHaveDisplayList();
13649                        }
13650                        break;
13651                    case LAYER_TYPE_NONE:
13652                        // Delay getting the display list until animation-driven alpha values are
13653                        // set up and possibly passed on to the view
13654                        hasDisplayList = canHaveDisplayList();
13655                        break;
13656                }
13657            }
13658        }
13659        useDisplayListProperties &= hasDisplayList;
13660        if (useDisplayListProperties) {
13661            displayList = getDisplayList();
13662            if (!displayList.isValid()) {
13663                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13664                // to getDisplayList(), the display list will be marked invalid and we should not
13665                // try to use it again.
13666                displayList = null;
13667                hasDisplayList = false;
13668                useDisplayListProperties = false;
13669            }
13670        }
13671
13672        int sx = 0;
13673        int sy = 0;
13674        if (!hasDisplayList) {
13675            computeScroll();
13676            sx = mScrollX;
13677            sy = mScrollY;
13678        }
13679
13680        final boolean hasNoCache = cache == null || hasDisplayList;
13681        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13682                layerType != LAYER_TYPE_HARDWARE;
13683
13684        int restoreTo = -1;
13685        if (!useDisplayListProperties || transformToApply != null) {
13686            restoreTo = canvas.save();
13687        }
13688        if (offsetForScroll) {
13689            canvas.translate(mLeft - sx, mTop - sy);
13690        } else {
13691            if (!useDisplayListProperties) {
13692                canvas.translate(mLeft, mTop);
13693            }
13694            if (scalingRequired) {
13695                if (useDisplayListProperties) {
13696                    // TODO: Might not need this if we put everything inside the DL
13697                    restoreTo = canvas.save();
13698                }
13699                // mAttachInfo cannot be null, otherwise scalingRequired == false
13700                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13701                canvas.scale(scale, scale);
13702            }
13703        }
13704
13705        float alpha = useDisplayListProperties ? 1 : getAlpha();
13706        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13707                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13708            if (transformToApply != null || !childHasIdentityMatrix) {
13709                int transX = 0;
13710                int transY = 0;
13711
13712                if (offsetForScroll) {
13713                    transX = -sx;
13714                    transY = -sy;
13715                }
13716
13717                if (transformToApply != null) {
13718                    if (concatMatrix) {
13719                        if (useDisplayListProperties) {
13720                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13721                        } else {
13722                            // Undo the scroll translation, apply the transformation matrix,
13723                            // then redo the scroll translate to get the correct result.
13724                            canvas.translate(-transX, -transY);
13725                            canvas.concat(transformToApply.getMatrix());
13726                            canvas.translate(transX, transY);
13727                        }
13728                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13729                    }
13730
13731                    float transformAlpha = transformToApply.getAlpha();
13732                    if (transformAlpha < 1) {
13733                        alpha *= transformAlpha;
13734                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13735                    }
13736                }
13737
13738                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13739                    canvas.translate(-transX, -transY);
13740                    canvas.concat(getMatrix());
13741                    canvas.translate(transX, transY);
13742                }
13743            }
13744
13745            // Deal with alpha if it is or used to be <1
13746            if (alpha < 1 ||
13747                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13748                if (alpha < 1) {
13749                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13750                } else {
13751                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13752                }
13753                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13754                if (hasNoCache) {
13755                    final int multipliedAlpha = (int) (255 * alpha);
13756                    if (!onSetAlpha(multipliedAlpha)) {
13757                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13758                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13759                                layerType != LAYER_TYPE_NONE) {
13760                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13761                        }
13762                        if (useDisplayListProperties) {
13763                            displayList.setAlpha(alpha * getAlpha());
13764                        } else  if (layerType == LAYER_TYPE_NONE) {
13765                            final int scrollX = hasDisplayList ? 0 : sx;
13766                            final int scrollY = hasDisplayList ? 0 : sy;
13767                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13768                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13769                        }
13770                    } else {
13771                        // Alpha is handled by the child directly, clobber the layer's alpha
13772                        mPrivateFlags |= PFLAG_ALPHA_SET;
13773                    }
13774                }
13775            }
13776        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13777            onSetAlpha(255);
13778            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13779        }
13780
13781        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13782                !useDisplayListProperties && layerType == LAYER_TYPE_NONE) {
13783            if (offsetForScroll) {
13784                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13785            } else {
13786                if (!scalingRequired || cache == null) {
13787                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13788                } else {
13789                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13790                }
13791            }
13792        }
13793
13794        if (!useDisplayListProperties && hasDisplayList) {
13795            displayList = getDisplayList();
13796            if (!displayList.isValid()) {
13797                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13798                // to getDisplayList(), the display list will be marked invalid and we should not
13799                // try to use it again.
13800                displayList = null;
13801                hasDisplayList = false;
13802            }
13803        }
13804
13805        if (hasNoCache) {
13806            boolean layerRendered = false;
13807            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13808                final HardwareLayer layer = getHardwareLayer();
13809                if (layer != null && layer.isValid()) {
13810                    mLayerPaint.setAlpha((int) (alpha * 255));
13811                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13812                    layerRendered = true;
13813                } else {
13814                    final int scrollX = hasDisplayList ? 0 : sx;
13815                    final int scrollY = hasDisplayList ? 0 : sy;
13816                    canvas.saveLayer(scrollX, scrollY,
13817                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13818                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13819                }
13820            }
13821
13822            if (!layerRendered) {
13823                if (!hasDisplayList) {
13824                    // Fast path for layouts with no backgrounds
13825                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13826                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13827                        dispatchDraw(canvas);
13828                    } else {
13829                        draw(canvas);
13830                    }
13831                } else {
13832                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13833                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13834                }
13835            }
13836        } else if (cache != null) {
13837            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13838            Paint cachePaint;
13839
13840            if (layerType == LAYER_TYPE_NONE) {
13841                cachePaint = parent.mCachePaint;
13842                if (cachePaint == null) {
13843                    cachePaint = new Paint();
13844                    cachePaint.setDither(false);
13845                    parent.mCachePaint = cachePaint;
13846                }
13847                if (alpha < 1) {
13848                    cachePaint.setAlpha((int) (alpha * 255));
13849                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13850                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13851                    cachePaint.setAlpha(255);
13852                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13853                }
13854            } else {
13855                cachePaint = mLayerPaint;
13856                cachePaint.setAlpha((int) (alpha * 255));
13857            }
13858            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13859        }
13860
13861        if (restoreTo >= 0) {
13862            canvas.restoreToCount(restoreTo);
13863        }
13864
13865        if (a != null && !more) {
13866            if (!hardwareAccelerated && !a.getFillAfter()) {
13867                onSetAlpha(255);
13868            }
13869            parent.finishAnimatingView(this, a);
13870        }
13871
13872        if (more && hardwareAccelerated) {
13873            // invalidation is the trigger to recreate display lists, so if we're using
13874            // display lists to render, force an invalidate to allow the animation to
13875            // continue drawing another frame
13876            parent.invalidate(true);
13877            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13878                // alpha animations should cause the child to recreate its display list
13879                invalidate(true);
13880            }
13881        }
13882
13883        mRecreateDisplayList = false;
13884
13885        return more;
13886    }
13887
13888    /**
13889     * Manually render this view (and all of its children) to the given Canvas.
13890     * The view must have already done a full layout before this function is
13891     * called.  When implementing a view, implement
13892     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13893     * If you do need to override this method, call the superclass version.
13894     *
13895     * @param canvas The Canvas to which the View is rendered.
13896     */
13897    public void draw(Canvas canvas) {
13898        if (mClipBounds != null) {
13899            canvas.clipRect(mClipBounds);
13900        }
13901        final int privateFlags = mPrivateFlags;
13902        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13903                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13904        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13905
13906        /*
13907         * Draw traversal performs several drawing steps which must be executed
13908         * in the appropriate order:
13909         *
13910         *      1. Draw the background
13911         *      2. If necessary, save the canvas' layers to prepare for fading
13912         *      3. Draw view's content
13913         *      4. Draw children
13914         *      5. If necessary, draw the fading edges and restore layers
13915         *      6. Draw decorations (scrollbars for instance)
13916         */
13917
13918        // Step 1, draw the background, if needed
13919        int saveCount;
13920
13921        if (!dirtyOpaque) {
13922            final Drawable background = mBackground;
13923            if (background != null) {
13924                final int scrollX = mScrollX;
13925                final int scrollY = mScrollY;
13926
13927                if (mBackgroundSizeChanged) {
13928                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13929                    mBackgroundSizeChanged = false;
13930                }
13931
13932                if ((scrollX | scrollY) == 0) {
13933                    background.draw(canvas);
13934                } else {
13935                    canvas.translate(scrollX, scrollY);
13936                    background.draw(canvas);
13937                    canvas.translate(-scrollX, -scrollY);
13938                }
13939            }
13940        }
13941
13942        // skip step 2 & 5 if possible (common case)
13943        final int viewFlags = mViewFlags;
13944        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13945        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13946        if (!verticalEdges && !horizontalEdges) {
13947            // Step 3, draw the content
13948            if (!dirtyOpaque) onDraw(canvas);
13949
13950            // Step 4, draw the children
13951            dispatchDraw(canvas);
13952
13953            // Step 6, draw decorations (scrollbars)
13954            onDrawScrollBars(canvas);
13955
13956            if (mOverlay != null && !mOverlay.isEmpty()) {
13957                mOverlay.getOverlayView().dispatchDraw(canvas);
13958            }
13959
13960            // we're done...
13961            return;
13962        }
13963
13964        /*
13965         * Here we do the full fledged routine...
13966         * (this is an uncommon case where speed matters less,
13967         * this is why we repeat some of the tests that have been
13968         * done above)
13969         */
13970
13971        boolean drawTop = false;
13972        boolean drawBottom = false;
13973        boolean drawLeft = false;
13974        boolean drawRight = false;
13975
13976        float topFadeStrength = 0.0f;
13977        float bottomFadeStrength = 0.0f;
13978        float leftFadeStrength = 0.0f;
13979        float rightFadeStrength = 0.0f;
13980
13981        // Step 2, save the canvas' layers
13982        int paddingLeft = mPaddingLeft;
13983
13984        final boolean offsetRequired = isPaddingOffsetRequired();
13985        if (offsetRequired) {
13986            paddingLeft += getLeftPaddingOffset();
13987        }
13988
13989        int left = mScrollX + paddingLeft;
13990        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13991        int top = mScrollY + getFadeTop(offsetRequired);
13992        int bottom = top + getFadeHeight(offsetRequired);
13993
13994        if (offsetRequired) {
13995            right += getRightPaddingOffset();
13996            bottom += getBottomPaddingOffset();
13997        }
13998
13999        final ScrollabilityCache scrollabilityCache = mScrollCache;
14000        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14001        int length = (int) fadeHeight;
14002
14003        // clip the fade length if top and bottom fades overlap
14004        // overlapping fades produce odd-looking artifacts
14005        if (verticalEdges && (top + length > bottom - length)) {
14006            length = (bottom - top) / 2;
14007        }
14008
14009        // also clip horizontal fades if necessary
14010        if (horizontalEdges && (left + length > right - length)) {
14011            length = (right - left) / 2;
14012        }
14013
14014        if (verticalEdges) {
14015            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14016            drawTop = topFadeStrength * fadeHeight > 1.0f;
14017            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14018            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14019        }
14020
14021        if (horizontalEdges) {
14022            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14023            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14024            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14025            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14026        }
14027
14028        saveCount = canvas.getSaveCount();
14029
14030        int solidColor = getSolidColor();
14031        if (solidColor == 0) {
14032            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14033
14034            if (drawTop) {
14035                canvas.saveLayer(left, top, right, top + length, null, flags);
14036            }
14037
14038            if (drawBottom) {
14039                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14040            }
14041
14042            if (drawLeft) {
14043                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14044            }
14045
14046            if (drawRight) {
14047                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14048            }
14049        } else {
14050            scrollabilityCache.setFadeColor(solidColor);
14051        }
14052
14053        // Step 3, draw the content
14054        if (!dirtyOpaque) onDraw(canvas);
14055
14056        // Step 4, draw the children
14057        dispatchDraw(canvas);
14058
14059        // Step 5, draw the fade effect and restore layers
14060        final Paint p = scrollabilityCache.paint;
14061        final Matrix matrix = scrollabilityCache.matrix;
14062        final Shader fade = scrollabilityCache.shader;
14063
14064        if (drawTop) {
14065            matrix.setScale(1, fadeHeight * topFadeStrength);
14066            matrix.postTranslate(left, top);
14067            fade.setLocalMatrix(matrix);
14068            canvas.drawRect(left, top, right, top + length, p);
14069        }
14070
14071        if (drawBottom) {
14072            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14073            matrix.postRotate(180);
14074            matrix.postTranslate(left, bottom);
14075            fade.setLocalMatrix(matrix);
14076            canvas.drawRect(left, bottom - length, right, bottom, p);
14077        }
14078
14079        if (drawLeft) {
14080            matrix.setScale(1, fadeHeight * leftFadeStrength);
14081            matrix.postRotate(-90);
14082            matrix.postTranslate(left, top);
14083            fade.setLocalMatrix(matrix);
14084            canvas.drawRect(left, top, left + length, bottom, p);
14085        }
14086
14087        if (drawRight) {
14088            matrix.setScale(1, fadeHeight * rightFadeStrength);
14089            matrix.postRotate(90);
14090            matrix.postTranslate(right, top);
14091            fade.setLocalMatrix(matrix);
14092            canvas.drawRect(right - length, top, right, bottom, p);
14093        }
14094
14095        canvas.restoreToCount(saveCount);
14096
14097        // Step 6, draw decorations (scrollbars)
14098        onDrawScrollBars(canvas);
14099
14100        if (mOverlay != null && !mOverlay.isEmpty()) {
14101            mOverlay.getOverlayView().dispatchDraw(canvas);
14102        }
14103    }
14104
14105    /**
14106     * Returns the overlay for this view, creating it if it does not yet exist.
14107     * Adding drawables to the overlay will cause them to be displayed whenever
14108     * the view itself is redrawn. Objects in the overlay should be actively
14109     * managed: remove them when they should not be displayed anymore. The
14110     * overlay will always have the same size as its host view.
14111     *
14112     * <p>Note: Overlays do not currently work correctly with {@link
14113     * SurfaceView} or {@link TextureView}; contents in overlays for these
14114     * types of views may not display correctly.</p>
14115     *
14116     * @return The ViewOverlay object for this view.
14117     * @see ViewOverlay
14118     */
14119    public ViewOverlay getOverlay() {
14120        if (mOverlay == null) {
14121            mOverlay = new ViewOverlay(mContext, this);
14122        }
14123        return mOverlay;
14124    }
14125
14126    /**
14127     * Override this if your view is known to always be drawn on top of a solid color background,
14128     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14129     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14130     * should be set to 0xFF.
14131     *
14132     * @see #setVerticalFadingEdgeEnabled(boolean)
14133     * @see #setHorizontalFadingEdgeEnabled(boolean)
14134     *
14135     * @return The known solid color background for this view, or 0 if the color may vary
14136     */
14137    @ViewDebug.ExportedProperty(category = "drawing")
14138    public int getSolidColor() {
14139        return 0;
14140    }
14141
14142    /**
14143     * Build a human readable string representation of the specified view flags.
14144     *
14145     * @param flags the view flags to convert to a string
14146     * @return a String representing the supplied flags
14147     */
14148    private static String printFlags(int flags) {
14149        String output = "";
14150        int numFlags = 0;
14151        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14152            output += "TAKES_FOCUS";
14153            numFlags++;
14154        }
14155
14156        switch (flags & VISIBILITY_MASK) {
14157        case INVISIBLE:
14158            if (numFlags > 0) {
14159                output += " ";
14160            }
14161            output += "INVISIBLE";
14162            // USELESS HERE numFlags++;
14163            break;
14164        case GONE:
14165            if (numFlags > 0) {
14166                output += " ";
14167            }
14168            output += "GONE";
14169            // USELESS HERE numFlags++;
14170            break;
14171        default:
14172            break;
14173        }
14174        return output;
14175    }
14176
14177    /**
14178     * Build a human readable string representation of the specified private
14179     * view flags.
14180     *
14181     * @param privateFlags the private view flags to convert to a string
14182     * @return a String representing the supplied flags
14183     */
14184    private static String printPrivateFlags(int privateFlags) {
14185        String output = "";
14186        int numFlags = 0;
14187
14188        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14189            output += "WANTS_FOCUS";
14190            numFlags++;
14191        }
14192
14193        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14194            if (numFlags > 0) {
14195                output += " ";
14196            }
14197            output += "FOCUSED";
14198            numFlags++;
14199        }
14200
14201        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14202            if (numFlags > 0) {
14203                output += " ";
14204            }
14205            output += "SELECTED";
14206            numFlags++;
14207        }
14208
14209        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14210            if (numFlags > 0) {
14211                output += " ";
14212            }
14213            output += "IS_ROOT_NAMESPACE";
14214            numFlags++;
14215        }
14216
14217        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14218            if (numFlags > 0) {
14219                output += " ";
14220            }
14221            output += "HAS_BOUNDS";
14222            numFlags++;
14223        }
14224
14225        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14226            if (numFlags > 0) {
14227                output += " ";
14228            }
14229            output += "DRAWN";
14230            // USELESS HERE numFlags++;
14231        }
14232        return output;
14233    }
14234
14235    /**
14236     * <p>Indicates whether or not this view's layout will be requested during
14237     * the next hierarchy layout pass.</p>
14238     *
14239     * @return true if the layout will be forced during next layout pass
14240     */
14241    public boolean isLayoutRequested() {
14242        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14243    }
14244
14245    /**
14246     * Return true if o is a ViewGroup that is laying out using optical bounds.
14247     * @hide
14248     */
14249    public static boolean isLayoutModeOptical(Object o) {
14250        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14251    }
14252
14253    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14254        Insets parentInsets = mParent instanceof View ?
14255                ((View) mParent).getOpticalInsets() : Insets.NONE;
14256        Insets childInsets = getOpticalInsets();
14257        return setFrame(
14258                left   + parentInsets.left - childInsets.left,
14259                top    + parentInsets.top  - childInsets.top,
14260                right  + parentInsets.left + childInsets.right,
14261                bottom + parentInsets.top  + childInsets.bottom);
14262    }
14263
14264    /**
14265     * Assign a size and position to a view and all of its
14266     * descendants
14267     *
14268     * <p>This is the second phase of the layout mechanism.
14269     * (The first is measuring). In this phase, each parent calls
14270     * layout on all of its children to position them.
14271     * This is typically done using the child measurements
14272     * that were stored in the measure pass().</p>
14273     *
14274     * <p>Derived classes should not override this method.
14275     * Derived classes with children should override
14276     * onLayout. In that method, they should
14277     * call layout on each of their children.</p>
14278     *
14279     * @param l Left position, relative to parent
14280     * @param t Top position, relative to parent
14281     * @param r Right position, relative to parent
14282     * @param b Bottom position, relative to parent
14283     */
14284    @SuppressWarnings({"unchecked"})
14285    public void layout(int l, int t, int r, int b) {
14286        int oldL = mLeft;
14287        int oldT = mTop;
14288        int oldB = mBottom;
14289        int oldR = mRight;
14290        boolean changed = isLayoutModeOptical(mParent) ?
14291                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14292        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14293            onLayout(changed, l, t, r, b);
14294            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14295
14296            ListenerInfo li = mListenerInfo;
14297            if (li != null && li.mOnLayoutChangeListeners != null) {
14298                ArrayList<OnLayoutChangeListener> listenersCopy =
14299                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14300                int numListeners = listenersCopy.size();
14301                for (int i = 0; i < numListeners; ++i) {
14302                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14303                }
14304            }
14305        }
14306        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14307    }
14308
14309    /**
14310     * Called from layout when this view should
14311     * assign a size and position to each of its children.
14312     *
14313     * Derived classes with children should override
14314     * this method and call layout on each of
14315     * their children.
14316     * @param changed This is a new size or position for this view
14317     * @param left Left position, relative to parent
14318     * @param top Top position, relative to parent
14319     * @param right Right position, relative to parent
14320     * @param bottom Bottom position, relative to parent
14321     */
14322    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14323    }
14324
14325    /**
14326     * Assign a size and position to this view.
14327     *
14328     * This is called from layout.
14329     *
14330     * @param left Left position, relative to parent
14331     * @param top Top position, relative to parent
14332     * @param right Right position, relative to parent
14333     * @param bottom Bottom position, relative to parent
14334     * @return true if the new size and position are different than the
14335     *         previous ones
14336     * {@hide}
14337     */
14338    protected boolean setFrame(int left, int top, int right, int bottom) {
14339        boolean changed = false;
14340
14341        if (DBG) {
14342            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14343                    + right + "," + bottom + ")");
14344        }
14345
14346        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14347            changed = true;
14348
14349            // Remember our drawn bit
14350            int drawn = mPrivateFlags & PFLAG_DRAWN;
14351
14352            int oldWidth = mRight - mLeft;
14353            int oldHeight = mBottom - mTop;
14354            int newWidth = right - left;
14355            int newHeight = bottom - top;
14356            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14357
14358            // Invalidate our old position
14359            invalidate(sizeChanged);
14360
14361            mLeft = left;
14362            mTop = top;
14363            mRight = right;
14364            mBottom = bottom;
14365            if (mDisplayList != null) {
14366                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14367            }
14368
14369            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14370
14371
14372            if (sizeChanged) {
14373                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14374                    // A change in dimension means an auto-centered pivot point changes, too
14375                    if (mTransformationInfo != null) {
14376                        mTransformationInfo.mMatrixDirty = true;
14377                    }
14378                }
14379                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14380            }
14381
14382            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14383                // If we are visible, force the DRAWN bit to on so that
14384                // this invalidate will go through (at least to our parent).
14385                // This is because someone may have invalidated this view
14386                // before this call to setFrame came in, thereby clearing
14387                // the DRAWN bit.
14388                mPrivateFlags |= PFLAG_DRAWN;
14389                invalidate(sizeChanged);
14390                // parent display list may need to be recreated based on a change in the bounds
14391                // of any child
14392                invalidateParentCaches();
14393            }
14394
14395            // Reset drawn bit to original value (invalidate turns it off)
14396            mPrivateFlags |= drawn;
14397
14398            mBackgroundSizeChanged = true;
14399        }
14400        return changed;
14401    }
14402
14403    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14404        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14405        if (mOverlay != null) {
14406            mOverlay.getOverlayView().setRight(newWidth);
14407            mOverlay.getOverlayView().setBottom(newHeight);
14408        }
14409    }
14410
14411    /**
14412     * Finalize inflating a view from XML.  This is called as the last phase
14413     * of inflation, after all child views have been added.
14414     *
14415     * <p>Even if the subclass overrides onFinishInflate, they should always be
14416     * sure to call the super method, so that we get called.
14417     */
14418    protected void onFinishInflate() {
14419    }
14420
14421    /**
14422     * Returns the resources associated with this view.
14423     *
14424     * @return Resources object.
14425     */
14426    public Resources getResources() {
14427        return mResources;
14428    }
14429
14430    /**
14431     * Invalidates the specified Drawable.
14432     *
14433     * @param drawable the drawable to invalidate
14434     */
14435    public void invalidateDrawable(Drawable drawable) {
14436        if (verifyDrawable(drawable)) {
14437            final Rect dirty = drawable.getBounds();
14438            final int scrollX = mScrollX;
14439            final int scrollY = mScrollY;
14440
14441            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14442                    dirty.right + scrollX, dirty.bottom + scrollY);
14443        }
14444    }
14445
14446    /**
14447     * Schedules an action on a drawable to occur at a specified time.
14448     *
14449     * @param who the recipient of the action
14450     * @param what the action to run on the drawable
14451     * @param when the time at which the action must occur. Uses the
14452     *        {@link SystemClock#uptimeMillis} timebase.
14453     */
14454    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14455        if (verifyDrawable(who) && what != null) {
14456            final long delay = when - SystemClock.uptimeMillis();
14457            if (mAttachInfo != null) {
14458                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14459                        Choreographer.CALLBACK_ANIMATION, what, who,
14460                        Choreographer.subtractFrameDelay(delay));
14461            } else {
14462                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14463            }
14464        }
14465    }
14466
14467    /**
14468     * Cancels a scheduled action on a drawable.
14469     *
14470     * @param who the recipient of the action
14471     * @param what the action to cancel
14472     */
14473    public void unscheduleDrawable(Drawable who, Runnable what) {
14474        if (verifyDrawable(who) && what != null) {
14475            if (mAttachInfo != null) {
14476                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14477                        Choreographer.CALLBACK_ANIMATION, what, who);
14478            } else {
14479                ViewRootImpl.getRunQueue().removeCallbacks(what);
14480            }
14481        }
14482    }
14483
14484    /**
14485     * Unschedule any events associated with the given Drawable.  This can be
14486     * used when selecting a new Drawable into a view, so that the previous
14487     * one is completely unscheduled.
14488     *
14489     * @param who The Drawable to unschedule.
14490     *
14491     * @see #drawableStateChanged
14492     */
14493    public void unscheduleDrawable(Drawable who) {
14494        if (mAttachInfo != null && who != null) {
14495            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14496                    Choreographer.CALLBACK_ANIMATION, null, who);
14497        }
14498    }
14499
14500    /**
14501     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14502     * that the View directionality can and will be resolved before its Drawables.
14503     *
14504     * Will call {@link View#onResolveDrawables} when resolution is done.
14505     *
14506     * @hide
14507     */
14508    protected void resolveDrawables() {
14509        if (canResolveLayoutDirection()) {
14510            if (mBackground != null) {
14511                mBackground.setLayoutDirection(getLayoutDirection());
14512            }
14513            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14514            onResolveDrawables(getLayoutDirection());
14515        }
14516    }
14517
14518    /**
14519     * Called when layout direction has been resolved.
14520     *
14521     * The default implementation does nothing.
14522     *
14523     * @param layoutDirection The resolved layout direction.
14524     *
14525     * @see #LAYOUT_DIRECTION_LTR
14526     * @see #LAYOUT_DIRECTION_RTL
14527     *
14528     * @hide
14529     */
14530    public void onResolveDrawables(int layoutDirection) {
14531    }
14532
14533    /**
14534     * @hide
14535     */
14536    protected void resetResolvedDrawables() {
14537        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14538    }
14539
14540    private boolean isDrawablesResolved() {
14541        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14542    }
14543
14544    /**
14545     * If your view subclass is displaying its own Drawable objects, it should
14546     * override this function and return true for any Drawable it is
14547     * displaying.  This allows animations for those drawables to be
14548     * scheduled.
14549     *
14550     * <p>Be sure to call through to the super class when overriding this
14551     * function.
14552     *
14553     * @param who The Drawable to verify.  Return true if it is one you are
14554     *            displaying, else return the result of calling through to the
14555     *            super class.
14556     *
14557     * @return boolean If true than the Drawable is being displayed in the
14558     *         view; else false and it is not allowed to animate.
14559     *
14560     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14561     * @see #drawableStateChanged()
14562     */
14563    protected boolean verifyDrawable(Drawable who) {
14564        return who == mBackground;
14565    }
14566
14567    /**
14568     * This function is called whenever the state of the view changes in such
14569     * a way that it impacts the state of drawables being shown.
14570     *
14571     * <p>Be sure to call through to the superclass when overriding this
14572     * function.
14573     *
14574     * @see Drawable#setState(int[])
14575     */
14576    protected void drawableStateChanged() {
14577        Drawable d = mBackground;
14578        if (d != null && d.isStateful()) {
14579            d.setState(getDrawableState());
14580        }
14581    }
14582
14583    /**
14584     * Call this to force a view to update its drawable state. This will cause
14585     * drawableStateChanged to be called on this view. Views that are interested
14586     * in the new state should call getDrawableState.
14587     *
14588     * @see #drawableStateChanged
14589     * @see #getDrawableState
14590     */
14591    public void refreshDrawableState() {
14592        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14593        drawableStateChanged();
14594
14595        ViewParent parent = mParent;
14596        if (parent != null) {
14597            parent.childDrawableStateChanged(this);
14598        }
14599    }
14600
14601    /**
14602     * Return an array of resource IDs of the drawable states representing the
14603     * current state of the view.
14604     *
14605     * @return The current drawable state
14606     *
14607     * @see Drawable#setState(int[])
14608     * @see #drawableStateChanged()
14609     * @see #onCreateDrawableState(int)
14610     */
14611    public final int[] getDrawableState() {
14612        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14613            return mDrawableState;
14614        } else {
14615            mDrawableState = onCreateDrawableState(0);
14616            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14617            return mDrawableState;
14618        }
14619    }
14620
14621    /**
14622     * Generate the new {@link android.graphics.drawable.Drawable} state for
14623     * this view. This is called by the view
14624     * system when the cached Drawable state is determined to be invalid.  To
14625     * retrieve the current state, you should use {@link #getDrawableState}.
14626     *
14627     * @param extraSpace if non-zero, this is the number of extra entries you
14628     * would like in the returned array in which you can place your own
14629     * states.
14630     *
14631     * @return Returns an array holding the current {@link Drawable} state of
14632     * the view.
14633     *
14634     * @see #mergeDrawableStates(int[], int[])
14635     */
14636    protected int[] onCreateDrawableState(int extraSpace) {
14637        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14638                mParent instanceof View) {
14639            return ((View) mParent).onCreateDrawableState(extraSpace);
14640        }
14641
14642        int[] drawableState;
14643
14644        int privateFlags = mPrivateFlags;
14645
14646        int viewStateIndex = 0;
14647        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14648        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14649        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14650        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14651        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14652        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14653        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14654                HardwareRenderer.isAvailable()) {
14655            // This is set if HW acceleration is requested, even if the current
14656            // process doesn't allow it.  This is just to allow app preview
14657            // windows to better match their app.
14658            viewStateIndex |= VIEW_STATE_ACCELERATED;
14659        }
14660        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14661
14662        final int privateFlags2 = mPrivateFlags2;
14663        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14664        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14665
14666        drawableState = VIEW_STATE_SETS[viewStateIndex];
14667
14668        //noinspection ConstantIfStatement
14669        if (false) {
14670            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14671            Log.i("View", toString()
14672                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14673                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14674                    + " fo=" + hasFocus()
14675                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14676                    + " wf=" + hasWindowFocus()
14677                    + ": " + Arrays.toString(drawableState));
14678        }
14679
14680        if (extraSpace == 0) {
14681            return drawableState;
14682        }
14683
14684        final int[] fullState;
14685        if (drawableState != null) {
14686            fullState = new int[drawableState.length + extraSpace];
14687            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14688        } else {
14689            fullState = new int[extraSpace];
14690        }
14691
14692        return fullState;
14693    }
14694
14695    /**
14696     * Merge your own state values in <var>additionalState</var> into the base
14697     * state values <var>baseState</var> that were returned by
14698     * {@link #onCreateDrawableState(int)}.
14699     *
14700     * @param baseState The base state values returned by
14701     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14702     * own additional state values.
14703     *
14704     * @param additionalState The additional state values you would like
14705     * added to <var>baseState</var>; this array is not modified.
14706     *
14707     * @return As a convenience, the <var>baseState</var> array you originally
14708     * passed into the function is returned.
14709     *
14710     * @see #onCreateDrawableState(int)
14711     */
14712    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14713        final int N = baseState.length;
14714        int i = N - 1;
14715        while (i >= 0 && baseState[i] == 0) {
14716            i--;
14717        }
14718        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14719        return baseState;
14720    }
14721
14722    /**
14723     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14724     * on all Drawable objects associated with this view.
14725     */
14726    public void jumpDrawablesToCurrentState() {
14727        if (mBackground != null) {
14728            mBackground.jumpToCurrentState();
14729        }
14730    }
14731
14732    /**
14733     * Sets the background color for this view.
14734     * @param color the color of the background
14735     */
14736    @RemotableViewMethod
14737    public void setBackgroundColor(int color) {
14738        if (mBackground instanceof ColorDrawable) {
14739            ((ColorDrawable) mBackground.mutate()).setColor(color);
14740            computeOpaqueFlags();
14741            mBackgroundResource = 0;
14742        } else {
14743            setBackground(new ColorDrawable(color));
14744        }
14745    }
14746
14747    /**
14748     * Set the background to a given resource. The resource should refer to
14749     * a Drawable object or 0 to remove the background.
14750     * @param resid The identifier of the resource.
14751     *
14752     * @attr ref android.R.styleable#View_background
14753     */
14754    @RemotableViewMethod
14755    public void setBackgroundResource(int resid) {
14756        if (resid != 0 && resid == mBackgroundResource) {
14757            return;
14758        }
14759
14760        Drawable d= null;
14761        if (resid != 0) {
14762            d = mResources.getDrawable(resid);
14763        }
14764        setBackground(d);
14765
14766        mBackgroundResource = resid;
14767    }
14768
14769    /**
14770     * Set the background to a given Drawable, or remove the background. If the
14771     * background has padding, this View's padding is set to the background's
14772     * padding. However, when a background is removed, this View's padding isn't
14773     * touched. If setting the padding is desired, please use
14774     * {@link #setPadding(int, int, int, int)}.
14775     *
14776     * @param background The Drawable to use as the background, or null to remove the
14777     *        background
14778     */
14779    public void setBackground(Drawable background) {
14780        //noinspection deprecation
14781        setBackgroundDrawable(background);
14782    }
14783
14784    /**
14785     * @deprecated use {@link #setBackground(Drawable)} instead
14786     */
14787    @Deprecated
14788    public void setBackgroundDrawable(Drawable background) {
14789        computeOpaqueFlags();
14790
14791        if (background == mBackground) {
14792            return;
14793        }
14794
14795        boolean requestLayout = false;
14796
14797        mBackgroundResource = 0;
14798
14799        /*
14800         * Regardless of whether we're setting a new background or not, we want
14801         * to clear the previous drawable.
14802         */
14803        if (mBackground != null) {
14804            mBackground.setCallback(null);
14805            unscheduleDrawable(mBackground);
14806        }
14807
14808        if (background != null) {
14809            Rect padding = sThreadLocal.get();
14810            if (padding == null) {
14811                padding = new Rect();
14812                sThreadLocal.set(padding);
14813            }
14814            resetResolvedDrawables();
14815            background.setLayoutDirection(getLayoutDirection());
14816            if (background.getPadding(padding)) {
14817                resetResolvedPadding();
14818                switch (background.getLayoutDirection()) {
14819                    case LAYOUT_DIRECTION_RTL:
14820                        mUserPaddingLeftInitial = padding.right;
14821                        mUserPaddingRightInitial = padding.left;
14822                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14823                        break;
14824                    case LAYOUT_DIRECTION_LTR:
14825                    default:
14826                        mUserPaddingLeftInitial = padding.left;
14827                        mUserPaddingRightInitial = padding.right;
14828                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14829                }
14830            }
14831
14832            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14833            // if it has a different minimum size, we should layout again
14834            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14835                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14836                requestLayout = true;
14837            }
14838
14839            background.setCallback(this);
14840            if (background.isStateful()) {
14841                background.setState(getDrawableState());
14842            }
14843            background.setVisible(getVisibility() == VISIBLE, false);
14844            mBackground = background;
14845
14846            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14847                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14848                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14849                requestLayout = true;
14850            }
14851        } else {
14852            /* Remove the background */
14853            mBackground = null;
14854
14855            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14856                /*
14857                 * This view ONLY drew the background before and we're removing
14858                 * the background, so now it won't draw anything
14859                 * (hence we SKIP_DRAW)
14860                 */
14861                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14862                mPrivateFlags |= PFLAG_SKIP_DRAW;
14863            }
14864
14865            /*
14866             * When the background is set, we try to apply its padding to this
14867             * View. When the background is removed, we don't touch this View's
14868             * padding. This is noted in the Javadocs. Hence, we don't need to
14869             * requestLayout(), the invalidate() below is sufficient.
14870             */
14871
14872            // The old background's minimum size could have affected this
14873            // View's layout, so let's requestLayout
14874            requestLayout = true;
14875        }
14876
14877        computeOpaqueFlags();
14878
14879        if (requestLayout) {
14880            requestLayout();
14881        }
14882
14883        mBackgroundSizeChanged = true;
14884        invalidate(true);
14885    }
14886
14887    /**
14888     * Gets the background drawable
14889     *
14890     * @return The drawable used as the background for this view, if any.
14891     *
14892     * @see #setBackground(Drawable)
14893     *
14894     * @attr ref android.R.styleable#View_background
14895     */
14896    public Drawable getBackground() {
14897        return mBackground;
14898    }
14899
14900    /**
14901     * Sets the padding. The view may add on the space required to display
14902     * the scrollbars, depending on the style and visibility of the scrollbars.
14903     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14904     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14905     * from the values set in this call.
14906     *
14907     * @attr ref android.R.styleable#View_padding
14908     * @attr ref android.R.styleable#View_paddingBottom
14909     * @attr ref android.R.styleable#View_paddingLeft
14910     * @attr ref android.R.styleable#View_paddingRight
14911     * @attr ref android.R.styleable#View_paddingTop
14912     * @param left the left padding in pixels
14913     * @param top the top padding in pixels
14914     * @param right the right padding in pixels
14915     * @param bottom the bottom padding in pixels
14916     */
14917    public void setPadding(int left, int top, int right, int bottom) {
14918        resetResolvedPadding();
14919
14920        mUserPaddingStart = UNDEFINED_PADDING;
14921        mUserPaddingEnd = UNDEFINED_PADDING;
14922
14923        mUserPaddingLeftInitial = left;
14924        mUserPaddingRightInitial = right;
14925
14926        internalSetPadding(left, top, right, bottom);
14927    }
14928
14929    /**
14930     * @hide
14931     */
14932    protected void internalSetPadding(int left, int top, int right, int bottom) {
14933        mUserPaddingLeft = left;
14934        mUserPaddingRight = right;
14935        mUserPaddingBottom = bottom;
14936
14937        final int viewFlags = mViewFlags;
14938        boolean changed = false;
14939
14940        // Common case is there are no scroll bars.
14941        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14942            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14943                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14944                        ? 0 : getVerticalScrollbarWidth();
14945                switch (mVerticalScrollbarPosition) {
14946                    case SCROLLBAR_POSITION_DEFAULT:
14947                        if (isLayoutRtl()) {
14948                            left += offset;
14949                        } else {
14950                            right += offset;
14951                        }
14952                        break;
14953                    case SCROLLBAR_POSITION_RIGHT:
14954                        right += offset;
14955                        break;
14956                    case SCROLLBAR_POSITION_LEFT:
14957                        left += offset;
14958                        break;
14959                }
14960            }
14961            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14962                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14963                        ? 0 : getHorizontalScrollbarHeight();
14964            }
14965        }
14966
14967        if (mPaddingLeft != left) {
14968            changed = true;
14969            mPaddingLeft = left;
14970        }
14971        if (mPaddingTop != top) {
14972            changed = true;
14973            mPaddingTop = top;
14974        }
14975        if (mPaddingRight != right) {
14976            changed = true;
14977            mPaddingRight = right;
14978        }
14979        if (mPaddingBottom != bottom) {
14980            changed = true;
14981            mPaddingBottom = bottom;
14982        }
14983
14984        if (changed) {
14985            requestLayout();
14986        }
14987    }
14988
14989    /**
14990     * Sets the relative padding. The view may add on the space required to display
14991     * the scrollbars, depending on the style and visibility of the scrollbars.
14992     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14993     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14994     * from the values set in this call.
14995     *
14996     * @attr ref android.R.styleable#View_padding
14997     * @attr ref android.R.styleable#View_paddingBottom
14998     * @attr ref android.R.styleable#View_paddingStart
14999     * @attr ref android.R.styleable#View_paddingEnd
15000     * @attr ref android.R.styleable#View_paddingTop
15001     * @param start the start padding in pixels
15002     * @param top the top padding in pixels
15003     * @param end the end padding in pixels
15004     * @param bottom the bottom padding in pixels
15005     */
15006    public void setPaddingRelative(int start, int top, int end, int bottom) {
15007        resetResolvedPadding();
15008
15009        mUserPaddingStart = start;
15010        mUserPaddingEnd = end;
15011
15012        switch(getLayoutDirection()) {
15013            case LAYOUT_DIRECTION_RTL:
15014                mUserPaddingLeftInitial = end;
15015                mUserPaddingRightInitial = start;
15016                internalSetPadding(end, top, start, bottom);
15017                break;
15018            case LAYOUT_DIRECTION_LTR:
15019            default:
15020                mUserPaddingLeftInitial = start;
15021                mUserPaddingRightInitial = end;
15022                internalSetPadding(start, top, end, bottom);
15023        }
15024    }
15025
15026    /**
15027     * Returns the top padding of this view.
15028     *
15029     * @return the top padding in pixels
15030     */
15031    public int getPaddingTop() {
15032        return mPaddingTop;
15033    }
15034
15035    /**
15036     * Returns the bottom padding of this view. If there are inset and enabled
15037     * scrollbars, this value may include the space required to display the
15038     * scrollbars as well.
15039     *
15040     * @return the bottom padding in pixels
15041     */
15042    public int getPaddingBottom() {
15043        return mPaddingBottom;
15044    }
15045
15046    /**
15047     * Returns the left padding of this view. If there are inset and enabled
15048     * scrollbars, this value may include the space required to display the
15049     * scrollbars as well.
15050     *
15051     * @return the left padding in pixels
15052     */
15053    public int getPaddingLeft() {
15054        if (!isPaddingResolved()) {
15055            resolvePadding();
15056        }
15057        return mPaddingLeft;
15058    }
15059
15060    /**
15061     * Returns the start padding of this view depending on its resolved layout direction.
15062     * If there are inset and enabled scrollbars, this value may include the space
15063     * required to display the scrollbars as well.
15064     *
15065     * @return the start padding in pixels
15066     */
15067    public int getPaddingStart() {
15068        if (!isPaddingResolved()) {
15069            resolvePadding();
15070        }
15071        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15072                mPaddingRight : mPaddingLeft;
15073    }
15074
15075    /**
15076     * Returns the right padding of this view. If there are inset and enabled
15077     * scrollbars, this value may include the space required to display the
15078     * scrollbars as well.
15079     *
15080     * @return the right padding in pixels
15081     */
15082    public int getPaddingRight() {
15083        if (!isPaddingResolved()) {
15084            resolvePadding();
15085        }
15086        return mPaddingRight;
15087    }
15088
15089    /**
15090     * Returns the end padding of this view depending on its resolved layout direction.
15091     * If there are inset and enabled scrollbars, this value may include the space
15092     * required to display the scrollbars as well.
15093     *
15094     * @return the end padding in pixels
15095     */
15096    public int getPaddingEnd() {
15097        if (!isPaddingResolved()) {
15098            resolvePadding();
15099        }
15100        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15101                mPaddingLeft : mPaddingRight;
15102    }
15103
15104    /**
15105     * Return if the padding as been set thru relative values
15106     * {@link #setPaddingRelative(int, int, int, int)} or thru
15107     * @attr ref android.R.styleable#View_paddingStart or
15108     * @attr ref android.R.styleable#View_paddingEnd
15109     *
15110     * @return true if the padding is relative or false if it is not.
15111     */
15112    public boolean isPaddingRelative() {
15113        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15114    }
15115
15116    Insets computeOpticalInsets() {
15117        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15118    }
15119
15120    /**
15121     * @hide
15122     */
15123    public void resetPaddingToInitialValues() {
15124        if (isRtlCompatibilityMode()) {
15125            mPaddingLeft = mUserPaddingLeftInitial;
15126            mPaddingRight = mUserPaddingRightInitial;
15127            return;
15128        }
15129        if (isLayoutRtl()) {
15130            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15131            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15132        } else {
15133            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15134            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15135        }
15136    }
15137
15138    /**
15139     * @hide
15140     */
15141    public Insets getOpticalInsets() {
15142        if (mLayoutInsets == null) {
15143            mLayoutInsets = computeOpticalInsets();
15144        }
15145        return mLayoutInsets;
15146    }
15147
15148    /**
15149     * Changes the selection state of this view. A view can be selected or not.
15150     * Note that selection is not the same as focus. Views are typically
15151     * selected in the context of an AdapterView like ListView or GridView;
15152     * the selected view is the view that is highlighted.
15153     *
15154     * @param selected true if the view must be selected, false otherwise
15155     */
15156    public void setSelected(boolean selected) {
15157        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15158            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15159            if (!selected) resetPressedState();
15160            invalidate(true);
15161            refreshDrawableState();
15162            dispatchSetSelected(selected);
15163            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
15164                notifyAccessibilityStateChanged();
15165            }
15166        }
15167    }
15168
15169    /**
15170     * Dispatch setSelected to all of this View's children.
15171     *
15172     * @see #setSelected(boolean)
15173     *
15174     * @param selected The new selected state
15175     */
15176    protected void dispatchSetSelected(boolean selected) {
15177    }
15178
15179    /**
15180     * Indicates the selection state of this view.
15181     *
15182     * @return true if the view is selected, false otherwise
15183     */
15184    @ViewDebug.ExportedProperty
15185    public boolean isSelected() {
15186        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15187    }
15188
15189    /**
15190     * Changes the activated state of this view. A view can be activated or not.
15191     * Note that activation is not the same as selection.  Selection is
15192     * a transient property, representing the view (hierarchy) the user is
15193     * currently interacting with.  Activation is a longer-term state that the
15194     * user can move views in and out of.  For example, in a list view with
15195     * single or multiple selection enabled, the views in the current selection
15196     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15197     * here.)  The activated state is propagated down to children of the view it
15198     * is set on.
15199     *
15200     * @param activated true if the view must be activated, false otherwise
15201     */
15202    public void setActivated(boolean activated) {
15203        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15204            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15205            invalidate(true);
15206            refreshDrawableState();
15207            dispatchSetActivated(activated);
15208        }
15209    }
15210
15211    /**
15212     * Dispatch setActivated to all of this View's children.
15213     *
15214     * @see #setActivated(boolean)
15215     *
15216     * @param activated The new activated state
15217     */
15218    protected void dispatchSetActivated(boolean activated) {
15219    }
15220
15221    /**
15222     * Indicates the activation state of this view.
15223     *
15224     * @return true if the view is activated, false otherwise
15225     */
15226    @ViewDebug.ExportedProperty
15227    public boolean isActivated() {
15228        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15229    }
15230
15231    /**
15232     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15233     * observer can be used to get notifications when global events, like
15234     * layout, happen.
15235     *
15236     * The returned ViewTreeObserver observer is not guaranteed to remain
15237     * valid for the lifetime of this View. If the caller of this method keeps
15238     * a long-lived reference to ViewTreeObserver, it should always check for
15239     * the return value of {@link ViewTreeObserver#isAlive()}.
15240     *
15241     * @return The ViewTreeObserver for this view's hierarchy.
15242     */
15243    public ViewTreeObserver getViewTreeObserver() {
15244        if (mAttachInfo != null) {
15245            return mAttachInfo.mTreeObserver;
15246        }
15247        if (mFloatingTreeObserver == null) {
15248            mFloatingTreeObserver = new ViewTreeObserver();
15249        }
15250        return mFloatingTreeObserver;
15251    }
15252
15253    /**
15254     * <p>Finds the topmost view in the current view hierarchy.</p>
15255     *
15256     * @return the topmost view containing this view
15257     */
15258    public View getRootView() {
15259        if (mAttachInfo != null) {
15260            final View v = mAttachInfo.mRootView;
15261            if (v != null) {
15262                return v;
15263            }
15264        }
15265
15266        View parent = this;
15267
15268        while (parent.mParent != null && parent.mParent instanceof View) {
15269            parent = (View) parent.mParent;
15270        }
15271
15272        return parent;
15273    }
15274
15275    /**
15276     * <p>Computes the coordinates of this view on the screen. The argument
15277     * must be an array of two integers. After the method returns, the array
15278     * contains the x and y location in that order.</p>
15279     *
15280     * @param location an array of two integers in which to hold the coordinates
15281     */
15282    public void getLocationOnScreen(int[] location) {
15283        getLocationInWindow(location);
15284
15285        final AttachInfo info = mAttachInfo;
15286        if (info != null) {
15287            location[0] += info.mWindowLeft;
15288            location[1] += info.mWindowTop;
15289        }
15290    }
15291
15292    /**
15293     * <p>Computes the coordinates of this view in its window. The argument
15294     * must be an array of two integers. After the method returns, the array
15295     * contains the x and y location in that order.</p>
15296     *
15297     * @param location an array of two integers in which to hold the coordinates
15298     */
15299    public void getLocationInWindow(int[] location) {
15300        if (location == null || location.length < 2) {
15301            throw new IllegalArgumentException("location must be an array of two integers");
15302        }
15303
15304        if (mAttachInfo == null) {
15305            // When the view is not attached to a window, this method does not make sense
15306            location[0] = location[1] = 0;
15307            return;
15308        }
15309
15310        float[] position = mAttachInfo.mTmpTransformLocation;
15311        position[0] = position[1] = 0.0f;
15312
15313        if (!hasIdentityMatrix()) {
15314            getMatrix().mapPoints(position);
15315        }
15316
15317        position[0] += mLeft;
15318        position[1] += mTop;
15319
15320        ViewParent viewParent = mParent;
15321        while (viewParent instanceof View) {
15322            final View view = (View) viewParent;
15323
15324            position[0] -= view.mScrollX;
15325            position[1] -= view.mScrollY;
15326
15327            if (!view.hasIdentityMatrix()) {
15328                view.getMatrix().mapPoints(position);
15329            }
15330
15331            position[0] += view.mLeft;
15332            position[1] += view.mTop;
15333
15334            viewParent = view.mParent;
15335         }
15336
15337        if (viewParent instanceof ViewRootImpl) {
15338            // *cough*
15339            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15340            position[1] -= vr.mCurScrollY;
15341        }
15342
15343        location[0] = (int) (position[0] + 0.5f);
15344        location[1] = (int) (position[1] + 0.5f);
15345    }
15346
15347    /**
15348     * {@hide}
15349     * @param id the id of the view to be found
15350     * @return the view of the specified id, null if cannot be found
15351     */
15352    protected View findViewTraversal(int id) {
15353        if (id == mID) {
15354            return this;
15355        }
15356        return null;
15357    }
15358
15359    /**
15360     * {@hide}
15361     * @param tag the tag of the view to be found
15362     * @return the view of specified tag, null if cannot be found
15363     */
15364    protected View findViewWithTagTraversal(Object tag) {
15365        if (tag != null && tag.equals(mTag)) {
15366            return this;
15367        }
15368        return null;
15369    }
15370
15371    /**
15372     * {@hide}
15373     * @param predicate The predicate to evaluate.
15374     * @param childToSkip If not null, ignores this child during the recursive traversal.
15375     * @return The first view that matches the predicate or null.
15376     */
15377    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15378        if (predicate.apply(this)) {
15379            return this;
15380        }
15381        return null;
15382    }
15383
15384    /**
15385     * Look for a child view with the given id.  If this view has the given
15386     * id, return this view.
15387     *
15388     * @param id The id to search for.
15389     * @return The view that has the given id in the hierarchy or null
15390     */
15391    public final View findViewById(int id) {
15392        if (id < 0) {
15393            return null;
15394        }
15395        return findViewTraversal(id);
15396    }
15397
15398    /**
15399     * Finds a view by its unuque and stable accessibility id.
15400     *
15401     * @param accessibilityId The searched accessibility id.
15402     * @return The found view.
15403     */
15404    final View findViewByAccessibilityId(int accessibilityId) {
15405        if (accessibilityId < 0) {
15406            return null;
15407        }
15408        return findViewByAccessibilityIdTraversal(accessibilityId);
15409    }
15410
15411    /**
15412     * Performs the traversal to find a view by its unuque and stable accessibility id.
15413     *
15414     * <strong>Note:</strong>This method does not stop at the root namespace
15415     * boundary since the user can touch the screen at an arbitrary location
15416     * potentially crossing the root namespace bounday which will send an
15417     * accessibility event to accessibility services and they should be able
15418     * to obtain the event source. Also accessibility ids are guaranteed to be
15419     * unique in the window.
15420     *
15421     * @param accessibilityId The accessibility id.
15422     * @return The found view.
15423     */
15424    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15425        if (getAccessibilityViewId() == accessibilityId) {
15426            return this;
15427        }
15428        return null;
15429    }
15430
15431    /**
15432     * Look for a child view with the given tag.  If this view has the given
15433     * tag, return this view.
15434     *
15435     * @param tag The tag to search for, using "tag.equals(getTag())".
15436     * @return The View that has the given tag in the hierarchy or null
15437     */
15438    public final View findViewWithTag(Object tag) {
15439        if (tag == null) {
15440            return null;
15441        }
15442        return findViewWithTagTraversal(tag);
15443    }
15444
15445    /**
15446     * {@hide}
15447     * Look for a child view that matches the specified predicate.
15448     * If this view matches the predicate, return this view.
15449     *
15450     * @param predicate The predicate to evaluate.
15451     * @return The first view that matches the predicate or null.
15452     */
15453    public final View findViewByPredicate(Predicate<View> predicate) {
15454        return findViewByPredicateTraversal(predicate, null);
15455    }
15456
15457    /**
15458     * {@hide}
15459     * Look for a child view that matches the specified predicate,
15460     * starting with the specified view and its descendents and then
15461     * recusively searching the ancestors and siblings of that view
15462     * until this view is reached.
15463     *
15464     * This method is useful in cases where the predicate does not match
15465     * a single unique view (perhaps multiple views use the same id)
15466     * and we are trying to find the view that is "closest" in scope to the
15467     * starting view.
15468     *
15469     * @param start The view to start from.
15470     * @param predicate The predicate to evaluate.
15471     * @return The first view that matches the predicate or null.
15472     */
15473    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15474        View childToSkip = null;
15475        for (;;) {
15476            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15477            if (view != null || start == this) {
15478                return view;
15479            }
15480
15481            ViewParent parent = start.getParent();
15482            if (parent == null || !(parent instanceof View)) {
15483                return null;
15484            }
15485
15486            childToSkip = start;
15487            start = (View) parent;
15488        }
15489    }
15490
15491    /**
15492     * Sets the identifier for this view. The identifier does not have to be
15493     * unique in this view's hierarchy. The identifier should be a positive
15494     * number.
15495     *
15496     * @see #NO_ID
15497     * @see #getId()
15498     * @see #findViewById(int)
15499     *
15500     * @param id a number used to identify the view
15501     *
15502     * @attr ref android.R.styleable#View_id
15503     */
15504    public void setId(int id) {
15505        mID = id;
15506        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15507            mID = generateViewId();
15508        }
15509    }
15510
15511    /**
15512     * {@hide}
15513     *
15514     * @param isRoot true if the view belongs to the root namespace, false
15515     *        otherwise
15516     */
15517    public void setIsRootNamespace(boolean isRoot) {
15518        if (isRoot) {
15519            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15520        } else {
15521            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15522        }
15523    }
15524
15525    /**
15526     * {@hide}
15527     *
15528     * @return true if the view belongs to the root namespace, false otherwise
15529     */
15530    public boolean isRootNamespace() {
15531        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15532    }
15533
15534    /**
15535     * Returns this view's identifier.
15536     *
15537     * @return a positive integer used to identify the view or {@link #NO_ID}
15538     *         if the view has no ID
15539     *
15540     * @see #setId(int)
15541     * @see #findViewById(int)
15542     * @attr ref android.R.styleable#View_id
15543     */
15544    @ViewDebug.CapturedViewProperty
15545    public int getId() {
15546        return mID;
15547    }
15548
15549    /**
15550     * Returns this view's tag.
15551     *
15552     * @return the Object stored in this view as a tag
15553     *
15554     * @see #setTag(Object)
15555     * @see #getTag(int)
15556     */
15557    @ViewDebug.ExportedProperty
15558    public Object getTag() {
15559        return mTag;
15560    }
15561
15562    /**
15563     * Sets the tag associated with this view. A tag can be used to mark
15564     * a view in its hierarchy and does not have to be unique within the
15565     * hierarchy. Tags can also be used to store data within a view without
15566     * resorting to another data structure.
15567     *
15568     * @param tag an Object to tag the view with
15569     *
15570     * @see #getTag()
15571     * @see #setTag(int, Object)
15572     */
15573    public void setTag(final Object tag) {
15574        mTag = tag;
15575    }
15576
15577    /**
15578     * Returns the tag associated with this view and the specified key.
15579     *
15580     * @param key The key identifying the tag
15581     *
15582     * @return the Object stored in this view as a tag
15583     *
15584     * @see #setTag(int, Object)
15585     * @see #getTag()
15586     */
15587    public Object getTag(int key) {
15588        if (mKeyedTags != null) return mKeyedTags.get(key);
15589        return null;
15590    }
15591
15592    /**
15593     * Sets a tag associated with this view and a key. A tag can be used
15594     * to mark a view in its hierarchy and does not have to be unique within
15595     * the hierarchy. Tags can also be used to store data within a view
15596     * without resorting to another data structure.
15597     *
15598     * The specified key should be an id declared in the resources of the
15599     * application to ensure it is unique (see the <a
15600     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15601     * Keys identified as belonging to
15602     * the Android framework or not associated with any package will cause
15603     * an {@link IllegalArgumentException} to be thrown.
15604     *
15605     * @param key The key identifying the tag
15606     * @param tag An Object to tag the view with
15607     *
15608     * @throws IllegalArgumentException If they specified key is not valid
15609     *
15610     * @see #setTag(Object)
15611     * @see #getTag(int)
15612     */
15613    public void setTag(int key, final Object tag) {
15614        // If the package id is 0x00 or 0x01, it's either an undefined package
15615        // or a framework id
15616        if ((key >>> 24) < 2) {
15617            throw new IllegalArgumentException("The key must be an application-specific "
15618                    + "resource id.");
15619        }
15620
15621        setKeyedTag(key, tag);
15622    }
15623
15624    /**
15625     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15626     * framework id.
15627     *
15628     * @hide
15629     */
15630    public void setTagInternal(int key, Object tag) {
15631        if ((key >>> 24) != 0x1) {
15632            throw new IllegalArgumentException("The key must be a framework-specific "
15633                    + "resource id.");
15634        }
15635
15636        setKeyedTag(key, tag);
15637    }
15638
15639    private void setKeyedTag(int key, Object tag) {
15640        if (mKeyedTags == null) {
15641            mKeyedTags = new SparseArray<Object>();
15642        }
15643
15644        mKeyedTags.put(key, tag);
15645    }
15646
15647    /**
15648     * Prints information about this view in the log output, with the tag
15649     * {@link #VIEW_LOG_TAG}.
15650     *
15651     * @hide
15652     */
15653    public void debug() {
15654        debug(0);
15655    }
15656
15657    /**
15658     * Prints information about this view in the log output, with the tag
15659     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15660     * indentation defined by the <code>depth</code>.
15661     *
15662     * @param depth the indentation level
15663     *
15664     * @hide
15665     */
15666    protected void debug(int depth) {
15667        String output = debugIndent(depth - 1);
15668
15669        output += "+ " + this;
15670        int id = getId();
15671        if (id != -1) {
15672            output += " (id=" + id + ")";
15673        }
15674        Object tag = getTag();
15675        if (tag != null) {
15676            output += " (tag=" + tag + ")";
15677        }
15678        Log.d(VIEW_LOG_TAG, output);
15679
15680        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15681            output = debugIndent(depth) + " FOCUSED";
15682            Log.d(VIEW_LOG_TAG, output);
15683        }
15684
15685        output = debugIndent(depth);
15686        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15687                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15688                + "} ";
15689        Log.d(VIEW_LOG_TAG, output);
15690
15691        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15692                || mPaddingBottom != 0) {
15693            output = debugIndent(depth);
15694            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15695                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15696            Log.d(VIEW_LOG_TAG, output);
15697        }
15698
15699        output = debugIndent(depth);
15700        output += "mMeasureWidth=" + mMeasuredWidth +
15701                " mMeasureHeight=" + mMeasuredHeight;
15702        Log.d(VIEW_LOG_TAG, output);
15703
15704        output = debugIndent(depth);
15705        if (mLayoutParams == null) {
15706            output += "BAD! no layout params";
15707        } else {
15708            output = mLayoutParams.debug(output);
15709        }
15710        Log.d(VIEW_LOG_TAG, output);
15711
15712        output = debugIndent(depth);
15713        output += "flags={";
15714        output += View.printFlags(mViewFlags);
15715        output += "}";
15716        Log.d(VIEW_LOG_TAG, output);
15717
15718        output = debugIndent(depth);
15719        output += "privateFlags={";
15720        output += View.printPrivateFlags(mPrivateFlags);
15721        output += "}";
15722        Log.d(VIEW_LOG_TAG, output);
15723    }
15724
15725    /**
15726     * Creates a string of whitespaces used for indentation.
15727     *
15728     * @param depth the indentation level
15729     * @return a String containing (depth * 2 + 3) * 2 white spaces
15730     *
15731     * @hide
15732     */
15733    protected static String debugIndent(int depth) {
15734        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15735        for (int i = 0; i < (depth * 2) + 3; i++) {
15736            spaces.append(' ').append(' ');
15737        }
15738        return spaces.toString();
15739    }
15740
15741    /**
15742     * <p>Return the offset of the widget's text baseline from the widget's top
15743     * boundary. If this widget does not support baseline alignment, this
15744     * method returns -1. </p>
15745     *
15746     * @return the offset of the baseline within the widget's bounds or -1
15747     *         if baseline alignment is not supported
15748     */
15749    @ViewDebug.ExportedProperty(category = "layout")
15750    public int getBaseline() {
15751        return -1;
15752    }
15753
15754    /**
15755     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15756     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15757     * a layout pass.
15758     *
15759     * @return whether the view hierarchy is currently undergoing a layout pass
15760     */
15761    public boolean isInLayout() {
15762        ViewRootImpl viewRoot = getViewRootImpl();
15763        return (viewRoot != null && viewRoot.isInLayout());
15764    }
15765
15766    /**
15767     * Call this when something has changed which has invalidated the
15768     * layout of this view. This will schedule a layout pass of the view
15769     * tree. This should not be called while the view hierarchy is currently in a layout
15770     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15771     * end of the current layout pass (and then layout will run again) or after the current
15772     * frame is drawn and the next layout occurs.
15773     *
15774     * <p>Subclasses which override this method should call the superclass method to
15775     * handle possible request-during-layout errors correctly.</p>
15776     */
15777    public void requestLayout() {
15778        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15779            // Only trigger request-during-layout logic if this is the view requesting it,
15780            // not the views in its parent hierarchy
15781            ViewRootImpl viewRoot = getViewRootImpl();
15782            if (viewRoot != null && viewRoot.isInLayout()) {
15783                if (!viewRoot.requestLayoutDuringLayout(this)) {
15784                    return;
15785                }
15786            }
15787            mAttachInfo.mViewRequestingLayout = this;
15788        }
15789
15790        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15791        mPrivateFlags |= PFLAG_INVALIDATED;
15792
15793        if (mParent != null && !mParent.isLayoutRequested()) {
15794            mParent.requestLayout();
15795        }
15796        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15797            mAttachInfo.mViewRequestingLayout = null;
15798        }
15799    }
15800
15801    /**
15802     * Forces this view to be laid out during the next layout pass.
15803     * This method does not call requestLayout() or forceLayout()
15804     * on the parent.
15805     */
15806    public void forceLayout() {
15807        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15808        mPrivateFlags |= PFLAG_INVALIDATED;
15809    }
15810
15811    /**
15812     * <p>
15813     * This is called to find out how big a view should be. The parent
15814     * supplies constraint information in the width and height parameters.
15815     * </p>
15816     *
15817     * <p>
15818     * The actual measurement work of a view is performed in
15819     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15820     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15821     * </p>
15822     *
15823     *
15824     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15825     *        parent
15826     * @param heightMeasureSpec Vertical space requirements as imposed by the
15827     *        parent
15828     *
15829     * @see #onMeasure(int, int)
15830     */
15831    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15832        boolean optical = isLayoutModeOptical(this);
15833        if (optical != isLayoutModeOptical(mParent)) {
15834            Insets insets = getOpticalInsets();
15835            int oWidth  = insets.left + insets.right;
15836            int oHeight = insets.top  + insets.bottom;
15837            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15838            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15839        }
15840        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15841                widthMeasureSpec != mOldWidthMeasureSpec ||
15842                heightMeasureSpec != mOldHeightMeasureSpec) {
15843
15844            // first clears the measured dimension flag
15845            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15846
15847            resolveRtlPropertiesIfNeeded();
15848
15849            // measure ourselves, this should set the measured dimension flag back
15850            onMeasure(widthMeasureSpec, heightMeasureSpec);
15851
15852            // flag not set, setMeasuredDimension() was not invoked, we raise
15853            // an exception to warn the developer
15854            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15855                throw new IllegalStateException("onMeasure() did not set the"
15856                        + " measured dimension by calling"
15857                        + " setMeasuredDimension()");
15858            }
15859
15860            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15861        }
15862
15863        mOldWidthMeasureSpec = widthMeasureSpec;
15864        mOldHeightMeasureSpec = heightMeasureSpec;
15865    }
15866
15867    /**
15868     * <p>
15869     * Measure the view and its content to determine the measured width and the
15870     * measured height. This method is invoked by {@link #measure(int, int)} and
15871     * should be overriden by subclasses to provide accurate and efficient
15872     * measurement of their contents.
15873     * </p>
15874     *
15875     * <p>
15876     * <strong>CONTRACT:</strong> When overriding this method, you
15877     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15878     * measured width and height of this view. Failure to do so will trigger an
15879     * <code>IllegalStateException</code>, thrown by
15880     * {@link #measure(int, int)}. Calling the superclass'
15881     * {@link #onMeasure(int, int)} is a valid use.
15882     * </p>
15883     *
15884     * <p>
15885     * The base class implementation of measure defaults to the background size,
15886     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15887     * override {@link #onMeasure(int, int)} to provide better measurements of
15888     * their content.
15889     * </p>
15890     *
15891     * <p>
15892     * If this method is overridden, it is the subclass's responsibility to make
15893     * sure the measured height and width are at least the view's minimum height
15894     * and width ({@link #getSuggestedMinimumHeight()} and
15895     * {@link #getSuggestedMinimumWidth()}).
15896     * </p>
15897     *
15898     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15899     *                         The requirements are encoded with
15900     *                         {@link android.view.View.MeasureSpec}.
15901     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15902     *                         The requirements are encoded with
15903     *                         {@link android.view.View.MeasureSpec}.
15904     *
15905     * @see #getMeasuredWidth()
15906     * @see #getMeasuredHeight()
15907     * @see #setMeasuredDimension(int, int)
15908     * @see #getSuggestedMinimumHeight()
15909     * @see #getSuggestedMinimumWidth()
15910     * @see android.view.View.MeasureSpec#getMode(int)
15911     * @see android.view.View.MeasureSpec#getSize(int)
15912     */
15913    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15914        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15915                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15916    }
15917
15918    /**
15919     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15920     * measured width and measured height. Failing to do so will trigger an
15921     * exception at measurement time.</p>
15922     *
15923     * @param measuredWidth The measured width of this view.  May be a complex
15924     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15925     * {@link #MEASURED_STATE_TOO_SMALL}.
15926     * @param measuredHeight The measured height of this view.  May be a complex
15927     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15928     * {@link #MEASURED_STATE_TOO_SMALL}.
15929     */
15930    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15931        boolean optical = isLayoutModeOptical(this);
15932        if (optical != isLayoutModeOptical(mParent)) {
15933            Insets insets = getOpticalInsets();
15934            int opticalWidth  = insets.left + insets.right;
15935            int opticalHeight = insets.top  + insets.bottom;
15936
15937            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
15938            measuredHeight += optical ? opticalHeight : -opticalHeight;
15939        }
15940        mMeasuredWidth = measuredWidth;
15941        mMeasuredHeight = measuredHeight;
15942
15943        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15944    }
15945
15946    /**
15947     * Merge two states as returned by {@link #getMeasuredState()}.
15948     * @param curState The current state as returned from a view or the result
15949     * of combining multiple views.
15950     * @param newState The new view state to combine.
15951     * @return Returns a new integer reflecting the combination of the two
15952     * states.
15953     */
15954    public static int combineMeasuredStates(int curState, int newState) {
15955        return curState | newState;
15956    }
15957
15958    /**
15959     * Version of {@link #resolveSizeAndState(int, int, int)}
15960     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15961     */
15962    public static int resolveSize(int size, int measureSpec) {
15963        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15964    }
15965
15966    /**
15967     * Utility to reconcile a desired size and state, with constraints imposed
15968     * by a MeasureSpec.  Will take the desired size, unless a different size
15969     * is imposed by the constraints.  The returned value is a compound integer,
15970     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15971     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15972     * size is smaller than the size the view wants to be.
15973     *
15974     * @param size How big the view wants to be
15975     * @param measureSpec Constraints imposed by the parent
15976     * @return Size information bit mask as defined by
15977     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15978     */
15979    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15980        int result = size;
15981        int specMode = MeasureSpec.getMode(measureSpec);
15982        int specSize =  MeasureSpec.getSize(measureSpec);
15983        switch (specMode) {
15984        case MeasureSpec.UNSPECIFIED:
15985            result = size;
15986            break;
15987        case MeasureSpec.AT_MOST:
15988            if (specSize < size) {
15989                result = specSize | MEASURED_STATE_TOO_SMALL;
15990            } else {
15991                result = size;
15992            }
15993            break;
15994        case MeasureSpec.EXACTLY:
15995            result = specSize;
15996            break;
15997        }
15998        return result | (childMeasuredState&MEASURED_STATE_MASK);
15999    }
16000
16001    /**
16002     * Utility to return a default size. Uses the supplied size if the
16003     * MeasureSpec imposed no constraints. Will get larger if allowed
16004     * by the MeasureSpec.
16005     *
16006     * @param size Default size for this view
16007     * @param measureSpec Constraints imposed by the parent
16008     * @return The size this view should be.
16009     */
16010    public static int getDefaultSize(int size, int measureSpec) {
16011        int result = size;
16012        int specMode = MeasureSpec.getMode(measureSpec);
16013        int specSize = MeasureSpec.getSize(measureSpec);
16014
16015        switch (specMode) {
16016        case MeasureSpec.UNSPECIFIED:
16017            result = size;
16018            break;
16019        case MeasureSpec.AT_MOST:
16020        case MeasureSpec.EXACTLY:
16021            result = specSize;
16022            break;
16023        }
16024        return result;
16025    }
16026
16027    /**
16028     * Returns the suggested minimum height that the view should use. This
16029     * returns the maximum of the view's minimum height
16030     * and the background's minimum height
16031     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16032     * <p>
16033     * When being used in {@link #onMeasure(int, int)}, the caller should still
16034     * ensure the returned height is within the requirements of the parent.
16035     *
16036     * @return The suggested minimum height of the view.
16037     */
16038    protected int getSuggestedMinimumHeight() {
16039        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16040
16041    }
16042
16043    /**
16044     * Returns the suggested minimum width that the view should use. This
16045     * returns the maximum of the view's minimum width)
16046     * and the background's minimum width
16047     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16048     * <p>
16049     * When being used in {@link #onMeasure(int, int)}, the caller should still
16050     * ensure the returned width is within the requirements of the parent.
16051     *
16052     * @return The suggested minimum width of the view.
16053     */
16054    protected int getSuggestedMinimumWidth() {
16055        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16056    }
16057
16058    /**
16059     * Returns the minimum height of the view.
16060     *
16061     * @return the minimum height the view will try to be.
16062     *
16063     * @see #setMinimumHeight(int)
16064     *
16065     * @attr ref android.R.styleable#View_minHeight
16066     */
16067    public int getMinimumHeight() {
16068        return mMinHeight;
16069    }
16070
16071    /**
16072     * Sets the minimum height of the view. It is not guaranteed the view will
16073     * be able to achieve this minimum height (for example, if its parent layout
16074     * constrains it with less available height).
16075     *
16076     * @param minHeight The minimum height the view will try to be.
16077     *
16078     * @see #getMinimumHeight()
16079     *
16080     * @attr ref android.R.styleable#View_minHeight
16081     */
16082    public void setMinimumHeight(int minHeight) {
16083        mMinHeight = minHeight;
16084        requestLayout();
16085    }
16086
16087    /**
16088     * Returns the minimum width of the view.
16089     *
16090     * @return the minimum width the view will try to be.
16091     *
16092     * @see #setMinimumWidth(int)
16093     *
16094     * @attr ref android.R.styleable#View_minWidth
16095     */
16096    public int getMinimumWidth() {
16097        return mMinWidth;
16098    }
16099
16100    /**
16101     * Sets the minimum width of the view. It is not guaranteed the view will
16102     * be able to achieve this minimum width (for example, if its parent layout
16103     * constrains it with less available width).
16104     *
16105     * @param minWidth The minimum width the view will try to be.
16106     *
16107     * @see #getMinimumWidth()
16108     *
16109     * @attr ref android.R.styleable#View_minWidth
16110     */
16111    public void setMinimumWidth(int minWidth) {
16112        mMinWidth = minWidth;
16113        requestLayout();
16114
16115    }
16116
16117    /**
16118     * Get the animation currently associated with this view.
16119     *
16120     * @return The animation that is currently playing or
16121     *         scheduled to play for this view.
16122     */
16123    public Animation getAnimation() {
16124        return mCurrentAnimation;
16125    }
16126
16127    /**
16128     * Start the specified animation now.
16129     *
16130     * @param animation the animation to start now
16131     */
16132    public void startAnimation(Animation animation) {
16133        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16134        setAnimation(animation);
16135        invalidateParentCaches();
16136        invalidate(true);
16137    }
16138
16139    /**
16140     * Cancels any animations for this view.
16141     */
16142    public void clearAnimation() {
16143        if (mCurrentAnimation != null) {
16144            mCurrentAnimation.detach();
16145        }
16146        mCurrentAnimation = null;
16147        invalidateParentIfNeeded();
16148    }
16149
16150    /**
16151     * Sets the next animation to play for this view.
16152     * If you want the animation to play immediately, use
16153     * {@link #startAnimation(android.view.animation.Animation)} instead.
16154     * This method provides allows fine-grained
16155     * control over the start time and invalidation, but you
16156     * must make sure that 1) the animation has a start time set, and
16157     * 2) the view's parent (which controls animations on its children)
16158     * will be invalidated when the animation is supposed to
16159     * start.
16160     *
16161     * @param animation The next animation, or null.
16162     */
16163    public void setAnimation(Animation animation) {
16164        mCurrentAnimation = animation;
16165
16166        if (animation != null) {
16167            // If the screen is off assume the animation start time is now instead of
16168            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16169            // would cause the animation to start when the screen turns back on
16170            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16171                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16172                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16173            }
16174            animation.reset();
16175        }
16176    }
16177
16178    /**
16179     * Invoked by a parent ViewGroup to notify the start of the animation
16180     * currently associated with this view. If you override this method,
16181     * always call super.onAnimationStart();
16182     *
16183     * @see #setAnimation(android.view.animation.Animation)
16184     * @see #getAnimation()
16185     */
16186    protected void onAnimationStart() {
16187        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16188    }
16189
16190    /**
16191     * Invoked by a parent ViewGroup to notify the end of the animation
16192     * currently associated with this view. If you override this method,
16193     * always call super.onAnimationEnd();
16194     *
16195     * @see #setAnimation(android.view.animation.Animation)
16196     * @see #getAnimation()
16197     */
16198    protected void onAnimationEnd() {
16199        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16200    }
16201
16202    /**
16203     * Invoked if there is a Transform that involves alpha. Subclass that can
16204     * draw themselves with the specified alpha should return true, and then
16205     * respect that alpha when their onDraw() is called. If this returns false
16206     * then the view may be redirected to draw into an offscreen buffer to
16207     * fulfill the request, which will look fine, but may be slower than if the
16208     * subclass handles it internally. The default implementation returns false.
16209     *
16210     * @param alpha The alpha (0..255) to apply to the view's drawing
16211     * @return true if the view can draw with the specified alpha.
16212     */
16213    protected boolean onSetAlpha(int alpha) {
16214        return false;
16215    }
16216
16217    /**
16218     * This is used by the RootView to perform an optimization when
16219     * the view hierarchy contains one or several SurfaceView.
16220     * SurfaceView is always considered transparent, but its children are not,
16221     * therefore all View objects remove themselves from the global transparent
16222     * region (passed as a parameter to this function).
16223     *
16224     * @param region The transparent region for this ViewAncestor (window).
16225     *
16226     * @return Returns true if the effective visibility of the view at this
16227     * point is opaque, regardless of the transparent region; returns false
16228     * if it is possible for underlying windows to be seen behind the view.
16229     *
16230     * {@hide}
16231     */
16232    public boolean gatherTransparentRegion(Region region) {
16233        final AttachInfo attachInfo = mAttachInfo;
16234        if (region != null && attachInfo != null) {
16235            final int pflags = mPrivateFlags;
16236            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16237                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16238                // remove it from the transparent region.
16239                final int[] location = attachInfo.mTransparentLocation;
16240                getLocationInWindow(location);
16241                region.op(location[0], location[1], location[0] + mRight - mLeft,
16242                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16243            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16244                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16245                // exists, so we remove the background drawable's non-transparent
16246                // parts from this transparent region.
16247                applyDrawableToTransparentRegion(mBackground, region);
16248            }
16249        }
16250        return true;
16251    }
16252
16253    /**
16254     * Play a sound effect for this view.
16255     *
16256     * <p>The framework will play sound effects for some built in actions, such as
16257     * clicking, but you may wish to play these effects in your widget,
16258     * for instance, for internal navigation.
16259     *
16260     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16261     * {@link #isSoundEffectsEnabled()} is true.
16262     *
16263     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16264     */
16265    public void playSoundEffect(int soundConstant) {
16266        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16267            return;
16268        }
16269        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16270    }
16271
16272    /**
16273     * BZZZTT!!1!
16274     *
16275     * <p>Provide haptic feedback to the user for this view.
16276     *
16277     * <p>The framework will provide haptic feedback for some built in actions,
16278     * such as long presses, but you may wish to provide feedback for your
16279     * own widget.
16280     *
16281     * <p>The feedback will only be performed if
16282     * {@link #isHapticFeedbackEnabled()} is true.
16283     *
16284     * @param feedbackConstant One of the constants defined in
16285     * {@link HapticFeedbackConstants}
16286     */
16287    public boolean performHapticFeedback(int feedbackConstant) {
16288        return performHapticFeedback(feedbackConstant, 0);
16289    }
16290
16291    /**
16292     * BZZZTT!!1!
16293     *
16294     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16295     *
16296     * @param feedbackConstant One of the constants defined in
16297     * {@link HapticFeedbackConstants}
16298     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16299     */
16300    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16301        if (mAttachInfo == null) {
16302            return false;
16303        }
16304        //noinspection SimplifiableIfStatement
16305        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16306                && !isHapticFeedbackEnabled()) {
16307            return false;
16308        }
16309        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16310                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16311    }
16312
16313    /**
16314     * Request that the visibility of the status bar or other screen/window
16315     * decorations be changed.
16316     *
16317     * <p>This method is used to put the over device UI into temporary modes
16318     * where the user's attention is focused more on the application content,
16319     * by dimming or hiding surrounding system affordances.  This is typically
16320     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16321     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16322     * to be placed behind the action bar (and with these flags other system
16323     * affordances) so that smooth transitions between hiding and showing them
16324     * can be done.
16325     *
16326     * <p>Two representative examples of the use of system UI visibility is
16327     * implementing a content browsing application (like a magazine reader)
16328     * and a video playing application.
16329     *
16330     * <p>The first code shows a typical implementation of a View in a content
16331     * browsing application.  In this implementation, the application goes
16332     * into a content-oriented mode by hiding the status bar and action bar,
16333     * and putting the navigation elements into lights out mode.  The user can
16334     * then interact with content while in this mode.  Such an application should
16335     * provide an easy way for the user to toggle out of the mode (such as to
16336     * check information in the status bar or access notifications).  In the
16337     * implementation here, this is done simply by tapping on the content.
16338     *
16339     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16340     *      content}
16341     *
16342     * <p>This second code sample shows a typical implementation of a View
16343     * in a video playing application.  In this situation, while the video is
16344     * playing the application would like to go into a complete full-screen mode,
16345     * to use as much of the display as possible for the video.  When in this state
16346     * the user can not interact with the application; the system intercepts
16347     * touching on the screen to pop the UI out of full screen mode.  See
16348     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16349     *
16350     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16351     *      content}
16352     *
16353     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16354     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16355     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16356     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16357     */
16358    public void setSystemUiVisibility(int visibility) {
16359        if (visibility != mSystemUiVisibility) {
16360            mSystemUiVisibility = visibility;
16361            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16362                mParent.recomputeViewAttributes(this);
16363            }
16364        }
16365    }
16366
16367    /**
16368     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16369     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16370     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16371     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16372     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16373     */
16374    public int getSystemUiVisibility() {
16375        return mSystemUiVisibility;
16376    }
16377
16378    /**
16379     * Returns the current system UI visibility that is currently set for
16380     * the entire window.  This is the combination of the
16381     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16382     * views in the window.
16383     */
16384    public int getWindowSystemUiVisibility() {
16385        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16386    }
16387
16388    /**
16389     * Override to find out when the window's requested system UI visibility
16390     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16391     * This is different from the callbacks recieved through
16392     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16393     * in that this is only telling you about the local request of the window,
16394     * not the actual values applied by the system.
16395     */
16396    public void onWindowSystemUiVisibilityChanged(int visible) {
16397    }
16398
16399    /**
16400     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16401     * the view hierarchy.
16402     */
16403    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16404        onWindowSystemUiVisibilityChanged(visible);
16405    }
16406
16407    /**
16408     * Set a listener to receive callbacks when the visibility of the system bar changes.
16409     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16410     */
16411    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16412        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16413        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16414            mParent.recomputeViewAttributes(this);
16415        }
16416    }
16417
16418    /**
16419     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16420     * the view hierarchy.
16421     */
16422    public void dispatchSystemUiVisibilityChanged(int visibility) {
16423        ListenerInfo li = mListenerInfo;
16424        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16425            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16426                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16427        }
16428    }
16429
16430    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16431        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16432        if (val != mSystemUiVisibility) {
16433            setSystemUiVisibility(val);
16434            return true;
16435        }
16436        return false;
16437    }
16438
16439    /** @hide */
16440    public void setDisabledSystemUiVisibility(int flags) {
16441        if (mAttachInfo != null) {
16442            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16443                mAttachInfo.mDisabledSystemUiVisibility = flags;
16444                if (mParent != null) {
16445                    mParent.recomputeViewAttributes(this);
16446                }
16447            }
16448        }
16449    }
16450
16451    /**
16452     * Creates an image that the system displays during the drag and drop
16453     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16454     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16455     * appearance as the given View. The default also positions the center of the drag shadow
16456     * directly under the touch point. If no View is provided (the constructor with no parameters
16457     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16458     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16459     * default is an invisible drag shadow.
16460     * <p>
16461     * You are not required to use the View you provide to the constructor as the basis of the
16462     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16463     * anything you want as the drag shadow.
16464     * </p>
16465     * <p>
16466     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16467     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16468     *  size and position of the drag shadow. It uses this data to construct a
16469     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16470     *  so that your application can draw the shadow image in the Canvas.
16471     * </p>
16472     *
16473     * <div class="special reference">
16474     * <h3>Developer Guides</h3>
16475     * <p>For a guide to implementing drag and drop features, read the
16476     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16477     * </div>
16478     */
16479    public static class DragShadowBuilder {
16480        private final WeakReference<View> mView;
16481
16482        /**
16483         * Constructs a shadow image builder based on a View. By default, the resulting drag
16484         * shadow will have the same appearance and dimensions as the View, with the touch point
16485         * over the center of the View.
16486         * @param view A View. Any View in scope can be used.
16487         */
16488        public DragShadowBuilder(View view) {
16489            mView = new WeakReference<View>(view);
16490        }
16491
16492        /**
16493         * Construct a shadow builder object with no associated View.  This
16494         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16495         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16496         * to supply the drag shadow's dimensions and appearance without
16497         * reference to any View object. If they are not overridden, then the result is an
16498         * invisible drag shadow.
16499         */
16500        public DragShadowBuilder() {
16501            mView = new WeakReference<View>(null);
16502        }
16503
16504        /**
16505         * Returns the View object that had been passed to the
16506         * {@link #View.DragShadowBuilder(View)}
16507         * constructor.  If that View parameter was {@code null} or if the
16508         * {@link #View.DragShadowBuilder()}
16509         * constructor was used to instantiate the builder object, this method will return
16510         * null.
16511         *
16512         * @return The View object associate with this builder object.
16513         */
16514        @SuppressWarnings({"JavadocReference"})
16515        final public View getView() {
16516            return mView.get();
16517        }
16518
16519        /**
16520         * Provides the metrics for the shadow image. These include the dimensions of
16521         * the shadow image, and the point within that shadow that should
16522         * be centered under the touch location while dragging.
16523         * <p>
16524         * The default implementation sets the dimensions of the shadow to be the
16525         * same as the dimensions of the View itself and centers the shadow under
16526         * the touch point.
16527         * </p>
16528         *
16529         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16530         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16531         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16532         * image.
16533         *
16534         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16535         * shadow image that should be underneath the touch point during the drag and drop
16536         * operation. Your application must set {@link android.graphics.Point#x} to the
16537         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16538         */
16539        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16540            final View view = mView.get();
16541            if (view != null) {
16542                shadowSize.set(view.getWidth(), view.getHeight());
16543                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16544            } else {
16545                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16546            }
16547        }
16548
16549        /**
16550         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16551         * based on the dimensions it received from the
16552         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16553         *
16554         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16555         */
16556        public void onDrawShadow(Canvas canvas) {
16557            final View view = mView.get();
16558            if (view != null) {
16559                view.draw(canvas);
16560            } else {
16561                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16562            }
16563        }
16564    }
16565
16566    /**
16567     * Starts a drag and drop operation. When your application calls this method, it passes a
16568     * {@link android.view.View.DragShadowBuilder} object to the system. The
16569     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16570     * to get metrics for the drag shadow, and then calls the object's
16571     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16572     * <p>
16573     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16574     *  drag events to all the View objects in your application that are currently visible. It does
16575     *  this either by calling the View object's drag listener (an implementation of
16576     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16577     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16578     *  Both are passed a {@link android.view.DragEvent} object that has a
16579     *  {@link android.view.DragEvent#getAction()} value of
16580     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16581     * </p>
16582     * <p>
16583     * Your application can invoke startDrag() on any attached View object. The View object does not
16584     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16585     * be related to the View the user selected for dragging.
16586     * </p>
16587     * @param data A {@link android.content.ClipData} object pointing to the data to be
16588     * transferred by the drag and drop operation.
16589     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16590     * drag shadow.
16591     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16592     * drop operation. This Object is put into every DragEvent object sent by the system during the
16593     * current drag.
16594     * <p>
16595     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16596     * to the target Views. For example, it can contain flags that differentiate between a
16597     * a copy operation and a move operation.
16598     * </p>
16599     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16600     * so the parameter should be set to 0.
16601     * @return {@code true} if the method completes successfully, or
16602     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16603     * do a drag, and so no drag operation is in progress.
16604     */
16605    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16606            Object myLocalState, int flags) {
16607        if (ViewDebug.DEBUG_DRAG) {
16608            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16609        }
16610        boolean okay = false;
16611
16612        Point shadowSize = new Point();
16613        Point shadowTouchPoint = new Point();
16614        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16615
16616        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16617                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16618            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16619        }
16620
16621        if (ViewDebug.DEBUG_DRAG) {
16622            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16623                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16624        }
16625        Surface surface = new Surface();
16626        try {
16627            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16628                    flags, shadowSize.x, shadowSize.y, surface);
16629            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16630                    + " surface=" + surface);
16631            if (token != null) {
16632                Canvas canvas = surface.lockCanvas(null);
16633                try {
16634                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16635                    shadowBuilder.onDrawShadow(canvas);
16636                } finally {
16637                    surface.unlockCanvasAndPost(canvas);
16638                }
16639
16640                final ViewRootImpl root = getViewRootImpl();
16641
16642                // Cache the local state object for delivery with DragEvents
16643                root.setLocalDragState(myLocalState);
16644
16645                // repurpose 'shadowSize' for the last touch point
16646                root.getLastTouchPoint(shadowSize);
16647
16648                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16649                        shadowSize.x, shadowSize.y,
16650                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16651                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16652
16653                // Off and running!  Release our local surface instance; the drag
16654                // shadow surface is now managed by the system process.
16655                surface.release();
16656            }
16657        } catch (Exception e) {
16658            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16659            surface.destroy();
16660        }
16661
16662        return okay;
16663    }
16664
16665    /**
16666     * Handles drag events sent by the system following a call to
16667     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16668     *<p>
16669     * When the system calls this method, it passes a
16670     * {@link android.view.DragEvent} object. A call to
16671     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16672     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16673     * operation.
16674     * @param event The {@link android.view.DragEvent} sent by the system.
16675     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16676     * in DragEvent, indicating the type of drag event represented by this object.
16677     * @return {@code true} if the method was successful, otherwise {@code false}.
16678     * <p>
16679     *  The method should return {@code true} in response to an action type of
16680     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16681     *  operation.
16682     * </p>
16683     * <p>
16684     *  The method should also return {@code true} in response to an action type of
16685     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16686     *  {@code false} if it didn't.
16687     * </p>
16688     */
16689    public boolean onDragEvent(DragEvent event) {
16690        return false;
16691    }
16692
16693    /**
16694     * Detects if this View is enabled and has a drag event listener.
16695     * If both are true, then it calls the drag event listener with the
16696     * {@link android.view.DragEvent} it received. If the drag event listener returns
16697     * {@code true}, then dispatchDragEvent() returns {@code true}.
16698     * <p>
16699     * For all other cases, the method calls the
16700     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16701     * method and returns its result.
16702     * </p>
16703     * <p>
16704     * This ensures that a drag event is always consumed, even if the View does not have a drag
16705     * event listener. However, if the View has a listener and the listener returns true, then
16706     * onDragEvent() is not called.
16707     * </p>
16708     */
16709    public boolean dispatchDragEvent(DragEvent event) {
16710        //noinspection SimplifiableIfStatement
16711        ListenerInfo li = mListenerInfo;
16712        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16713                && li.mOnDragListener.onDrag(this, event)) {
16714            return true;
16715        }
16716        return onDragEvent(event);
16717    }
16718
16719    boolean canAcceptDrag() {
16720        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16721    }
16722
16723    /**
16724     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16725     * it is ever exposed at all.
16726     * @hide
16727     */
16728    public void onCloseSystemDialogs(String reason) {
16729    }
16730
16731    /**
16732     * Given a Drawable whose bounds have been set to draw into this view,
16733     * update a Region being computed for
16734     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16735     * that any non-transparent parts of the Drawable are removed from the
16736     * given transparent region.
16737     *
16738     * @param dr The Drawable whose transparency is to be applied to the region.
16739     * @param region A Region holding the current transparency information,
16740     * where any parts of the region that are set are considered to be
16741     * transparent.  On return, this region will be modified to have the
16742     * transparency information reduced by the corresponding parts of the
16743     * Drawable that are not transparent.
16744     * {@hide}
16745     */
16746    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16747        if (DBG) {
16748            Log.i("View", "Getting transparent region for: " + this);
16749        }
16750        final Region r = dr.getTransparentRegion();
16751        final Rect db = dr.getBounds();
16752        final AttachInfo attachInfo = mAttachInfo;
16753        if (r != null && attachInfo != null) {
16754            final int w = getRight()-getLeft();
16755            final int h = getBottom()-getTop();
16756            if (db.left > 0) {
16757                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16758                r.op(0, 0, db.left, h, Region.Op.UNION);
16759            }
16760            if (db.right < w) {
16761                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16762                r.op(db.right, 0, w, h, Region.Op.UNION);
16763            }
16764            if (db.top > 0) {
16765                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16766                r.op(0, 0, w, db.top, Region.Op.UNION);
16767            }
16768            if (db.bottom < h) {
16769                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16770                r.op(0, db.bottom, w, h, Region.Op.UNION);
16771            }
16772            final int[] location = attachInfo.mTransparentLocation;
16773            getLocationInWindow(location);
16774            r.translate(location[0], location[1]);
16775            region.op(r, Region.Op.INTERSECT);
16776        } else {
16777            region.op(db, Region.Op.DIFFERENCE);
16778        }
16779    }
16780
16781    private void checkForLongClick(int delayOffset) {
16782        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16783            mHasPerformedLongPress = false;
16784
16785            if (mPendingCheckForLongPress == null) {
16786                mPendingCheckForLongPress = new CheckForLongPress();
16787            }
16788            mPendingCheckForLongPress.rememberWindowAttachCount();
16789            postDelayed(mPendingCheckForLongPress,
16790                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16791        }
16792    }
16793
16794    /**
16795     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16796     * LayoutInflater} class, which provides a full range of options for view inflation.
16797     *
16798     * @param context The Context object for your activity or application.
16799     * @param resource The resource ID to inflate
16800     * @param root A view group that will be the parent.  Used to properly inflate the
16801     * layout_* parameters.
16802     * @see LayoutInflater
16803     */
16804    public static View inflate(Context context, int resource, ViewGroup root) {
16805        LayoutInflater factory = LayoutInflater.from(context);
16806        return factory.inflate(resource, root);
16807    }
16808
16809    /**
16810     * Scroll the view with standard behavior for scrolling beyond the normal
16811     * content boundaries. Views that call this method should override
16812     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16813     * results of an over-scroll operation.
16814     *
16815     * Views can use this method to handle any touch or fling-based scrolling.
16816     *
16817     * @param deltaX Change in X in pixels
16818     * @param deltaY Change in Y in pixels
16819     * @param scrollX Current X scroll value in pixels before applying deltaX
16820     * @param scrollY Current Y scroll value in pixels before applying deltaY
16821     * @param scrollRangeX Maximum content scroll range along the X axis
16822     * @param scrollRangeY Maximum content scroll range along the Y axis
16823     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16824     *          along the X axis.
16825     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16826     *          along the Y axis.
16827     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16828     * @return true if scrolling was clamped to an over-scroll boundary along either
16829     *          axis, false otherwise.
16830     */
16831    @SuppressWarnings({"UnusedParameters"})
16832    protected boolean overScrollBy(int deltaX, int deltaY,
16833            int scrollX, int scrollY,
16834            int scrollRangeX, int scrollRangeY,
16835            int maxOverScrollX, int maxOverScrollY,
16836            boolean isTouchEvent) {
16837        final int overScrollMode = mOverScrollMode;
16838        final boolean canScrollHorizontal =
16839                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16840        final boolean canScrollVertical =
16841                computeVerticalScrollRange() > computeVerticalScrollExtent();
16842        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16843                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16844        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16845                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16846
16847        int newScrollX = scrollX + deltaX;
16848        if (!overScrollHorizontal) {
16849            maxOverScrollX = 0;
16850        }
16851
16852        int newScrollY = scrollY + deltaY;
16853        if (!overScrollVertical) {
16854            maxOverScrollY = 0;
16855        }
16856
16857        // Clamp values if at the limits and record
16858        final int left = -maxOverScrollX;
16859        final int right = maxOverScrollX + scrollRangeX;
16860        final int top = -maxOverScrollY;
16861        final int bottom = maxOverScrollY + scrollRangeY;
16862
16863        boolean clampedX = false;
16864        if (newScrollX > right) {
16865            newScrollX = right;
16866            clampedX = true;
16867        } else if (newScrollX < left) {
16868            newScrollX = left;
16869            clampedX = true;
16870        }
16871
16872        boolean clampedY = false;
16873        if (newScrollY > bottom) {
16874            newScrollY = bottom;
16875            clampedY = true;
16876        } else if (newScrollY < top) {
16877            newScrollY = top;
16878            clampedY = true;
16879        }
16880
16881        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16882
16883        return clampedX || clampedY;
16884    }
16885
16886    /**
16887     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16888     * respond to the results of an over-scroll operation.
16889     *
16890     * @param scrollX New X scroll value in pixels
16891     * @param scrollY New Y scroll value in pixels
16892     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16893     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16894     */
16895    protected void onOverScrolled(int scrollX, int scrollY,
16896            boolean clampedX, boolean clampedY) {
16897        // Intentionally empty.
16898    }
16899
16900    /**
16901     * Returns the over-scroll mode for this view. The result will be
16902     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16903     * (allow over-scrolling only if the view content is larger than the container),
16904     * or {@link #OVER_SCROLL_NEVER}.
16905     *
16906     * @return This view's over-scroll mode.
16907     */
16908    public int getOverScrollMode() {
16909        return mOverScrollMode;
16910    }
16911
16912    /**
16913     * Set the over-scroll mode for this view. Valid over-scroll modes are
16914     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16915     * (allow over-scrolling only if the view content is larger than the container),
16916     * or {@link #OVER_SCROLL_NEVER}.
16917     *
16918     * Setting the over-scroll mode of a view will have an effect only if the
16919     * view is capable of scrolling.
16920     *
16921     * @param overScrollMode The new over-scroll mode for this view.
16922     */
16923    public void setOverScrollMode(int overScrollMode) {
16924        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16925                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16926                overScrollMode != OVER_SCROLL_NEVER) {
16927            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16928        }
16929        mOverScrollMode = overScrollMode;
16930    }
16931
16932    /**
16933     * Gets a scale factor that determines the distance the view should scroll
16934     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16935     * @return The vertical scroll scale factor.
16936     * @hide
16937     */
16938    protected float getVerticalScrollFactor() {
16939        if (mVerticalScrollFactor == 0) {
16940            TypedValue outValue = new TypedValue();
16941            if (!mContext.getTheme().resolveAttribute(
16942                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16943                throw new IllegalStateException(
16944                        "Expected theme to define listPreferredItemHeight.");
16945            }
16946            mVerticalScrollFactor = outValue.getDimension(
16947                    mContext.getResources().getDisplayMetrics());
16948        }
16949        return mVerticalScrollFactor;
16950    }
16951
16952    /**
16953     * Gets a scale factor that determines the distance the view should scroll
16954     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16955     * @return The horizontal scroll scale factor.
16956     * @hide
16957     */
16958    protected float getHorizontalScrollFactor() {
16959        // TODO: Should use something else.
16960        return getVerticalScrollFactor();
16961    }
16962
16963    /**
16964     * Return the value specifying the text direction or policy that was set with
16965     * {@link #setTextDirection(int)}.
16966     *
16967     * @return the defined text direction. It can be one of:
16968     *
16969     * {@link #TEXT_DIRECTION_INHERIT},
16970     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16971     * {@link #TEXT_DIRECTION_ANY_RTL},
16972     * {@link #TEXT_DIRECTION_LTR},
16973     * {@link #TEXT_DIRECTION_RTL},
16974     * {@link #TEXT_DIRECTION_LOCALE}
16975     *
16976     * @attr ref android.R.styleable#View_textDirection
16977     *
16978     * @hide
16979     */
16980    @ViewDebug.ExportedProperty(category = "text", mapping = {
16981            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16982            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16983            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16984            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16985            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16986            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16987    })
16988    public int getRawTextDirection() {
16989        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16990    }
16991
16992    /**
16993     * Set the text direction.
16994     *
16995     * @param textDirection the direction to set. Should be one of:
16996     *
16997     * {@link #TEXT_DIRECTION_INHERIT},
16998     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16999     * {@link #TEXT_DIRECTION_ANY_RTL},
17000     * {@link #TEXT_DIRECTION_LTR},
17001     * {@link #TEXT_DIRECTION_RTL},
17002     * {@link #TEXT_DIRECTION_LOCALE}
17003     *
17004     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17005     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17006     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17007     *
17008     * @attr ref android.R.styleable#View_textDirection
17009     */
17010    public void setTextDirection(int textDirection) {
17011        if (getRawTextDirection() != textDirection) {
17012            // Reset the current text direction and the resolved one
17013            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17014            resetResolvedTextDirection();
17015            // Set the new text direction
17016            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17017            // Do resolution
17018            resolveTextDirection();
17019            // Notify change
17020            onRtlPropertiesChanged(getLayoutDirection());
17021            // Refresh
17022            requestLayout();
17023            invalidate(true);
17024        }
17025    }
17026
17027    /**
17028     * Return the resolved text direction.
17029     *
17030     * @return the resolved text direction. Returns one of:
17031     *
17032     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17033     * {@link #TEXT_DIRECTION_ANY_RTL},
17034     * {@link #TEXT_DIRECTION_LTR},
17035     * {@link #TEXT_DIRECTION_RTL},
17036     * {@link #TEXT_DIRECTION_LOCALE}
17037     *
17038     * @attr ref android.R.styleable#View_textDirection
17039     */
17040    @ViewDebug.ExportedProperty(category = "text", mapping = {
17041            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17042            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17043            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17044            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17045            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17046            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17047    })
17048    public int getTextDirection() {
17049        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17050    }
17051
17052    /**
17053     * Resolve the text direction.
17054     *
17055     * @return true if resolution has been done, false otherwise.
17056     *
17057     * @hide
17058     */
17059    public boolean resolveTextDirection() {
17060        // Reset any previous text direction resolution
17061        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17062
17063        if (hasRtlSupport()) {
17064            // Set resolved text direction flag depending on text direction flag
17065            final int textDirection = getRawTextDirection();
17066            switch(textDirection) {
17067                case TEXT_DIRECTION_INHERIT:
17068                    if (!canResolveTextDirection()) {
17069                        // We cannot do the resolution if there is no parent, so use the default one
17070                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17071                        // Resolution will need to happen again later
17072                        return false;
17073                    }
17074
17075                    // Parent has not yet resolved, so we still return the default
17076                    if (!mParent.isTextDirectionResolved()) {
17077                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17078                        // Resolution will need to happen again later
17079                        return false;
17080                    }
17081
17082                    // Set current resolved direction to the same value as the parent's one
17083                    final int parentResolvedDirection = mParent.getTextDirection();
17084                    switch (parentResolvedDirection) {
17085                        case TEXT_DIRECTION_FIRST_STRONG:
17086                        case TEXT_DIRECTION_ANY_RTL:
17087                        case TEXT_DIRECTION_LTR:
17088                        case TEXT_DIRECTION_RTL:
17089                        case TEXT_DIRECTION_LOCALE:
17090                            mPrivateFlags2 |=
17091                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17092                            break;
17093                        default:
17094                            // Default resolved direction is "first strong" heuristic
17095                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17096                    }
17097                    break;
17098                case TEXT_DIRECTION_FIRST_STRONG:
17099                case TEXT_DIRECTION_ANY_RTL:
17100                case TEXT_DIRECTION_LTR:
17101                case TEXT_DIRECTION_RTL:
17102                case TEXT_DIRECTION_LOCALE:
17103                    // Resolved direction is the same as text direction
17104                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17105                    break;
17106                default:
17107                    // Default resolved direction is "first strong" heuristic
17108                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17109            }
17110        } else {
17111            // Default resolved direction is "first strong" heuristic
17112            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17113        }
17114
17115        // Set to resolved
17116        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17117        return true;
17118    }
17119
17120    /**
17121     * Check if text direction resolution can be done.
17122     *
17123     * @return true if text direction resolution can be done otherwise return false.
17124     *
17125     * @hide
17126     */
17127    public boolean canResolveTextDirection() {
17128        switch (getRawTextDirection()) {
17129            case TEXT_DIRECTION_INHERIT:
17130                return (mParent != null) && mParent.canResolveTextDirection();
17131            default:
17132                return true;
17133        }
17134    }
17135
17136    /**
17137     * Reset resolved text direction. Text direction will be resolved during a call to
17138     * {@link #onMeasure(int, int)}.
17139     *
17140     * @hide
17141     */
17142    public void resetResolvedTextDirection() {
17143        // Reset any previous text direction resolution
17144        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17145        // Set to default value
17146        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17147    }
17148
17149    /**
17150     * @return true if text direction is inherited.
17151     *
17152     * @hide
17153     */
17154    public boolean isTextDirectionInherited() {
17155        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17156    }
17157
17158    /**
17159     * @return true if text direction is resolved.
17160     *
17161     * @hide
17162     */
17163    public boolean isTextDirectionResolved() {
17164        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17165    }
17166
17167    /**
17168     * Return the value specifying the text alignment or policy that was set with
17169     * {@link #setTextAlignment(int)}.
17170     *
17171     * @return the defined text alignment. It can be one of:
17172     *
17173     * {@link #TEXT_ALIGNMENT_INHERIT},
17174     * {@link #TEXT_ALIGNMENT_GRAVITY},
17175     * {@link #TEXT_ALIGNMENT_CENTER},
17176     * {@link #TEXT_ALIGNMENT_TEXT_START},
17177     * {@link #TEXT_ALIGNMENT_TEXT_END},
17178     * {@link #TEXT_ALIGNMENT_VIEW_START},
17179     * {@link #TEXT_ALIGNMENT_VIEW_END}
17180     *
17181     * @attr ref android.R.styleable#View_textAlignment
17182     *
17183     * @hide
17184     */
17185    @ViewDebug.ExportedProperty(category = "text", mapping = {
17186            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17187            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17188            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17189            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17190            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17191            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17192            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17193    })
17194    public int getRawTextAlignment() {
17195        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17196    }
17197
17198    /**
17199     * Set the text alignment.
17200     *
17201     * @param textAlignment The text alignment to set. Should be one of
17202     *
17203     * {@link #TEXT_ALIGNMENT_INHERIT},
17204     * {@link #TEXT_ALIGNMENT_GRAVITY},
17205     * {@link #TEXT_ALIGNMENT_CENTER},
17206     * {@link #TEXT_ALIGNMENT_TEXT_START},
17207     * {@link #TEXT_ALIGNMENT_TEXT_END},
17208     * {@link #TEXT_ALIGNMENT_VIEW_START},
17209     * {@link #TEXT_ALIGNMENT_VIEW_END}
17210     *
17211     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17212     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17213     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17214     *
17215     * @attr ref android.R.styleable#View_textAlignment
17216     */
17217    public void setTextAlignment(int textAlignment) {
17218        if (textAlignment != getRawTextAlignment()) {
17219            // Reset the current and resolved text alignment
17220            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17221            resetResolvedTextAlignment();
17222            // Set the new text alignment
17223            mPrivateFlags2 |=
17224                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17225            // Do resolution
17226            resolveTextAlignment();
17227            // Notify change
17228            onRtlPropertiesChanged(getLayoutDirection());
17229            // Refresh
17230            requestLayout();
17231            invalidate(true);
17232        }
17233    }
17234
17235    /**
17236     * Return the resolved text alignment.
17237     *
17238     * @return the resolved text alignment. Returns one of:
17239     *
17240     * {@link #TEXT_ALIGNMENT_GRAVITY},
17241     * {@link #TEXT_ALIGNMENT_CENTER},
17242     * {@link #TEXT_ALIGNMENT_TEXT_START},
17243     * {@link #TEXT_ALIGNMENT_TEXT_END},
17244     * {@link #TEXT_ALIGNMENT_VIEW_START},
17245     * {@link #TEXT_ALIGNMENT_VIEW_END}
17246     *
17247     * @attr ref android.R.styleable#View_textAlignment
17248     */
17249    @ViewDebug.ExportedProperty(category = "text", mapping = {
17250            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17251            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17252            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17253            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17254            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17255            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17256            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17257    })
17258    public int getTextAlignment() {
17259        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17260                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17261    }
17262
17263    /**
17264     * Resolve the text alignment.
17265     *
17266     * @return true if resolution has been done, false otherwise.
17267     *
17268     * @hide
17269     */
17270    public boolean resolveTextAlignment() {
17271        // Reset any previous text alignment resolution
17272        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17273
17274        if (hasRtlSupport()) {
17275            // Set resolved text alignment flag depending on text alignment flag
17276            final int textAlignment = getRawTextAlignment();
17277            switch (textAlignment) {
17278                case TEXT_ALIGNMENT_INHERIT:
17279                    // Check if we can resolve the text alignment
17280                    if (!canResolveTextAlignment()) {
17281                        // We cannot do the resolution if there is no parent so use the default
17282                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17283                        // Resolution will need to happen again later
17284                        return false;
17285                    }
17286
17287                    // Parent has not yet resolved, so we still return the default
17288                    if (!mParent.isTextAlignmentResolved()) {
17289                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17290                        // Resolution will need to happen again later
17291                        return false;
17292                    }
17293
17294                    final int parentResolvedTextAlignment = mParent.getTextAlignment();
17295                    switch (parentResolvedTextAlignment) {
17296                        case TEXT_ALIGNMENT_GRAVITY:
17297                        case TEXT_ALIGNMENT_TEXT_START:
17298                        case TEXT_ALIGNMENT_TEXT_END:
17299                        case TEXT_ALIGNMENT_CENTER:
17300                        case TEXT_ALIGNMENT_VIEW_START:
17301                        case TEXT_ALIGNMENT_VIEW_END:
17302                            // Resolved text alignment is the same as the parent resolved
17303                            // text alignment
17304                            mPrivateFlags2 |=
17305                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17306                            break;
17307                        default:
17308                            // Use default resolved text alignment
17309                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17310                    }
17311                    break;
17312                case TEXT_ALIGNMENT_GRAVITY:
17313                case TEXT_ALIGNMENT_TEXT_START:
17314                case TEXT_ALIGNMENT_TEXT_END:
17315                case TEXT_ALIGNMENT_CENTER:
17316                case TEXT_ALIGNMENT_VIEW_START:
17317                case TEXT_ALIGNMENT_VIEW_END:
17318                    // Resolved text alignment is the same as text alignment
17319                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17320                    break;
17321                default:
17322                    // Use default resolved text alignment
17323                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17324            }
17325        } else {
17326            // Use default resolved text alignment
17327            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17328        }
17329
17330        // Set the resolved
17331        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17332        return true;
17333    }
17334
17335    /**
17336     * Check if text alignment resolution can be done.
17337     *
17338     * @return true if text alignment resolution can be done otherwise return false.
17339     *
17340     * @hide
17341     */
17342    public boolean canResolveTextAlignment() {
17343        switch (getRawTextAlignment()) {
17344            case TEXT_DIRECTION_INHERIT:
17345                return (mParent != null) && mParent.canResolveTextAlignment();
17346            default:
17347                return true;
17348        }
17349    }
17350
17351    /**
17352     * Reset resolved text alignment. Text alignment will be resolved during a call to
17353     * {@link #onMeasure(int, int)}.
17354     *
17355     * @hide
17356     */
17357    public void resetResolvedTextAlignment() {
17358        // Reset any previous text alignment resolution
17359        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17360        // Set to default
17361        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17362    }
17363
17364    /**
17365     * @return true if text alignment is inherited.
17366     *
17367     * @hide
17368     */
17369    public boolean isTextAlignmentInherited() {
17370        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17371    }
17372
17373    /**
17374     * @return true if text alignment is resolved.
17375     *
17376     * @hide
17377     */
17378    public boolean isTextAlignmentResolved() {
17379        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17380    }
17381
17382    /**
17383     * Generate a value suitable for use in {@link #setId(int)}.
17384     * This value will not collide with ID values generated at build time by aapt for R.id.
17385     *
17386     * @return a generated ID value
17387     */
17388    public static int generateViewId() {
17389        for (;;) {
17390            final int result = sNextGeneratedId.get();
17391            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17392            int newValue = result + 1;
17393            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17394            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17395                return result;
17396            }
17397        }
17398    }
17399
17400    //
17401    // Properties
17402    //
17403    /**
17404     * A Property wrapper around the <code>alpha</code> functionality handled by the
17405     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17406     */
17407    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17408        @Override
17409        public void setValue(View object, float value) {
17410            object.setAlpha(value);
17411        }
17412
17413        @Override
17414        public Float get(View object) {
17415            return object.getAlpha();
17416        }
17417    };
17418
17419    /**
17420     * A Property wrapper around the <code>translationX</code> functionality handled by the
17421     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17422     */
17423    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17424        @Override
17425        public void setValue(View object, float value) {
17426            object.setTranslationX(value);
17427        }
17428
17429                @Override
17430        public Float get(View object) {
17431            return object.getTranslationX();
17432        }
17433    };
17434
17435    /**
17436     * A Property wrapper around the <code>translationY</code> functionality handled by the
17437     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17438     */
17439    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17440        @Override
17441        public void setValue(View object, float value) {
17442            object.setTranslationY(value);
17443        }
17444
17445        @Override
17446        public Float get(View object) {
17447            return object.getTranslationY();
17448        }
17449    };
17450
17451    /**
17452     * A Property wrapper around the <code>x</code> functionality handled by the
17453     * {@link View#setX(float)} and {@link View#getX()} methods.
17454     */
17455    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17456        @Override
17457        public void setValue(View object, float value) {
17458            object.setX(value);
17459        }
17460
17461        @Override
17462        public Float get(View object) {
17463            return object.getX();
17464        }
17465    };
17466
17467    /**
17468     * A Property wrapper around the <code>y</code> functionality handled by the
17469     * {@link View#setY(float)} and {@link View#getY()} methods.
17470     */
17471    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17472        @Override
17473        public void setValue(View object, float value) {
17474            object.setY(value);
17475        }
17476
17477        @Override
17478        public Float get(View object) {
17479            return object.getY();
17480        }
17481    };
17482
17483    /**
17484     * A Property wrapper around the <code>rotation</code> functionality handled by the
17485     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17486     */
17487    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17488        @Override
17489        public void setValue(View object, float value) {
17490            object.setRotation(value);
17491        }
17492
17493        @Override
17494        public Float get(View object) {
17495            return object.getRotation();
17496        }
17497    };
17498
17499    /**
17500     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17501     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17502     */
17503    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17504        @Override
17505        public void setValue(View object, float value) {
17506            object.setRotationX(value);
17507        }
17508
17509        @Override
17510        public Float get(View object) {
17511            return object.getRotationX();
17512        }
17513    };
17514
17515    /**
17516     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17517     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17518     */
17519    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17520        @Override
17521        public void setValue(View object, float value) {
17522            object.setRotationY(value);
17523        }
17524
17525        @Override
17526        public Float get(View object) {
17527            return object.getRotationY();
17528        }
17529    };
17530
17531    /**
17532     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17533     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17534     */
17535    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17536        @Override
17537        public void setValue(View object, float value) {
17538            object.setScaleX(value);
17539        }
17540
17541        @Override
17542        public Float get(View object) {
17543            return object.getScaleX();
17544        }
17545    };
17546
17547    /**
17548     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17549     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17550     */
17551    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17552        @Override
17553        public void setValue(View object, float value) {
17554            object.setScaleY(value);
17555        }
17556
17557        @Override
17558        public Float get(View object) {
17559            return object.getScaleY();
17560        }
17561    };
17562
17563    /**
17564     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17565     * Each MeasureSpec represents a requirement for either the width or the height.
17566     * A MeasureSpec is comprised of a size and a mode. There are three possible
17567     * modes:
17568     * <dl>
17569     * <dt>UNSPECIFIED</dt>
17570     * <dd>
17571     * The parent has not imposed any constraint on the child. It can be whatever size
17572     * it wants.
17573     * </dd>
17574     *
17575     * <dt>EXACTLY</dt>
17576     * <dd>
17577     * The parent has determined an exact size for the child. The child is going to be
17578     * given those bounds regardless of how big it wants to be.
17579     * </dd>
17580     *
17581     * <dt>AT_MOST</dt>
17582     * <dd>
17583     * The child can be as large as it wants up to the specified size.
17584     * </dd>
17585     * </dl>
17586     *
17587     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17588     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17589     */
17590    public static class MeasureSpec {
17591        private static final int MODE_SHIFT = 30;
17592        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17593
17594        /**
17595         * Measure specification mode: The parent has not imposed any constraint
17596         * on the child. It can be whatever size it wants.
17597         */
17598        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17599
17600        /**
17601         * Measure specification mode: The parent has determined an exact size
17602         * for the child. The child is going to be given those bounds regardless
17603         * of how big it wants to be.
17604         */
17605        public static final int EXACTLY     = 1 << MODE_SHIFT;
17606
17607        /**
17608         * Measure specification mode: The child can be as large as it wants up
17609         * to the specified size.
17610         */
17611        public static final int AT_MOST     = 2 << MODE_SHIFT;
17612
17613        /**
17614         * Creates a measure specification based on the supplied size and mode.
17615         *
17616         * The mode must always be one of the following:
17617         * <ul>
17618         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17619         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17620         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17621         * </ul>
17622         *
17623         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17624         * implementation was such that the order of arguments did not matter
17625         * and overflow in either value could impact the resulting MeasureSpec.
17626         * {@link android.widget.RelativeLayout} was affected by this bug.
17627         * Apps targeting API levels greater than 17 will get the fixed, more strict
17628         * behavior.</p>
17629         *
17630         * @param size the size of the measure specification
17631         * @param mode the mode of the measure specification
17632         * @return the measure specification based on size and mode
17633         */
17634        public static int makeMeasureSpec(int size, int mode) {
17635            if (sUseBrokenMakeMeasureSpec) {
17636                return size + mode;
17637            } else {
17638                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17639            }
17640        }
17641
17642        /**
17643         * Extracts the mode from the supplied measure specification.
17644         *
17645         * @param measureSpec the measure specification to extract the mode from
17646         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17647         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17648         *         {@link android.view.View.MeasureSpec#EXACTLY}
17649         */
17650        public static int getMode(int measureSpec) {
17651            return (measureSpec & MODE_MASK);
17652        }
17653
17654        /**
17655         * Extracts the size from the supplied measure specification.
17656         *
17657         * @param measureSpec the measure specification to extract the size from
17658         * @return the size in pixels defined in the supplied measure specification
17659         */
17660        public static int getSize(int measureSpec) {
17661            return (measureSpec & ~MODE_MASK);
17662        }
17663
17664        static int adjust(int measureSpec, int delta) {
17665            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17666        }
17667
17668        /**
17669         * Returns a String representation of the specified measure
17670         * specification.
17671         *
17672         * @param measureSpec the measure specification to convert to a String
17673         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17674         */
17675        public static String toString(int measureSpec) {
17676            int mode = getMode(measureSpec);
17677            int size = getSize(measureSpec);
17678
17679            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17680
17681            if (mode == UNSPECIFIED)
17682                sb.append("UNSPECIFIED ");
17683            else if (mode == EXACTLY)
17684                sb.append("EXACTLY ");
17685            else if (mode == AT_MOST)
17686                sb.append("AT_MOST ");
17687            else
17688                sb.append(mode).append(" ");
17689
17690            sb.append(size);
17691            return sb.toString();
17692        }
17693    }
17694
17695    class CheckForLongPress implements Runnable {
17696
17697        private int mOriginalWindowAttachCount;
17698
17699        public void run() {
17700            if (isPressed() && (mParent != null)
17701                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17702                if (performLongClick()) {
17703                    mHasPerformedLongPress = true;
17704                }
17705            }
17706        }
17707
17708        public void rememberWindowAttachCount() {
17709            mOriginalWindowAttachCount = mWindowAttachCount;
17710        }
17711    }
17712
17713    private final class CheckForTap implements Runnable {
17714        public void run() {
17715            mPrivateFlags &= ~PFLAG_PREPRESSED;
17716            setPressed(true);
17717            checkForLongClick(ViewConfiguration.getTapTimeout());
17718        }
17719    }
17720
17721    private final class PerformClick implements Runnable {
17722        public void run() {
17723            performClick();
17724        }
17725    }
17726
17727    /** @hide */
17728    public void hackTurnOffWindowResizeAnim(boolean off) {
17729        mAttachInfo.mTurnOffWindowResizeAnim = off;
17730    }
17731
17732    /**
17733     * This method returns a ViewPropertyAnimator object, which can be used to animate
17734     * specific properties on this View.
17735     *
17736     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17737     */
17738    public ViewPropertyAnimator animate() {
17739        if (mAnimator == null) {
17740            mAnimator = new ViewPropertyAnimator(this);
17741        }
17742        return mAnimator;
17743    }
17744
17745    /**
17746     * Interface definition for a callback to be invoked when a hardware key event is
17747     * dispatched to this view. The callback will be invoked before the key event is
17748     * given to the view. This is only useful for hardware keyboards; a software input
17749     * method has no obligation to trigger this listener.
17750     */
17751    public interface OnKeyListener {
17752        /**
17753         * Called when a hardware key is dispatched to a view. This allows listeners to
17754         * get a chance to respond before the target view.
17755         * <p>Key presses in software keyboards will generally NOT trigger this method,
17756         * although some may elect to do so in some situations. Do not assume a
17757         * software input method has to be key-based; even if it is, it may use key presses
17758         * in a different way than you expect, so there is no way to reliably catch soft
17759         * input key presses.
17760         *
17761         * @param v The view the key has been dispatched to.
17762         * @param keyCode The code for the physical key that was pressed
17763         * @param event The KeyEvent object containing full information about
17764         *        the event.
17765         * @return True if the listener has consumed the event, false otherwise.
17766         */
17767        boolean onKey(View v, int keyCode, KeyEvent event);
17768    }
17769
17770    /**
17771     * Interface definition for a callback to be invoked when a touch event is
17772     * dispatched to this view. The callback will be invoked before the touch
17773     * event is given to the view.
17774     */
17775    public interface OnTouchListener {
17776        /**
17777         * Called when a touch event is dispatched to a view. This allows listeners to
17778         * get a chance to respond before the target view.
17779         *
17780         * @param v The view the touch event has been dispatched to.
17781         * @param event The MotionEvent object containing full information about
17782         *        the event.
17783         * @return True if the listener has consumed the event, false otherwise.
17784         */
17785        boolean onTouch(View v, MotionEvent event);
17786    }
17787
17788    /**
17789     * Interface definition for a callback to be invoked when a hover event is
17790     * dispatched to this view. The callback will be invoked before the hover
17791     * event is given to the view.
17792     */
17793    public interface OnHoverListener {
17794        /**
17795         * Called when a hover event is dispatched to a view. This allows listeners to
17796         * get a chance to respond before the target view.
17797         *
17798         * @param v The view the hover event has been dispatched to.
17799         * @param event The MotionEvent object containing full information about
17800         *        the event.
17801         * @return True if the listener has consumed the event, false otherwise.
17802         */
17803        boolean onHover(View v, MotionEvent event);
17804    }
17805
17806    /**
17807     * Interface definition for a callback to be invoked when a generic motion event is
17808     * dispatched to this view. The callback will be invoked before the generic motion
17809     * event is given to the view.
17810     */
17811    public interface OnGenericMotionListener {
17812        /**
17813         * Called when a generic motion event is dispatched to a view. This allows listeners to
17814         * get a chance to respond before the target view.
17815         *
17816         * @param v The view the generic motion event has been dispatched to.
17817         * @param event The MotionEvent object containing full information about
17818         *        the event.
17819         * @return True if the listener has consumed the event, false otherwise.
17820         */
17821        boolean onGenericMotion(View v, MotionEvent event);
17822    }
17823
17824    /**
17825     * Interface definition for a callback to be invoked when a view has been clicked and held.
17826     */
17827    public interface OnLongClickListener {
17828        /**
17829         * Called when a view has been clicked and held.
17830         *
17831         * @param v The view that was clicked and held.
17832         *
17833         * @return true if the callback consumed the long click, false otherwise.
17834         */
17835        boolean onLongClick(View v);
17836    }
17837
17838    /**
17839     * Interface definition for a callback to be invoked when a drag is being dispatched
17840     * to this view.  The callback will be invoked before the hosting view's own
17841     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17842     * onDrag(event) behavior, it should return 'false' from this callback.
17843     *
17844     * <div class="special reference">
17845     * <h3>Developer Guides</h3>
17846     * <p>For a guide to implementing drag and drop features, read the
17847     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17848     * </div>
17849     */
17850    public interface OnDragListener {
17851        /**
17852         * Called when a drag event is dispatched to a view. This allows listeners
17853         * to get a chance to override base View behavior.
17854         *
17855         * @param v The View that received the drag event.
17856         * @param event The {@link android.view.DragEvent} object for the drag event.
17857         * @return {@code true} if the drag event was handled successfully, or {@code false}
17858         * if the drag event was not handled. Note that {@code false} will trigger the View
17859         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17860         */
17861        boolean onDrag(View v, DragEvent event);
17862    }
17863
17864    /**
17865     * Interface definition for a callback to be invoked when the focus state of
17866     * a view changed.
17867     */
17868    public interface OnFocusChangeListener {
17869        /**
17870         * Called when the focus state of a view has changed.
17871         *
17872         * @param v The view whose state has changed.
17873         * @param hasFocus The new focus state of v.
17874         */
17875        void onFocusChange(View v, boolean hasFocus);
17876    }
17877
17878    /**
17879     * Interface definition for a callback to be invoked when a view is clicked.
17880     */
17881    public interface OnClickListener {
17882        /**
17883         * Called when a view has been clicked.
17884         *
17885         * @param v The view that was clicked.
17886         */
17887        void onClick(View v);
17888    }
17889
17890    /**
17891     * Interface definition for a callback to be invoked when the context menu
17892     * for this view is being built.
17893     */
17894    public interface OnCreateContextMenuListener {
17895        /**
17896         * Called when the context menu for this view is being built. It is not
17897         * safe to hold onto the menu after this method returns.
17898         *
17899         * @param menu The context menu that is being built
17900         * @param v The view for which the context menu is being built
17901         * @param menuInfo Extra information about the item for which the
17902         *            context menu should be shown. This information will vary
17903         *            depending on the class of v.
17904         */
17905        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17906    }
17907
17908    /**
17909     * Interface definition for a callback to be invoked when the status bar changes
17910     * visibility.  This reports <strong>global</strong> changes to the system UI
17911     * state, not what the application is requesting.
17912     *
17913     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17914     */
17915    public interface OnSystemUiVisibilityChangeListener {
17916        /**
17917         * Called when the status bar changes visibility because of a call to
17918         * {@link View#setSystemUiVisibility(int)}.
17919         *
17920         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17921         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17922         * This tells you the <strong>global</strong> state of these UI visibility
17923         * flags, not what your app is currently applying.
17924         */
17925        public void onSystemUiVisibilityChange(int visibility);
17926    }
17927
17928    /**
17929     * Interface definition for a callback to be invoked when this view is attached
17930     * or detached from its window.
17931     */
17932    public interface OnAttachStateChangeListener {
17933        /**
17934         * Called when the view is attached to a window.
17935         * @param v The view that was attached
17936         */
17937        public void onViewAttachedToWindow(View v);
17938        /**
17939         * Called when the view is detached from a window.
17940         * @param v The view that was detached
17941         */
17942        public void onViewDetachedFromWindow(View v);
17943    }
17944
17945    private final class UnsetPressedState implements Runnable {
17946        public void run() {
17947            setPressed(false);
17948        }
17949    }
17950
17951    /**
17952     * Base class for derived classes that want to save and restore their own
17953     * state in {@link android.view.View#onSaveInstanceState()}.
17954     */
17955    public static class BaseSavedState extends AbsSavedState {
17956        /**
17957         * Constructor used when reading from a parcel. Reads the state of the superclass.
17958         *
17959         * @param source
17960         */
17961        public BaseSavedState(Parcel source) {
17962            super(source);
17963        }
17964
17965        /**
17966         * Constructor called by derived classes when creating their SavedState objects
17967         *
17968         * @param superState The state of the superclass of this view
17969         */
17970        public BaseSavedState(Parcelable superState) {
17971            super(superState);
17972        }
17973
17974        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17975                new Parcelable.Creator<BaseSavedState>() {
17976            public BaseSavedState createFromParcel(Parcel in) {
17977                return new BaseSavedState(in);
17978            }
17979
17980            public BaseSavedState[] newArray(int size) {
17981                return new BaseSavedState[size];
17982            }
17983        };
17984    }
17985
17986    /**
17987     * A set of information given to a view when it is attached to its parent
17988     * window.
17989     */
17990    static class AttachInfo {
17991        interface Callbacks {
17992            void playSoundEffect(int effectId);
17993            boolean performHapticFeedback(int effectId, boolean always);
17994        }
17995
17996        /**
17997         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17998         * to a Handler. This class contains the target (View) to invalidate and
17999         * the coordinates of the dirty rectangle.
18000         *
18001         * For performance purposes, this class also implements a pool of up to
18002         * POOL_LIMIT objects that get reused. This reduces memory allocations
18003         * whenever possible.
18004         */
18005        static class InvalidateInfo {
18006            private static final int POOL_LIMIT = 10;
18007
18008            private static final SynchronizedPool<InvalidateInfo> sPool =
18009                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18010
18011            View target;
18012
18013            int left;
18014            int top;
18015            int right;
18016            int bottom;
18017
18018            public static InvalidateInfo obtain() {
18019                InvalidateInfo instance = sPool.acquire();
18020                return (instance != null) ? instance : new InvalidateInfo();
18021            }
18022
18023            public void recycle() {
18024                target = null;
18025                sPool.release(this);
18026            }
18027        }
18028
18029        final IWindowSession mSession;
18030
18031        final IWindow mWindow;
18032
18033        final IBinder mWindowToken;
18034
18035        final Display mDisplay;
18036
18037        final Callbacks mRootCallbacks;
18038
18039        HardwareCanvas mHardwareCanvas;
18040
18041        IWindowId mIWindowId;
18042        WindowId mWindowId;
18043
18044        /**
18045         * The top view of the hierarchy.
18046         */
18047        View mRootView;
18048
18049        IBinder mPanelParentWindowToken;
18050        Surface mSurface;
18051
18052        boolean mHardwareAccelerated;
18053        boolean mHardwareAccelerationRequested;
18054        HardwareRenderer mHardwareRenderer;
18055
18056        boolean mScreenOn;
18057
18058        /**
18059         * Scale factor used by the compatibility mode
18060         */
18061        float mApplicationScale;
18062
18063        /**
18064         * Indicates whether the application is in compatibility mode
18065         */
18066        boolean mScalingRequired;
18067
18068        /**
18069         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18070         */
18071        boolean mTurnOffWindowResizeAnim;
18072
18073        /**
18074         * Left position of this view's window
18075         */
18076        int mWindowLeft;
18077
18078        /**
18079         * Top position of this view's window
18080         */
18081        int mWindowTop;
18082
18083        /**
18084         * Indicates whether views need to use 32-bit drawing caches
18085         */
18086        boolean mUse32BitDrawingCache;
18087
18088        /**
18089         * For windows that are full-screen but using insets to layout inside
18090         * of the screen areas, these are the current insets to appear inside
18091         * the overscan area of the display.
18092         */
18093        final Rect mOverscanInsets = new Rect();
18094
18095        /**
18096         * For windows that are full-screen but using insets to layout inside
18097         * of the screen decorations, these are the current insets for the
18098         * content of the window.
18099         */
18100        final Rect mContentInsets = new Rect();
18101
18102        /**
18103         * For windows that are full-screen but using insets to layout inside
18104         * of the screen decorations, these are the current insets for the
18105         * actual visible parts of the window.
18106         */
18107        final Rect mVisibleInsets = new Rect();
18108
18109        /**
18110         * The internal insets given by this window.  This value is
18111         * supplied by the client (through
18112         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18113         * be given to the window manager when changed to be used in laying
18114         * out windows behind it.
18115         */
18116        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18117                = new ViewTreeObserver.InternalInsetsInfo();
18118
18119        /**
18120         * All views in the window's hierarchy that serve as scroll containers,
18121         * used to determine if the window can be resized or must be panned
18122         * to adjust for a soft input area.
18123         */
18124        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18125
18126        final KeyEvent.DispatcherState mKeyDispatchState
18127                = new KeyEvent.DispatcherState();
18128
18129        /**
18130         * Indicates whether the view's window currently has the focus.
18131         */
18132        boolean mHasWindowFocus;
18133
18134        /**
18135         * The current visibility of the window.
18136         */
18137        int mWindowVisibility;
18138
18139        /**
18140         * Indicates the time at which drawing started to occur.
18141         */
18142        long mDrawingTime;
18143
18144        /**
18145         * Indicates whether or not ignoring the DIRTY_MASK flags.
18146         */
18147        boolean mIgnoreDirtyState;
18148
18149        /**
18150         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18151         * to avoid clearing that flag prematurely.
18152         */
18153        boolean mSetIgnoreDirtyState = false;
18154
18155        /**
18156         * Indicates whether the view's window is currently in touch mode.
18157         */
18158        boolean mInTouchMode;
18159
18160        /**
18161         * Indicates that ViewAncestor should trigger a global layout change
18162         * the next time it performs a traversal
18163         */
18164        boolean mRecomputeGlobalAttributes;
18165
18166        /**
18167         * Always report new attributes at next traversal.
18168         */
18169        boolean mForceReportNewAttributes;
18170
18171        /**
18172         * Set during a traveral if any views want to keep the screen on.
18173         */
18174        boolean mKeepScreenOn;
18175
18176        /**
18177         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18178         */
18179        int mSystemUiVisibility;
18180
18181        /**
18182         * Hack to force certain system UI visibility flags to be cleared.
18183         */
18184        int mDisabledSystemUiVisibility;
18185
18186        /**
18187         * Last global system UI visibility reported by the window manager.
18188         */
18189        int mGlobalSystemUiVisibility;
18190
18191        /**
18192         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18193         * attached.
18194         */
18195        boolean mHasSystemUiListeners;
18196
18197        /**
18198         * Set if the window has requested to extend into the overscan region
18199         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18200         */
18201        boolean mOverscanRequested;
18202
18203        /**
18204         * Set if the visibility of any views has changed.
18205         */
18206        boolean mViewVisibilityChanged;
18207
18208        /**
18209         * Set to true if a view has been scrolled.
18210         */
18211        boolean mViewScrollChanged;
18212
18213        /**
18214         * Global to the view hierarchy used as a temporary for dealing with
18215         * x/y points in the transparent region computations.
18216         */
18217        final int[] mTransparentLocation = new int[2];
18218
18219        /**
18220         * Global to the view hierarchy used as a temporary for dealing with
18221         * x/y points in the ViewGroup.invalidateChild implementation.
18222         */
18223        final int[] mInvalidateChildLocation = new int[2];
18224
18225
18226        /**
18227         * Global to the view hierarchy used as a temporary for dealing with
18228         * x/y location when view is transformed.
18229         */
18230        final float[] mTmpTransformLocation = new float[2];
18231
18232        /**
18233         * The view tree observer used to dispatch global events like
18234         * layout, pre-draw, touch mode change, etc.
18235         */
18236        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18237
18238        /**
18239         * A Canvas used by the view hierarchy to perform bitmap caching.
18240         */
18241        Canvas mCanvas;
18242
18243        /**
18244         * The view root impl.
18245         */
18246        final ViewRootImpl mViewRootImpl;
18247
18248        /**
18249         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18250         * handler can be used to pump events in the UI events queue.
18251         */
18252        final Handler mHandler;
18253
18254        /**
18255         * Temporary for use in computing invalidate rectangles while
18256         * calling up the hierarchy.
18257         */
18258        final Rect mTmpInvalRect = new Rect();
18259
18260        /**
18261         * Temporary for use in computing hit areas with transformed views
18262         */
18263        final RectF mTmpTransformRect = new RectF();
18264
18265        /**
18266         * Temporary for use in transforming invalidation rect
18267         */
18268        final Matrix mTmpMatrix = new Matrix();
18269
18270        /**
18271         * Temporary for use in transforming invalidation rect
18272         */
18273        final Transformation mTmpTransformation = new Transformation();
18274
18275        /**
18276         * Temporary list for use in collecting focusable descendents of a view.
18277         */
18278        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18279
18280        /**
18281         * The id of the window for accessibility purposes.
18282         */
18283        int mAccessibilityWindowId = View.NO_ID;
18284
18285        /**
18286         * Flags related to accessibility processing.
18287         *
18288         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18289         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18290         */
18291        int mAccessibilityFetchFlags;
18292
18293        /**
18294         * The drawable for highlighting accessibility focus.
18295         */
18296        Drawable mAccessibilityFocusDrawable;
18297
18298        /**
18299         * Show where the margins, bounds and layout bounds are for each view.
18300         */
18301        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18302
18303        /**
18304         * Point used to compute visible regions.
18305         */
18306        final Point mPoint = new Point();
18307
18308        /**
18309         * Used to track which View originated a requestLayout() call, used when
18310         * requestLayout() is called during layout.
18311         */
18312        View mViewRequestingLayout;
18313
18314        /**
18315         * Creates a new set of attachment information with the specified
18316         * events handler and thread.
18317         *
18318         * @param handler the events handler the view must use
18319         */
18320        AttachInfo(IWindowSession session, IWindow window, Display display,
18321                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18322            mSession = session;
18323            mWindow = window;
18324            mWindowToken = window.asBinder();
18325            mDisplay = display;
18326            mViewRootImpl = viewRootImpl;
18327            mHandler = handler;
18328            mRootCallbacks = effectPlayer;
18329        }
18330    }
18331
18332    /**
18333     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18334     * is supported. This avoids keeping too many unused fields in most
18335     * instances of View.</p>
18336     */
18337    private static class ScrollabilityCache implements Runnable {
18338
18339        /**
18340         * Scrollbars are not visible
18341         */
18342        public static final int OFF = 0;
18343
18344        /**
18345         * Scrollbars are visible
18346         */
18347        public static final int ON = 1;
18348
18349        /**
18350         * Scrollbars are fading away
18351         */
18352        public static final int FADING = 2;
18353
18354        public boolean fadeScrollBars;
18355
18356        public int fadingEdgeLength;
18357        public int scrollBarDefaultDelayBeforeFade;
18358        public int scrollBarFadeDuration;
18359
18360        public int scrollBarSize;
18361        public ScrollBarDrawable scrollBar;
18362        public float[] interpolatorValues;
18363        public View host;
18364
18365        public final Paint paint;
18366        public final Matrix matrix;
18367        public Shader shader;
18368
18369        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18370
18371        private static final float[] OPAQUE = { 255 };
18372        private static final float[] TRANSPARENT = { 0.0f };
18373
18374        /**
18375         * When fading should start. This time moves into the future every time
18376         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18377         */
18378        public long fadeStartTime;
18379
18380
18381        /**
18382         * The current state of the scrollbars: ON, OFF, or FADING
18383         */
18384        public int state = OFF;
18385
18386        private int mLastColor;
18387
18388        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18389            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18390            scrollBarSize = configuration.getScaledScrollBarSize();
18391            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18392            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18393
18394            paint = new Paint();
18395            matrix = new Matrix();
18396            // use use a height of 1, and then wack the matrix each time we
18397            // actually use it.
18398            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18399            paint.setShader(shader);
18400            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18401
18402            this.host = host;
18403        }
18404
18405        public void setFadeColor(int color) {
18406            if (color != mLastColor) {
18407                mLastColor = color;
18408
18409                if (color != 0) {
18410                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18411                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18412                    paint.setShader(shader);
18413                    // Restore the default transfer mode (src_over)
18414                    paint.setXfermode(null);
18415                } else {
18416                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18417                    paint.setShader(shader);
18418                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18419                }
18420            }
18421        }
18422
18423        public void run() {
18424            long now = AnimationUtils.currentAnimationTimeMillis();
18425            if (now >= fadeStartTime) {
18426
18427                // the animation fades the scrollbars out by changing
18428                // the opacity (alpha) from fully opaque to fully
18429                // transparent
18430                int nextFrame = (int) now;
18431                int framesCount = 0;
18432
18433                Interpolator interpolator = scrollBarInterpolator;
18434
18435                // Start opaque
18436                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18437
18438                // End transparent
18439                nextFrame += scrollBarFadeDuration;
18440                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18441
18442                state = FADING;
18443
18444                // Kick off the fade animation
18445                host.invalidate(true);
18446            }
18447        }
18448    }
18449
18450    /**
18451     * Resuable callback for sending
18452     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18453     */
18454    private class SendViewScrolledAccessibilityEvent implements Runnable {
18455        public volatile boolean mIsPending;
18456
18457        public void run() {
18458            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18459            mIsPending = false;
18460        }
18461    }
18462
18463    /**
18464     * <p>
18465     * This class represents a delegate that can be registered in a {@link View}
18466     * to enhance accessibility support via composition rather via inheritance.
18467     * It is specifically targeted to widget developers that extend basic View
18468     * classes i.e. classes in package android.view, that would like their
18469     * applications to be backwards compatible.
18470     * </p>
18471     * <div class="special reference">
18472     * <h3>Developer Guides</h3>
18473     * <p>For more information about making applications accessible, read the
18474     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18475     * developer guide.</p>
18476     * </div>
18477     * <p>
18478     * A scenario in which a developer would like to use an accessibility delegate
18479     * is overriding a method introduced in a later API version then the minimal API
18480     * version supported by the application. For example, the method
18481     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18482     * in API version 4 when the accessibility APIs were first introduced. If a
18483     * developer would like his application to run on API version 4 devices (assuming
18484     * all other APIs used by the application are version 4 or lower) and take advantage
18485     * of this method, instead of overriding the method which would break the application's
18486     * backwards compatibility, he can override the corresponding method in this
18487     * delegate and register the delegate in the target View if the API version of
18488     * the system is high enough i.e. the API version is same or higher to the API
18489     * version that introduced
18490     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18491     * </p>
18492     * <p>
18493     * Here is an example implementation:
18494     * </p>
18495     * <code><pre><p>
18496     * if (Build.VERSION.SDK_INT >= 14) {
18497     *     // If the API version is equal of higher than the version in
18498     *     // which onInitializeAccessibilityNodeInfo was introduced we
18499     *     // register a delegate with a customized implementation.
18500     *     View view = findViewById(R.id.view_id);
18501     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18502     *         public void onInitializeAccessibilityNodeInfo(View host,
18503     *                 AccessibilityNodeInfo info) {
18504     *             // Let the default implementation populate the info.
18505     *             super.onInitializeAccessibilityNodeInfo(host, info);
18506     *             // Set some other information.
18507     *             info.setEnabled(host.isEnabled());
18508     *         }
18509     *     });
18510     * }
18511     * </code></pre></p>
18512     * <p>
18513     * This delegate contains methods that correspond to the accessibility methods
18514     * in View. If a delegate has been specified the implementation in View hands
18515     * off handling to the corresponding method in this delegate. The default
18516     * implementation the delegate methods behaves exactly as the corresponding
18517     * method in View for the case of no accessibility delegate been set. Hence,
18518     * to customize the behavior of a View method, clients can override only the
18519     * corresponding delegate method without altering the behavior of the rest
18520     * accessibility related methods of the host view.
18521     * </p>
18522     */
18523    public static class AccessibilityDelegate {
18524
18525        /**
18526         * Sends an accessibility event of the given type. If accessibility is not
18527         * enabled this method has no effect.
18528         * <p>
18529         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18530         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18531         * been set.
18532         * </p>
18533         *
18534         * @param host The View hosting the delegate.
18535         * @param eventType The type of the event to send.
18536         *
18537         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18538         */
18539        public void sendAccessibilityEvent(View host, int eventType) {
18540            host.sendAccessibilityEventInternal(eventType);
18541        }
18542
18543        /**
18544         * Performs the specified accessibility action on the view. For
18545         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18546         * <p>
18547         * The default implementation behaves as
18548         * {@link View#performAccessibilityAction(int, Bundle)
18549         *  View#performAccessibilityAction(int, Bundle)} for the case of
18550         *  no accessibility delegate been set.
18551         * </p>
18552         *
18553         * @param action The action to perform.
18554         * @return Whether the action was performed.
18555         *
18556         * @see View#performAccessibilityAction(int, Bundle)
18557         *      View#performAccessibilityAction(int, Bundle)
18558         */
18559        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18560            return host.performAccessibilityActionInternal(action, args);
18561        }
18562
18563        /**
18564         * Sends an accessibility event. This method behaves exactly as
18565         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18566         * empty {@link AccessibilityEvent} and does not perform a check whether
18567         * accessibility is enabled.
18568         * <p>
18569         * The default implementation behaves as
18570         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18571         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18572         * the case of no accessibility delegate been set.
18573         * </p>
18574         *
18575         * @param host The View hosting the delegate.
18576         * @param event The event to send.
18577         *
18578         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18579         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18580         */
18581        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18582            host.sendAccessibilityEventUncheckedInternal(event);
18583        }
18584
18585        /**
18586         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18587         * to its children for adding their text content to the event.
18588         * <p>
18589         * The default implementation behaves as
18590         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18591         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18592         * the case of no accessibility delegate been set.
18593         * </p>
18594         *
18595         * @param host The View hosting the delegate.
18596         * @param event The event.
18597         * @return True if the event population was completed.
18598         *
18599         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18600         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18601         */
18602        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18603            return host.dispatchPopulateAccessibilityEventInternal(event);
18604        }
18605
18606        /**
18607         * Gives a chance to the host View to populate the accessibility event with its
18608         * text content.
18609         * <p>
18610         * The default implementation behaves as
18611         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18612         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18613         * the case of no accessibility delegate been set.
18614         * </p>
18615         *
18616         * @param host The View hosting the delegate.
18617         * @param event The accessibility event which to populate.
18618         *
18619         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18620         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18621         */
18622        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18623            host.onPopulateAccessibilityEventInternal(event);
18624        }
18625
18626        /**
18627         * Initializes an {@link AccessibilityEvent} with information about the
18628         * the host View which is the event source.
18629         * <p>
18630         * The default implementation behaves as
18631         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18632         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18633         * the case of no accessibility delegate been set.
18634         * </p>
18635         *
18636         * @param host The View hosting the delegate.
18637         * @param event The event to initialize.
18638         *
18639         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18640         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18641         */
18642        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18643            host.onInitializeAccessibilityEventInternal(event);
18644        }
18645
18646        /**
18647         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18648         * <p>
18649         * The default implementation behaves as
18650         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18651         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18652         * the case of no accessibility delegate been set.
18653         * </p>
18654         *
18655         * @param host The View hosting the delegate.
18656         * @param info The instance to initialize.
18657         *
18658         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18659         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18660         */
18661        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18662            host.onInitializeAccessibilityNodeInfoInternal(info);
18663        }
18664
18665        /**
18666         * Called when a child of the host View has requested sending an
18667         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18668         * to augment the event.
18669         * <p>
18670         * The default implementation behaves as
18671         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18672         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18673         * the case of no accessibility delegate been set.
18674         * </p>
18675         *
18676         * @param host The View hosting the delegate.
18677         * @param child The child which requests sending the event.
18678         * @param event The event to be sent.
18679         * @return True if the event should be sent
18680         *
18681         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18682         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18683         */
18684        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18685                AccessibilityEvent event) {
18686            return host.onRequestSendAccessibilityEventInternal(child, event);
18687        }
18688
18689        /**
18690         * Gets the provider for managing a virtual view hierarchy rooted at this View
18691         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18692         * that explore the window content.
18693         * <p>
18694         * The default implementation behaves as
18695         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18696         * the case of no accessibility delegate been set.
18697         * </p>
18698         *
18699         * @return The provider.
18700         *
18701         * @see AccessibilityNodeProvider
18702         */
18703        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18704            return null;
18705        }
18706    }
18707
18708    private class MatchIdPredicate implements Predicate<View> {
18709        public int mId;
18710
18711        @Override
18712        public boolean apply(View view) {
18713            return (view.mID == mId);
18714        }
18715    }
18716
18717    private class MatchLabelForPredicate implements Predicate<View> {
18718        private int mLabeledId;
18719
18720        @Override
18721        public boolean apply(View view) {
18722            return (view.mLabelForId == mLabeledId);
18723        }
18724    }
18725
18726    /**
18727     * Dump all private flags in readable format, useful for documentation and
18728     * sanity checking.
18729     */
18730    private static void dumpFlags() {
18731        final HashMap<String, String> found = Maps.newHashMap();
18732        try {
18733            for (Field field : View.class.getDeclaredFields()) {
18734                final int modifiers = field.getModifiers();
18735                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18736                    if (field.getType().equals(int.class)) {
18737                        final int value = field.getInt(null);
18738                        dumpFlag(found, field.getName(), value);
18739                    } else if (field.getType().equals(int[].class)) {
18740                        final int[] values = (int[]) field.get(null);
18741                        for (int i = 0; i < values.length; i++) {
18742                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18743                        }
18744                    }
18745                }
18746            }
18747        } catch (IllegalAccessException e) {
18748            throw new RuntimeException(e);
18749        }
18750
18751        final ArrayList<String> keys = Lists.newArrayList();
18752        keys.addAll(found.keySet());
18753        Collections.sort(keys);
18754        for (String key : keys) {
18755            Log.d(VIEW_LOG_TAG, found.get(key));
18756        }
18757    }
18758
18759    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18760        // Sort flags by prefix, then by bits, always keeping unique keys
18761        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18762        final int prefix = name.indexOf('_');
18763        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18764        final String output = bits + " " + name;
18765        found.put(key, output);
18766    }
18767}
18768