View.java revision 1ae3b6aedde52a4b13003ee078aa193ffc611793
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;
2919
2920    /**
2921     * Cache initial right padding.
2922     *
2923     * @hide
2924     */
2925    int mUserPaddingRightInitial;
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 = (startPadding != UNDEFINED_PADDING);
3392                    break;
3393                case com.android.internal.R.styleable.View_paddingEnd:
3394                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3395                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
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            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3716
3717            if (leftPaddingDefined && !hasRelativePadding) {
3718                mUserPaddingLeftInitial = leftPadding;
3719            }
3720            if (rightPaddingDefined && !hasRelativePadding) {
3721                mUserPaddingRightInitial = rightPadding;
3722            }
3723        }
3724
3725        internalSetPadding(
3726                mUserPaddingLeftInitial,
3727                topPadding >= 0 ? topPadding : mPaddingTop,
3728                mUserPaddingRightInitial,
3729                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3730
3731        if (viewFlagMasks != 0) {
3732            setFlags(viewFlagValues, viewFlagMasks);
3733        }
3734
3735        if (initializeScrollbars) {
3736            initializeScrollbars(a);
3737        }
3738
3739        a.recycle();
3740
3741        // Needs to be called after mViewFlags is set
3742        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3743            recomputePadding();
3744        }
3745
3746        if (x != 0 || y != 0) {
3747            scrollTo(x, y);
3748        }
3749
3750        if (transformSet) {
3751            setTranslationX(tx);
3752            setTranslationY(ty);
3753            setRotation(rotation);
3754            setRotationX(rotationX);
3755            setRotationY(rotationY);
3756            setScaleX(sx);
3757            setScaleY(sy);
3758        }
3759
3760        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3761            setScrollContainer(true);
3762        }
3763
3764        computeOpaqueFlags();
3765    }
3766
3767    /**
3768     * Non-public constructor for use in testing
3769     */
3770    View() {
3771        mResources = null;
3772    }
3773
3774    public String toString() {
3775        StringBuilder out = new StringBuilder(128);
3776        out.append(getClass().getName());
3777        out.append('{');
3778        out.append(Integer.toHexString(System.identityHashCode(this)));
3779        out.append(' ');
3780        switch (mViewFlags&VISIBILITY_MASK) {
3781            case VISIBLE: out.append('V'); break;
3782            case INVISIBLE: out.append('I'); break;
3783            case GONE: out.append('G'); break;
3784            default: out.append('.'); break;
3785        }
3786        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3787        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3788        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3789        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3790        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3791        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3792        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3793        out.append(' ');
3794        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3795        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3796        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3797        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3798            out.append('p');
3799        } else {
3800            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3801        }
3802        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3803        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3804        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3805        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3806        out.append(' ');
3807        out.append(mLeft);
3808        out.append(',');
3809        out.append(mTop);
3810        out.append('-');
3811        out.append(mRight);
3812        out.append(',');
3813        out.append(mBottom);
3814        final int id = getId();
3815        if (id != NO_ID) {
3816            out.append(" #");
3817            out.append(Integer.toHexString(id));
3818            final Resources r = mResources;
3819            if (id != 0 && r != null) {
3820                try {
3821                    String pkgname;
3822                    switch (id&0xff000000) {
3823                        case 0x7f000000:
3824                            pkgname="app";
3825                            break;
3826                        case 0x01000000:
3827                            pkgname="android";
3828                            break;
3829                        default:
3830                            pkgname = r.getResourcePackageName(id);
3831                            break;
3832                    }
3833                    String typename = r.getResourceTypeName(id);
3834                    String entryname = r.getResourceEntryName(id);
3835                    out.append(" ");
3836                    out.append(pkgname);
3837                    out.append(":");
3838                    out.append(typename);
3839                    out.append("/");
3840                    out.append(entryname);
3841                } catch (Resources.NotFoundException e) {
3842                }
3843            }
3844        }
3845        out.append("}");
3846        return out.toString();
3847    }
3848
3849    /**
3850     * <p>
3851     * Initializes the fading edges from a given set of styled attributes. This
3852     * method should be called by subclasses that need fading edges and when an
3853     * instance of these subclasses is created programmatically rather than
3854     * being inflated from XML. This method is automatically called when the XML
3855     * is inflated.
3856     * </p>
3857     *
3858     * @param a the styled attributes set to initialize the fading edges from
3859     */
3860    protected void initializeFadingEdge(TypedArray a) {
3861        initScrollCache();
3862
3863        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3864                R.styleable.View_fadingEdgeLength,
3865                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3866    }
3867
3868    /**
3869     * Returns the size of the vertical faded edges used to indicate that more
3870     * content in this view is visible.
3871     *
3872     * @return The size in pixels of the vertical faded edge or 0 if vertical
3873     *         faded edges are not enabled for this view.
3874     * @attr ref android.R.styleable#View_fadingEdgeLength
3875     */
3876    public int getVerticalFadingEdgeLength() {
3877        if (isVerticalFadingEdgeEnabled()) {
3878            ScrollabilityCache cache = mScrollCache;
3879            if (cache != null) {
3880                return cache.fadingEdgeLength;
3881            }
3882        }
3883        return 0;
3884    }
3885
3886    /**
3887     * Set the size of the faded edge used to indicate that more content in this
3888     * view is available.  Will not change whether the fading edge is enabled; use
3889     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3890     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3891     * for the vertical or horizontal fading edges.
3892     *
3893     * @param length The size in pixels of the faded edge used to indicate that more
3894     *        content in this view is visible.
3895     */
3896    public void setFadingEdgeLength(int length) {
3897        initScrollCache();
3898        mScrollCache.fadingEdgeLength = length;
3899    }
3900
3901    /**
3902     * Returns the size of the horizontal faded edges used to indicate that more
3903     * content in this view is visible.
3904     *
3905     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3906     *         faded edges are not enabled for this view.
3907     * @attr ref android.R.styleable#View_fadingEdgeLength
3908     */
3909    public int getHorizontalFadingEdgeLength() {
3910        if (isHorizontalFadingEdgeEnabled()) {
3911            ScrollabilityCache cache = mScrollCache;
3912            if (cache != null) {
3913                return cache.fadingEdgeLength;
3914            }
3915        }
3916        return 0;
3917    }
3918
3919    /**
3920     * Returns the width of the vertical scrollbar.
3921     *
3922     * @return The width in pixels of the vertical scrollbar or 0 if there
3923     *         is no vertical scrollbar.
3924     */
3925    public int getVerticalScrollbarWidth() {
3926        ScrollabilityCache cache = mScrollCache;
3927        if (cache != null) {
3928            ScrollBarDrawable scrollBar = cache.scrollBar;
3929            if (scrollBar != null) {
3930                int size = scrollBar.getSize(true);
3931                if (size <= 0) {
3932                    size = cache.scrollBarSize;
3933                }
3934                return size;
3935            }
3936            return 0;
3937        }
3938        return 0;
3939    }
3940
3941    /**
3942     * Returns the height of the horizontal scrollbar.
3943     *
3944     * @return The height in pixels of the horizontal scrollbar or 0 if
3945     *         there is no horizontal scrollbar.
3946     */
3947    protected int getHorizontalScrollbarHeight() {
3948        ScrollabilityCache cache = mScrollCache;
3949        if (cache != null) {
3950            ScrollBarDrawable scrollBar = cache.scrollBar;
3951            if (scrollBar != null) {
3952                int size = scrollBar.getSize(false);
3953                if (size <= 0) {
3954                    size = cache.scrollBarSize;
3955                }
3956                return size;
3957            }
3958            return 0;
3959        }
3960        return 0;
3961    }
3962
3963    /**
3964     * <p>
3965     * Initializes the scrollbars from a given set of styled attributes. This
3966     * method should be called by subclasses that need scrollbars and when an
3967     * instance of these subclasses is created programmatically rather than
3968     * being inflated from XML. This method is automatically called when the XML
3969     * is inflated.
3970     * </p>
3971     *
3972     * @param a the styled attributes set to initialize the scrollbars from
3973     */
3974    protected void initializeScrollbars(TypedArray a) {
3975        initScrollCache();
3976
3977        final ScrollabilityCache scrollabilityCache = mScrollCache;
3978
3979        if (scrollabilityCache.scrollBar == null) {
3980            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3981        }
3982
3983        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3984
3985        if (!fadeScrollbars) {
3986            scrollabilityCache.state = ScrollabilityCache.ON;
3987        }
3988        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3989
3990
3991        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3992                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3993                        .getScrollBarFadeDuration());
3994        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3995                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3996                ViewConfiguration.getScrollDefaultDelay());
3997
3998
3999        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4000                com.android.internal.R.styleable.View_scrollbarSize,
4001                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4002
4003        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4004        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4005
4006        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4007        if (thumb != null) {
4008            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4009        }
4010
4011        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4012                false);
4013        if (alwaysDraw) {
4014            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4015        }
4016
4017        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4018        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4019
4020        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4021        if (thumb != null) {
4022            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4023        }
4024
4025        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4026                false);
4027        if (alwaysDraw) {
4028            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4029        }
4030
4031        // Apply layout direction to the new Drawables if needed
4032        final int layoutDirection = getLayoutDirection();
4033        if (track != null) {
4034            track.setLayoutDirection(layoutDirection);
4035        }
4036        if (thumb != null) {
4037            thumb.setLayoutDirection(layoutDirection);
4038        }
4039
4040        // Re-apply user/background padding so that scrollbar(s) get added
4041        resolvePadding();
4042    }
4043
4044    /**
4045     * <p>
4046     * Initalizes the scrollability cache if necessary.
4047     * </p>
4048     */
4049    private void initScrollCache() {
4050        if (mScrollCache == null) {
4051            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4052        }
4053    }
4054
4055    private ScrollabilityCache getScrollCache() {
4056        initScrollCache();
4057        return mScrollCache;
4058    }
4059
4060    /**
4061     * Set the position of the vertical scroll bar. Should be one of
4062     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4063     * {@link #SCROLLBAR_POSITION_RIGHT}.
4064     *
4065     * @param position Where the vertical scroll bar should be positioned.
4066     */
4067    public void setVerticalScrollbarPosition(int position) {
4068        if (mVerticalScrollbarPosition != position) {
4069            mVerticalScrollbarPosition = position;
4070            computeOpaqueFlags();
4071            resolvePadding();
4072        }
4073    }
4074
4075    /**
4076     * @return The position where the vertical scroll bar will show, if applicable.
4077     * @see #setVerticalScrollbarPosition(int)
4078     */
4079    public int getVerticalScrollbarPosition() {
4080        return mVerticalScrollbarPosition;
4081    }
4082
4083    ListenerInfo getListenerInfo() {
4084        if (mListenerInfo != null) {
4085            return mListenerInfo;
4086        }
4087        mListenerInfo = new ListenerInfo();
4088        return mListenerInfo;
4089    }
4090
4091    /**
4092     * Register a callback to be invoked when focus of this view changed.
4093     *
4094     * @param l The callback that will run.
4095     */
4096    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4097        getListenerInfo().mOnFocusChangeListener = l;
4098    }
4099
4100    /**
4101     * Add a listener that will be called when the bounds of the view change due to
4102     * layout processing.
4103     *
4104     * @param listener The listener that will be called when layout bounds change.
4105     */
4106    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4107        ListenerInfo li = getListenerInfo();
4108        if (li.mOnLayoutChangeListeners == null) {
4109            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4110        }
4111        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4112            li.mOnLayoutChangeListeners.add(listener);
4113        }
4114    }
4115
4116    /**
4117     * Remove a listener for layout changes.
4118     *
4119     * @param listener The listener for layout bounds change.
4120     */
4121    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4122        ListenerInfo li = mListenerInfo;
4123        if (li == null || li.mOnLayoutChangeListeners == null) {
4124            return;
4125        }
4126        li.mOnLayoutChangeListeners.remove(listener);
4127    }
4128
4129    /**
4130     * Add a listener for attach state changes.
4131     *
4132     * This listener will be called whenever this view is attached or detached
4133     * from a window. Remove the listener using
4134     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4135     *
4136     * @param listener Listener to attach
4137     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4138     */
4139    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4140        ListenerInfo li = getListenerInfo();
4141        if (li.mOnAttachStateChangeListeners == null) {
4142            li.mOnAttachStateChangeListeners
4143                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4144        }
4145        li.mOnAttachStateChangeListeners.add(listener);
4146    }
4147
4148    /**
4149     * Remove a listener for attach state changes. The listener will receive no further
4150     * notification of window attach/detach events.
4151     *
4152     * @param listener Listener to remove
4153     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4154     */
4155    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4156        ListenerInfo li = mListenerInfo;
4157        if (li == null || li.mOnAttachStateChangeListeners == null) {
4158            return;
4159        }
4160        li.mOnAttachStateChangeListeners.remove(listener);
4161    }
4162
4163    /**
4164     * Returns the focus-change callback registered for this view.
4165     *
4166     * @return The callback, or null if one is not registered.
4167     */
4168    public OnFocusChangeListener getOnFocusChangeListener() {
4169        ListenerInfo li = mListenerInfo;
4170        return li != null ? li.mOnFocusChangeListener : null;
4171    }
4172
4173    /**
4174     * Register a callback to be invoked when this view is clicked. If this view is not
4175     * clickable, it becomes clickable.
4176     *
4177     * @param l The callback that will run
4178     *
4179     * @see #setClickable(boolean)
4180     */
4181    public void setOnClickListener(OnClickListener l) {
4182        if (!isClickable()) {
4183            setClickable(true);
4184        }
4185        getListenerInfo().mOnClickListener = l;
4186    }
4187
4188    /**
4189     * Return whether this view has an attached OnClickListener.  Returns
4190     * true if there is a listener, false if there is none.
4191     */
4192    public boolean hasOnClickListeners() {
4193        ListenerInfo li = mListenerInfo;
4194        return (li != null && li.mOnClickListener != null);
4195    }
4196
4197    /**
4198     * Register a callback to be invoked when this view is clicked and held. If this view is not
4199     * long clickable, it becomes long clickable.
4200     *
4201     * @param l The callback that will run
4202     *
4203     * @see #setLongClickable(boolean)
4204     */
4205    public void setOnLongClickListener(OnLongClickListener l) {
4206        if (!isLongClickable()) {
4207            setLongClickable(true);
4208        }
4209        getListenerInfo().mOnLongClickListener = l;
4210    }
4211
4212    /**
4213     * Register a callback to be invoked when the context menu for this view is
4214     * being built. If this view is not long clickable, it becomes long clickable.
4215     *
4216     * @param l The callback that will run
4217     *
4218     */
4219    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4220        if (!isLongClickable()) {
4221            setLongClickable(true);
4222        }
4223        getListenerInfo().mOnCreateContextMenuListener = l;
4224    }
4225
4226    /**
4227     * Call this view's OnClickListener, if it is defined.  Performs all normal
4228     * actions associated with clicking: reporting accessibility event, playing
4229     * a sound, etc.
4230     *
4231     * @return True there was an assigned OnClickListener that was called, false
4232     *         otherwise is returned.
4233     */
4234    public boolean performClick() {
4235        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4236
4237        ListenerInfo li = mListenerInfo;
4238        if (li != null && li.mOnClickListener != null) {
4239            playSoundEffect(SoundEffectConstants.CLICK);
4240            li.mOnClickListener.onClick(this);
4241            return true;
4242        }
4243
4244        return false;
4245    }
4246
4247    /**
4248     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4249     * this only calls the listener, and does not do any associated clicking
4250     * actions like reporting an accessibility event.
4251     *
4252     * @return True there was an assigned OnClickListener that was called, false
4253     *         otherwise is returned.
4254     */
4255    public boolean callOnClick() {
4256        ListenerInfo li = mListenerInfo;
4257        if (li != null && li.mOnClickListener != null) {
4258            li.mOnClickListener.onClick(this);
4259            return true;
4260        }
4261        return false;
4262    }
4263
4264    /**
4265     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4266     * OnLongClickListener did not consume the event.
4267     *
4268     * @return True if one of the above receivers consumed the event, false otherwise.
4269     */
4270    public boolean performLongClick() {
4271        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4272
4273        boolean handled = false;
4274        ListenerInfo li = mListenerInfo;
4275        if (li != null && li.mOnLongClickListener != null) {
4276            handled = li.mOnLongClickListener.onLongClick(View.this);
4277        }
4278        if (!handled) {
4279            handled = showContextMenu();
4280        }
4281        if (handled) {
4282            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4283        }
4284        return handled;
4285    }
4286
4287    /**
4288     * Performs button-related actions during a touch down event.
4289     *
4290     * @param event The event.
4291     * @return True if the down was consumed.
4292     *
4293     * @hide
4294     */
4295    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4296        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4297            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4298                return true;
4299            }
4300        }
4301        return false;
4302    }
4303
4304    /**
4305     * Bring up the context menu for this view.
4306     *
4307     * @return Whether a context menu was displayed.
4308     */
4309    public boolean showContextMenu() {
4310        return getParent().showContextMenuForChild(this);
4311    }
4312
4313    /**
4314     * Bring up the context menu for this view, referring to the item under the specified point.
4315     *
4316     * @param x The referenced x coordinate.
4317     * @param y The referenced y coordinate.
4318     * @param metaState The keyboard modifiers that were pressed.
4319     * @return Whether a context menu was displayed.
4320     *
4321     * @hide
4322     */
4323    public boolean showContextMenu(float x, float y, int metaState) {
4324        return showContextMenu();
4325    }
4326
4327    /**
4328     * Start an action mode.
4329     *
4330     * @param callback Callback that will control the lifecycle of the action mode
4331     * @return The new action mode if it is started, null otherwise
4332     *
4333     * @see ActionMode
4334     */
4335    public ActionMode startActionMode(ActionMode.Callback callback) {
4336        ViewParent parent = getParent();
4337        if (parent == null) return null;
4338        return parent.startActionModeForChild(this, callback);
4339    }
4340
4341    /**
4342     * Register a callback to be invoked when a hardware key is pressed in this view.
4343     * Key presses in software input methods will generally not trigger the methods of
4344     * this listener.
4345     * @param l the key listener to attach to this view
4346     */
4347    public void setOnKeyListener(OnKeyListener l) {
4348        getListenerInfo().mOnKeyListener = l;
4349    }
4350
4351    /**
4352     * Register a callback to be invoked when a touch event is sent to this view.
4353     * @param l the touch listener to attach to this view
4354     */
4355    public void setOnTouchListener(OnTouchListener l) {
4356        getListenerInfo().mOnTouchListener = l;
4357    }
4358
4359    /**
4360     * Register a callback to be invoked when a generic motion event is sent to this view.
4361     * @param l the generic motion listener to attach to this view
4362     */
4363    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4364        getListenerInfo().mOnGenericMotionListener = l;
4365    }
4366
4367    /**
4368     * Register a callback to be invoked when a hover event is sent to this view.
4369     * @param l the hover listener to attach to this view
4370     */
4371    public void setOnHoverListener(OnHoverListener l) {
4372        getListenerInfo().mOnHoverListener = l;
4373    }
4374
4375    /**
4376     * Register a drag event listener callback object for this View. The parameter is
4377     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4378     * View, the system calls the
4379     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4380     * @param l An implementation of {@link android.view.View.OnDragListener}.
4381     */
4382    public void setOnDragListener(OnDragListener l) {
4383        getListenerInfo().mOnDragListener = l;
4384    }
4385
4386    /**
4387     * Give this view focus. This will cause
4388     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4389     *
4390     * Note: this does not check whether this {@link View} should get focus, it just
4391     * gives it focus no matter what.  It should only be called internally by framework
4392     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4393     *
4394     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4395     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4396     *        focus moved when requestFocus() is called. It may not always
4397     *        apply, in which case use the default View.FOCUS_DOWN.
4398     * @param previouslyFocusedRect The rectangle of the view that had focus
4399     *        prior in this View's coordinate system.
4400     */
4401    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4402        if (DBG) {
4403            System.out.println(this + " requestFocus()");
4404        }
4405
4406        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4407            mPrivateFlags |= PFLAG_FOCUSED;
4408
4409            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4410
4411            if (mParent != null) {
4412                mParent.requestChildFocus(this, this);
4413            }
4414
4415            if (mAttachInfo != null) {
4416                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4417            }
4418
4419            onFocusChanged(true, direction, previouslyFocusedRect);
4420            refreshDrawableState();
4421
4422            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4423                notifyAccessibilityStateChanged();
4424            }
4425        }
4426    }
4427
4428    /**
4429     * Request that a rectangle of this view be visible on the screen,
4430     * scrolling if necessary just enough.
4431     *
4432     * <p>A View should call this if it maintains some notion of which part
4433     * of its content is interesting.  For example, a text editing view
4434     * should call this when its cursor moves.
4435     *
4436     * @param rectangle The rectangle.
4437     * @return Whether any parent scrolled.
4438     */
4439    public boolean requestRectangleOnScreen(Rect rectangle) {
4440        return requestRectangleOnScreen(rectangle, false);
4441    }
4442
4443    /**
4444     * Request that a rectangle of this view be visible on the screen,
4445     * scrolling if necessary just enough.
4446     *
4447     * <p>A View should call this if it maintains some notion of which part
4448     * of its content is interesting.  For example, a text editing view
4449     * should call this when its cursor moves.
4450     *
4451     * <p>When <code>immediate</code> is set to true, scrolling will not be
4452     * animated.
4453     *
4454     * @param rectangle The rectangle.
4455     * @param immediate True to forbid animated scrolling, false otherwise
4456     * @return Whether any parent scrolled.
4457     */
4458    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4459        if (mParent == null) {
4460            return false;
4461        }
4462
4463        View child = this;
4464
4465        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4466        position.set(rectangle);
4467
4468        ViewParent parent = mParent;
4469        boolean scrolled = false;
4470        while (parent != null) {
4471            rectangle.set((int) position.left, (int) position.top,
4472                    (int) position.right, (int) position.bottom);
4473
4474            scrolled |= parent.requestChildRectangleOnScreen(child,
4475                    rectangle, immediate);
4476
4477            if (!child.hasIdentityMatrix()) {
4478                child.getMatrix().mapRect(position);
4479            }
4480
4481            position.offset(child.mLeft, child.mTop);
4482
4483            if (!(parent instanceof View)) {
4484                break;
4485            }
4486
4487            View parentView = (View) parent;
4488
4489            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4490
4491            child = parentView;
4492            parent = child.getParent();
4493        }
4494
4495        return scrolled;
4496    }
4497
4498    /**
4499     * Called when this view wants to give up focus. If focus is cleared
4500     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4501     * <p>
4502     * <strong>Note:</strong> When a View clears focus the framework is trying
4503     * to give focus to the first focusable View from the top. Hence, if this
4504     * View is the first from the top that can take focus, then all callbacks
4505     * related to clearing focus will be invoked after wich the framework will
4506     * give focus to this view.
4507     * </p>
4508     */
4509    public void clearFocus() {
4510        if (DBG) {
4511            System.out.println(this + " clearFocus()");
4512        }
4513
4514        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4515            mPrivateFlags &= ~PFLAG_FOCUSED;
4516
4517            if (mParent != null) {
4518                mParent.clearChildFocus(this);
4519            }
4520
4521            onFocusChanged(false, 0, null);
4522
4523            refreshDrawableState();
4524
4525            if (!rootViewRequestFocus()) {
4526                notifyGlobalFocusCleared(this);
4527            }
4528
4529            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4530                notifyAccessibilityStateChanged();
4531            }
4532        }
4533    }
4534
4535    void notifyGlobalFocusCleared(View oldFocus) {
4536        if (oldFocus != null && mAttachInfo != null) {
4537            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4538        }
4539    }
4540
4541    boolean rootViewRequestFocus() {
4542        View root = getRootView();
4543        if (root != null) {
4544            return root.requestFocus();
4545        }
4546        return false;
4547    }
4548
4549    /**
4550     * Called internally by the view system when a new view is getting focus.
4551     * This is what clears the old focus.
4552     */
4553    void unFocus() {
4554        if (DBG) {
4555            System.out.println(this + " unFocus()");
4556        }
4557
4558        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4559            mPrivateFlags &= ~PFLAG_FOCUSED;
4560
4561            onFocusChanged(false, 0, null);
4562            refreshDrawableState();
4563
4564            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4565                notifyAccessibilityStateChanged();
4566            }
4567        }
4568    }
4569
4570    /**
4571     * Returns true if this view has focus iteself, or is the ancestor of the
4572     * view that has focus.
4573     *
4574     * @return True if this view has or contains focus, false otherwise.
4575     */
4576    @ViewDebug.ExportedProperty(category = "focus")
4577    public boolean hasFocus() {
4578        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4579    }
4580
4581    /**
4582     * Returns true if this view is focusable or if it contains a reachable View
4583     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4584     * is a View whose parents do not block descendants focus.
4585     *
4586     * Only {@link #VISIBLE} views are considered focusable.
4587     *
4588     * @return True if the view is focusable or if the view contains a focusable
4589     *         View, false otherwise.
4590     *
4591     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4592     */
4593    public boolean hasFocusable() {
4594        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4595    }
4596
4597    /**
4598     * Called by the view system when the focus state of this view changes.
4599     * When the focus change event is caused by directional navigation, direction
4600     * and previouslyFocusedRect provide insight into where the focus is coming from.
4601     * When overriding, be sure to call up through to the super class so that
4602     * the standard focus handling will occur.
4603     *
4604     * @param gainFocus True if the View has focus; false otherwise.
4605     * @param direction The direction focus has moved when requestFocus()
4606     *                  is called to give this view focus. Values are
4607     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4608     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4609     *                  It may not always apply, in which case use the default.
4610     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4611     *        system, of the previously focused view.  If applicable, this will be
4612     *        passed in as finer grained information about where the focus is coming
4613     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4614     */
4615    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4616        if (gainFocus) {
4617            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4618                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4619            }
4620        }
4621
4622        InputMethodManager imm = InputMethodManager.peekInstance();
4623        if (!gainFocus) {
4624            if (isPressed()) {
4625                setPressed(false);
4626            }
4627            if (imm != null && mAttachInfo != null
4628                    && mAttachInfo.mHasWindowFocus) {
4629                imm.focusOut(this);
4630            }
4631            onFocusLost();
4632        } else if (imm != null && mAttachInfo != null
4633                && mAttachInfo.mHasWindowFocus) {
4634            imm.focusIn(this);
4635        }
4636
4637        invalidate(true);
4638        ListenerInfo li = mListenerInfo;
4639        if (li != null && li.mOnFocusChangeListener != null) {
4640            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4641        }
4642
4643        if (mAttachInfo != null) {
4644            mAttachInfo.mKeyDispatchState.reset(this);
4645        }
4646    }
4647
4648    /**
4649     * Sends an accessibility event of the given type. If accessibility is
4650     * not enabled this method has no effect. The default implementation calls
4651     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4652     * to populate information about the event source (this View), then calls
4653     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4654     * populate the text content of the event source including its descendants,
4655     * and last calls
4656     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4657     * on its parent to resuest sending of the event to interested parties.
4658     * <p>
4659     * If an {@link AccessibilityDelegate} has been specified via calling
4660     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4661     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4662     * responsible for handling this call.
4663     * </p>
4664     *
4665     * @param eventType The type of the event to send, as defined by several types from
4666     * {@link android.view.accessibility.AccessibilityEvent}, such as
4667     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4668     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4669     *
4670     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4671     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4672     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4673     * @see AccessibilityDelegate
4674     */
4675    public void sendAccessibilityEvent(int eventType) {
4676        if (mAccessibilityDelegate != null) {
4677            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4678        } else {
4679            sendAccessibilityEventInternal(eventType);
4680        }
4681    }
4682
4683    /**
4684     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4685     * {@link AccessibilityEvent} to make an announcement which is related to some
4686     * sort of a context change for which none of the events representing UI transitions
4687     * is a good fit. For example, announcing a new page in a book. If accessibility
4688     * is not enabled this method does nothing.
4689     *
4690     * @param text The announcement text.
4691     */
4692    public void announceForAccessibility(CharSequence text) {
4693        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4694            AccessibilityEvent event = AccessibilityEvent.obtain(
4695                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4696            onInitializeAccessibilityEvent(event);
4697            event.getText().add(text);
4698            event.setContentDescription(null);
4699            mParent.requestSendAccessibilityEvent(this, event);
4700        }
4701    }
4702
4703    /**
4704     * @see #sendAccessibilityEvent(int)
4705     *
4706     * Note: Called from the default {@link AccessibilityDelegate}.
4707     */
4708    void sendAccessibilityEventInternal(int eventType) {
4709        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4710            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4711        }
4712    }
4713
4714    /**
4715     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4716     * takes as an argument an empty {@link AccessibilityEvent} and does not
4717     * perform a check whether accessibility is enabled.
4718     * <p>
4719     * If an {@link AccessibilityDelegate} has been specified via calling
4720     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4721     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4722     * is responsible for handling this call.
4723     * </p>
4724     *
4725     * @param event The event to send.
4726     *
4727     * @see #sendAccessibilityEvent(int)
4728     */
4729    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4730        if (mAccessibilityDelegate != null) {
4731            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4732        } else {
4733            sendAccessibilityEventUncheckedInternal(event);
4734        }
4735    }
4736
4737    /**
4738     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4739     *
4740     * Note: Called from the default {@link AccessibilityDelegate}.
4741     */
4742    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4743        if (!isShown()) {
4744            return;
4745        }
4746        onInitializeAccessibilityEvent(event);
4747        // Only a subset of accessibility events populates text content.
4748        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4749            dispatchPopulateAccessibilityEvent(event);
4750        }
4751        // In the beginning we called #isShown(), so we know that getParent() is not null.
4752        getParent().requestSendAccessibilityEvent(this, event);
4753    }
4754
4755    /**
4756     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4757     * to its children for adding their text content to the event. Note that the
4758     * event text is populated in a separate dispatch path since we add to the
4759     * event not only the text of the source but also the text of all its descendants.
4760     * A typical implementation will call
4761     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4762     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4763     * on each child. Override this method if custom population of the event text
4764     * content is required.
4765     * <p>
4766     * If an {@link AccessibilityDelegate} has been specified via calling
4767     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4768     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4769     * is responsible for handling this call.
4770     * </p>
4771     * <p>
4772     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4773     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4774     * </p>
4775     *
4776     * @param event The event.
4777     *
4778     * @return True if the event population was completed.
4779     */
4780    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4781        if (mAccessibilityDelegate != null) {
4782            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4783        } else {
4784            return dispatchPopulateAccessibilityEventInternal(event);
4785        }
4786    }
4787
4788    /**
4789     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4790     *
4791     * Note: Called from the default {@link AccessibilityDelegate}.
4792     */
4793    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4794        onPopulateAccessibilityEvent(event);
4795        return false;
4796    }
4797
4798    /**
4799     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4800     * giving a chance to this View to populate the accessibility event with its
4801     * text content. While this method is free to modify event
4802     * attributes other than text content, doing so should normally be performed in
4803     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4804     * <p>
4805     * Example: Adding formatted date string to an accessibility event in addition
4806     *          to the text added by the super implementation:
4807     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4808     *     super.onPopulateAccessibilityEvent(event);
4809     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4810     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4811     *         mCurrentDate.getTimeInMillis(), flags);
4812     *     event.getText().add(selectedDateUtterance);
4813     * }</pre>
4814     * <p>
4815     * If an {@link AccessibilityDelegate} has been specified via calling
4816     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4817     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4818     * is responsible for handling this call.
4819     * </p>
4820     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4821     * information to the event, in case the default implementation has basic information to add.
4822     * </p>
4823     *
4824     * @param event The accessibility event which to populate.
4825     *
4826     * @see #sendAccessibilityEvent(int)
4827     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4828     */
4829    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4830        if (mAccessibilityDelegate != null) {
4831            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4832        } else {
4833            onPopulateAccessibilityEventInternal(event);
4834        }
4835    }
4836
4837    /**
4838     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4839     *
4840     * Note: Called from the default {@link AccessibilityDelegate}.
4841     */
4842    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4843
4844    }
4845
4846    /**
4847     * Initializes an {@link AccessibilityEvent} with information about
4848     * this View which is the event source. In other words, the source of
4849     * an accessibility event is the view whose state change triggered firing
4850     * the event.
4851     * <p>
4852     * Example: Setting the password property of an event in addition
4853     *          to properties set by the super implementation:
4854     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4855     *     super.onInitializeAccessibilityEvent(event);
4856     *     event.setPassword(true);
4857     * }</pre>
4858     * <p>
4859     * If an {@link AccessibilityDelegate} has been specified via calling
4860     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4861     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4862     * is responsible for handling this call.
4863     * </p>
4864     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4865     * information to the event, in case the default implementation has basic information to add.
4866     * </p>
4867     * @param event The event to initialize.
4868     *
4869     * @see #sendAccessibilityEvent(int)
4870     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4871     */
4872    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4873        if (mAccessibilityDelegate != null) {
4874            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4875        } else {
4876            onInitializeAccessibilityEventInternal(event);
4877        }
4878    }
4879
4880    /**
4881     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4882     *
4883     * Note: Called from the default {@link AccessibilityDelegate}.
4884     */
4885    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4886        event.setSource(this);
4887        event.setClassName(View.class.getName());
4888        event.setPackageName(getContext().getPackageName());
4889        event.setEnabled(isEnabled());
4890        event.setContentDescription(mContentDescription);
4891
4892        switch (event.getEventType()) {
4893            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4894                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4895                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4896                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4897                event.setItemCount(focusablesTempList.size());
4898                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4899                if (mAttachInfo != null) {
4900                    focusablesTempList.clear();
4901                }
4902            } break;
4903            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4904                CharSequence text = getIterableTextForAccessibility();
4905                if (text != null && text.length() > 0) {
4906                    event.setFromIndex(getAccessibilitySelectionStart());
4907                    event.setToIndex(getAccessibilitySelectionEnd());
4908                    event.setItemCount(text.length());
4909                }
4910            } break;
4911        }
4912    }
4913
4914    /**
4915     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4916     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4917     * This method is responsible for obtaining an accessibility node info from a
4918     * pool of reusable instances and calling
4919     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4920     * initialize the former.
4921     * <p>
4922     * Note: The client is responsible for recycling the obtained instance by calling
4923     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4924     * </p>
4925     *
4926     * @return A populated {@link AccessibilityNodeInfo}.
4927     *
4928     * @see AccessibilityNodeInfo
4929     */
4930    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4931        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4932        if (provider != null) {
4933            return provider.createAccessibilityNodeInfo(View.NO_ID);
4934        } else {
4935            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4936            onInitializeAccessibilityNodeInfo(info);
4937            return info;
4938        }
4939    }
4940
4941    /**
4942     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4943     * The base implementation sets:
4944     * <ul>
4945     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4946     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4947     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4948     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4949     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4950     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4951     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4952     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4953     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4954     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4955     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4956     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4957     * </ul>
4958     * <p>
4959     * Subclasses should override this method, call the super implementation,
4960     * and set additional attributes.
4961     * </p>
4962     * <p>
4963     * If an {@link AccessibilityDelegate} has been specified via calling
4964     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4965     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4966     * is responsible for handling this call.
4967     * </p>
4968     *
4969     * @param info The instance to initialize.
4970     */
4971    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4972        if (mAccessibilityDelegate != null) {
4973            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4974        } else {
4975            onInitializeAccessibilityNodeInfoInternal(info);
4976        }
4977    }
4978
4979    /**
4980     * Gets the location of this view in screen coordintates.
4981     *
4982     * @param outRect The output location
4983     */
4984    void getBoundsOnScreen(Rect outRect) {
4985        if (mAttachInfo == null) {
4986            return;
4987        }
4988
4989        RectF position = mAttachInfo.mTmpTransformRect;
4990        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4991
4992        if (!hasIdentityMatrix()) {
4993            getMatrix().mapRect(position);
4994        }
4995
4996        position.offset(mLeft, mTop);
4997
4998        ViewParent parent = mParent;
4999        while (parent instanceof View) {
5000            View parentView = (View) parent;
5001
5002            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5003
5004            if (!parentView.hasIdentityMatrix()) {
5005                parentView.getMatrix().mapRect(position);
5006            }
5007
5008            position.offset(parentView.mLeft, parentView.mTop);
5009
5010            parent = parentView.mParent;
5011        }
5012
5013        if (parent instanceof ViewRootImpl) {
5014            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5015            position.offset(0, -viewRootImpl.mCurScrollY);
5016        }
5017
5018        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5019
5020        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5021                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5022    }
5023
5024    /**
5025     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5026     *
5027     * Note: Called from the default {@link AccessibilityDelegate}.
5028     */
5029    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5030        Rect bounds = mAttachInfo.mTmpInvalRect;
5031
5032        getDrawingRect(bounds);
5033        info.setBoundsInParent(bounds);
5034
5035        getBoundsOnScreen(bounds);
5036        info.setBoundsInScreen(bounds);
5037
5038        ViewParent parent = getParentForAccessibility();
5039        if (parent instanceof View) {
5040            info.setParent((View) parent);
5041        }
5042
5043        if (mID != View.NO_ID) {
5044            View rootView = getRootView();
5045            if (rootView == null) {
5046                rootView = this;
5047            }
5048            View label = rootView.findLabelForView(this, mID);
5049            if (label != null) {
5050                info.setLabeledBy(label);
5051            }
5052
5053            if ((mAttachInfo.mAccessibilityFetchFlags
5054                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5055                    && Resources.resourceHasPackage(mID)) {
5056                try {
5057                    String viewId = getResources().getResourceName(mID);
5058                    info.setViewIdResourceName(viewId);
5059                } catch (Resources.NotFoundException nfe) {
5060                    /* ignore */
5061                }
5062            }
5063        }
5064
5065        if (mLabelForId != View.NO_ID) {
5066            View rootView = getRootView();
5067            if (rootView == null) {
5068                rootView = this;
5069            }
5070            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5071            if (labeled != null) {
5072                info.setLabelFor(labeled);
5073            }
5074        }
5075
5076        info.setVisibleToUser(isVisibleToUser());
5077
5078        info.setPackageName(mContext.getPackageName());
5079        info.setClassName(View.class.getName());
5080        info.setContentDescription(getContentDescription());
5081
5082        info.setEnabled(isEnabled());
5083        info.setClickable(isClickable());
5084        info.setFocusable(isFocusable());
5085        info.setFocused(isFocused());
5086        info.setAccessibilityFocused(isAccessibilityFocused());
5087        info.setSelected(isSelected());
5088        info.setLongClickable(isLongClickable());
5089
5090        // TODO: These make sense only if we are in an AdapterView but all
5091        // views can be selected. Maybe from accessibility perspective
5092        // we should report as selectable view in an AdapterView.
5093        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5094        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5095
5096        if (isFocusable()) {
5097            if (isFocused()) {
5098                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5099            } else {
5100                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5101            }
5102        }
5103
5104        if (!isAccessibilityFocused()) {
5105            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5106        } else {
5107            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5108        }
5109
5110        if (isClickable() && isEnabled()) {
5111            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5112        }
5113
5114        if (isLongClickable() && isEnabled()) {
5115            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5116        }
5117
5118        CharSequence text = getIterableTextForAccessibility();
5119        if (text != null && text.length() > 0) {
5120            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5121
5122            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5123            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5124            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5125            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5126                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5127                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5128        }
5129    }
5130
5131    private View findLabelForView(View view, int labeledId) {
5132        if (mMatchLabelForPredicate == null) {
5133            mMatchLabelForPredicate = new MatchLabelForPredicate();
5134        }
5135        mMatchLabelForPredicate.mLabeledId = labeledId;
5136        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5137    }
5138
5139    /**
5140     * Computes whether this view is visible to the user. Such a view is
5141     * attached, visible, all its predecessors are visible, it is not clipped
5142     * entirely by its predecessors, and has an alpha greater than zero.
5143     *
5144     * @return Whether the view is visible on the screen.
5145     *
5146     * @hide
5147     */
5148    protected boolean isVisibleToUser() {
5149        return isVisibleToUser(null);
5150    }
5151
5152    /**
5153     * Computes whether the given portion of this view is visible to the user.
5154     * Such a view is attached, visible, all its predecessors are visible,
5155     * has an alpha greater than zero, and the specified portion is not
5156     * clipped entirely by its predecessors.
5157     *
5158     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5159     *                    <code>null</code>, and the entire view will be tested in this case.
5160     *                    When <code>true</code> is returned by the function, the actual visible
5161     *                    region will be stored in this parameter; that is, if boundInView is fully
5162     *                    contained within the view, no modification will be made, otherwise regions
5163     *                    outside of the visible area of the view will be clipped.
5164     *
5165     * @return Whether the specified portion of the view is visible on the screen.
5166     *
5167     * @hide
5168     */
5169    protected boolean isVisibleToUser(Rect boundInView) {
5170        if (mAttachInfo != null) {
5171            // Attached to invisible window means this view is not visible.
5172            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5173                return false;
5174            }
5175            // An invisible predecessor or one with alpha zero means
5176            // that this view is not visible to the user.
5177            Object current = this;
5178            while (current instanceof View) {
5179                View view = (View) current;
5180                // We have attach info so this view is attached and there is no
5181                // need to check whether we reach to ViewRootImpl on the way up.
5182                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5183                    return false;
5184                }
5185                current = view.mParent;
5186            }
5187            // Check if the view is entirely covered by its predecessors.
5188            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5189            Point offset = mAttachInfo.mPoint;
5190            if (!getGlobalVisibleRect(visibleRect, offset)) {
5191                return false;
5192            }
5193            // Check if the visible portion intersects the rectangle of interest.
5194            if (boundInView != null) {
5195                visibleRect.offset(-offset.x, -offset.y);
5196                return boundInView.intersect(visibleRect);
5197            }
5198            return true;
5199        }
5200        return false;
5201    }
5202
5203    /**
5204     * Returns the delegate for implementing accessibility support via
5205     * composition. For more details see {@link AccessibilityDelegate}.
5206     *
5207     * @return The delegate, or null if none set.
5208     *
5209     * @hide
5210     */
5211    public AccessibilityDelegate getAccessibilityDelegate() {
5212        return mAccessibilityDelegate;
5213    }
5214
5215    /**
5216     * Sets a delegate for implementing accessibility support via composition as
5217     * opposed to inheritance. The delegate's primary use is for implementing
5218     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5219     *
5220     * @param delegate The delegate instance.
5221     *
5222     * @see AccessibilityDelegate
5223     */
5224    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5225        mAccessibilityDelegate = delegate;
5226    }
5227
5228    /**
5229     * Gets the provider for managing a virtual view hierarchy rooted at this View
5230     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5231     * that explore the window content.
5232     * <p>
5233     * If this method returns an instance, this instance is responsible for managing
5234     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5235     * View including the one representing the View itself. Similarly the returned
5236     * instance is responsible for performing accessibility actions on any virtual
5237     * view or the root view itself.
5238     * </p>
5239     * <p>
5240     * If an {@link AccessibilityDelegate} has been specified via calling
5241     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5242     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5243     * is responsible for handling this call.
5244     * </p>
5245     *
5246     * @return The provider.
5247     *
5248     * @see AccessibilityNodeProvider
5249     */
5250    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5251        if (mAccessibilityDelegate != null) {
5252            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5253        } else {
5254            return null;
5255        }
5256    }
5257
5258    /**
5259     * Gets the unique identifier of this view on the screen for accessibility purposes.
5260     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5261     *
5262     * @return The view accessibility id.
5263     *
5264     * @hide
5265     */
5266    public int getAccessibilityViewId() {
5267        if (mAccessibilityViewId == NO_ID) {
5268            mAccessibilityViewId = sNextAccessibilityViewId++;
5269        }
5270        return mAccessibilityViewId;
5271    }
5272
5273    /**
5274     * Gets the unique identifier of the window in which this View reseides.
5275     *
5276     * @return The window accessibility id.
5277     *
5278     * @hide
5279     */
5280    public int getAccessibilityWindowId() {
5281        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5282    }
5283
5284    /**
5285     * Gets the {@link View} description. It briefly describes the view and is
5286     * primarily used for accessibility support. Set this property to enable
5287     * better accessibility support for your application. This is especially
5288     * true for views that do not have textual representation (For example,
5289     * ImageButton).
5290     *
5291     * @return The content description.
5292     *
5293     * @attr ref android.R.styleable#View_contentDescription
5294     */
5295    @ViewDebug.ExportedProperty(category = "accessibility")
5296    public CharSequence getContentDescription() {
5297        return mContentDescription;
5298    }
5299
5300    /**
5301     * Sets the {@link View} description. It briefly describes the view and is
5302     * primarily used for accessibility support. Set this property to enable
5303     * better accessibility support for your application. This is especially
5304     * true for views that do not have textual representation (For example,
5305     * ImageButton).
5306     *
5307     * @param contentDescription The content description.
5308     *
5309     * @attr ref android.R.styleable#View_contentDescription
5310     */
5311    @RemotableViewMethod
5312    public void setContentDescription(CharSequence contentDescription) {
5313        if (mContentDescription == null) {
5314            if (contentDescription == null) {
5315                return;
5316            }
5317        } else if (mContentDescription.equals(contentDescription)) {
5318            return;
5319        }
5320        mContentDescription = contentDescription;
5321        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5322        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5323             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5324        }
5325        notifyAccessibilityStateChanged();
5326    }
5327
5328    /**
5329     * Gets the id of a view for which this view serves as a label for
5330     * accessibility purposes.
5331     *
5332     * @return The labeled view id.
5333     */
5334    @ViewDebug.ExportedProperty(category = "accessibility")
5335    public int getLabelFor() {
5336        return mLabelForId;
5337    }
5338
5339    /**
5340     * Sets the id of a view for which this view serves as a label for
5341     * accessibility purposes.
5342     *
5343     * @param id The labeled view id.
5344     */
5345    @RemotableViewMethod
5346    public void setLabelFor(int id) {
5347        mLabelForId = id;
5348        if (mLabelForId != View.NO_ID
5349                && mID == View.NO_ID) {
5350            mID = generateViewId();
5351        }
5352    }
5353
5354    /**
5355     * Invoked whenever this view loses focus, either by losing window focus or by losing
5356     * focus within its window. This method can be used to clear any state tied to the
5357     * focus. For instance, if a button is held pressed with the trackball and the window
5358     * loses focus, this method can be used to cancel the press.
5359     *
5360     * Subclasses of View overriding this method should always call super.onFocusLost().
5361     *
5362     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5363     * @see #onWindowFocusChanged(boolean)
5364     *
5365     * @hide pending API council approval
5366     */
5367    protected void onFocusLost() {
5368        resetPressedState();
5369    }
5370
5371    private void resetPressedState() {
5372        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5373            return;
5374        }
5375
5376        if (isPressed()) {
5377            setPressed(false);
5378
5379            if (!mHasPerformedLongPress) {
5380                removeLongPressCallback();
5381            }
5382        }
5383    }
5384
5385    /**
5386     * Returns true if this view has focus
5387     *
5388     * @return True if this view has focus, false otherwise.
5389     */
5390    @ViewDebug.ExportedProperty(category = "focus")
5391    public boolean isFocused() {
5392        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5393    }
5394
5395    /**
5396     * Find the view in the hierarchy rooted at this view that currently has
5397     * focus.
5398     *
5399     * @return The view that currently has focus, or null if no focused view can
5400     *         be found.
5401     */
5402    public View findFocus() {
5403        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5404    }
5405
5406    /**
5407     * Indicates whether this view is one of the set of scrollable containers in
5408     * its window.
5409     *
5410     * @return whether this view is one of the set of scrollable containers in
5411     * its window
5412     *
5413     * @attr ref android.R.styleable#View_isScrollContainer
5414     */
5415    public boolean isScrollContainer() {
5416        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5417    }
5418
5419    /**
5420     * Change whether this view is one of the set of scrollable containers in
5421     * its window.  This will be used to determine whether the window can
5422     * resize or must pan when a soft input area is open -- scrollable
5423     * containers allow the window to use resize mode since the container
5424     * will appropriately shrink.
5425     *
5426     * @attr ref android.R.styleable#View_isScrollContainer
5427     */
5428    public void setScrollContainer(boolean isScrollContainer) {
5429        if (isScrollContainer) {
5430            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5431                mAttachInfo.mScrollContainers.add(this);
5432                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5433            }
5434            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5435        } else {
5436            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5437                mAttachInfo.mScrollContainers.remove(this);
5438            }
5439            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5440        }
5441    }
5442
5443    /**
5444     * Returns the quality of the drawing cache.
5445     *
5446     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5447     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5448     *
5449     * @see #setDrawingCacheQuality(int)
5450     * @see #setDrawingCacheEnabled(boolean)
5451     * @see #isDrawingCacheEnabled()
5452     *
5453     * @attr ref android.R.styleable#View_drawingCacheQuality
5454     */
5455    public int getDrawingCacheQuality() {
5456        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5457    }
5458
5459    /**
5460     * Set the drawing cache quality of this view. This value is used only when the
5461     * drawing cache is enabled
5462     *
5463     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5464     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5465     *
5466     * @see #getDrawingCacheQuality()
5467     * @see #setDrawingCacheEnabled(boolean)
5468     * @see #isDrawingCacheEnabled()
5469     *
5470     * @attr ref android.R.styleable#View_drawingCacheQuality
5471     */
5472    public void setDrawingCacheQuality(int quality) {
5473        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5474    }
5475
5476    /**
5477     * Returns whether the screen should remain on, corresponding to the current
5478     * value of {@link #KEEP_SCREEN_ON}.
5479     *
5480     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5481     *
5482     * @see #setKeepScreenOn(boolean)
5483     *
5484     * @attr ref android.R.styleable#View_keepScreenOn
5485     */
5486    public boolean getKeepScreenOn() {
5487        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5488    }
5489
5490    /**
5491     * Controls whether the screen should remain on, modifying the
5492     * value of {@link #KEEP_SCREEN_ON}.
5493     *
5494     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5495     *
5496     * @see #getKeepScreenOn()
5497     *
5498     * @attr ref android.R.styleable#View_keepScreenOn
5499     */
5500    public void setKeepScreenOn(boolean keepScreenOn) {
5501        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5502    }
5503
5504    /**
5505     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5506     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5507     *
5508     * @attr ref android.R.styleable#View_nextFocusLeft
5509     */
5510    public int getNextFocusLeftId() {
5511        return mNextFocusLeftId;
5512    }
5513
5514    /**
5515     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5516     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5517     * decide automatically.
5518     *
5519     * @attr ref android.R.styleable#View_nextFocusLeft
5520     */
5521    public void setNextFocusLeftId(int nextFocusLeftId) {
5522        mNextFocusLeftId = nextFocusLeftId;
5523    }
5524
5525    /**
5526     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5527     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5528     *
5529     * @attr ref android.R.styleable#View_nextFocusRight
5530     */
5531    public int getNextFocusRightId() {
5532        return mNextFocusRightId;
5533    }
5534
5535    /**
5536     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5537     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5538     * decide automatically.
5539     *
5540     * @attr ref android.R.styleable#View_nextFocusRight
5541     */
5542    public void setNextFocusRightId(int nextFocusRightId) {
5543        mNextFocusRightId = nextFocusRightId;
5544    }
5545
5546    /**
5547     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5548     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5549     *
5550     * @attr ref android.R.styleable#View_nextFocusUp
5551     */
5552    public int getNextFocusUpId() {
5553        return mNextFocusUpId;
5554    }
5555
5556    /**
5557     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5558     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5559     * decide automatically.
5560     *
5561     * @attr ref android.R.styleable#View_nextFocusUp
5562     */
5563    public void setNextFocusUpId(int nextFocusUpId) {
5564        mNextFocusUpId = nextFocusUpId;
5565    }
5566
5567    /**
5568     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5569     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5570     *
5571     * @attr ref android.R.styleable#View_nextFocusDown
5572     */
5573    public int getNextFocusDownId() {
5574        return mNextFocusDownId;
5575    }
5576
5577    /**
5578     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5579     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5580     * decide automatically.
5581     *
5582     * @attr ref android.R.styleable#View_nextFocusDown
5583     */
5584    public void setNextFocusDownId(int nextFocusDownId) {
5585        mNextFocusDownId = nextFocusDownId;
5586    }
5587
5588    /**
5589     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5590     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5591     *
5592     * @attr ref android.R.styleable#View_nextFocusForward
5593     */
5594    public int getNextFocusForwardId() {
5595        return mNextFocusForwardId;
5596    }
5597
5598    /**
5599     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5600     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5601     * decide automatically.
5602     *
5603     * @attr ref android.R.styleable#View_nextFocusForward
5604     */
5605    public void setNextFocusForwardId(int nextFocusForwardId) {
5606        mNextFocusForwardId = nextFocusForwardId;
5607    }
5608
5609    /**
5610     * Returns the visibility of this view and all of its ancestors
5611     *
5612     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5613     */
5614    public boolean isShown() {
5615        View current = this;
5616        //noinspection ConstantConditions
5617        do {
5618            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5619                return false;
5620            }
5621            ViewParent parent = current.mParent;
5622            if (parent == null) {
5623                return false; // We are not attached to the view root
5624            }
5625            if (!(parent instanceof View)) {
5626                return true;
5627            }
5628            current = (View) parent;
5629        } while (current != null);
5630
5631        return false;
5632    }
5633
5634    /**
5635     * Called by the view hierarchy when the content insets for a window have
5636     * changed, to allow it to adjust its content to fit within those windows.
5637     * The content insets tell you the space that the status bar, input method,
5638     * and other system windows infringe on the application's window.
5639     *
5640     * <p>You do not normally need to deal with this function, since the default
5641     * window decoration given to applications takes care of applying it to the
5642     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5643     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5644     * and your content can be placed under those system elements.  You can then
5645     * use this method within your view hierarchy if you have parts of your UI
5646     * which you would like to ensure are not being covered.
5647     *
5648     * <p>The default implementation of this method simply applies the content
5649     * inset's to the view's padding, consuming that content (modifying the
5650     * insets to be 0), and returning true.  This behavior is off by default, but can
5651     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5652     *
5653     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5654     * insets object is propagated down the hierarchy, so any changes made to it will
5655     * be seen by all following views (including potentially ones above in
5656     * the hierarchy since this is a depth-first traversal).  The first view
5657     * that returns true will abort the entire traversal.
5658     *
5659     * <p>The default implementation works well for a situation where it is
5660     * used with a container that covers the entire window, allowing it to
5661     * apply the appropriate insets to its content on all edges.  If you need
5662     * a more complicated layout (such as two different views fitting system
5663     * windows, one on the top of the window, and one on the bottom),
5664     * you can override the method and handle the insets however you would like.
5665     * Note that the insets provided by the framework are always relative to the
5666     * far edges of the window, not accounting for the location of the called view
5667     * within that window.  (In fact when this method is called you do not yet know
5668     * where the layout will place the view, as it is done before layout happens.)
5669     *
5670     * <p>Note: unlike many View methods, there is no dispatch phase to this
5671     * call.  If you are overriding it in a ViewGroup and want to allow the
5672     * call to continue to your children, you must be sure to call the super
5673     * implementation.
5674     *
5675     * <p>Here is a sample layout that makes use of fitting system windows
5676     * to have controls for a video view placed inside of the window decorations
5677     * that it hides and shows.  This can be used with code like the second
5678     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5679     *
5680     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5681     *
5682     * @param insets Current content insets of the window.  Prior to
5683     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5684     * the insets or else you and Android will be unhappy.
5685     *
5686     * @return Return true if this view applied the insets and it should not
5687     * continue propagating further down the hierarchy, false otherwise.
5688     * @see #getFitsSystemWindows()
5689     * @see #setFitsSystemWindows(boolean)
5690     * @see #setSystemUiVisibility(int)
5691     */
5692    protected boolean fitSystemWindows(Rect insets) {
5693        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5694            mUserPaddingStart = UNDEFINED_PADDING;
5695            mUserPaddingEnd = UNDEFINED_PADDING;
5696            Rect localInsets = sThreadLocal.get();
5697            if (localInsets == null) {
5698                localInsets = new Rect();
5699                sThreadLocal.set(localInsets);
5700            }
5701            boolean res = computeFitSystemWindows(insets, localInsets);
5702            internalSetPadding(localInsets.left, localInsets.top,
5703                    localInsets.right, localInsets.bottom);
5704            return res;
5705        }
5706        return false;
5707    }
5708
5709    /**
5710     * @hide Compute the insets that should be consumed by this view and the ones
5711     * that should propagate to those under it.
5712     */
5713    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5714        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5715                || mAttachInfo == null
5716                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5717                        && !mAttachInfo.mOverscanRequested)) {
5718            outLocalInsets.set(inoutInsets);
5719            inoutInsets.set(0, 0, 0, 0);
5720            return true;
5721        } else {
5722            // The application wants to take care of fitting system window for
5723            // the content...  however we still need to take care of any overscan here.
5724            final Rect overscan = mAttachInfo.mOverscanInsets;
5725            outLocalInsets.set(overscan);
5726            inoutInsets.left -= overscan.left;
5727            inoutInsets.top -= overscan.top;
5728            inoutInsets.right -= overscan.right;
5729            inoutInsets.bottom -= overscan.bottom;
5730            return false;
5731        }
5732    }
5733
5734    /**
5735     * Sets whether or not this view should account for system screen decorations
5736     * such as the status bar and inset its content; that is, controlling whether
5737     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5738     * executed.  See that method for more details.
5739     *
5740     * <p>Note that if you are providing your own implementation of
5741     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5742     * flag to true -- your implementation will be overriding the default
5743     * implementation that checks this flag.
5744     *
5745     * @param fitSystemWindows If true, then the default implementation of
5746     * {@link #fitSystemWindows(Rect)} will be executed.
5747     *
5748     * @attr ref android.R.styleable#View_fitsSystemWindows
5749     * @see #getFitsSystemWindows()
5750     * @see #fitSystemWindows(Rect)
5751     * @see #setSystemUiVisibility(int)
5752     */
5753    public void setFitsSystemWindows(boolean fitSystemWindows) {
5754        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5755    }
5756
5757    /**
5758     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5759     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5760     * will be executed.
5761     *
5762     * @return Returns true if the default implementation of
5763     * {@link #fitSystemWindows(Rect)} will be executed.
5764     *
5765     * @attr ref android.R.styleable#View_fitsSystemWindows
5766     * @see #setFitsSystemWindows()
5767     * @see #fitSystemWindows(Rect)
5768     * @see #setSystemUiVisibility(int)
5769     */
5770    public boolean getFitsSystemWindows() {
5771        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5772    }
5773
5774    /** @hide */
5775    public boolean fitsSystemWindows() {
5776        return getFitsSystemWindows();
5777    }
5778
5779    /**
5780     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5781     */
5782    public void requestFitSystemWindows() {
5783        if (mParent != null) {
5784            mParent.requestFitSystemWindows();
5785        }
5786    }
5787
5788    /**
5789     * For use by PhoneWindow to make its own system window fitting optional.
5790     * @hide
5791     */
5792    public void makeOptionalFitsSystemWindows() {
5793        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5794    }
5795
5796    /**
5797     * Returns the visibility status for this view.
5798     *
5799     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5800     * @attr ref android.R.styleable#View_visibility
5801     */
5802    @ViewDebug.ExportedProperty(mapping = {
5803        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5804        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5805        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5806    })
5807    public int getVisibility() {
5808        return mViewFlags & VISIBILITY_MASK;
5809    }
5810
5811    /**
5812     * Set the enabled state of this view.
5813     *
5814     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5815     * @attr ref android.R.styleable#View_visibility
5816     */
5817    @RemotableViewMethod
5818    public void setVisibility(int visibility) {
5819        setFlags(visibility, VISIBILITY_MASK);
5820        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5821    }
5822
5823    /**
5824     * Returns the enabled status for this view. The interpretation of the
5825     * enabled state varies by subclass.
5826     *
5827     * @return True if this view is enabled, false otherwise.
5828     */
5829    @ViewDebug.ExportedProperty
5830    public boolean isEnabled() {
5831        return (mViewFlags & ENABLED_MASK) == ENABLED;
5832    }
5833
5834    /**
5835     * Set the enabled state of this view. The interpretation of the enabled
5836     * state varies by subclass.
5837     *
5838     * @param enabled True if this view is enabled, false otherwise.
5839     */
5840    @RemotableViewMethod
5841    public void setEnabled(boolean enabled) {
5842        if (enabled == isEnabled()) return;
5843
5844        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5845
5846        /*
5847         * The View most likely has to change its appearance, so refresh
5848         * the drawable state.
5849         */
5850        refreshDrawableState();
5851
5852        // Invalidate too, since the default behavior for views is to be
5853        // be drawn at 50% alpha rather than to change the drawable.
5854        invalidate(true);
5855    }
5856
5857    /**
5858     * Set whether this view can receive the focus.
5859     *
5860     * Setting this to false will also ensure that this view is not focusable
5861     * in touch mode.
5862     *
5863     * @param focusable If true, this view can receive the focus.
5864     *
5865     * @see #setFocusableInTouchMode(boolean)
5866     * @attr ref android.R.styleable#View_focusable
5867     */
5868    public void setFocusable(boolean focusable) {
5869        if (!focusable) {
5870            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5871        }
5872        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5873    }
5874
5875    /**
5876     * Set whether this view can receive focus while in touch mode.
5877     *
5878     * Setting this to true will also ensure that this view is focusable.
5879     *
5880     * @param focusableInTouchMode If true, this view can receive the focus while
5881     *   in touch mode.
5882     *
5883     * @see #setFocusable(boolean)
5884     * @attr ref android.R.styleable#View_focusableInTouchMode
5885     */
5886    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5887        // Focusable in touch mode should always be set before the focusable flag
5888        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5889        // which, in touch mode, will not successfully request focus on this view
5890        // because the focusable in touch mode flag is not set
5891        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5892        if (focusableInTouchMode) {
5893            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5894        }
5895    }
5896
5897    /**
5898     * Set whether this view should have sound effects enabled for events such as
5899     * clicking and touching.
5900     *
5901     * <p>You may wish to disable sound effects for a view if you already play sounds,
5902     * for instance, a dial key that plays dtmf tones.
5903     *
5904     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5905     * @see #isSoundEffectsEnabled()
5906     * @see #playSoundEffect(int)
5907     * @attr ref android.R.styleable#View_soundEffectsEnabled
5908     */
5909    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5910        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5911    }
5912
5913    /**
5914     * @return whether this view should have sound effects enabled for events such as
5915     *     clicking and touching.
5916     *
5917     * @see #setSoundEffectsEnabled(boolean)
5918     * @see #playSoundEffect(int)
5919     * @attr ref android.R.styleable#View_soundEffectsEnabled
5920     */
5921    @ViewDebug.ExportedProperty
5922    public boolean isSoundEffectsEnabled() {
5923        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5924    }
5925
5926    /**
5927     * Set whether this view should have haptic feedback for events such as
5928     * long presses.
5929     *
5930     * <p>You may wish to disable haptic feedback if your view already controls
5931     * its own haptic feedback.
5932     *
5933     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5934     * @see #isHapticFeedbackEnabled()
5935     * @see #performHapticFeedback(int)
5936     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5937     */
5938    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5939        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5940    }
5941
5942    /**
5943     * @return whether this view should have haptic feedback enabled for events
5944     * long presses.
5945     *
5946     * @see #setHapticFeedbackEnabled(boolean)
5947     * @see #performHapticFeedback(int)
5948     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5949     */
5950    @ViewDebug.ExportedProperty
5951    public boolean isHapticFeedbackEnabled() {
5952        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5953    }
5954
5955    /**
5956     * Returns the layout direction for this view.
5957     *
5958     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5959     *   {@link #LAYOUT_DIRECTION_RTL},
5960     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5961     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5962     *
5963     * @attr ref android.R.styleable#View_layoutDirection
5964     *
5965     * @hide
5966     */
5967    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5968        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5969        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5970        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5971        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5972    })
5973    public int getRawLayoutDirection() {
5974        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5975    }
5976
5977    /**
5978     * Set the layout direction for this view. This will propagate a reset of layout direction
5979     * resolution to the view's children and resolve layout direction for this view.
5980     *
5981     * @param layoutDirection the layout direction to set. Should be one of:
5982     *
5983     * {@link #LAYOUT_DIRECTION_LTR},
5984     * {@link #LAYOUT_DIRECTION_RTL},
5985     * {@link #LAYOUT_DIRECTION_INHERIT},
5986     * {@link #LAYOUT_DIRECTION_LOCALE}.
5987     *
5988     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5989     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5990     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5991     *
5992     * @attr ref android.R.styleable#View_layoutDirection
5993     */
5994    @RemotableViewMethod
5995    public void setLayoutDirection(int layoutDirection) {
5996        if (getRawLayoutDirection() != layoutDirection) {
5997            // Reset the current layout direction and the resolved one
5998            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5999            resetRtlProperties();
6000            // Set the new layout direction (filtered)
6001            mPrivateFlags2 |=
6002                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6003            // We need to resolve all RTL properties as they all depend on layout direction
6004            resolveRtlPropertiesIfNeeded();
6005            requestLayout();
6006            invalidate(true);
6007        }
6008    }
6009
6010    /**
6011     * Returns the resolved layout direction for this view.
6012     *
6013     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6014     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6015     *
6016     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6017     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6018     *
6019     * @attr ref android.R.styleable#View_layoutDirection
6020     */
6021    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6022        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6023        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6024    })
6025    public int getLayoutDirection() {
6026        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6027        if (targetSdkVersion < JELLY_BEAN_MR1) {
6028            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6029            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6030        }
6031        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6032                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6033    }
6034
6035    /**
6036     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6037     * layout attribute and/or the inherited value from the parent
6038     *
6039     * @return true if the layout is right-to-left.
6040     *
6041     * @hide
6042     */
6043    @ViewDebug.ExportedProperty(category = "layout")
6044    public boolean isLayoutRtl() {
6045        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6046    }
6047
6048    /**
6049     * Indicates whether the view is currently tracking transient state that the
6050     * app should not need to concern itself with saving and restoring, but that
6051     * the framework should take special note to preserve when possible.
6052     *
6053     * <p>A view with transient state cannot be trivially rebound from an external
6054     * data source, such as an adapter binding item views in a list. This may be
6055     * because the view is performing an animation, tracking user selection
6056     * of content, or similar.</p>
6057     *
6058     * @return true if the view has transient state
6059     */
6060    @ViewDebug.ExportedProperty(category = "layout")
6061    public boolean hasTransientState() {
6062        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6063    }
6064
6065    /**
6066     * Set whether this view is currently tracking transient state that the
6067     * framework should attempt to preserve when possible. This flag is reference counted,
6068     * so every call to setHasTransientState(true) should be paired with a later call
6069     * to setHasTransientState(false).
6070     *
6071     * <p>A view with transient state cannot be trivially rebound from an external
6072     * data source, such as an adapter binding item views in a list. This may be
6073     * because the view is performing an animation, tracking user selection
6074     * of content, or similar.</p>
6075     *
6076     * @param hasTransientState true if this view has transient state
6077     */
6078    public void setHasTransientState(boolean hasTransientState) {
6079        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6080                mTransientStateCount - 1;
6081        if (mTransientStateCount < 0) {
6082            mTransientStateCount = 0;
6083            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6084                    "unmatched pair of setHasTransientState calls");
6085        } else if ((hasTransientState && mTransientStateCount == 1) ||
6086                (!hasTransientState && mTransientStateCount == 0)) {
6087            // update flag if we've just incremented up from 0 or decremented down to 0
6088            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6089                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6090            if (mParent != null) {
6091                try {
6092                    mParent.childHasTransientStateChanged(this, hasTransientState);
6093                } catch (AbstractMethodError e) {
6094                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6095                            " does not fully implement ViewParent", e);
6096                }
6097            }
6098        }
6099    }
6100
6101    /**
6102     * If this view doesn't do any drawing on its own, set this flag to
6103     * allow further optimizations. By default, this flag is not set on
6104     * View, but could be set on some View subclasses such as ViewGroup.
6105     *
6106     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6107     * you should clear this flag.
6108     *
6109     * @param willNotDraw whether or not this View draw on its own
6110     */
6111    public void setWillNotDraw(boolean willNotDraw) {
6112        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6113    }
6114
6115    /**
6116     * Returns whether or not this View draws on its own.
6117     *
6118     * @return true if this view has nothing to draw, false otherwise
6119     */
6120    @ViewDebug.ExportedProperty(category = "drawing")
6121    public boolean willNotDraw() {
6122        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6123    }
6124
6125    /**
6126     * When a View's drawing cache is enabled, drawing is redirected to an
6127     * offscreen bitmap. Some views, like an ImageView, must be able to
6128     * bypass this mechanism if they already draw a single bitmap, to avoid
6129     * unnecessary usage of the memory.
6130     *
6131     * @param willNotCacheDrawing true if this view does not cache its
6132     *        drawing, false otherwise
6133     */
6134    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6135        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6136    }
6137
6138    /**
6139     * Returns whether or not this View can cache its drawing or not.
6140     *
6141     * @return true if this view does not cache its drawing, false otherwise
6142     */
6143    @ViewDebug.ExportedProperty(category = "drawing")
6144    public boolean willNotCacheDrawing() {
6145        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6146    }
6147
6148    /**
6149     * Indicates whether this view reacts to click events or not.
6150     *
6151     * @return true if the view is clickable, false otherwise
6152     *
6153     * @see #setClickable(boolean)
6154     * @attr ref android.R.styleable#View_clickable
6155     */
6156    @ViewDebug.ExportedProperty
6157    public boolean isClickable() {
6158        return (mViewFlags & CLICKABLE) == CLICKABLE;
6159    }
6160
6161    /**
6162     * Enables or disables click events for this view. When a view
6163     * is clickable it will change its state to "pressed" on every click.
6164     * Subclasses should set the view clickable to visually react to
6165     * user's clicks.
6166     *
6167     * @param clickable true to make the view clickable, false otherwise
6168     *
6169     * @see #isClickable()
6170     * @attr ref android.R.styleable#View_clickable
6171     */
6172    public void setClickable(boolean clickable) {
6173        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6174    }
6175
6176    /**
6177     * Indicates whether this view reacts to long click events or not.
6178     *
6179     * @return true if the view is long clickable, false otherwise
6180     *
6181     * @see #setLongClickable(boolean)
6182     * @attr ref android.R.styleable#View_longClickable
6183     */
6184    public boolean isLongClickable() {
6185        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6186    }
6187
6188    /**
6189     * Enables or disables long click events for this view. When a view is long
6190     * clickable it reacts to the user holding down the button for a longer
6191     * duration than a tap. This event can either launch the listener or a
6192     * context menu.
6193     *
6194     * @param longClickable true to make the view long clickable, false otherwise
6195     * @see #isLongClickable()
6196     * @attr ref android.R.styleable#View_longClickable
6197     */
6198    public void setLongClickable(boolean longClickable) {
6199        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6200    }
6201
6202    /**
6203     * Sets the pressed state for this view.
6204     *
6205     * @see #isClickable()
6206     * @see #setClickable(boolean)
6207     *
6208     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6209     *        the View's internal state from a previously set "pressed" state.
6210     */
6211    public void setPressed(boolean pressed) {
6212        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6213
6214        if (pressed) {
6215            mPrivateFlags |= PFLAG_PRESSED;
6216        } else {
6217            mPrivateFlags &= ~PFLAG_PRESSED;
6218        }
6219
6220        if (needsRefresh) {
6221            refreshDrawableState();
6222        }
6223        dispatchSetPressed(pressed);
6224    }
6225
6226    /**
6227     * Dispatch setPressed to all of this View's children.
6228     *
6229     * @see #setPressed(boolean)
6230     *
6231     * @param pressed The new pressed state
6232     */
6233    protected void dispatchSetPressed(boolean pressed) {
6234    }
6235
6236    /**
6237     * Indicates whether the view is currently in pressed state. Unless
6238     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6239     * the pressed state.
6240     *
6241     * @see #setPressed(boolean)
6242     * @see #isClickable()
6243     * @see #setClickable(boolean)
6244     *
6245     * @return true if the view is currently pressed, false otherwise
6246     */
6247    public boolean isPressed() {
6248        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6249    }
6250
6251    /**
6252     * Indicates whether this view will save its state (that is,
6253     * whether its {@link #onSaveInstanceState} method will be called).
6254     *
6255     * @return Returns true if the view state saving is enabled, else false.
6256     *
6257     * @see #setSaveEnabled(boolean)
6258     * @attr ref android.R.styleable#View_saveEnabled
6259     */
6260    public boolean isSaveEnabled() {
6261        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6262    }
6263
6264    /**
6265     * Controls whether the saving of this view's state is
6266     * enabled (that is, whether its {@link #onSaveInstanceState} method
6267     * will be called).  Note that even if freezing is enabled, the
6268     * view still must have an id assigned to it (via {@link #setId(int)})
6269     * for its state to be saved.  This flag can only disable the
6270     * saving of this view; any child views may still have their state saved.
6271     *
6272     * @param enabled Set to false to <em>disable</em> state saving, or true
6273     * (the default) to allow it.
6274     *
6275     * @see #isSaveEnabled()
6276     * @see #setId(int)
6277     * @see #onSaveInstanceState()
6278     * @attr ref android.R.styleable#View_saveEnabled
6279     */
6280    public void setSaveEnabled(boolean enabled) {
6281        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6282    }
6283
6284    /**
6285     * Gets whether the framework should discard touches when the view's
6286     * window is obscured by another visible window.
6287     * Refer to the {@link View} security documentation for more details.
6288     *
6289     * @return True if touch filtering is enabled.
6290     *
6291     * @see #setFilterTouchesWhenObscured(boolean)
6292     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6293     */
6294    @ViewDebug.ExportedProperty
6295    public boolean getFilterTouchesWhenObscured() {
6296        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6297    }
6298
6299    /**
6300     * Sets whether the framework should discard touches when the view's
6301     * window is obscured by another visible window.
6302     * Refer to the {@link View} security documentation for more details.
6303     *
6304     * @param enabled True if touch filtering should be enabled.
6305     *
6306     * @see #getFilterTouchesWhenObscured
6307     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6308     */
6309    public void setFilterTouchesWhenObscured(boolean enabled) {
6310        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6311                FILTER_TOUCHES_WHEN_OBSCURED);
6312    }
6313
6314    /**
6315     * Indicates whether the entire hierarchy under this view will save its
6316     * state when a state saving traversal occurs from its parent.  The default
6317     * is true; if false, these views will not be saved unless
6318     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6319     *
6320     * @return Returns true if the view state saving from parent is enabled, else false.
6321     *
6322     * @see #setSaveFromParentEnabled(boolean)
6323     */
6324    public boolean isSaveFromParentEnabled() {
6325        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6326    }
6327
6328    /**
6329     * Controls whether the entire hierarchy under this view will save its
6330     * state when a state saving traversal occurs from its parent.  The default
6331     * is true; if false, these views will not be saved unless
6332     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6333     *
6334     * @param enabled Set to false to <em>disable</em> state saving, or true
6335     * (the default) to allow it.
6336     *
6337     * @see #isSaveFromParentEnabled()
6338     * @see #setId(int)
6339     * @see #onSaveInstanceState()
6340     */
6341    public void setSaveFromParentEnabled(boolean enabled) {
6342        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6343    }
6344
6345
6346    /**
6347     * Returns whether this View is able to take focus.
6348     *
6349     * @return True if this view can take focus, or false otherwise.
6350     * @attr ref android.R.styleable#View_focusable
6351     */
6352    @ViewDebug.ExportedProperty(category = "focus")
6353    public final boolean isFocusable() {
6354        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6355    }
6356
6357    /**
6358     * When a view is focusable, it may not want to take focus when in touch mode.
6359     * For example, a button would like focus when the user is navigating via a D-pad
6360     * so that the user can click on it, but once the user starts touching the screen,
6361     * the button shouldn't take focus
6362     * @return Whether the view is focusable in touch mode.
6363     * @attr ref android.R.styleable#View_focusableInTouchMode
6364     */
6365    @ViewDebug.ExportedProperty
6366    public final boolean isFocusableInTouchMode() {
6367        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6368    }
6369
6370    /**
6371     * Find the nearest view in the specified direction that can take focus.
6372     * This does not actually give focus to that view.
6373     *
6374     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6375     *
6376     * @return The nearest focusable in the specified direction, or null if none
6377     *         can be found.
6378     */
6379    public View focusSearch(int direction) {
6380        if (mParent != null) {
6381            return mParent.focusSearch(this, direction);
6382        } else {
6383            return null;
6384        }
6385    }
6386
6387    /**
6388     * This method is the last chance for the focused view and its ancestors to
6389     * respond to an arrow key. This is called when the focused view did not
6390     * consume the key internally, nor could the view system find a new view in
6391     * the requested direction to give focus to.
6392     *
6393     * @param focused The currently focused view.
6394     * @param direction The direction focus wants to move. One of FOCUS_UP,
6395     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6396     * @return True if the this view consumed this unhandled move.
6397     */
6398    public boolean dispatchUnhandledMove(View focused, int direction) {
6399        return false;
6400    }
6401
6402    /**
6403     * If a user manually specified the next view id for a particular direction,
6404     * use the root to look up the view.
6405     * @param root The root view of the hierarchy containing this view.
6406     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6407     * or FOCUS_BACKWARD.
6408     * @return The user specified next view, or null if there is none.
6409     */
6410    View findUserSetNextFocus(View root, int direction) {
6411        switch (direction) {
6412            case FOCUS_LEFT:
6413                if (mNextFocusLeftId == View.NO_ID) return null;
6414                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6415            case FOCUS_RIGHT:
6416                if (mNextFocusRightId == View.NO_ID) return null;
6417                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6418            case FOCUS_UP:
6419                if (mNextFocusUpId == View.NO_ID) return null;
6420                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6421            case FOCUS_DOWN:
6422                if (mNextFocusDownId == View.NO_ID) return null;
6423                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6424            case FOCUS_FORWARD:
6425                if (mNextFocusForwardId == View.NO_ID) return null;
6426                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6427            case FOCUS_BACKWARD: {
6428                if (mID == View.NO_ID) return null;
6429                final int id = mID;
6430                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6431                    @Override
6432                    public boolean apply(View t) {
6433                        return t.mNextFocusForwardId == id;
6434                    }
6435                });
6436            }
6437        }
6438        return null;
6439    }
6440
6441    private View findViewInsideOutShouldExist(View root, int id) {
6442        if (mMatchIdPredicate == null) {
6443            mMatchIdPredicate = new MatchIdPredicate();
6444        }
6445        mMatchIdPredicate.mId = id;
6446        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6447        if (result == null) {
6448            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6449        }
6450        return result;
6451    }
6452
6453    /**
6454     * Find and return all focusable views that are descendants of this view,
6455     * possibly including this view if it is focusable itself.
6456     *
6457     * @param direction The direction of the focus
6458     * @return A list of focusable views
6459     */
6460    public ArrayList<View> getFocusables(int direction) {
6461        ArrayList<View> result = new ArrayList<View>(24);
6462        addFocusables(result, direction);
6463        return result;
6464    }
6465
6466    /**
6467     * Add any focusable views that are descendants of this view (possibly
6468     * including this view if it is focusable itself) to views.  If we are in touch mode,
6469     * only add views that are also focusable in touch mode.
6470     *
6471     * @param views Focusable views found so far
6472     * @param direction The direction of the focus
6473     */
6474    public void addFocusables(ArrayList<View> views, int direction) {
6475        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6476    }
6477
6478    /**
6479     * Adds any focusable views that are descendants of this view (possibly
6480     * including this view if it is focusable itself) to views. This method
6481     * adds all focusable views regardless if we are in touch mode or
6482     * only views focusable in touch mode if we are in touch mode or
6483     * only views that can take accessibility focus if accessibility is enabeld
6484     * depending on the focusable mode paramater.
6485     *
6486     * @param views Focusable views found so far or null if all we are interested is
6487     *        the number of focusables.
6488     * @param direction The direction of the focus.
6489     * @param focusableMode The type of focusables to be added.
6490     *
6491     * @see #FOCUSABLES_ALL
6492     * @see #FOCUSABLES_TOUCH_MODE
6493     */
6494    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6495        if (views == null) {
6496            return;
6497        }
6498        if (!isFocusable()) {
6499            return;
6500        }
6501        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6502                && isInTouchMode() && !isFocusableInTouchMode()) {
6503            return;
6504        }
6505        views.add(this);
6506    }
6507
6508    /**
6509     * Finds the Views that contain given text. The containment is case insensitive.
6510     * The search is performed by either the text that the View renders or the content
6511     * description that describes the view for accessibility purposes and the view does
6512     * not render or both. Clients can specify how the search is to be performed via
6513     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6514     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6515     *
6516     * @param outViews The output list of matching Views.
6517     * @param searched The text to match against.
6518     *
6519     * @see #FIND_VIEWS_WITH_TEXT
6520     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6521     * @see #setContentDescription(CharSequence)
6522     */
6523    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6524        if (getAccessibilityNodeProvider() != null) {
6525            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6526                outViews.add(this);
6527            }
6528        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6529                && (searched != null && searched.length() > 0)
6530                && (mContentDescription != null && mContentDescription.length() > 0)) {
6531            String searchedLowerCase = searched.toString().toLowerCase();
6532            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6533            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6534                outViews.add(this);
6535            }
6536        }
6537    }
6538
6539    /**
6540     * Find and return all touchable views that are descendants of this view,
6541     * possibly including this view if it is touchable itself.
6542     *
6543     * @return A list of touchable views
6544     */
6545    public ArrayList<View> getTouchables() {
6546        ArrayList<View> result = new ArrayList<View>();
6547        addTouchables(result);
6548        return result;
6549    }
6550
6551    /**
6552     * Add any touchable views that are descendants of this view (possibly
6553     * including this view if it is touchable itself) to views.
6554     *
6555     * @param views Touchable views found so far
6556     */
6557    public void addTouchables(ArrayList<View> views) {
6558        final int viewFlags = mViewFlags;
6559
6560        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6561                && (viewFlags & ENABLED_MASK) == ENABLED) {
6562            views.add(this);
6563        }
6564    }
6565
6566    /**
6567     * Returns whether this View is accessibility focused.
6568     *
6569     * @return True if this View is accessibility focused.
6570     */
6571    boolean isAccessibilityFocused() {
6572        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6573    }
6574
6575    /**
6576     * Call this to try to give accessibility focus to this view.
6577     *
6578     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6579     * returns false or the view is no visible or the view already has accessibility
6580     * focus.
6581     *
6582     * See also {@link #focusSearch(int)}, which is what you call to say that you
6583     * have focus, and you want your parent to look for the next one.
6584     *
6585     * @return Whether this view actually took accessibility focus.
6586     *
6587     * @hide
6588     */
6589    public boolean requestAccessibilityFocus() {
6590        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6591        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6592            return false;
6593        }
6594        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6595            return false;
6596        }
6597        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6598            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6599            ViewRootImpl viewRootImpl = getViewRootImpl();
6600            if (viewRootImpl != null) {
6601                viewRootImpl.setAccessibilityFocus(this, null);
6602            }
6603            invalidate();
6604            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6605            notifyAccessibilityStateChanged();
6606            return true;
6607        }
6608        return false;
6609    }
6610
6611    /**
6612     * Call this to try to clear accessibility focus of this view.
6613     *
6614     * See also {@link #focusSearch(int)}, which is what you call to say that you
6615     * have focus, and you want your parent to look for the next one.
6616     *
6617     * @hide
6618     */
6619    public void clearAccessibilityFocus() {
6620        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6621            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6622            invalidate();
6623            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6624            notifyAccessibilityStateChanged();
6625        }
6626        // Clear the global reference of accessibility focus if this
6627        // view or any of its descendants had accessibility focus.
6628        ViewRootImpl viewRootImpl = getViewRootImpl();
6629        if (viewRootImpl != null) {
6630            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6631            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6632                viewRootImpl.setAccessibilityFocus(null, null);
6633            }
6634        }
6635    }
6636
6637    private void sendAccessibilityHoverEvent(int eventType) {
6638        // Since we are not delivering to a client accessibility events from not
6639        // important views (unless the clinet request that) we need to fire the
6640        // event from the deepest view exposed to the client. As a consequence if
6641        // the user crosses a not exposed view the client will see enter and exit
6642        // of the exposed predecessor followed by and enter and exit of that same
6643        // predecessor when entering and exiting the not exposed descendant. This
6644        // is fine since the client has a clear idea which view is hovered at the
6645        // price of a couple more events being sent. This is a simple and
6646        // working solution.
6647        View source = this;
6648        while (true) {
6649            if (source.includeForAccessibility()) {
6650                source.sendAccessibilityEvent(eventType);
6651                return;
6652            }
6653            ViewParent parent = source.getParent();
6654            if (parent instanceof View) {
6655                source = (View) parent;
6656            } else {
6657                return;
6658            }
6659        }
6660    }
6661
6662    /**
6663     * Clears accessibility focus without calling any callback methods
6664     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6665     * is used for clearing accessibility focus when giving this focus to
6666     * another view.
6667     */
6668    void clearAccessibilityFocusNoCallbacks() {
6669        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6670            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6671            invalidate();
6672        }
6673    }
6674
6675    /**
6676     * Call this to try to give focus to a specific view or to one of its
6677     * descendants.
6678     *
6679     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6680     * false), or if it is focusable and it is not focusable in touch mode
6681     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6682     *
6683     * See also {@link #focusSearch(int)}, which is what you call to say that you
6684     * have focus, and you want your parent to look for the next one.
6685     *
6686     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6687     * {@link #FOCUS_DOWN} and <code>null</code>.
6688     *
6689     * @return Whether this view or one of its descendants actually took focus.
6690     */
6691    public final boolean requestFocus() {
6692        return requestFocus(View.FOCUS_DOWN);
6693    }
6694
6695    /**
6696     * Call this to try to give focus to a specific view or to one of its
6697     * descendants and give it a hint about what direction focus is heading.
6698     *
6699     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6700     * false), or if it is focusable and it is not focusable in touch mode
6701     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6702     *
6703     * See also {@link #focusSearch(int)}, which is what you call to say that you
6704     * have focus, and you want your parent to look for the next one.
6705     *
6706     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6707     * <code>null</code> set for the previously focused rectangle.
6708     *
6709     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6710     * @return Whether this view or one of its descendants actually took focus.
6711     */
6712    public final boolean requestFocus(int direction) {
6713        return requestFocus(direction, null);
6714    }
6715
6716    /**
6717     * Call this to try to give focus to a specific view or to one of its descendants
6718     * and give it hints about the direction and a specific rectangle that the focus
6719     * is coming from.  The rectangle can help give larger views a finer grained hint
6720     * about where focus is coming from, and therefore, where to show selection, or
6721     * forward focus change internally.
6722     *
6723     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6724     * false), or if it is focusable and it is not focusable in touch mode
6725     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6726     *
6727     * A View will not take focus if it is not visible.
6728     *
6729     * A View will not take focus if one of its parents has
6730     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6731     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6732     *
6733     * See also {@link #focusSearch(int)}, which is what you call to say that you
6734     * have focus, and you want your parent to look for the next one.
6735     *
6736     * You may wish to override this method if your custom {@link View} has an internal
6737     * {@link View} that it wishes to forward the request to.
6738     *
6739     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6740     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6741     *        to give a finer grained hint about where focus is coming from.  May be null
6742     *        if there is no hint.
6743     * @return Whether this view or one of its descendants actually took focus.
6744     */
6745    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6746        return requestFocusNoSearch(direction, previouslyFocusedRect);
6747    }
6748
6749    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6750        // need to be focusable
6751        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6752                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6753            return false;
6754        }
6755
6756        // need to be focusable in touch mode if in touch mode
6757        if (isInTouchMode() &&
6758            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6759               return false;
6760        }
6761
6762        // need to not have any parents blocking us
6763        if (hasAncestorThatBlocksDescendantFocus()) {
6764            return false;
6765        }
6766
6767        handleFocusGainInternal(direction, previouslyFocusedRect);
6768        return true;
6769    }
6770
6771    /**
6772     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6773     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6774     * touch mode to request focus when they are touched.
6775     *
6776     * @return Whether this view or one of its descendants actually took focus.
6777     *
6778     * @see #isInTouchMode()
6779     *
6780     */
6781    public final boolean requestFocusFromTouch() {
6782        // Leave touch mode if we need to
6783        if (isInTouchMode()) {
6784            ViewRootImpl viewRoot = getViewRootImpl();
6785            if (viewRoot != null) {
6786                viewRoot.ensureTouchMode(false);
6787            }
6788        }
6789        return requestFocus(View.FOCUS_DOWN);
6790    }
6791
6792    /**
6793     * @return Whether any ancestor of this view blocks descendant focus.
6794     */
6795    private boolean hasAncestorThatBlocksDescendantFocus() {
6796        ViewParent ancestor = mParent;
6797        while (ancestor instanceof ViewGroup) {
6798            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6799            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6800                return true;
6801            } else {
6802                ancestor = vgAncestor.getParent();
6803            }
6804        }
6805        return false;
6806    }
6807
6808    /**
6809     * Gets the mode for determining whether this View is important for accessibility
6810     * which is if it fires accessibility events and if it is reported to
6811     * accessibility services that query the screen.
6812     *
6813     * @return The mode for determining whether a View is important for accessibility.
6814     *
6815     * @attr ref android.R.styleable#View_importantForAccessibility
6816     *
6817     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6818     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6819     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6820     */
6821    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6822            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6823            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6824            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6825        })
6826    public int getImportantForAccessibility() {
6827        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6828                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6829    }
6830
6831    /**
6832     * Sets how to determine whether this view is important for accessibility
6833     * which is if it fires accessibility events and if it is reported to
6834     * accessibility services that query the screen.
6835     *
6836     * @param mode How to determine whether this view is important for accessibility.
6837     *
6838     * @attr ref android.R.styleable#View_importantForAccessibility
6839     *
6840     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6841     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6842     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6843     */
6844    public void setImportantForAccessibility(int mode) {
6845        if (mode != getImportantForAccessibility()) {
6846            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6847            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6848                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6849            notifyAccessibilityStateChanged();
6850        }
6851    }
6852
6853    /**
6854     * Gets whether this view should be exposed for accessibility.
6855     *
6856     * @return Whether the view is exposed for accessibility.
6857     *
6858     * @hide
6859     */
6860    public boolean isImportantForAccessibility() {
6861        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6862                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6863        switch (mode) {
6864            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6865                return true;
6866            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6867                return false;
6868            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6869                return isActionableForAccessibility() || hasListenersForAccessibility()
6870                        || getAccessibilityNodeProvider() != null;
6871            default:
6872                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6873                        + mode);
6874        }
6875    }
6876
6877    /**
6878     * Gets the parent for accessibility purposes. Note that the parent for
6879     * accessibility is not necessary the immediate parent. It is the first
6880     * predecessor that is important for accessibility.
6881     *
6882     * @return The parent for accessibility purposes.
6883     */
6884    public ViewParent getParentForAccessibility() {
6885        if (mParent instanceof View) {
6886            View parentView = (View) mParent;
6887            if (parentView.includeForAccessibility()) {
6888                return mParent;
6889            } else {
6890                return mParent.getParentForAccessibility();
6891            }
6892        }
6893        return null;
6894    }
6895
6896    /**
6897     * Adds the children of a given View for accessibility. Since some Views are
6898     * not important for accessibility the children for accessibility are not
6899     * necessarily direct children of the view, rather they are the first level of
6900     * descendants important for accessibility.
6901     *
6902     * @param children The list of children for accessibility.
6903     */
6904    public void addChildrenForAccessibility(ArrayList<View> children) {
6905        if (includeForAccessibility()) {
6906            children.add(this);
6907        }
6908    }
6909
6910    /**
6911     * Whether to regard this view for accessibility. A view is regarded for
6912     * accessibility if it is important for accessibility or the querying
6913     * accessibility service has explicitly requested that view not
6914     * important for accessibility are regarded.
6915     *
6916     * @return Whether to regard the view for accessibility.
6917     *
6918     * @hide
6919     */
6920    public boolean includeForAccessibility() {
6921        if (mAttachInfo != null) {
6922            return (mAttachInfo.mAccessibilityFetchFlags
6923                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6924                    || isImportantForAccessibility();
6925        }
6926        return false;
6927    }
6928
6929    /**
6930     * Returns whether the View is considered actionable from
6931     * accessibility perspective. Such view are important for
6932     * accessibility.
6933     *
6934     * @return True if the view is actionable for accessibility.
6935     *
6936     * @hide
6937     */
6938    public boolean isActionableForAccessibility() {
6939        return (isClickable() || isLongClickable() || isFocusable());
6940    }
6941
6942    /**
6943     * Returns whether the View has registered callbacks wich makes it
6944     * important for accessibility.
6945     *
6946     * @return True if the view is actionable for accessibility.
6947     */
6948    private boolean hasListenersForAccessibility() {
6949        ListenerInfo info = getListenerInfo();
6950        return mTouchDelegate != null || info.mOnKeyListener != null
6951                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6952                || info.mOnHoverListener != null || info.mOnDragListener != null;
6953    }
6954
6955    /**
6956     * Notifies accessibility services that some view's important for
6957     * accessibility state has changed. Note that such notifications
6958     * are made at most once every
6959     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6960     * to avoid unnecessary load to the system. Also once a view has
6961     * made a notifucation this method is a NOP until the notification has
6962     * been sent to clients.
6963     *
6964     * @hide
6965     *
6966     * TODO: Makse sure this method is called for any view state change
6967     *       that is interesting for accessilility purposes.
6968     */
6969    public void notifyAccessibilityStateChanged() {
6970        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6971            return;
6972        }
6973        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6974            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6975            if (mParent != null) {
6976                mParent.childAccessibilityStateChanged(this);
6977            }
6978        }
6979    }
6980
6981    /**
6982     * Reset the state indicating the this view has requested clients
6983     * interested in its accessibility state to be notified.
6984     *
6985     * @hide
6986     */
6987    public void resetAccessibilityStateChanged() {
6988        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6989    }
6990
6991    /**
6992     * Performs the specified accessibility action on the view. For
6993     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6994     * <p>
6995     * If an {@link AccessibilityDelegate} has been specified via calling
6996     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6997     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6998     * is responsible for handling this call.
6999     * </p>
7000     *
7001     * @param action The action to perform.
7002     * @param arguments Optional action arguments.
7003     * @return Whether the action was performed.
7004     */
7005    public boolean performAccessibilityAction(int action, Bundle arguments) {
7006      if (mAccessibilityDelegate != null) {
7007          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7008      } else {
7009          return performAccessibilityActionInternal(action, arguments);
7010      }
7011    }
7012
7013   /**
7014    * @see #performAccessibilityAction(int, Bundle)
7015    *
7016    * Note: Called from the default {@link AccessibilityDelegate}.
7017    */
7018    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7019        switch (action) {
7020            case AccessibilityNodeInfo.ACTION_CLICK: {
7021                if (isClickable()) {
7022                    performClick();
7023                    return true;
7024                }
7025            } break;
7026            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7027                if (isLongClickable()) {
7028                    performLongClick();
7029                    return true;
7030                }
7031            } break;
7032            case AccessibilityNodeInfo.ACTION_FOCUS: {
7033                if (!hasFocus()) {
7034                    // Get out of touch mode since accessibility
7035                    // wants to move focus around.
7036                    getViewRootImpl().ensureTouchMode(false);
7037                    return requestFocus();
7038                }
7039            } break;
7040            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7041                if (hasFocus()) {
7042                    clearFocus();
7043                    return !isFocused();
7044                }
7045            } break;
7046            case AccessibilityNodeInfo.ACTION_SELECT: {
7047                if (!isSelected()) {
7048                    setSelected(true);
7049                    return isSelected();
7050                }
7051            } break;
7052            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7053                if (isSelected()) {
7054                    setSelected(false);
7055                    return !isSelected();
7056                }
7057            } break;
7058            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7059                if (!isAccessibilityFocused()) {
7060                    return requestAccessibilityFocus();
7061                }
7062            } break;
7063            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7064                if (isAccessibilityFocused()) {
7065                    clearAccessibilityFocus();
7066                    return true;
7067                }
7068            } break;
7069            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7070                if (arguments != null) {
7071                    final int granularity = arguments.getInt(
7072                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7073                    final boolean extendSelection = arguments.getBoolean(
7074                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7075                    return nextAtGranularity(granularity, extendSelection);
7076                }
7077            } break;
7078            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7079                if (arguments != null) {
7080                    final int granularity = arguments.getInt(
7081                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7082                    final boolean extendSelection = arguments.getBoolean(
7083                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7084                    return previousAtGranularity(granularity, extendSelection);
7085                }
7086            } break;
7087            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7088                CharSequence text = getIterableTextForAccessibility();
7089                if (text == null) {
7090                    return false;
7091                }
7092                final int start = (arguments != null) ? arguments.getInt(
7093                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7094                final int end = (arguments != null) ? arguments.getInt(
7095                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7096                // Only cursor position can be specified (selection length == 0)
7097                if ((getAccessibilitySelectionStart() != start
7098                        || getAccessibilitySelectionEnd() != end)
7099                        && (start == end)) {
7100                    setAccessibilitySelection(start, end);
7101                    notifyAccessibilityStateChanged();
7102                    return true;
7103                }
7104            } break;
7105        }
7106        return false;
7107    }
7108
7109    private boolean nextAtGranularity(int granularity, boolean extendSelection) {
7110        CharSequence text = getIterableTextForAccessibility();
7111        if (text == null || text.length() == 0) {
7112            return false;
7113        }
7114        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7115        if (iterator == null) {
7116            return false;
7117        }
7118        int current = getAccessibilitySelectionEnd();
7119        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7120            current = 0;
7121        }
7122        final int[] range = iterator.following(current);
7123        if (range == null) {
7124            return false;
7125        }
7126        final int start = range[0];
7127        final int end = range[1];
7128        if (extendSelection && isAccessibilitySelectionExtendable()) {
7129            int selectionStart = getAccessibilitySelectionStart();
7130            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7131                selectionStart = start;
7132            }
7133            setAccessibilitySelection(selectionStart, end);
7134        } else {
7135            setAccessibilitySelection(end, end);
7136        }
7137        sendViewTextTraversedAtGranularityEvent(
7138                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
7139                granularity, start, end);
7140        return true;
7141    }
7142
7143    private boolean previousAtGranularity(int granularity, boolean extendSelection) {
7144        CharSequence text = getIterableTextForAccessibility();
7145        if (text == null || text.length() == 0) {
7146            return false;
7147        }
7148        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7149        if (iterator == null) {
7150            return false;
7151        }
7152        int current = getAccessibilitySelectionStart();
7153        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7154            current = text.length();
7155        }
7156        final int[] range = iterator.preceding(current);
7157        if (range == null) {
7158            return false;
7159        }
7160        final int start = range[0];
7161        final int end = range[1];
7162        if (extendSelection && isAccessibilitySelectionExtendable()) {
7163            int selectionEnd = getAccessibilitySelectionEnd();
7164            if (selectionEnd == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7165                selectionEnd = end;
7166            }
7167            setAccessibilitySelection(start, selectionEnd);
7168        } else {
7169            setAccessibilitySelection(start, start);
7170        }
7171        sendViewTextTraversedAtGranularityEvent(
7172                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
7173                granularity, start, end);
7174        return true;
7175    }
7176
7177    /**
7178     * Gets the text reported for accessibility purposes.
7179     *
7180     * @return The accessibility text.
7181     *
7182     * @hide
7183     */
7184    public CharSequence getIterableTextForAccessibility() {
7185        return getContentDescription();
7186    }
7187
7188    /**
7189     * Gets whether accessibility selection can be extended.
7190     *
7191     * @return If selection is extensible.
7192     *
7193     * @hide
7194     */
7195    public boolean isAccessibilitySelectionExtendable() {
7196        return false;
7197    }
7198
7199    /**
7200     * @hide
7201     */
7202    public int getAccessibilitySelectionStart() {
7203        return mAccessibilityCursorPosition;
7204    }
7205
7206    /**
7207     * @hide
7208     */
7209    public int getAccessibilitySelectionEnd() {
7210        return getAccessibilitySelectionStart();
7211    }
7212
7213    /**
7214     * @hide
7215     */
7216    public void setAccessibilitySelection(int start, int end) {
7217        if (start ==  end && end == mAccessibilityCursorPosition) {
7218            return;
7219        }
7220        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7221            mAccessibilityCursorPosition = start;
7222        } else {
7223            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7224        }
7225        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7226    }
7227
7228    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7229            int fromIndex, int toIndex) {
7230        if (mParent == null) {
7231            return;
7232        }
7233        AccessibilityEvent event = AccessibilityEvent.obtain(
7234                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7235        onInitializeAccessibilityEvent(event);
7236        onPopulateAccessibilityEvent(event);
7237        event.setFromIndex(fromIndex);
7238        event.setToIndex(toIndex);
7239        event.setAction(action);
7240        event.setMovementGranularity(granularity);
7241        mParent.requestSendAccessibilityEvent(this, event);
7242    }
7243
7244    /**
7245     * @hide
7246     */
7247    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7248        switch (granularity) {
7249            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7250                CharSequence text = getIterableTextForAccessibility();
7251                if (text != null && text.length() > 0) {
7252                    CharacterTextSegmentIterator iterator =
7253                        CharacterTextSegmentIterator.getInstance(
7254                                mContext.getResources().getConfiguration().locale);
7255                    iterator.initialize(text.toString());
7256                    return iterator;
7257                }
7258            } break;
7259            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7260                CharSequence text = getIterableTextForAccessibility();
7261                if (text != null && text.length() > 0) {
7262                    WordTextSegmentIterator iterator =
7263                        WordTextSegmentIterator.getInstance(
7264                                mContext.getResources().getConfiguration().locale);
7265                    iterator.initialize(text.toString());
7266                    return iterator;
7267                }
7268            } break;
7269            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7270                CharSequence text = getIterableTextForAccessibility();
7271                if (text != null && text.length() > 0) {
7272                    ParagraphTextSegmentIterator iterator =
7273                        ParagraphTextSegmentIterator.getInstance();
7274                    iterator.initialize(text.toString());
7275                    return iterator;
7276                }
7277            } break;
7278        }
7279        return null;
7280    }
7281
7282    /**
7283     * @hide
7284     */
7285    public void dispatchStartTemporaryDetach() {
7286        clearAccessibilityFocus();
7287        clearDisplayList();
7288
7289        onStartTemporaryDetach();
7290    }
7291
7292    /**
7293     * This is called when a container is going to temporarily detach a child, with
7294     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7295     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7296     * {@link #onDetachedFromWindow()} when the container is done.
7297     */
7298    public void onStartTemporaryDetach() {
7299        removeUnsetPressCallback();
7300        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7301    }
7302
7303    /**
7304     * @hide
7305     */
7306    public void dispatchFinishTemporaryDetach() {
7307        onFinishTemporaryDetach();
7308    }
7309
7310    /**
7311     * Called after {@link #onStartTemporaryDetach} when the container is done
7312     * changing the view.
7313     */
7314    public void onFinishTemporaryDetach() {
7315    }
7316
7317    /**
7318     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7319     * for this view's window.  Returns null if the view is not currently attached
7320     * to the window.  Normally you will not need to use this directly, but
7321     * just use the standard high-level event callbacks like
7322     * {@link #onKeyDown(int, KeyEvent)}.
7323     */
7324    public KeyEvent.DispatcherState getKeyDispatcherState() {
7325        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7326    }
7327
7328    /**
7329     * Dispatch a key event before it is processed by any input method
7330     * associated with the view hierarchy.  This can be used to intercept
7331     * key events in special situations before the IME consumes them; a
7332     * typical example would be handling the BACK key to update the application's
7333     * UI instead of allowing the IME to see it and close itself.
7334     *
7335     * @param event The key event to be dispatched.
7336     * @return True if the event was handled, false otherwise.
7337     */
7338    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7339        return onKeyPreIme(event.getKeyCode(), event);
7340    }
7341
7342    /**
7343     * Dispatch a key event to the next view on the focus path. This path runs
7344     * from the top of the view tree down to the currently focused view. If this
7345     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7346     * the next node down the focus path. This method also fires any key
7347     * listeners.
7348     *
7349     * @param event The key event to be dispatched.
7350     * @return True if the event was handled, false otherwise.
7351     */
7352    public boolean dispatchKeyEvent(KeyEvent event) {
7353        if (mInputEventConsistencyVerifier != null) {
7354            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7355        }
7356
7357        // Give any attached key listener a first crack at the event.
7358        //noinspection SimplifiableIfStatement
7359        ListenerInfo li = mListenerInfo;
7360        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7361                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7362            return true;
7363        }
7364
7365        if (event.dispatch(this, mAttachInfo != null
7366                ? mAttachInfo.mKeyDispatchState : null, this)) {
7367            return true;
7368        }
7369
7370        if (mInputEventConsistencyVerifier != null) {
7371            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7372        }
7373        return false;
7374    }
7375
7376    /**
7377     * Dispatches a key shortcut event.
7378     *
7379     * @param event The key event to be dispatched.
7380     * @return True if the event was handled by the view, false otherwise.
7381     */
7382    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7383        return onKeyShortcut(event.getKeyCode(), event);
7384    }
7385
7386    /**
7387     * Pass the touch screen motion event down to the target view, or this
7388     * view if it is the target.
7389     *
7390     * @param event The motion event to be dispatched.
7391     * @return True if the event was handled by the view, false otherwise.
7392     */
7393    public boolean dispatchTouchEvent(MotionEvent event) {
7394        if (mInputEventConsistencyVerifier != null) {
7395            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7396        }
7397
7398        if (onFilterTouchEventForSecurity(event)) {
7399            //noinspection SimplifiableIfStatement
7400            ListenerInfo li = mListenerInfo;
7401            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7402                    && li.mOnTouchListener.onTouch(this, event)) {
7403                return true;
7404            }
7405
7406            if (onTouchEvent(event)) {
7407                return true;
7408            }
7409        }
7410
7411        if (mInputEventConsistencyVerifier != null) {
7412            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7413        }
7414        return false;
7415    }
7416
7417    /**
7418     * Filter the touch event to apply security policies.
7419     *
7420     * @param event The motion event to be filtered.
7421     * @return True if the event should be dispatched, false if the event should be dropped.
7422     *
7423     * @see #getFilterTouchesWhenObscured
7424     */
7425    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7426        //noinspection RedundantIfStatement
7427        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7428                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7429            // Window is obscured, drop this touch.
7430            return false;
7431        }
7432        return true;
7433    }
7434
7435    /**
7436     * Pass a trackball motion event down to the focused view.
7437     *
7438     * @param event The motion event to be dispatched.
7439     * @return True if the event was handled by the view, false otherwise.
7440     */
7441    public boolean dispatchTrackballEvent(MotionEvent event) {
7442        if (mInputEventConsistencyVerifier != null) {
7443            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7444        }
7445
7446        return onTrackballEvent(event);
7447    }
7448
7449    /**
7450     * Dispatch a generic motion event.
7451     * <p>
7452     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7453     * are delivered to the view under the pointer.  All other generic motion events are
7454     * delivered to the focused view.  Hover events are handled specially and are delivered
7455     * to {@link #onHoverEvent(MotionEvent)}.
7456     * </p>
7457     *
7458     * @param event The motion event to be dispatched.
7459     * @return True if the event was handled by the view, false otherwise.
7460     */
7461    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7462        if (mInputEventConsistencyVerifier != null) {
7463            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7464        }
7465
7466        final int source = event.getSource();
7467        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7468            final int action = event.getAction();
7469            if (action == MotionEvent.ACTION_HOVER_ENTER
7470                    || action == MotionEvent.ACTION_HOVER_MOVE
7471                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7472                if (dispatchHoverEvent(event)) {
7473                    return true;
7474                }
7475            } else if (dispatchGenericPointerEvent(event)) {
7476                return true;
7477            }
7478        } else if (dispatchGenericFocusedEvent(event)) {
7479            return true;
7480        }
7481
7482        if (dispatchGenericMotionEventInternal(event)) {
7483            return true;
7484        }
7485
7486        if (mInputEventConsistencyVerifier != null) {
7487            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7488        }
7489        return false;
7490    }
7491
7492    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7493        //noinspection SimplifiableIfStatement
7494        ListenerInfo li = mListenerInfo;
7495        if (li != null && li.mOnGenericMotionListener != null
7496                && (mViewFlags & ENABLED_MASK) == ENABLED
7497                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7498            return true;
7499        }
7500
7501        if (onGenericMotionEvent(event)) {
7502            return true;
7503        }
7504
7505        if (mInputEventConsistencyVerifier != null) {
7506            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7507        }
7508        return false;
7509    }
7510
7511    /**
7512     * Dispatch a hover event.
7513     * <p>
7514     * Do not call this method directly.
7515     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7516     * </p>
7517     *
7518     * @param event The motion event to be dispatched.
7519     * @return True if the event was handled by the view, false otherwise.
7520     */
7521    protected boolean dispatchHoverEvent(MotionEvent event) {
7522        //noinspection SimplifiableIfStatement
7523        ListenerInfo li = mListenerInfo;
7524        if (li != null && li.mOnHoverListener != null
7525                && (mViewFlags & ENABLED_MASK) == ENABLED
7526                && li.mOnHoverListener.onHover(this, event)) {
7527            return true;
7528        }
7529
7530        return onHoverEvent(event);
7531    }
7532
7533    /**
7534     * Returns true if the view has a child to which it has recently sent
7535     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7536     * it does not have a hovered child, then it must be the innermost hovered view.
7537     * @hide
7538     */
7539    protected boolean hasHoveredChild() {
7540        return false;
7541    }
7542
7543    /**
7544     * Dispatch a generic motion event to the view under the first pointer.
7545     * <p>
7546     * Do not call this method directly.
7547     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7548     * </p>
7549     *
7550     * @param event The motion event to be dispatched.
7551     * @return True if the event was handled by the view, false otherwise.
7552     */
7553    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7554        return false;
7555    }
7556
7557    /**
7558     * Dispatch a generic motion event to the currently focused view.
7559     * <p>
7560     * Do not call this method directly.
7561     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7562     * </p>
7563     *
7564     * @param event The motion event to be dispatched.
7565     * @return True if the event was handled by the view, false otherwise.
7566     */
7567    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7568        return false;
7569    }
7570
7571    /**
7572     * Dispatch a pointer event.
7573     * <p>
7574     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7575     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7576     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7577     * and should not be expected to handle other pointing device features.
7578     * </p>
7579     *
7580     * @param event The motion event to be dispatched.
7581     * @return True if the event was handled by the view, false otherwise.
7582     * @hide
7583     */
7584    public final boolean dispatchPointerEvent(MotionEvent event) {
7585        if (event.isTouchEvent()) {
7586            return dispatchTouchEvent(event);
7587        } else {
7588            return dispatchGenericMotionEvent(event);
7589        }
7590    }
7591
7592    /**
7593     * Called when the window containing this view gains or loses window focus.
7594     * ViewGroups should override to route to their children.
7595     *
7596     * @param hasFocus True if the window containing this view now has focus,
7597     *        false otherwise.
7598     */
7599    public void dispatchWindowFocusChanged(boolean hasFocus) {
7600        onWindowFocusChanged(hasFocus);
7601    }
7602
7603    /**
7604     * Called when the window containing this view gains or loses focus.  Note
7605     * that this is separate from view focus: to receive key events, both
7606     * your view and its window must have focus.  If a window is displayed
7607     * on top of yours that takes input focus, then your own window will lose
7608     * focus but the view focus will remain unchanged.
7609     *
7610     * @param hasWindowFocus True if the window containing this view now has
7611     *        focus, false otherwise.
7612     */
7613    public void onWindowFocusChanged(boolean hasWindowFocus) {
7614        InputMethodManager imm = InputMethodManager.peekInstance();
7615        if (!hasWindowFocus) {
7616            if (isPressed()) {
7617                setPressed(false);
7618            }
7619            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7620                imm.focusOut(this);
7621            }
7622            removeLongPressCallback();
7623            removeTapCallback();
7624            onFocusLost();
7625        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7626            imm.focusIn(this);
7627        }
7628        refreshDrawableState();
7629    }
7630
7631    /**
7632     * Returns true if this view is in a window that currently has window focus.
7633     * Note that this is not the same as the view itself having focus.
7634     *
7635     * @return True if this view is in a window that currently has window focus.
7636     */
7637    public boolean hasWindowFocus() {
7638        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7639    }
7640
7641    /**
7642     * Dispatch a view visibility change down the view hierarchy.
7643     * ViewGroups should override to route to their children.
7644     * @param changedView The view whose visibility changed. Could be 'this' or
7645     * an ancestor view.
7646     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7647     * {@link #INVISIBLE} or {@link #GONE}.
7648     */
7649    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7650        onVisibilityChanged(changedView, visibility);
7651    }
7652
7653    /**
7654     * Called when the visibility of the view or an ancestor of the view is changed.
7655     * @param changedView The view whose visibility changed. Could be 'this' or
7656     * an ancestor view.
7657     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7658     * {@link #INVISIBLE} or {@link #GONE}.
7659     */
7660    protected void onVisibilityChanged(View changedView, int visibility) {
7661        if (visibility == VISIBLE) {
7662            if (mAttachInfo != null) {
7663                initialAwakenScrollBars();
7664            } else {
7665                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7666            }
7667        }
7668    }
7669
7670    /**
7671     * Dispatch a hint about whether this view is displayed. For instance, when
7672     * a View moves out of the screen, it might receives a display hint indicating
7673     * the view is not displayed. Applications should not <em>rely</em> on this hint
7674     * as there is no guarantee that they will receive one.
7675     *
7676     * @param hint A hint about whether or not this view is displayed:
7677     * {@link #VISIBLE} or {@link #INVISIBLE}.
7678     */
7679    public void dispatchDisplayHint(int hint) {
7680        onDisplayHint(hint);
7681    }
7682
7683    /**
7684     * Gives this view a hint about whether is displayed or not. For instance, when
7685     * a View moves out of the screen, it might receives a display hint indicating
7686     * the view is not displayed. Applications should not <em>rely</em> on this hint
7687     * as there is no guarantee that they will receive one.
7688     *
7689     * @param hint A hint about whether or not this view is displayed:
7690     * {@link #VISIBLE} or {@link #INVISIBLE}.
7691     */
7692    protected void onDisplayHint(int hint) {
7693    }
7694
7695    /**
7696     * Dispatch a window visibility change down the view hierarchy.
7697     * ViewGroups should override to route to their children.
7698     *
7699     * @param visibility The new visibility of the window.
7700     *
7701     * @see #onWindowVisibilityChanged(int)
7702     */
7703    public void dispatchWindowVisibilityChanged(int visibility) {
7704        onWindowVisibilityChanged(visibility);
7705    }
7706
7707    /**
7708     * Called when the window containing has change its visibility
7709     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7710     * that this tells you whether or not your window is being made visible
7711     * to the window manager; this does <em>not</em> tell you whether or not
7712     * your window is obscured by other windows on the screen, even if it
7713     * is itself visible.
7714     *
7715     * @param visibility The new visibility of the window.
7716     */
7717    protected void onWindowVisibilityChanged(int visibility) {
7718        if (visibility == VISIBLE) {
7719            initialAwakenScrollBars();
7720        }
7721    }
7722
7723    /**
7724     * Returns the current visibility of the window this view is attached to
7725     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7726     *
7727     * @return Returns the current visibility of the view's window.
7728     */
7729    public int getWindowVisibility() {
7730        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7731    }
7732
7733    /**
7734     * Retrieve the overall visible display size in which the window this view is
7735     * attached to has been positioned in.  This takes into account screen
7736     * decorations above the window, for both cases where the window itself
7737     * is being position inside of them or the window is being placed under
7738     * then and covered insets are used for the window to position its content
7739     * inside.  In effect, this tells you the available area where content can
7740     * be placed and remain visible to users.
7741     *
7742     * <p>This function requires an IPC back to the window manager to retrieve
7743     * the requested information, so should not be used in performance critical
7744     * code like drawing.
7745     *
7746     * @param outRect Filled in with the visible display frame.  If the view
7747     * is not attached to a window, this is simply the raw display size.
7748     */
7749    public void getWindowVisibleDisplayFrame(Rect outRect) {
7750        if (mAttachInfo != null) {
7751            try {
7752                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7753            } catch (RemoteException e) {
7754                return;
7755            }
7756            // XXX This is really broken, and probably all needs to be done
7757            // in the window manager, and we need to know more about whether
7758            // we want the area behind or in front of the IME.
7759            final Rect insets = mAttachInfo.mVisibleInsets;
7760            outRect.left += insets.left;
7761            outRect.top += insets.top;
7762            outRect.right -= insets.right;
7763            outRect.bottom -= insets.bottom;
7764            return;
7765        }
7766        // The view is not attached to a display so we don't have a context.
7767        // Make a best guess about the display size.
7768        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7769        d.getRectSize(outRect);
7770    }
7771
7772    /**
7773     * Dispatch a notification about a resource configuration change down
7774     * the view hierarchy.
7775     * ViewGroups should override to route to their children.
7776     *
7777     * @param newConfig The new resource configuration.
7778     *
7779     * @see #onConfigurationChanged(android.content.res.Configuration)
7780     */
7781    public void dispatchConfigurationChanged(Configuration newConfig) {
7782        onConfigurationChanged(newConfig);
7783    }
7784
7785    /**
7786     * Called when the current configuration of the resources being used
7787     * by the application have changed.  You can use this to decide when
7788     * to reload resources that can changed based on orientation and other
7789     * configuration characterstics.  You only need to use this if you are
7790     * not relying on the normal {@link android.app.Activity} mechanism of
7791     * recreating the activity instance upon a configuration change.
7792     *
7793     * @param newConfig The new resource configuration.
7794     */
7795    protected void onConfigurationChanged(Configuration newConfig) {
7796    }
7797
7798    /**
7799     * Private function to aggregate all per-view attributes in to the view
7800     * root.
7801     */
7802    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7803        performCollectViewAttributes(attachInfo, visibility);
7804    }
7805
7806    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7807        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7808            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7809                attachInfo.mKeepScreenOn = true;
7810            }
7811            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7812            ListenerInfo li = mListenerInfo;
7813            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7814                attachInfo.mHasSystemUiListeners = true;
7815            }
7816        }
7817    }
7818
7819    void needGlobalAttributesUpdate(boolean force) {
7820        final AttachInfo ai = mAttachInfo;
7821        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7822            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7823                    || ai.mHasSystemUiListeners) {
7824                ai.mRecomputeGlobalAttributes = true;
7825            }
7826        }
7827    }
7828
7829    /**
7830     * Returns whether the device is currently in touch mode.  Touch mode is entered
7831     * once the user begins interacting with the device by touch, and affects various
7832     * things like whether focus is always visible to the user.
7833     *
7834     * @return Whether the device is in touch mode.
7835     */
7836    @ViewDebug.ExportedProperty
7837    public boolean isInTouchMode() {
7838        if (mAttachInfo != null) {
7839            return mAttachInfo.mInTouchMode;
7840        } else {
7841            return ViewRootImpl.isInTouchMode();
7842        }
7843    }
7844
7845    /**
7846     * Returns the context the view is running in, through which it can
7847     * access the current theme, resources, etc.
7848     *
7849     * @return The view's Context.
7850     */
7851    @ViewDebug.CapturedViewProperty
7852    public final Context getContext() {
7853        return mContext;
7854    }
7855
7856    /**
7857     * Handle a key event before it is processed by any input method
7858     * associated with the view hierarchy.  This can be used to intercept
7859     * key events in special situations before the IME consumes them; a
7860     * typical example would be handling the BACK key to update the application's
7861     * UI instead of allowing the IME to see it and close itself.
7862     *
7863     * @param keyCode The value in event.getKeyCode().
7864     * @param event Description of the key event.
7865     * @return If you handled the event, return true. If you want to allow the
7866     *         event to be handled by the next receiver, return false.
7867     */
7868    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7869        return false;
7870    }
7871
7872    /**
7873     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7874     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7875     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7876     * is released, if the view is enabled and clickable.
7877     *
7878     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7879     * although some may elect to do so in some situations. Do not rely on this to
7880     * catch software key presses.
7881     *
7882     * @param keyCode A key code that represents the button pressed, from
7883     *                {@link android.view.KeyEvent}.
7884     * @param event   The KeyEvent object that defines the button action.
7885     */
7886    public boolean onKeyDown(int keyCode, KeyEvent event) {
7887        boolean result = false;
7888
7889        switch (keyCode) {
7890            case KeyEvent.KEYCODE_DPAD_CENTER:
7891            case KeyEvent.KEYCODE_ENTER: {
7892                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7893                    return true;
7894                }
7895                // Long clickable items don't necessarily have to be clickable
7896                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7897                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7898                        (event.getRepeatCount() == 0)) {
7899                    setPressed(true);
7900                    checkForLongClick(0);
7901                    return true;
7902                }
7903                break;
7904            }
7905        }
7906        return result;
7907    }
7908
7909    /**
7910     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7911     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7912     * the event).
7913     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7914     * although some may elect to do so in some situations. Do not rely on this to
7915     * catch software key presses.
7916     */
7917    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7918        return false;
7919    }
7920
7921    /**
7922     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7923     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7924     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7925     * {@link KeyEvent#KEYCODE_ENTER} is released.
7926     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7927     * although some may elect to do so in some situations. Do not rely on this to
7928     * catch software key presses.
7929     *
7930     * @param keyCode A key code that represents the button pressed, from
7931     *                {@link android.view.KeyEvent}.
7932     * @param event   The KeyEvent object that defines the button action.
7933     */
7934    public boolean onKeyUp(int keyCode, KeyEvent event) {
7935        boolean result = false;
7936
7937        switch (keyCode) {
7938            case KeyEvent.KEYCODE_DPAD_CENTER:
7939            case KeyEvent.KEYCODE_ENTER: {
7940                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7941                    return true;
7942                }
7943                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7944                    setPressed(false);
7945
7946                    if (!mHasPerformedLongPress) {
7947                        // This is a tap, so remove the longpress check
7948                        removeLongPressCallback();
7949
7950                        result = performClick();
7951                    }
7952                }
7953                break;
7954            }
7955        }
7956        return result;
7957    }
7958
7959    /**
7960     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7961     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7962     * the event).
7963     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7964     * although some may elect to do so in some situations. Do not rely on this to
7965     * catch software key presses.
7966     *
7967     * @param keyCode     A key code that represents the button pressed, from
7968     *                    {@link android.view.KeyEvent}.
7969     * @param repeatCount The number of times the action was made.
7970     * @param event       The KeyEvent object that defines the button action.
7971     */
7972    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7973        return false;
7974    }
7975
7976    /**
7977     * Called on the focused view when a key shortcut event is not handled.
7978     * Override this method to implement local key shortcuts for the View.
7979     * Key shortcuts can also be implemented by setting the
7980     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7981     *
7982     * @param keyCode The value in event.getKeyCode().
7983     * @param event Description of the key event.
7984     * @return If you handled the event, return true. If you want to allow the
7985     *         event to be handled by the next receiver, return false.
7986     */
7987    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7988        return false;
7989    }
7990
7991    /**
7992     * Check whether the called view is a text editor, in which case it
7993     * would make sense to automatically display a soft input window for
7994     * it.  Subclasses should override this if they implement
7995     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7996     * a call on that method would return a non-null InputConnection, and
7997     * they are really a first-class editor that the user would normally
7998     * start typing on when the go into a window containing your view.
7999     *
8000     * <p>The default implementation always returns false.  This does
8001     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8002     * will not be called or the user can not otherwise perform edits on your
8003     * view; it is just a hint to the system that this is not the primary
8004     * purpose of this view.
8005     *
8006     * @return Returns true if this view is a text editor, else false.
8007     */
8008    public boolean onCheckIsTextEditor() {
8009        return false;
8010    }
8011
8012    /**
8013     * Create a new InputConnection for an InputMethod to interact
8014     * with the view.  The default implementation returns null, since it doesn't
8015     * support input methods.  You can override this to implement such support.
8016     * This is only needed for views that take focus and text input.
8017     *
8018     * <p>When implementing this, you probably also want to implement
8019     * {@link #onCheckIsTextEditor()} to indicate you will return a
8020     * non-null InputConnection.
8021     *
8022     * @param outAttrs Fill in with attribute information about the connection.
8023     */
8024    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8025        return null;
8026    }
8027
8028    /**
8029     * Called by the {@link android.view.inputmethod.InputMethodManager}
8030     * when a view who is not the current
8031     * input connection target is trying to make a call on the manager.  The
8032     * default implementation returns false; you can override this to return
8033     * true for certain views if you are performing InputConnection proxying
8034     * to them.
8035     * @param view The View that is making the InputMethodManager call.
8036     * @return Return true to allow the call, false to reject.
8037     */
8038    public boolean checkInputConnectionProxy(View view) {
8039        return false;
8040    }
8041
8042    /**
8043     * Show the context menu for this view. It is not safe to hold on to the
8044     * menu after returning from this method.
8045     *
8046     * You should normally not overload this method. Overload
8047     * {@link #onCreateContextMenu(ContextMenu)} or define an
8048     * {@link OnCreateContextMenuListener} to add items to the context menu.
8049     *
8050     * @param menu The context menu to populate
8051     */
8052    public void createContextMenu(ContextMenu menu) {
8053        ContextMenuInfo menuInfo = getContextMenuInfo();
8054
8055        // Sets the current menu info so all items added to menu will have
8056        // my extra info set.
8057        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8058
8059        onCreateContextMenu(menu);
8060        ListenerInfo li = mListenerInfo;
8061        if (li != null && li.mOnCreateContextMenuListener != null) {
8062            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8063        }
8064
8065        // Clear the extra information so subsequent items that aren't mine don't
8066        // have my extra info.
8067        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8068
8069        if (mParent != null) {
8070            mParent.createContextMenu(menu);
8071        }
8072    }
8073
8074    /**
8075     * Views should implement this if they have extra information to associate
8076     * with the context menu. The return result is supplied as a parameter to
8077     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8078     * callback.
8079     *
8080     * @return Extra information about the item for which the context menu
8081     *         should be shown. This information will vary across different
8082     *         subclasses of View.
8083     */
8084    protected ContextMenuInfo getContextMenuInfo() {
8085        return null;
8086    }
8087
8088    /**
8089     * Views should implement this if the view itself is going to add items to
8090     * the context menu.
8091     *
8092     * @param menu the context menu to populate
8093     */
8094    protected void onCreateContextMenu(ContextMenu menu) {
8095    }
8096
8097    /**
8098     * Implement this method to handle trackball motion events.  The
8099     * <em>relative</em> movement of the trackball since the last event
8100     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8101     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8102     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8103     * they will often be fractional values, representing the more fine-grained
8104     * movement information available from a trackball).
8105     *
8106     * @param event The motion event.
8107     * @return True if the event was handled, false otherwise.
8108     */
8109    public boolean onTrackballEvent(MotionEvent event) {
8110        return false;
8111    }
8112
8113    /**
8114     * Implement this method to handle generic motion events.
8115     * <p>
8116     * Generic motion events describe joystick movements, mouse hovers, track pad
8117     * touches, scroll wheel movements and other input events.  The
8118     * {@link MotionEvent#getSource() source} of the motion event specifies
8119     * the class of input that was received.  Implementations of this method
8120     * must examine the bits in the source before processing the event.
8121     * The following code example shows how this is done.
8122     * </p><p>
8123     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8124     * are delivered to the view under the pointer.  All other generic motion events are
8125     * delivered to the focused view.
8126     * </p>
8127     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8128     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8129     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8130     *             // process the joystick movement...
8131     *             return true;
8132     *         }
8133     *     }
8134     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8135     *         switch (event.getAction()) {
8136     *             case MotionEvent.ACTION_HOVER_MOVE:
8137     *                 // process the mouse hover movement...
8138     *                 return true;
8139     *             case MotionEvent.ACTION_SCROLL:
8140     *                 // process the scroll wheel movement...
8141     *                 return true;
8142     *         }
8143     *     }
8144     *     return super.onGenericMotionEvent(event);
8145     * }</pre>
8146     *
8147     * @param event The generic motion event being processed.
8148     * @return True if the event was handled, false otherwise.
8149     */
8150    public boolean onGenericMotionEvent(MotionEvent event) {
8151        return false;
8152    }
8153
8154    /**
8155     * Implement this method to handle hover events.
8156     * <p>
8157     * This method is called whenever a pointer is hovering into, over, or out of the
8158     * bounds of a view and the view is not currently being touched.
8159     * Hover events are represented as pointer events with action
8160     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8161     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8162     * </p>
8163     * <ul>
8164     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8165     * when the pointer enters the bounds of the view.</li>
8166     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8167     * when the pointer has already entered the bounds of the view and has moved.</li>
8168     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8169     * when the pointer has exited the bounds of the view or when the pointer is
8170     * about to go down due to a button click, tap, or similar user action that
8171     * causes the view to be touched.</li>
8172     * </ul>
8173     * <p>
8174     * The view should implement this method to return true to indicate that it is
8175     * handling the hover event, such as by changing its drawable state.
8176     * </p><p>
8177     * The default implementation calls {@link #setHovered} to update the hovered state
8178     * of the view when a hover enter or hover exit event is received, if the view
8179     * is enabled and is clickable.  The default implementation also sends hover
8180     * accessibility events.
8181     * </p>
8182     *
8183     * @param event The motion event that describes the hover.
8184     * @return True if the view handled the hover event.
8185     *
8186     * @see #isHovered
8187     * @see #setHovered
8188     * @see #onHoverChanged
8189     */
8190    public boolean onHoverEvent(MotionEvent event) {
8191        // The root view may receive hover (or touch) events that are outside the bounds of
8192        // the window.  This code ensures that we only send accessibility events for
8193        // hovers that are actually within the bounds of the root view.
8194        final int action = event.getActionMasked();
8195        if (!mSendingHoverAccessibilityEvents) {
8196            if ((action == MotionEvent.ACTION_HOVER_ENTER
8197                    || action == MotionEvent.ACTION_HOVER_MOVE)
8198                    && !hasHoveredChild()
8199                    && pointInView(event.getX(), event.getY())) {
8200                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8201                mSendingHoverAccessibilityEvents = true;
8202            }
8203        } else {
8204            if (action == MotionEvent.ACTION_HOVER_EXIT
8205                    || (action == MotionEvent.ACTION_MOVE
8206                            && !pointInView(event.getX(), event.getY()))) {
8207                mSendingHoverAccessibilityEvents = false;
8208                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8209                // If the window does not have input focus we take away accessibility
8210                // focus as soon as the user stop hovering over the view.
8211                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8212                    getViewRootImpl().setAccessibilityFocus(null, null);
8213                }
8214            }
8215        }
8216
8217        if (isHoverable()) {
8218            switch (action) {
8219                case MotionEvent.ACTION_HOVER_ENTER:
8220                    setHovered(true);
8221                    break;
8222                case MotionEvent.ACTION_HOVER_EXIT:
8223                    setHovered(false);
8224                    break;
8225            }
8226
8227            // Dispatch the event to onGenericMotionEvent before returning true.
8228            // This is to provide compatibility with existing applications that
8229            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8230            // break because of the new default handling for hoverable views
8231            // in onHoverEvent.
8232            // Note that onGenericMotionEvent will be called by default when
8233            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8234            return dispatchGenericMotionEventInternal(event);
8235        }
8236
8237        return false;
8238    }
8239
8240    /**
8241     * Returns true if the view should handle {@link #onHoverEvent}
8242     * by calling {@link #setHovered} to change its hovered state.
8243     *
8244     * @return True if the view is hoverable.
8245     */
8246    private boolean isHoverable() {
8247        final int viewFlags = mViewFlags;
8248        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8249            return false;
8250        }
8251
8252        return (viewFlags & CLICKABLE) == CLICKABLE
8253                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8254    }
8255
8256    /**
8257     * Returns true if the view is currently hovered.
8258     *
8259     * @return True if the view is currently hovered.
8260     *
8261     * @see #setHovered
8262     * @see #onHoverChanged
8263     */
8264    @ViewDebug.ExportedProperty
8265    public boolean isHovered() {
8266        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8267    }
8268
8269    /**
8270     * Sets whether the view is currently hovered.
8271     * <p>
8272     * Calling this method also changes the drawable state of the view.  This
8273     * enables the view to react to hover by using different drawable resources
8274     * to change its appearance.
8275     * </p><p>
8276     * The {@link #onHoverChanged} method is called when the hovered state changes.
8277     * </p>
8278     *
8279     * @param hovered True if the view is hovered.
8280     *
8281     * @see #isHovered
8282     * @see #onHoverChanged
8283     */
8284    public void setHovered(boolean hovered) {
8285        if (hovered) {
8286            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8287                mPrivateFlags |= PFLAG_HOVERED;
8288                refreshDrawableState();
8289                onHoverChanged(true);
8290            }
8291        } else {
8292            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8293                mPrivateFlags &= ~PFLAG_HOVERED;
8294                refreshDrawableState();
8295                onHoverChanged(false);
8296            }
8297        }
8298    }
8299
8300    /**
8301     * Implement this method to handle hover state changes.
8302     * <p>
8303     * This method is called whenever the hover state changes as a result of a
8304     * call to {@link #setHovered}.
8305     * </p>
8306     *
8307     * @param hovered The current hover state, as returned by {@link #isHovered}.
8308     *
8309     * @see #isHovered
8310     * @see #setHovered
8311     */
8312    public void onHoverChanged(boolean hovered) {
8313    }
8314
8315    /**
8316     * Implement this method to handle touch screen motion events.
8317     *
8318     * @param event The motion event.
8319     * @return True if the event was handled, false otherwise.
8320     */
8321    public boolean onTouchEvent(MotionEvent event) {
8322        final int viewFlags = mViewFlags;
8323
8324        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8325            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8326                setPressed(false);
8327            }
8328            // A disabled view that is clickable still consumes the touch
8329            // events, it just doesn't respond to them.
8330            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8331                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8332        }
8333
8334        if (mTouchDelegate != null) {
8335            if (mTouchDelegate.onTouchEvent(event)) {
8336                return true;
8337            }
8338        }
8339
8340        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8341                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8342            switch (event.getAction()) {
8343                case MotionEvent.ACTION_UP:
8344                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8345                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8346                        // take focus if we don't have it already and we should in
8347                        // touch mode.
8348                        boolean focusTaken = false;
8349                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8350                            focusTaken = requestFocus();
8351                        }
8352
8353                        if (prepressed) {
8354                            // The button is being released before we actually
8355                            // showed it as pressed.  Make it show the pressed
8356                            // state now (before scheduling the click) to ensure
8357                            // the user sees it.
8358                            setPressed(true);
8359                       }
8360
8361                        if (!mHasPerformedLongPress) {
8362                            // This is a tap, so remove the longpress check
8363                            removeLongPressCallback();
8364
8365                            // Only perform take click actions if we were in the pressed state
8366                            if (!focusTaken) {
8367                                // Use a Runnable and post this rather than calling
8368                                // performClick directly. This lets other visual state
8369                                // of the view update before click actions start.
8370                                if (mPerformClick == null) {
8371                                    mPerformClick = new PerformClick();
8372                                }
8373                                if (!post(mPerformClick)) {
8374                                    performClick();
8375                                }
8376                            }
8377                        }
8378
8379                        if (mUnsetPressedState == null) {
8380                            mUnsetPressedState = new UnsetPressedState();
8381                        }
8382
8383                        if (prepressed) {
8384                            postDelayed(mUnsetPressedState,
8385                                    ViewConfiguration.getPressedStateDuration());
8386                        } else if (!post(mUnsetPressedState)) {
8387                            // If the post failed, unpress right now
8388                            mUnsetPressedState.run();
8389                        }
8390                        removeTapCallback();
8391                    }
8392                    break;
8393
8394                case MotionEvent.ACTION_DOWN:
8395                    mHasPerformedLongPress = false;
8396
8397                    if (performButtonActionOnTouchDown(event)) {
8398                        break;
8399                    }
8400
8401                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8402                    boolean isInScrollingContainer = isInScrollingContainer();
8403
8404                    // For views inside a scrolling container, delay the pressed feedback for
8405                    // a short period in case this is a scroll.
8406                    if (isInScrollingContainer) {
8407                        mPrivateFlags |= PFLAG_PREPRESSED;
8408                        if (mPendingCheckForTap == null) {
8409                            mPendingCheckForTap = new CheckForTap();
8410                        }
8411                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8412                    } else {
8413                        // Not inside a scrolling container, so show the feedback right away
8414                        setPressed(true);
8415                        checkForLongClick(0);
8416                    }
8417                    break;
8418
8419                case MotionEvent.ACTION_CANCEL:
8420                    setPressed(false);
8421                    removeTapCallback();
8422                    removeLongPressCallback();
8423                    break;
8424
8425                case MotionEvent.ACTION_MOVE:
8426                    final int x = (int) event.getX();
8427                    final int y = (int) event.getY();
8428
8429                    // Be lenient about moving outside of buttons
8430                    if (!pointInView(x, y, mTouchSlop)) {
8431                        // Outside button
8432                        removeTapCallback();
8433                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8434                            // Remove any future long press/tap checks
8435                            removeLongPressCallback();
8436
8437                            setPressed(false);
8438                        }
8439                    }
8440                    break;
8441            }
8442            return true;
8443        }
8444
8445        return false;
8446    }
8447
8448    /**
8449     * @hide
8450     */
8451    public boolean isInScrollingContainer() {
8452        ViewParent p = getParent();
8453        while (p != null && p instanceof ViewGroup) {
8454            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8455                return true;
8456            }
8457            p = p.getParent();
8458        }
8459        return false;
8460    }
8461
8462    /**
8463     * Remove the longpress detection timer.
8464     */
8465    private void removeLongPressCallback() {
8466        if (mPendingCheckForLongPress != null) {
8467          removeCallbacks(mPendingCheckForLongPress);
8468        }
8469    }
8470
8471    /**
8472     * Remove the pending click action
8473     */
8474    private void removePerformClickCallback() {
8475        if (mPerformClick != null) {
8476            removeCallbacks(mPerformClick);
8477        }
8478    }
8479
8480    /**
8481     * Remove the prepress detection timer.
8482     */
8483    private void removeUnsetPressCallback() {
8484        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8485            setPressed(false);
8486            removeCallbacks(mUnsetPressedState);
8487        }
8488    }
8489
8490    /**
8491     * Remove the tap detection timer.
8492     */
8493    private void removeTapCallback() {
8494        if (mPendingCheckForTap != null) {
8495            mPrivateFlags &= ~PFLAG_PREPRESSED;
8496            removeCallbacks(mPendingCheckForTap);
8497        }
8498    }
8499
8500    /**
8501     * Cancels a pending long press.  Your subclass can use this if you
8502     * want the context menu to come up if the user presses and holds
8503     * at the same place, but you don't want it to come up if they press
8504     * and then move around enough to cause scrolling.
8505     */
8506    public void cancelLongPress() {
8507        removeLongPressCallback();
8508
8509        /*
8510         * The prepressed state handled by the tap callback is a display
8511         * construct, but the tap callback will post a long press callback
8512         * less its own timeout. Remove it here.
8513         */
8514        removeTapCallback();
8515    }
8516
8517    /**
8518     * Remove the pending callback for sending a
8519     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8520     */
8521    private void removeSendViewScrolledAccessibilityEventCallback() {
8522        if (mSendViewScrolledAccessibilityEvent != null) {
8523            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8524            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8525        }
8526    }
8527
8528    /**
8529     * Sets the TouchDelegate for this View.
8530     */
8531    public void setTouchDelegate(TouchDelegate delegate) {
8532        mTouchDelegate = delegate;
8533    }
8534
8535    /**
8536     * Gets the TouchDelegate for this View.
8537     */
8538    public TouchDelegate getTouchDelegate() {
8539        return mTouchDelegate;
8540    }
8541
8542    /**
8543     * Set flags controlling behavior of this view.
8544     *
8545     * @param flags Constant indicating the value which should be set
8546     * @param mask Constant indicating the bit range that should be changed
8547     */
8548    void setFlags(int flags, int mask) {
8549        int old = mViewFlags;
8550        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8551
8552        int changed = mViewFlags ^ old;
8553        if (changed == 0) {
8554            return;
8555        }
8556        int privateFlags = mPrivateFlags;
8557
8558        /* Check if the FOCUSABLE bit has changed */
8559        if (((changed & FOCUSABLE_MASK) != 0) &&
8560                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8561            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8562                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8563                /* Give up focus if we are no longer focusable */
8564                clearFocus();
8565            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8566                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8567                /*
8568                 * Tell the view system that we are now available to take focus
8569                 * if no one else already has it.
8570                 */
8571                if (mParent != null) mParent.focusableViewAvailable(this);
8572            }
8573            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8574                notifyAccessibilityStateChanged();
8575            }
8576        }
8577
8578        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8579            if ((changed & VISIBILITY_MASK) != 0) {
8580                /*
8581                 * If this view is becoming visible, invalidate it in case it changed while
8582                 * it was not visible. Marking it drawn ensures that the invalidation will
8583                 * go through.
8584                 */
8585                mPrivateFlags |= PFLAG_DRAWN;
8586                invalidate(true);
8587
8588                needGlobalAttributesUpdate(true);
8589
8590                // a view becoming visible is worth notifying the parent
8591                // about in case nothing has focus.  even if this specific view
8592                // isn't focusable, it may contain something that is, so let
8593                // the root view try to give this focus if nothing else does.
8594                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8595                    mParent.focusableViewAvailable(this);
8596                }
8597            }
8598        }
8599
8600        /* Check if the GONE bit has changed */
8601        if ((changed & GONE) != 0) {
8602            needGlobalAttributesUpdate(false);
8603            requestLayout();
8604
8605            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8606                if (hasFocus()) clearFocus();
8607                clearAccessibilityFocus();
8608                destroyDrawingCache();
8609                if (mParent instanceof View) {
8610                    // GONE views noop invalidation, so invalidate the parent
8611                    ((View) mParent).invalidate(true);
8612                }
8613                // Mark the view drawn to ensure that it gets invalidated properly the next
8614                // time it is visible and gets invalidated
8615                mPrivateFlags |= PFLAG_DRAWN;
8616            }
8617            if (mAttachInfo != null) {
8618                mAttachInfo.mViewVisibilityChanged = true;
8619            }
8620        }
8621
8622        /* Check if the VISIBLE bit has changed */
8623        if ((changed & INVISIBLE) != 0) {
8624            needGlobalAttributesUpdate(false);
8625            /*
8626             * If this view is becoming invisible, set the DRAWN flag so that
8627             * the next invalidate() will not be skipped.
8628             */
8629            mPrivateFlags |= PFLAG_DRAWN;
8630
8631            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8632                // root view becoming invisible shouldn't clear focus and accessibility focus
8633                if (getRootView() != this) {
8634                    clearFocus();
8635                    clearAccessibilityFocus();
8636                }
8637            }
8638            if (mAttachInfo != null) {
8639                mAttachInfo.mViewVisibilityChanged = true;
8640            }
8641        }
8642
8643        if ((changed & VISIBILITY_MASK) != 0) {
8644            if (mParent instanceof ViewGroup) {
8645                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8646                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8647                ((View) mParent).invalidate(true);
8648            } else if (mParent != null) {
8649                mParent.invalidateChild(this, null);
8650            }
8651            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8652        }
8653
8654        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8655            destroyDrawingCache();
8656        }
8657
8658        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8659            destroyDrawingCache();
8660            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8661            invalidateParentCaches();
8662        }
8663
8664        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8665            destroyDrawingCache();
8666            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8667        }
8668
8669        if ((changed & DRAW_MASK) != 0) {
8670            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8671                if (mBackground != null) {
8672                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8673                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8674                } else {
8675                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8676                }
8677            } else {
8678                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8679            }
8680            requestLayout();
8681            invalidate(true);
8682        }
8683
8684        if ((changed & KEEP_SCREEN_ON) != 0) {
8685            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8686                mParent.recomputeViewAttributes(this);
8687            }
8688        }
8689
8690        if (AccessibilityManager.getInstance(mContext).isEnabled()
8691                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8692                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8693            notifyAccessibilityStateChanged();
8694        }
8695    }
8696
8697    /**
8698     * Change the view's z order in the tree, so it's on top of other sibling
8699     * views
8700     */
8701    public void bringToFront() {
8702        if (mParent != null) {
8703            mParent.bringChildToFront(this);
8704        }
8705    }
8706
8707    /**
8708     * This is called in response to an internal scroll in this view (i.e., the
8709     * view scrolled its own contents). This is typically as a result of
8710     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8711     * called.
8712     *
8713     * @param l Current horizontal scroll origin.
8714     * @param t Current vertical scroll origin.
8715     * @param oldl Previous horizontal scroll origin.
8716     * @param oldt Previous vertical scroll origin.
8717     */
8718    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8719        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8720            postSendViewScrolledAccessibilityEventCallback();
8721        }
8722
8723        mBackgroundSizeChanged = true;
8724
8725        final AttachInfo ai = mAttachInfo;
8726        if (ai != null) {
8727            ai.mViewScrollChanged = true;
8728        }
8729    }
8730
8731    /**
8732     * Interface definition for a callback to be invoked when the layout bounds of a view
8733     * changes due to layout processing.
8734     */
8735    public interface OnLayoutChangeListener {
8736        /**
8737         * Called when the focus state of a view has changed.
8738         *
8739         * @param v The view whose state has changed.
8740         * @param left The new value of the view's left property.
8741         * @param top The new value of the view's top property.
8742         * @param right The new value of the view's right property.
8743         * @param bottom The new value of the view's bottom property.
8744         * @param oldLeft The previous value of the view's left property.
8745         * @param oldTop The previous value of the view's top property.
8746         * @param oldRight The previous value of the view's right property.
8747         * @param oldBottom The previous value of the view's bottom property.
8748         */
8749        void onLayoutChange(View v, int left, int top, int right, int bottom,
8750            int oldLeft, int oldTop, int oldRight, int oldBottom);
8751    }
8752
8753    /**
8754     * This is called during layout when the size of this view has changed. If
8755     * you were just added to the view hierarchy, you're called with the old
8756     * values of 0.
8757     *
8758     * @param w Current width of this view.
8759     * @param h Current height of this view.
8760     * @param oldw Old width of this view.
8761     * @param oldh Old height of this view.
8762     */
8763    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8764    }
8765
8766    /**
8767     * Called by draw to draw the child views. This may be overridden
8768     * by derived classes to gain control just before its children are drawn
8769     * (but after its own view has been drawn).
8770     * @param canvas the canvas on which to draw the view
8771     */
8772    protected void dispatchDraw(Canvas canvas) {
8773
8774    }
8775
8776    /**
8777     * Gets the parent of this view. Note that the parent is a
8778     * ViewParent and not necessarily a View.
8779     *
8780     * @return Parent of this view.
8781     */
8782    public final ViewParent getParent() {
8783        return mParent;
8784    }
8785
8786    /**
8787     * Set the horizontal scrolled position of your view. This will cause a call to
8788     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8789     * invalidated.
8790     * @param value the x position to scroll to
8791     */
8792    public void setScrollX(int value) {
8793        scrollTo(value, mScrollY);
8794    }
8795
8796    /**
8797     * Set the vertical scrolled position of your view. This will cause a call to
8798     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8799     * invalidated.
8800     * @param value the y position to scroll to
8801     */
8802    public void setScrollY(int value) {
8803        scrollTo(mScrollX, value);
8804    }
8805
8806    /**
8807     * Return the scrolled left position of this view. This is the left edge of
8808     * the displayed part of your view. You do not need to draw any pixels
8809     * farther left, since those are outside of the frame of your view on
8810     * screen.
8811     *
8812     * @return The left edge of the displayed part of your view, in pixels.
8813     */
8814    public final int getScrollX() {
8815        return mScrollX;
8816    }
8817
8818    /**
8819     * Return the scrolled top position of this view. This is the top edge of
8820     * the displayed part of your view. You do not need to draw any pixels above
8821     * it, since those are outside of the frame of your view on screen.
8822     *
8823     * @return The top edge of the displayed part of your view, in pixels.
8824     */
8825    public final int getScrollY() {
8826        return mScrollY;
8827    }
8828
8829    /**
8830     * Return the width of the your view.
8831     *
8832     * @return The width of your view, in pixels.
8833     */
8834    @ViewDebug.ExportedProperty(category = "layout")
8835    public final int getWidth() {
8836        return mRight - mLeft;
8837    }
8838
8839    /**
8840     * Return the height of your view.
8841     *
8842     * @return The height of your view, in pixels.
8843     */
8844    @ViewDebug.ExportedProperty(category = "layout")
8845    public final int getHeight() {
8846        return mBottom - mTop;
8847    }
8848
8849    /**
8850     * Return the visible drawing bounds of your view. Fills in the output
8851     * rectangle with the values from getScrollX(), getScrollY(),
8852     * getWidth(), and getHeight(). These bounds do not account for any
8853     * transformation properties currently set on the view, such as
8854     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8855     *
8856     * @param outRect The (scrolled) drawing bounds of the view.
8857     */
8858    public void getDrawingRect(Rect outRect) {
8859        outRect.left = mScrollX;
8860        outRect.top = mScrollY;
8861        outRect.right = mScrollX + (mRight - mLeft);
8862        outRect.bottom = mScrollY + (mBottom - mTop);
8863    }
8864
8865    /**
8866     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8867     * raw width component (that is the result is masked by
8868     * {@link #MEASURED_SIZE_MASK}).
8869     *
8870     * @return The raw measured width of this view.
8871     */
8872    public final int getMeasuredWidth() {
8873        return mMeasuredWidth & MEASURED_SIZE_MASK;
8874    }
8875
8876    /**
8877     * Return the full width measurement information for this view as computed
8878     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8879     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8880     * This should be used during measurement and layout calculations only. Use
8881     * {@link #getWidth()} to see how wide a view is after layout.
8882     *
8883     * @return The measured width of this view as a bit mask.
8884     */
8885    public final int getMeasuredWidthAndState() {
8886        return mMeasuredWidth;
8887    }
8888
8889    /**
8890     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8891     * raw width component (that is the result is masked by
8892     * {@link #MEASURED_SIZE_MASK}).
8893     *
8894     * @return The raw measured height of this view.
8895     */
8896    public final int getMeasuredHeight() {
8897        return mMeasuredHeight & MEASURED_SIZE_MASK;
8898    }
8899
8900    /**
8901     * Return the full height measurement information for this view as computed
8902     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8903     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8904     * This should be used during measurement and layout calculations only. Use
8905     * {@link #getHeight()} to see how wide a view is after layout.
8906     *
8907     * @return The measured width of this view as a bit mask.
8908     */
8909    public final int getMeasuredHeightAndState() {
8910        return mMeasuredHeight;
8911    }
8912
8913    /**
8914     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8915     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8916     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8917     * and the height component is at the shifted bits
8918     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8919     */
8920    public final int getMeasuredState() {
8921        return (mMeasuredWidth&MEASURED_STATE_MASK)
8922                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8923                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8924    }
8925
8926    /**
8927     * The transform matrix of this view, which is calculated based on the current
8928     * roation, scale, and pivot properties.
8929     *
8930     * @see #getRotation()
8931     * @see #getScaleX()
8932     * @see #getScaleY()
8933     * @see #getPivotX()
8934     * @see #getPivotY()
8935     * @return The current transform matrix for the view
8936     */
8937    public Matrix getMatrix() {
8938        if (mTransformationInfo != null) {
8939            updateMatrix();
8940            return mTransformationInfo.mMatrix;
8941        }
8942        return Matrix.IDENTITY_MATRIX;
8943    }
8944
8945    /**
8946     * Utility function to determine if the value is far enough away from zero to be
8947     * considered non-zero.
8948     * @param value A floating point value to check for zero-ness
8949     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8950     */
8951    private static boolean nonzero(float value) {
8952        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8953    }
8954
8955    /**
8956     * Returns true if the transform matrix is the identity matrix.
8957     * Recomputes the matrix if necessary.
8958     *
8959     * @return True if the transform matrix is the identity matrix, false otherwise.
8960     */
8961    final boolean hasIdentityMatrix() {
8962        if (mTransformationInfo != null) {
8963            updateMatrix();
8964            return mTransformationInfo.mMatrixIsIdentity;
8965        }
8966        return true;
8967    }
8968
8969    void ensureTransformationInfo() {
8970        if (mTransformationInfo == null) {
8971            mTransformationInfo = new TransformationInfo();
8972        }
8973    }
8974
8975    /**
8976     * Recomputes the transform matrix if necessary.
8977     */
8978    private void updateMatrix() {
8979        final TransformationInfo info = mTransformationInfo;
8980        if (info == null) {
8981            return;
8982        }
8983        if (info.mMatrixDirty) {
8984            // transform-related properties have changed since the last time someone
8985            // asked for the matrix; recalculate it with the current values
8986
8987            // Figure out if we need to update the pivot point
8988            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8989                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8990                    info.mPrevWidth = mRight - mLeft;
8991                    info.mPrevHeight = mBottom - mTop;
8992                    info.mPivotX = info.mPrevWidth / 2f;
8993                    info.mPivotY = info.mPrevHeight / 2f;
8994                }
8995            }
8996            info.mMatrix.reset();
8997            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8998                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8999                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9000                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9001            } else {
9002                if (info.mCamera == null) {
9003                    info.mCamera = new Camera();
9004                    info.matrix3D = new Matrix();
9005                }
9006                info.mCamera.save();
9007                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9008                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9009                info.mCamera.getMatrix(info.matrix3D);
9010                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9011                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9012                        info.mPivotY + info.mTranslationY);
9013                info.mMatrix.postConcat(info.matrix3D);
9014                info.mCamera.restore();
9015            }
9016            info.mMatrixDirty = false;
9017            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9018            info.mInverseMatrixDirty = true;
9019        }
9020    }
9021
9022   /**
9023     * Utility method to retrieve the inverse of the current mMatrix property.
9024     * We cache the matrix to avoid recalculating it when transform properties
9025     * have not changed.
9026     *
9027     * @return The inverse of the current matrix of this view.
9028     */
9029    final Matrix getInverseMatrix() {
9030        final TransformationInfo info = mTransformationInfo;
9031        if (info != null) {
9032            updateMatrix();
9033            if (info.mInverseMatrixDirty) {
9034                if (info.mInverseMatrix == null) {
9035                    info.mInverseMatrix = new Matrix();
9036                }
9037                info.mMatrix.invert(info.mInverseMatrix);
9038                info.mInverseMatrixDirty = false;
9039            }
9040            return info.mInverseMatrix;
9041        }
9042        return Matrix.IDENTITY_MATRIX;
9043    }
9044
9045    /**
9046     * Gets the distance along the Z axis from the camera to this view.
9047     *
9048     * @see #setCameraDistance(float)
9049     *
9050     * @return The distance along the Z axis.
9051     */
9052    public float getCameraDistance() {
9053        ensureTransformationInfo();
9054        final float dpi = mResources.getDisplayMetrics().densityDpi;
9055        final TransformationInfo info = mTransformationInfo;
9056        if (info.mCamera == null) {
9057            info.mCamera = new Camera();
9058            info.matrix3D = new Matrix();
9059        }
9060        return -(info.mCamera.getLocationZ() * dpi);
9061    }
9062
9063    /**
9064     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9065     * views are drawn) from the camera to this view. The camera's distance
9066     * affects 3D transformations, for instance rotations around the X and Y
9067     * axis. If the rotationX or rotationY properties are changed and this view is
9068     * large (more than half the size of the screen), it is recommended to always
9069     * use a camera distance that's greater than the height (X axis rotation) or
9070     * the width (Y axis rotation) of this view.</p>
9071     *
9072     * <p>The distance of the camera from the view plane can have an affect on the
9073     * perspective distortion of the view when it is rotated around the x or y axis.
9074     * For example, a large distance will result in a large viewing angle, and there
9075     * will not be much perspective distortion of the view as it rotates. A short
9076     * distance may cause much more perspective distortion upon rotation, and can
9077     * also result in some drawing artifacts if the rotated view ends up partially
9078     * behind the camera (which is why the recommendation is to use a distance at
9079     * least as far as the size of the view, if the view is to be rotated.)</p>
9080     *
9081     * <p>The distance is expressed in "depth pixels." The default distance depends
9082     * on the screen density. For instance, on a medium density display, the
9083     * default distance is 1280. On a high density display, the default distance
9084     * is 1920.</p>
9085     *
9086     * <p>If you want to specify a distance that leads to visually consistent
9087     * results across various densities, use the following formula:</p>
9088     * <pre>
9089     * float scale = context.getResources().getDisplayMetrics().density;
9090     * view.setCameraDistance(distance * scale);
9091     * </pre>
9092     *
9093     * <p>The density scale factor of a high density display is 1.5,
9094     * and 1920 = 1280 * 1.5.</p>
9095     *
9096     * @param distance The distance in "depth pixels", if negative the opposite
9097     *        value is used
9098     *
9099     * @see #setRotationX(float)
9100     * @see #setRotationY(float)
9101     */
9102    public void setCameraDistance(float distance) {
9103        invalidateViewProperty(true, false);
9104
9105        ensureTransformationInfo();
9106        final float dpi = mResources.getDisplayMetrics().densityDpi;
9107        final TransformationInfo info = mTransformationInfo;
9108        if (info.mCamera == null) {
9109            info.mCamera = new Camera();
9110            info.matrix3D = new Matrix();
9111        }
9112
9113        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9114        info.mMatrixDirty = true;
9115
9116        invalidateViewProperty(false, false);
9117        if (mDisplayList != null) {
9118            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9119        }
9120        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9121            // View was rejected last time it was drawn by its parent; this may have changed
9122            invalidateParentIfNeeded();
9123        }
9124    }
9125
9126    /**
9127     * The degrees that the view is rotated around the pivot point.
9128     *
9129     * @see #setRotation(float)
9130     * @see #getPivotX()
9131     * @see #getPivotY()
9132     *
9133     * @return The degrees of rotation.
9134     */
9135    @ViewDebug.ExportedProperty(category = "drawing")
9136    public float getRotation() {
9137        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9138    }
9139
9140    /**
9141     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9142     * result in clockwise rotation.
9143     *
9144     * @param rotation The degrees of rotation.
9145     *
9146     * @see #getRotation()
9147     * @see #getPivotX()
9148     * @see #getPivotY()
9149     * @see #setRotationX(float)
9150     * @see #setRotationY(float)
9151     *
9152     * @attr ref android.R.styleable#View_rotation
9153     */
9154    public void setRotation(float rotation) {
9155        ensureTransformationInfo();
9156        final TransformationInfo info = mTransformationInfo;
9157        if (info.mRotation != rotation) {
9158            // Double-invalidation is necessary to capture view's old and new areas
9159            invalidateViewProperty(true, false);
9160            info.mRotation = rotation;
9161            info.mMatrixDirty = true;
9162            invalidateViewProperty(false, true);
9163            if (mDisplayList != null) {
9164                mDisplayList.setRotation(rotation);
9165            }
9166            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9167                // View was rejected last time it was drawn by its parent; this may have changed
9168                invalidateParentIfNeeded();
9169            }
9170        }
9171    }
9172
9173    /**
9174     * The degrees that the view is rotated around the vertical axis through the pivot point.
9175     *
9176     * @see #getPivotX()
9177     * @see #getPivotY()
9178     * @see #setRotationY(float)
9179     *
9180     * @return The degrees of Y rotation.
9181     */
9182    @ViewDebug.ExportedProperty(category = "drawing")
9183    public float getRotationY() {
9184        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9185    }
9186
9187    /**
9188     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9189     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9190     * down the y axis.
9191     *
9192     * When rotating large views, it is recommended to adjust the camera distance
9193     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9194     *
9195     * @param rotationY The degrees of Y rotation.
9196     *
9197     * @see #getRotationY()
9198     * @see #getPivotX()
9199     * @see #getPivotY()
9200     * @see #setRotation(float)
9201     * @see #setRotationX(float)
9202     * @see #setCameraDistance(float)
9203     *
9204     * @attr ref android.R.styleable#View_rotationY
9205     */
9206    public void setRotationY(float rotationY) {
9207        ensureTransformationInfo();
9208        final TransformationInfo info = mTransformationInfo;
9209        if (info.mRotationY != rotationY) {
9210            invalidateViewProperty(true, false);
9211            info.mRotationY = rotationY;
9212            info.mMatrixDirty = true;
9213            invalidateViewProperty(false, true);
9214            if (mDisplayList != null) {
9215                mDisplayList.setRotationY(rotationY);
9216            }
9217            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9218                // View was rejected last time it was drawn by its parent; this may have changed
9219                invalidateParentIfNeeded();
9220            }
9221        }
9222    }
9223
9224    /**
9225     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9226     *
9227     * @see #getPivotX()
9228     * @see #getPivotY()
9229     * @see #setRotationX(float)
9230     *
9231     * @return The degrees of X rotation.
9232     */
9233    @ViewDebug.ExportedProperty(category = "drawing")
9234    public float getRotationX() {
9235        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9236    }
9237
9238    /**
9239     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9240     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9241     * x axis.
9242     *
9243     * When rotating large views, it is recommended to adjust the camera distance
9244     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9245     *
9246     * @param rotationX The degrees of X rotation.
9247     *
9248     * @see #getRotationX()
9249     * @see #getPivotX()
9250     * @see #getPivotY()
9251     * @see #setRotation(float)
9252     * @see #setRotationY(float)
9253     * @see #setCameraDistance(float)
9254     *
9255     * @attr ref android.R.styleable#View_rotationX
9256     */
9257    public void setRotationX(float rotationX) {
9258        ensureTransformationInfo();
9259        final TransformationInfo info = mTransformationInfo;
9260        if (info.mRotationX != rotationX) {
9261            invalidateViewProperty(true, false);
9262            info.mRotationX = rotationX;
9263            info.mMatrixDirty = true;
9264            invalidateViewProperty(false, true);
9265            if (mDisplayList != null) {
9266                mDisplayList.setRotationX(rotationX);
9267            }
9268            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9269                // View was rejected last time it was drawn by its parent; this may have changed
9270                invalidateParentIfNeeded();
9271            }
9272        }
9273    }
9274
9275    /**
9276     * The amount that the view is scaled in x around the pivot point, as a proportion of
9277     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9278     *
9279     * <p>By default, this is 1.0f.
9280     *
9281     * @see #getPivotX()
9282     * @see #getPivotY()
9283     * @return The scaling factor.
9284     */
9285    @ViewDebug.ExportedProperty(category = "drawing")
9286    public float getScaleX() {
9287        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9288    }
9289
9290    /**
9291     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9292     * the view's unscaled width. A value of 1 means that no scaling is applied.
9293     *
9294     * @param scaleX The scaling factor.
9295     * @see #getPivotX()
9296     * @see #getPivotY()
9297     *
9298     * @attr ref android.R.styleable#View_scaleX
9299     */
9300    public void setScaleX(float scaleX) {
9301        ensureTransformationInfo();
9302        final TransformationInfo info = mTransformationInfo;
9303        if (info.mScaleX != scaleX) {
9304            invalidateViewProperty(true, false);
9305            info.mScaleX = scaleX;
9306            info.mMatrixDirty = true;
9307            invalidateViewProperty(false, true);
9308            if (mDisplayList != null) {
9309                mDisplayList.setScaleX(scaleX);
9310            }
9311            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9312                // View was rejected last time it was drawn by its parent; this may have changed
9313                invalidateParentIfNeeded();
9314            }
9315        }
9316    }
9317
9318    /**
9319     * The amount that the view is scaled in y around the pivot point, as a proportion of
9320     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9321     *
9322     * <p>By default, this is 1.0f.
9323     *
9324     * @see #getPivotX()
9325     * @see #getPivotY()
9326     * @return The scaling factor.
9327     */
9328    @ViewDebug.ExportedProperty(category = "drawing")
9329    public float getScaleY() {
9330        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9331    }
9332
9333    /**
9334     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9335     * the view's unscaled width. A value of 1 means that no scaling is applied.
9336     *
9337     * @param scaleY The scaling factor.
9338     * @see #getPivotX()
9339     * @see #getPivotY()
9340     *
9341     * @attr ref android.R.styleable#View_scaleY
9342     */
9343    public void setScaleY(float scaleY) {
9344        ensureTransformationInfo();
9345        final TransformationInfo info = mTransformationInfo;
9346        if (info.mScaleY != scaleY) {
9347            invalidateViewProperty(true, false);
9348            info.mScaleY = scaleY;
9349            info.mMatrixDirty = true;
9350            invalidateViewProperty(false, true);
9351            if (mDisplayList != null) {
9352                mDisplayList.setScaleY(scaleY);
9353            }
9354            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9355                // View was rejected last time it was drawn by its parent; this may have changed
9356                invalidateParentIfNeeded();
9357            }
9358        }
9359    }
9360
9361    /**
9362     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9363     * and {@link #setScaleX(float) scaled}.
9364     *
9365     * @see #getRotation()
9366     * @see #getScaleX()
9367     * @see #getScaleY()
9368     * @see #getPivotY()
9369     * @return The x location of the pivot point.
9370     *
9371     * @attr ref android.R.styleable#View_transformPivotX
9372     */
9373    @ViewDebug.ExportedProperty(category = "drawing")
9374    public float getPivotX() {
9375        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9376    }
9377
9378    /**
9379     * Sets the x location of the point around which the view is
9380     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9381     * By default, the pivot point is centered on the object.
9382     * Setting this property disables this behavior and causes the view to use only the
9383     * explicitly set pivotX and pivotY values.
9384     *
9385     * @param pivotX The x location of the pivot point.
9386     * @see #getRotation()
9387     * @see #getScaleX()
9388     * @see #getScaleY()
9389     * @see #getPivotY()
9390     *
9391     * @attr ref android.R.styleable#View_transformPivotX
9392     */
9393    public void setPivotX(float pivotX) {
9394        ensureTransformationInfo();
9395        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9396        final TransformationInfo info = mTransformationInfo;
9397        if (info.mPivotX != pivotX) {
9398            invalidateViewProperty(true, false);
9399            info.mPivotX = pivotX;
9400            info.mMatrixDirty = true;
9401            invalidateViewProperty(false, true);
9402            if (mDisplayList != null) {
9403                mDisplayList.setPivotX(pivotX);
9404            }
9405            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9406                // View was rejected last time it was drawn by its parent; this may have changed
9407                invalidateParentIfNeeded();
9408            }
9409        }
9410    }
9411
9412    /**
9413     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9414     * and {@link #setScaleY(float) scaled}.
9415     *
9416     * @see #getRotation()
9417     * @see #getScaleX()
9418     * @see #getScaleY()
9419     * @see #getPivotY()
9420     * @return The y location of the pivot point.
9421     *
9422     * @attr ref android.R.styleable#View_transformPivotY
9423     */
9424    @ViewDebug.ExportedProperty(category = "drawing")
9425    public float getPivotY() {
9426        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9427    }
9428
9429    /**
9430     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9431     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9432     * Setting this property disables this behavior and causes the view to use only the
9433     * explicitly set pivotX and pivotY values.
9434     *
9435     * @param pivotY The y location of the pivot point.
9436     * @see #getRotation()
9437     * @see #getScaleX()
9438     * @see #getScaleY()
9439     * @see #getPivotY()
9440     *
9441     * @attr ref android.R.styleable#View_transformPivotY
9442     */
9443    public void setPivotY(float pivotY) {
9444        ensureTransformationInfo();
9445        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9446        final TransformationInfo info = mTransformationInfo;
9447        if (info.mPivotY != pivotY) {
9448            invalidateViewProperty(true, false);
9449            info.mPivotY = pivotY;
9450            info.mMatrixDirty = true;
9451            invalidateViewProperty(false, true);
9452            if (mDisplayList != null) {
9453                mDisplayList.setPivotY(pivotY);
9454            }
9455            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9456                // View was rejected last time it was drawn by its parent; this may have changed
9457                invalidateParentIfNeeded();
9458            }
9459        }
9460    }
9461
9462    /**
9463     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9464     * completely transparent and 1 means the view is completely opaque.
9465     *
9466     * <p>By default this is 1.0f.
9467     * @return The opacity of the view.
9468     */
9469    @ViewDebug.ExportedProperty(category = "drawing")
9470    public float getAlpha() {
9471        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9472    }
9473
9474    /**
9475     * Returns whether this View has content which overlaps. This function, intended to be
9476     * overridden by specific View types, is an optimization when alpha is set on a view. If
9477     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9478     * and then composited it into place, which can be expensive. If the view has no overlapping
9479     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9480     * An example of overlapping rendering is a TextView with a background image, such as a
9481     * Button. An example of non-overlapping rendering is a TextView with no background, or
9482     * an ImageView with only the foreground image. The default implementation returns true;
9483     * subclasses should override if they have cases which can be optimized.
9484     *
9485     * @return true if the content in this view might overlap, false otherwise.
9486     */
9487    public boolean hasOverlappingRendering() {
9488        return true;
9489    }
9490
9491    /**
9492     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9493     * completely transparent and 1 means the view is completely opaque.</p>
9494     *
9495     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9496     * performance implications, especially for large views. It is best to use the alpha property
9497     * sparingly and transiently, as in the case of fading animations.</p>
9498     *
9499     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9500     * strongly recommended for performance reasons to either override
9501     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9502     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9503     *
9504     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9505     * responsible for applying the opacity itself.</p>
9506     *
9507     * <p>Note that if the view is backed by a
9508     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9509     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9510     * 1.0 will supercede the alpha of the layer paint.</p>
9511     *
9512     * @param alpha The opacity of the view.
9513     *
9514     * @see #hasOverlappingRendering()
9515     * @see #setLayerType(int, android.graphics.Paint)
9516     *
9517     * @attr ref android.R.styleable#View_alpha
9518     */
9519    public void setAlpha(float alpha) {
9520        ensureTransformationInfo();
9521        if (mTransformationInfo.mAlpha != alpha) {
9522            mTransformationInfo.mAlpha = alpha;
9523            if (onSetAlpha((int) (alpha * 255))) {
9524                mPrivateFlags |= PFLAG_ALPHA_SET;
9525                // subclass is handling alpha - don't optimize rendering cache invalidation
9526                invalidateParentCaches();
9527                invalidate(true);
9528            } else {
9529                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9530                invalidateViewProperty(true, false);
9531                if (mDisplayList != null) {
9532                    mDisplayList.setAlpha(alpha);
9533                }
9534            }
9535        }
9536    }
9537
9538    /**
9539     * Faster version of setAlpha() which performs the same steps except there are
9540     * no calls to invalidate(). The caller of this function should perform proper invalidation
9541     * on the parent and this object. The return value indicates whether the subclass handles
9542     * alpha (the return value for onSetAlpha()).
9543     *
9544     * @param alpha The new value for the alpha property
9545     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9546     *         the new value for the alpha property is different from the old value
9547     */
9548    boolean setAlphaNoInvalidation(float alpha) {
9549        ensureTransformationInfo();
9550        if (mTransformationInfo.mAlpha != alpha) {
9551            mTransformationInfo.mAlpha = alpha;
9552            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9553            if (subclassHandlesAlpha) {
9554                mPrivateFlags |= PFLAG_ALPHA_SET;
9555                return true;
9556            } else {
9557                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9558                if (mDisplayList != null) {
9559                    mDisplayList.setAlpha(alpha);
9560                }
9561            }
9562        }
9563        return false;
9564    }
9565
9566    /**
9567     * Top position of this view relative to its parent.
9568     *
9569     * @return The top of this view, in pixels.
9570     */
9571    @ViewDebug.CapturedViewProperty
9572    public final int getTop() {
9573        return mTop;
9574    }
9575
9576    /**
9577     * Sets the top position of this view relative to its parent. This method is meant to be called
9578     * by the layout system and should not generally be called otherwise, because the property
9579     * may be changed at any time by the layout.
9580     *
9581     * @param top The top of this view, in pixels.
9582     */
9583    public final void setTop(int top) {
9584        if (top != mTop) {
9585            updateMatrix();
9586            final boolean matrixIsIdentity = mTransformationInfo == null
9587                    || mTransformationInfo.mMatrixIsIdentity;
9588            if (matrixIsIdentity) {
9589                if (mAttachInfo != null) {
9590                    int minTop;
9591                    int yLoc;
9592                    if (top < mTop) {
9593                        minTop = top;
9594                        yLoc = top - mTop;
9595                    } else {
9596                        minTop = mTop;
9597                        yLoc = 0;
9598                    }
9599                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9600                }
9601            } else {
9602                // Double-invalidation is necessary to capture view's old and new areas
9603                invalidate(true);
9604            }
9605
9606            int width = mRight - mLeft;
9607            int oldHeight = mBottom - mTop;
9608
9609            mTop = top;
9610            if (mDisplayList != null) {
9611                mDisplayList.setTop(mTop);
9612            }
9613
9614            sizeChange(width, mBottom - mTop, width, oldHeight);
9615
9616            if (!matrixIsIdentity) {
9617                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9618                    // A change in dimension means an auto-centered pivot point changes, too
9619                    mTransformationInfo.mMatrixDirty = true;
9620                }
9621                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9622                invalidate(true);
9623            }
9624            mBackgroundSizeChanged = true;
9625            invalidateParentIfNeeded();
9626            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9627                // View was rejected last time it was drawn by its parent; this may have changed
9628                invalidateParentIfNeeded();
9629            }
9630        }
9631    }
9632
9633    /**
9634     * Bottom position of this view relative to its parent.
9635     *
9636     * @return The bottom of this view, in pixels.
9637     */
9638    @ViewDebug.CapturedViewProperty
9639    public final int getBottom() {
9640        return mBottom;
9641    }
9642
9643    /**
9644     * True if this view has changed since the last time being drawn.
9645     *
9646     * @return The dirty state of this view.
9647     */
9648    public boolean isDirty() {
9649        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9650    }
9651
9652    /**
9653     * Sets the bottom position of this view relative to its parent. This method is meant to be
9654     * called by the layout system and should not generally be called otherwise, because the
9655     * property may be changed at any time by the layout.
9656     *
9657     * @param bottom The bottom of this view, in pixels.
9658     */
9659    public final void setBottom(int bottom) {
9660        if (bottom != mBottom) {
9661            updateMatrix();
9662            final boolean matrixIsIdentity = mTransformationInfo == null
9663                    || mTransformationInfo.mMatrixIsIdentity;
9664            if (matrixIsIdentity) {
9665                if (mAttachInfo != null) {
9666                    int maxBottom;
9667                    if (bottom < mBottom) {
9668                        maxBottom = mBottom;
9669                    } else {
9670                        maxBottom = bottom;
9671                    }
9672                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9673                }
9674            } else {
9675                // Double-invalidation is necessary to capture view's old and new areas
9676                invalidate(true);
9677            }
9678
9679            int width = mRight - mLeft;
9680            int oldHeight = mBottom - mTop;
9681
9682            mBottom = bottom;
9683            if (mDisplayList != null) {
9684                mDisplayList.setBottom(mBottom);
9685            }
9686
9687            sizeChange(width, mBottom - mTop, width, oldHeight);
9688
9689            if (!matrixIsIdentity) {
9690                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9691                    // A change in dimension means an auto-centered pivot point changes, too
9692                    mTransformationInfo.mMatrixDirty = true;
9693                }
9694                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9695                invalidate(true);
9696            }
9697            mBackgroundSizeChanged = true;
9698            invalidateParentIfNeeded();
9699            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9700                // View was rejected last time it was drawn by its parent; this may have changed
9701                invalidateParentIfNeeded();
9702            }
9703        }
9704    }
9705
9706    /**
9707     * Left position of this view relative to its parent.
9708     *
9709     * @return The left edge of this view, in pixels.
9710     */
9711    @ViewDebug.CapturedViewProperty
9712    public final int getLeft() {
9713        return mLeft;
9714    }
9715
9716    /**
9717     * Sets the left position of this view relative to its parent. This method is meant to be called
9718     * by the layout system and should not generally be called otherwise, because the property
9719     * may be changed at any time by the layout.
9720     *
9721     * @param left The bottom of this view, in pixels.
9722     */
9723    public final void setLeft(int left) {
9724        if (left != mLeft) {
9725            updateMatrix();
9726            final boolean matrixIsIdentity = mTransformationInfo == null
9727                    || mTransformationInfo.mMatrixIsIdentity;
9728            if (matrixIsIdentity) {
9729                if (mAttachInfo != null) {
9730                    int minLeft;
9731                    int xLoc;
9732                    if (left < mLeft) {
9733                        minLeft = left;
9734                        xLoc = left - mLeft;
9735                    } else {
9736                        minLeft = mLeft;
9737                        xLoc = 0;
9738                    }
9739                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9740                }
9741            } else {
9742                // Double-invalidation is necessary to capture view's old and new areas
9743                invalidate(true);
9744            }
9745
9746            int oldWidth = mRight - mLeft;
9747            int height = mBottom - mTop;
9748
9749            mLeft = left;
9750            if (mDisplayList != null) {
9751                mDisplayList.setLeft(left);
9752            }
9753
9754            sizeChange(mRight - mLeft, height, oldWidth, height);
9755
9756            if (!matrixIsIdentity) {
9757                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9758                    // A change in dimension means an auto-centered pivot point changes, too
9759                    mTransformationInfo.mMatrixDirty = true;
9760                }
9761                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9762                invalidate(true);
9763            }
9764            mBackgroundSizeChanged = true;
9765            invalidateParentIfNeeded();
9766            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9767                // View was rejected last time it was drawn by its parent; this may have changed
9768                invalidateParentIfNeeded();
9769            }
9770        }
9771    }
9772
9773    /**
9774     * Right position of this view relative to its parent.
9775     *
9776     * @return The right edge of this view, in pixels.
9777     */
9778    @ViewDebug.CapturedViewProperty
9779    public final int getRight() {
9780        return mRight;
9781    }
9782
9783    /**
9784     * Sets the right position of this view relative to its parent. This method is meant to be called
9785     * by the layout system and should not generally be called otherwise, because the property
9786     * may be changed at any time by the layout.
9787     *
9788     * @param right The bottom of this view, in pixels.
9789     */
9790    public final void setRight(int right) {
9791        if (right != mRight) {
9792            updateMatrix();
9793            final boolean matrixIsIdentity = mTransformationInfo == null
9794                    || mTransformationInfo.mMatrixIsIdentity;
9795            if (matrixIsIdentity) {
9796                if (mAttachInfo != null) {
9797                    int maxRight;
9798                    if (right < mRight) {
9799                        maxRight = mRight;
9800                    } else {
9801                        maxRight = right;
9802                    }
9803                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9804                }
9805            } else {
9806                // Double-invalidation is necessary to capture view's old and new areas
9807                invalidate(true);
9808            }
9809
9810            int oldWidth = mRight - mLeft;
9811            int height = mBottom - mTop;
9812
9813            mRight = right;
9814            if (mDisplayList != null) {
9815                mDisplayList.setRight(mRight);
9816            }
9817
9818            sizeChange(mRight - mLeft, height, oldWidth, height);
9819
9820            if (!matrixIsIdentity) {
9821                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9822                    // A change in dimension means an auto-centered pivot point changes, too
9823                    mTransformationInfo.mMatrixDirty = true;
9824                }
9825                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9826                invalidate(true);
9827            }
9828            mBackgroundSizeChanged = true;
9829            invalidateParentIfNeeded();
9830            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9831                // View was rejected last time it was drawn by its parent; this may have changed
9832                invalidateParentIfNeeded();
9833            }
9834        }
9835    }
9836
9837    /**
9838     * The visual x position of this view, in pixels. This is equivalent to the
9839     * {@link #setTranslationX(float) translationX} property plus the current
9840     * {@link #getLeft() left} property.
9841     *
9842     * @return The visual x position of this view, in pixels.
9843     */
9844    @ViewDebug.ExportedProperty(category = "drawing")
9845    public float getX() {
9846        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9847    }
9848
9849    /**
9850     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9851     * {@link #setTranslationX(float) translationX} property to be the difference between
9852     * the x value passed in and the current {@link #getLeft() left} property.
9853     *
9854     * @param x The visual x position of this view, in pixels.
9855     */
9856    public void setX(float x) {
9857        setTranslationX(x - mLeft);
9858    }
9859
9860    /**
9861     * The visual y position of this view, in pixels. This is equivalent to the
9862     * {@link #setTranslationY(float) translationY} property plus the current
9863     * {@link #getTop() top} property.
9864     *
9865     * @return The visual y position of this view, in pixels.
9866     */
9867    @ViewDebug.ExportedProperty(category = "drawing")
9868    public float getY() {
9869        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9870    }
9871
9872    /**
9873     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9874     * {@link #setTranslationY(float) translationY} property to be the difference between
9875     * the y value passed in and the current {@link #getTop() top} property.
9876     *
9877     * @param y The visual y position of this view, in pixels.
9878     */
9879    public void setY(float y) {
9880        setTranslationY(y - mTop);
9881    }
9882
9883
9884    /**
9885     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9886     * This position is post-layout, in addition to wherever the object's
9887     * layout placed it.
9888     *
9889     * @return The horizontal position of this view relative to its left position, in pixels.
9890     */
9891    @ViewDebug.ExportedProperty(category = "drawing")
9892    public float getTranslationX() {
9893        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9894    }
9895
9896    /**
9897     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9898     * This effectively positions the object post-layout, in addition to wherever the object's
9899     * layout placed it.
9900     *
9901     * @param translationX The horizontal position of this view relative to its left position,
9902     * in pixels.
9903     *
9904     * @attr ref android.R.styleable#View_translationX
9905     */
9906    public void setTranslationX(float translationX) {
9907        ensureTransformationInfo();
9908        final TransformationInfo info = mTransformationInfo;
9909        if (info.mTranslationX != translationX) {
9910            // Double-invalidation is necessary to capture view's old and new areas
9911            invalidateViewProperty(true, false);
9912            info.mTranslationX = translationX;
9913            info.mMatrixDirty = true;
9914            invalidateViewProperty(false, true);
9915            if (mDisplayList != null) {
9916                mDisplayList.setTranslationX(translationX);
9917            }
9918            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9919                // View was rejected last time it was drawn by its parent; this may have changed
9920                invalidateParentIfNeeded();
9921            }
9922        }
9923    }
9924
9925    /**
9926     * The horizontal location of this view relative to its {@link #getTop() top} position.
9927     * This position is post-layout, in addition to wherever the object's
9928     * layout placed it.
9929     *
9930     * @return The vertical position of this view relative to its top position,
9931     * in pixels.
9932     */
9933    @ViewDebug.ExportedProperty(category = "drawing")
9934    public float getTranslationY() {
9935        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9936    }
9937
9938    /**
9939     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9940     * This effectively positions the object post-layout, in addition to wherever the object's
9941     * layout placed it.
9942     *
9943     * @param translationY The vertical position of this view relative to its top position,
9944     * in pixels.
9945     *
9946     * @attr ref android.R.styleable#View_translationY
9947     */
9948    public void setTranslationY(float translationY) {
9949        ensureTransformationInfo();
9950        final TransformationInfo info = mTransformationInfo;
9951        if (info.mTranslationY != translationY) {
9952            invalidateViewProperty(true, false);
9953            info.mTranslationY = translationY;
9954            info.mMatrixDirty = true;
9955            invalidateViewProperty(false, true);
9956            if (mDisplayList != null) {
9957                mDisplayList.setTranslationY(translationY);
9958            }
9959            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9960                // View was rejected last time it was drawn by its parent; this may have changed
9961                invalidateParentIfNeeded();
9962            }
9963        }
9964    }
9965
9966    /**
9967     * Hit rectangle in parent's coordinates
9968     *
9969     * @param outRect The hit rectangle of the view.
9970     */
9971    public void getHitRect(Rect outRect) {
9972        updateMatrix();
9973        final TransformationInfo info = mTransformationInfo;
9974        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9975            outRect.set(mLeft, mTop, mRight, mBottom);
9976        } else {
9977            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9978            tmpRect.set(0, 0, getWidth(), getHeight());
9979            info.mMatrix.mapRect(tmpRect);
9980            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9981                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9982        }
9983    }
9984
9985    /**
9986     * Determines whether the given point, in local coordinates is inside the view.
9987     */
9988    /*package*/ final boolean pointInView(float localX, float localY) {
9989        return localX >= 0 && localX < (mRight - mLeft)
9990                && localY >= 0 && localY < (mBottom - mTop);
9991    }
9992
9993    /**
9994     * Utility method to determine whether the given point, in local coordinates,
9995     * is inside the view, where the area of the view is expanded by the slop factor.
9996     * This method is called while processing touch-move events to determine if the event
9997     * is still within the view.
9998     */
9999    private boolean pointInView(float localX, float localY, float slop) {
10000        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10001                localY < ((mBottom - mTop) + slop);
10002    }
10003
10004    /**
10005     * When a view has focus and the user navigates away from it, the next view is searched for
10006     * starting from the rectangle filled in by this method.
10007     *
10008     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10009     * of the view.  However, if your view maintains some idea of internal selection,
10010     * such as a cursor, or a selected row or column, you should override this method and
10011     * fill in a more specific rectangle.
10012     *
10013     * @param r The rectangle to fill in, in this view's coordinates.
10014     */
10015    public void getFocusedRect(Rect r) {
10016        getDrawingRect(r);
10017    }
10018
10019    /**
10020     * If some part of this view is not clipped by any of its parents, then
10021     * return that area in r in global (root) coordinates. To convert r to local
10022     * coordinates (without taking possible View rotations into account), offset
10023     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10024     * If the view is completely clipped or translated out, return false.
10025     *
10026     * @param r If true is returned, r holds the global coordinates of the
10027     *        visible portion of this view.
10028     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10029     *        between this view and its root. globalOffet may be null.
10030     * @return true if r is non-empty (i.e. part of the view is visible at the
10031     *         root level.
10032     */
10033    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10034        int width = mRight - mLeft;
10035        int height = mBottom - mTop;
10036        if (width > 0 && height > 0) {
10037            r.set(0, 0, width, height);
10038            if (globalOffset != null) {
10039                globalOffset.set(-mScrollX, -mScrollY);
10040            }
10041            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10042        }
10043        return false;
10044    }
10045
10046    public final boolean getGlobalVisibleRect(Rect r) {
10047        return getGlobalVisibleRect(r, null);
10048    }
10049
10050    public final boolean getLocalVisibleRect(Rect r) {
10051        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10052        if (getGlobalVisibleRect(r, offset)) {
10053            r.offset(-offset.x, -offset.y); // make r local
10054            return true;
10055        }
10056        return false;
10057    }
10058
10059    /**
10060     * Offset this view's vertical location by the specified number of pixels.
10061     *
10062     * @param offset the number of pixels to offset the view by
10063     */
10064    public void offsetTopAndBottom(int offset) {
10065        if (offset != 0) {
10066            updateMatrix();
10067            final boolean matrixIsIdentity = mTransformationInfo == null
10068                    || mTransformationInfo.mMatrixIsIdentity;
10069            if (matrixIsIdentity) {
10070                if (mDisplayList != null) {
10071                    invalidateViewProperty(false, false);
10072                } else {
10073                    final ViewParent p = mParent;
10074                    if (p != null && mAttachInfo != null) {
10075                        final Rect r = mAttachInfo.mTmpInvalRect;
10076                        int minTop;
10077                        int maxBottom;
10078                        int yLoc;
10079                        if (offset < 0) {
10080                            minTop = mTop + offset;
10081                            maxBottom = mBottom;
10082                            yLoc = offset;
10083                        } else {
10084                            minTop = mTop;
10085                            maxBottom = mBottom + offset;
10086                            yLoc = 0;
10087                        }
10088                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10089                        p.invalidateChild(this, r);
10090                    }
10091                }
10092            } else {
10093                invalidateViewProperty(false, false);
10094            }
10095
10096            mTop += offset;
10097            mBottom += offset;
10098            if (mDisplayList != null) {
10099                mDisplayList.offsetTopAndBottom(offset);
10100                invalidateViewProperty(false, false);
10101            } else {
10102                if (!matrixIsIdentity) {
10103                    invalidateViewProperty(false, true);
10104                }
10105                invalidateParentIfNeeded();
10106            }
10107        }
10108    }
10109
10110    /**
10111     * Offset this view's horizontal location by the specified amount of pixels.
10112     *
10113     * @param offset the number of pixels to offset the view by
10114     */
10115    public void offsetLeftAndRight(int offset) {
10116        if (offset != 0) {
10117            updateMatrix();
10118            final boolean matrixIsIdentity = mTransformationInfo == null
10119                    || mTransformationInfo.mMatrixIsIdentity;
10120            if (matrixIsIdentity) {
10121                if (mDisplayList != null) {
10122                    invalidateViewProperty(false, false);
10123                } else {
10124                    final ViewParent p = mParent;
10125                    if (p != null && mAttachInfo != null) {
10126                        final Rect r = mAttachInfo.mTmpInvalRect;
10127                        int minLeft;
10128                        int maxRight;
10129                        if (offset < 0) {
10130                            minLeft = mLeft + offset;
10131                            maxRight = mRight;
10132                        } else {
10133                            minLeft = mLeft;
10134                            maxRight = mRight + offset;
10135                        }
10136                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10137                        p.invalidateChild(this, r);
10138                    }
10139                }
10140            } else {
10141                invalidateViewProperty(false, false);
10142            }
10143
10144            mLeft += offset;
10145            mRight += offset;
10146            if (mDisplayList != null) {
10147                mDisplayList.offsetLeftAndRight(offset);
10148                invalidateViewProperty(false, false);
10149            } else {
10150                if (!matrixIsIdentity) {
10151                    invalidateViewProperty(false, true);
10152                }
10153                invalidateParentIfNeeded();
10154            }
10155        }
10156    }
10157
10158    /**
10159     * Get the LayoutParams associated with this view. All views should have
10160     * layout parameters. These supply parameters to the <i>parent</i> of this
10161     * view specifying how it should be arranged. There are many subclasses of
10162     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10163     * of ViewGroup that are responsible for arranging their children.
10164     *
10165     * This method may return null if this View is not attached to a parent
10166     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10167     * was not invoked successfully. When a View is attached to a parent
10168     * ViewGroup, this method must not return null.
10169     *
10170     * @return The LayoutParams associated with this view, or null if no
10171     *         parameters have been set yet
10172     */
10173    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10174    public ViewGroup.LayoutParams getLayoutParams() {
10175        return mLayoutParams;
10176    }
10177
10178    /**
10179     * Set the layout parameters associated with this view. These supply
10180     * parameters to the <i>parent</i> of this view specifying how it should be
10181     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10182     * correspond to the different subclasses of ViewGroup that are responsible
10183     * for arranging their children.
10184     *
10185     * @param params The layout parameters for this view, cannot be null
10186     */
10187    public void setLayoutParams(ViewGroup.LayoutParams params) {
10188        if (params == null) {
10189            throw new NullPointerException("Layout parameters cannot be null");
10190        }
10191        mLayoutParams = params;
10192        resolveLayoutParams();
10193        if (mParent instanceof ViewGroup) {
10194            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10195        }
10196        requestLayout();
10197    }
10198
10199    /**
10200     * Resolve the layout parameters depending on the resolved layout direction
10201     *
10202     * @hide
10203     */
10204    public void resolveLayoutParams() {
10205        if (mLayoutParams != null) {
10206            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10207        }
10208    }
10209
10210    /**
10211     * Set the scrolled position of your view. This will cause a call to
10212     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10213     * invalidated.
10214     * @param x the x position to scroll to
10215     * @param y the y position to scroll to
10216     */
10217    public void scrollTo(int x, int y) {
10218        if (mScrollX != x || mScrollY != y) {
10219            int oldX = mScrollX;
10220            int oldY = mScrollY;
10221            mScrollX = x;
10222            mScrollY = y;
10223            invalidateParentCaches();
10224            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10225            if (!awakenScrollBars()) {
10226                postInvalidateOnAnimation();
10227            }
10228        }
10229    }
10230
10231    /**
10232     * Move the scrolled position of your view. This will cause a call to
10233     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10234     * invalidated.
10235     * @param x the amount of pixels to scroll by horizontally
10236     * @param y the amount of pixels to scroll by vertically
10237     */
10238    public void scrollBy(int x, int y) {
10239        scrollTo(mScrollX + x, mScrollY + y);
10240    }
10241
10242    /**
10243     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10244     * animation to fade the scrollbars out after a default delay. If a subclass
10245     * provides animated scrolling, the start delay should equal the duration
10246     * of the scrolling animation.</p>
10247     *
10248     * <p>The animation starts only if at least one of the scrollbars is
10249     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10250     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10251     * this method returns true, and false otherwise. If the animation is
10252     * started, this method calls {@link #invalidate()}; in that case the
10253     * caller should not call {@link #invalidate()}.</p>
10254     *
10255     * <p>This method should be invoked every time a subclass directly updates
10256     * the scroll parameters.</p>
10257     *
10258     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10259     * and {@link #scrollTo(int, int)}.</p>
10260     *
10261     * @return true if the animation is played, false otherwise
10262     *
10263     * @see #awakenScrollBars(int)
10264     * @see #scrollBy(int, int)
10265     * @see #scrollTo(int, int)
10266     * @see #isHorizontalScrollBarEnabled()
10267     * @see #isVerticalScrollBarEnabled()
10268     * @see #setHorizontalScrollBarEnabled(boolean)
10269     * @see #setVerticalScrollBarEnabled(boolean)
10270     */
10271    protected boolean awakenScrollBars() {
10272        return mScrollCache != null &&
10273                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10274    }
10275
10276    /**
10277     * Trigger the scrollbars to draw.
10278     * This method differs from awakenScrollBars() only in its default duration.
10279     * initialAwakenScrollBars() will show the scroll bars for longer than
10280     * usual to give the user more of a chance to notice them.
10281     *
10282     * @return true if the animation is played, false otherwise.
10283     */
10284    private boolean initialAwakenScrollBars() {
10285        return mScrollCache != null &&
10286                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10287    }
10288
10289    /**
10290     * <p>
10291     * Trigger the scrollbars to draw. When invoked this method starts an
10292     * animation to fade the scrollbars out after a fixed delay. If a subclass
10293     * provides animated scrolling, the start delay should equal the duration of
10294     * the scrolling animation.
10295     * </p>
10296     *
10297     * <p>
10298     * The animation starts only if at least one of the scrollbars is enabled,
10299     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10300     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10301     * this method returns true, and false otherwise. If the animation is
10302     * started, this method calls {@link #invalidate()}; in that case the caller
10303     * should not call {@link #invalidate()}.
10304     * </p>
10305     *
10306     * <p>
10307     * This method should be invoked everytime a subclass directly updates the
10308     * scroll parameters.
10309     * </p>
10310     *
10311     * @param startDelay the delay, in milliseconds, after which the animation
10312     *        should start; when the delay is 0, the animation starts
10313     *        immediately
10314     * @return true if the animation is played, false otherwise
10315     *
10316     * @see #scrollBy(int, int)
10317     * @see #scrollTo(int, int)
10318     * @see #isHorizontalScrollBarEnabled()
10319     * @see #isVerticalScrollBarEnabled()
10320     * @see #setHorizontalScrollBarEnabled(boolean)
10321     * @see #setVerticalScrollBarEnabled(boolean)
10322     */
10323    protected boolean awakenScrollBars(int startDelay) {
10324        return awakenScrollBars(startDelay, true);
10325    }
10326
10327    /**
10328     * <p>
10329     * Trigger the scrollbars to draw. When invoked this method starts an
10330     * animation to fade the scrollbars out after a fixed delay. If a subclass
10331     * provides animated scrolling, the start delay should equal the duration of
10332     * the scrolling animation.
10333     * </p>
10334     *
10335     * <p>
10336     * The animation starts only if at least one of the scrollbars is enabled,
10337     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10338     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10339     * this method returns true, and false otherwise. If the animation is
10340     * started, this method calls {@link #invalidate()} if the invalidate parameter
10341     * is set to true; in that case the caller
10342     * should not call {@link #invalidate()}.
10343     * </p>
10344     *
10345     * <p>
10346     * This method should be invoked everytime a subclass directly updates the
10347     * scroll parameters.
10348     * </p>
10349     *
10350     * @param startDelay the delay, in milliseconds, after which the animation
10351     *        should start; when the delay is 0, the animation starts
10352     *        immediately
10353     *
10354     * @param invalidate Wheter this method should call invalidate
10355     *
10356     * @return true if the animation is played, false otherwise
10357     *
10358     * @see #scrollBy(int, int)
10359     * @see #scrollTo(int, int)
10360     * @see #isHorizontalScrollBarEnabled()
10361     * @see #isVerticalScrollBarEnabled()
10362     * @see #setHorizontalScrollBarEnabled(boolean)
10363     * @see #setVerticalScrollBarEnabled(boolean)
10364     */
10365    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10366        final ScrollabilityCache scrollCache = mScrollCache;
10367
10368        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10369            return false;
10370        }
10371
10372        if (scrollCache.scrollBar == null) {
10373            scrollCache.scrollBar = new ScrollBarDrawable();
10374        }
10375
10376        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10377
10378            if (invalidate) {
10379                // Invalidate to show the scrollbars
10380                postInvalidateOnAnimation();
10381            }
10382
10383            if (scrollCache.state == ScrollabilityCache.OFF) {
10384                // FIXME: this is copied from WindowManagerService.
10385                // We should get this value from the system when it
10386                // is possible to do so.
10387                final int KEY_REPEAT_FIRST_DELAY = 750;
10388                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10389            }
10390
10391            // Tell mScrollCache when we should start fading. This may
10392            // extend the fade start time if one was already scheduled
10393            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10394            scrollCache.fadeStartTime = fadeStartTime;
10395            scrollCache.state = ScrollabilityCache.ON;
10396
10397            // Schedule our fader to run, unscheduling any old ones first
10398            if (mAttachInfo != null) {
10399                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10400                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10401            }
10402
10403            return true;
10404        }
10405
10406        return false;
10407    }
10408
10409    /**
10410     * Do not invalidate views which are not visible and which are not running an animation. They
10411     * will not get drawn and they should not set dirty flags as if they will be drawn
10412     */
10413    private boolean skipInvalidate() {
10414        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10415                (!(mParent instanceof ViewGroup) ||
10416                        !((ViewGroup) mParent).isViewTransitioning(this));
10417    }
10418    /**
10419     * Mark the area defined by dirty as needing to be drawn. If the view is
10420     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10421     * in the future. This must be called from a UI thread. To call from a non-UI
10422     * thread, call {@link #postInvalidate()}.
10423     *
10424     * WARNING: This method is destructive to dirty.
10425     * @param dirty the rectangle representing the bounds of the dirty region
10426     */
10427    public void invalidate(Rect dirty) {
10428        if (skipInvalidate()) {
10429            return;
10430        }
10431        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10432                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10433                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10434            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10435            mPrivateFlags |= PFLAG_INVALIDATED;
10436            mPrivateFlags |= PFLAG_DIRTY;
10437            final ViewParent p = mParent;
10438            final AttachInfo ai = mAttachInfo;
10439            //noinspection PointlessBooleanExpression,ConstantConditions
10440            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10441                if (p != null && ai != null && ai.mHardwareAccelerated) {
10442                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10443                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10444                    p.invalidateChild(this, null);
10445                    return;
10446                }
10447            }
10448            if (p != null && ai != null) {
10449                final int scrollX = mScrollX;
10450                final int scrollY = mScrollY;
10451                final Rect r = ai.mTmpInvalRect;
10452                r.set(dirty.left - scrollX, dirty.top - scrollY,
10453                        dirty.right - scrollX, dirty.bottom - scrollY);
10454                mParent.invalidateChild(this, r);
10455            }
10456        }
10457    }
10458
10459    /**
10460     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10461     * The coordinates of the dirty rect are relative to the view.
10462     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10463     * will be called at some point in the future. This must be called from
10464     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10465     * @param l the left position of the dirty region
10466     * @param t the top position of the dirty region
10467     * @param r the right position of the dirty region
10468     * @param b the bottom position of the dirty region
10469     */
10470    public void invalidate(int l, int t, int r, int b) {
10471        if (skipInvalidate()) {
10472            return;
10473        }
10474        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10475                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10476                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10477            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10478            mPrivateFlags |= PFLAG_INVALIDATED;
10479            mPrivateFlags |= PFLAG_DIRTY;
10480            final ViewParent p = mParent;
10481            final AttachInfo ai = mAttachInfo;
10482            //noinspection PointlessBooleanExpression,ConstantConditions
10483            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10484                if (p != null && ai != null && ai.mHardwareAccelerated) {
10485                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10486                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10487                    p.invalidateChild(this, null);
10488                    return;
10489                }
10490            }
10491            if (p != null && ai != null && l < r && t < b) {
10492                final int scrollX = mScrollX;
10493                final int scrollY = mScrollY;
10494                final Rect tmpr = ai.mTmpInvalRect;
10495                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10496                p.invalidateChild(this, tmpr);
10497            }
10498        }
10499    }
10500
10501    /**
10502     * Invalidate the whole view. If the view is visible,
10503     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10504     * the future. This must be called from a UI thread. To call from a non-UI thread,
10505     * call {@link #postInvalidate()}.
10506     */
10507    public void invalidate() {
10508        invalidate(true);
10509    }
10510
10511    /**
10512     * This is where the invalidate() work actually happens. A full invalidate()
10513     * causes the drawing cache to be invalidated, but this function can be called with
10514     * invalidateCache set to false to skip that invalidation step for cases that do not
10515     * need it (for example, a component that remains at the same dimensions with the same
10516     * content).
10517     *
10518     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10519     * well. This is usually true for a full invalidate, but may be set to false if the
10520     * View's contents or dimensions have not changed.
10521     */
10522    void invalidate(boolean invalidateCache) {
10523        if (skipInvalidate()) {
10524            return;
10525        }
10526        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10527                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10528                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10529            mLastIsOpaque = isOpaque();
10530            mPrivateFlags &= ~PFLAG_DRAWN;
10531            mPrivateFlags |= PFLAG_DIRTY;
10532            if (invalidateCache) {
10533                mPrivateFlags |= PFLAG_INVALIDATED;
10534                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10535            }
10536            final AttachInfo ai = mAttachInfo;
10537            final ViewParent p = mParent;
10538            //noinspection PointlessBooleanExpression,ConstantConditions
10539            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10540                if (p != null && ai != null && ai.mHardwareAccelerated) {
10541                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10542                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10543                    p.invalidateChild(this, null);
10544                    return;
10545                }
10546            }
10547
10548            if (p != null && ai != null) {
10549                final Rect r = ai.mTmpInvalRect;
10550                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10551                // Don't call invalidate -- we don't want to internally scroll
10552                // our own bounds
10553                p.invalidateChild(this, r);
10554            }
10555        }
10556    }
10557
10558    /**
10559     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10560     * set any flags or handle all of the cases handled by the default invalidation methods.
10561     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10562     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10563     * walk up the hierarchy, transforming the dirty rect as necessary.
10564     *
10565     * The method also handles normal invalidation logic if display list properties are not
10566     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10567     * backup approach, to handle these cases used in the various property-setting methods.
10568     *
10569     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10570     * are not being used in this view
10571     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10572     * list properties are not being used in this view
10573     */
10574    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10575        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10576            if (invalidateParent) {
10577                invalidateParentCaches();
10578            }
10579            if (forceRedraw) {
10580                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10581            }
10582            invalidate(false);
10583        } else {
10584            final AttachInfo ai = mAttachInfo;
10585            final ViewParent p = mParent;
10586            if (p != null && ai != null) {
10587                final Rect r = ai.mTmpInvalRect;
10588                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10589                if (mParent instanceof ViewGroup) {
10590                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10591                } else {
10592                    mParent.invalidateChild(this, r);
10593                }
10594            }
10595        }
10596    }
10597
10598    /**
10599     * Utility method to transform a given Rect by the current matrix of this view.
10600     */
10601    void transformRect(final Rect rect) {
10602        if (!getMatrix().isIdentity()) {
10603            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10604            boundingRect.set(rect);
10605            getMatrix().mapRect(boundingRect);
10606            rect.set((int) (boundingRect.left - 0.5f),
10607                    (int) (boundingRect.top - 0.5f),
10608                    (int) (boundingRect.right + 0.5f),
10609                    (int) (boundingRect.bottom + 0.5f));
10610        }
10611    }
10612
10613    /**
10614     * Used to indicate that the parent of this view should clear its caches. This functionality
10615     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10616     * which is necessary when various parent-managed properties of the view change, such as
10617     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10618     * clears the parent caches and does not causes an invalidate event.
10619     *
10620     * @hide
10621     */
10622    protected void invalidateParentCaches() {
10623        if (mParent instanceof View) {
10624            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10625        }
10626    }
10627
10628    /**
10629     * Used to indicate that the parent of this view should be invalidated. This functionality
10630     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10631     * which is necessary when various parent-managed properties of the view change, such as
10632     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10633     * an invalidation event to the parent.
10634     *
10635     * @hide
10636     */
10637    protected void invalidateParentIfNeeded() {
10638        if (isHardwareAccelerated() && mParent instanceof View) {
10639            ((View) mParent).invalidate(true);
10640        }
10641    }
10642
10643    /**
10644     * Indicates whether this View is opaque. An opaque View guarantees that it will
10645     * draw all the pixels overlapping its bounds using a fully opaque color.
10646     *
10647     * Subclasses of View should override this method whenever possible to indicate
10648     * whether an instance is opaque. Opaque Views are treated in a special way by
10649     * the View hierarchy, possibly allowing it to perform optimizations during
10650     * invalidate/draw passes.
10651     *
10652     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10653     */
10654    @ViewDebug.ExportedProperty(category = "drawing")
10655    public boolean isOpaque() {
10656        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10657                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10658    }
10659
10660    /**
10661     * @hide
10662     */
10663    protected void computeOpaqueFlags() {
10664        // Opaque if:
10665        //   - Has a background
10666        //   - Background is opaque
10667        //   - Doesn't have scrollbars or scrollbars overlay
10668
10669        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10670            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10671        } else {
10672            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10673        }
10674
10675        final int flags = mViewFlags;
10676        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10677                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10678                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10679            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10680        } else {
10681            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10682        }
10683    }
10684
10685    /**
10686     * @hide
10687     */
10688    protected boolean hasOpaqueScrollbars() {
10689        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10690    }
10691
10692    /**
10693     * @return A handler associated with the thread running the View. This
10694     * handler can be used to pump events in the UI events queue.
10695     */
10696    public Handler getHandler() {
10697        if (mAttachInfo != null) {
10698            return mAttachInfo.mHandler;
10699        }
10700        return null;
10701    }
10702
10703    /**
10704     * Gets the view root associated with the View.
10705     * @return The view root, or null if none.
10706     * @hide
10707     */
10708    public ViewRootImpl getViewRootImpl() {
10709        if (mAttachInfo != null) {
10710            return mAttachInfo.mViewRootImpl;
10711        }
10712        return null;
10713    }
10714
10715    /**
10716     * <p>Causes the Runnable to be added to the message queue.
10717     * The runnable will be run on the user interface thread.</p>
10718     *
10719     * @param action The Runnable that will be executed.
10720     *
10721     * @return Returns true if the Runnable was successfully placed in to the
10722     *         message queue.  Returns false on failure, usually because the
10723     *         looper processing the message queue is exiting.
10724     *
10725     * @see #postDelayed
10726     * @see #removeCallbacks
10727     */
10728    public boolean post(Runnable action) {
10729        final AttachInfo attachInfo = mAttachInfo;
10730        if (attachInfo != null) {
10731            return attachInfo.mHandler.post(action);
10732        }
10733        // Assume that post will succeed later
10734        ViewRootImpl.getRunQueue().post(action);
10735        return true;
10736    }
10737
10738    /**
10739     * <p>Causes the Runnable to be added to the message queue, to be run
10740     * after the specified amount of time elapses.
10741     * The runnable will be run on the user interface thread.</p>
10742     *
10743     * @param action The Runnable that will be executed.
10744     * @param delayMillis The delay (in milliseconds) until the Runnable
10745     *        will be executed.
10746     *
10747     * @return true if the Runnable was successfully placed in to the
10748     *         message queue.  Returns false on failure, usually because the
10749     *         looper processing the message queue is exiting.  Note that a
10750     *         result of true does not mean the Runnable will be processed --
10751     *         if the looper is quit before the delivery time of the message
10752     *         occurs then the message will be dropped.
10753     *
10754     * @see #post
10755     * @see #removeCallbacks
10756     */
10757    public boolean postDelayed(Runnable action, long delayMillis) {
10758        final AttachInfo attachInfo = mAttachInfo;
10759        if (attachInfo != null) {
10760            return attachInfo.mHandler.postDelayed(action, delayMillis);
10761        }
10762        // Assume that post will succeed later
10763        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10764        return true;
10765    }
10766
10767    /**
10768     * <p>Causes the Runnable to execute on the next animation time step.
10769     * The runnable will be run on the user interface thread.</p>
10770     *
10771     * @param action The Runnable that will be executed.
10772     *
10773     * @see #postOnAnimationDelayed
10774     * @see #removeCallbacks
10775     */
10776    public void postOnAnimation(Runnable action) {
10777        final AttachInfo attachInfo = mAttachInfo;
10778        if (attachInfo != null) {
10779            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10780                    Choreographer.CALLBACK_ANIMATION, action, null);
10781        } else {
10782            // Assume that post will succeed later
10783            ViewRootImpl.getRunQueue().post(action);
10784        }
10785    }
10786
10787    /**
10788     * <p>Causes the Runnable to execute on the next animation time step,
10789     * after the specified amount of time elapses.
10790     * The runnable will be run on the user interface thread.</p>
10791     *
10792     * @param action The Runnable that will be executed.
10793     * @param delayMillis The delay (in milliseconds) until the Runnable
10794     *        will be executed.
10795     *
10796     * @see #postOnAnimation
10797     * @see #removeCallbacks
10798     */
10799    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10800        final AttachInfo attachInfo = mAttachInfo;
10801        if (attachInfo != null) {
10802            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10803                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10804        } else {
10805            // Assume that post will succeed later
10806            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10807        }
10808    }
10809
10810    /**
10811     * <p>Removes the specified Runnable from the message queue.</p>
10812     *
10813     * @param action The Runnable to remove from the message handling queue
10814     *
10815     * @return true if this view could ask the Handler to remove the Runnable,
10816     *         false otherwise. When the returned value is true, the Runnable
10817     *         may or may not have been actually removed from the message queue
10818     *         (for instance, if the Runnable was not in the queue already.)
10819     *
10820     * @see #post
10821     * @see #postDelayed
10822     * @see #postOnAnimation
10823     * @see #postOnAnimationDelayed
10824     */
10825    public boolean removeCallbacks(Runnable action) {
10826        if (action != null) {
10827            final AttachInfo attachInfo = mAttachInfo;
10828            if (attachInfo != null) {
10829                attachInfo.mHandler.removeCallbacks(action);
10830                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10831                        Choreographer.CALLBACK_ANIMATION, action, null);
10832            } else {
10833                // Assume that post will succeed later
10834                ViewRootImpl.getRunQueue().removeCallbacks(action);
10835            }
10836        }
10837        return true;
10838    }
10839
10840    /**
10841     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10842     * Use this to invalidate the View from a non-UI thread.</p>
10843     *
10844     * <p>This method can be invoked from outside of the UI thread
10845     * only when this View is attached to a window.</p>
10846     *
10847     * @see #invalidate()
10848     * @see #postInvalidateDelayed(long)
10849     */
10850    public void postInvalidate() {
10851        postInvalidateDelayed(0);
10852    }
10853
10854    /**
10855     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10856     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10857     *
10858     * <p>This method can be invoked from outside of the UI thread
10859     * only when this View is attached to a window.</p>
10860     *
10861     * @param left The left coordinate of the rectangle to invalidate.
10862     * @param top The top coordinate of the rectangle to invalidate.
10863     * @param right The right coordinate of the rectangle to invalidate.
10864     * @param bottom The bottom coordinate of the rectangle to invalidate.
10865     *
10866     * @see #invalidate(int, int, int, int)
10867     * @see #invalidate(Rect)
10868     * @see #postInvalidateDelayed(long, int, int, int, int)
10869     */
10870    public void postInvalidate(int left, int top, int right, int bottom) {
10871        postInvalidateDelayed(0, left, top, right, bottom);
10872    }
10873
10874    /**
10875     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10876     * loop. Waits for the specified amount of time.</p>
10877     *
10878     * <p>This method can be invoked from outside of the UI thread
10879     * only when this View is attached to a window.</p>
10880     *
10881     * @param delayMilliseconds the duration in milliseconds to delay the
10882     *         invalidation by
10883     *
10884     * @see #invalidate()
10885     * @see #postInvalidate()
10886     */
10887    public void postInvalidateDelayed(long delayMilliseconds) {
10888        // We try only with the AttachInfo because there's no point in invalidating
10889        // if we are not attached to our window
10890        final AttachInfo attachInfo = mAttachInfo;
10891        if (attachInfo != null) {
10892            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10893        }
10894    }
10895
10896    /**
10897     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10898     * through the event loop. Waits for the specified amount of time.</p>
10899     *
10900     * <p>This method can be invoked from outside of the UI thread
10901     * only when this View is attached to a window.</p>
10902     *
10903     * @param delayMilliseconds the duration in milliseconds to delay the
10904     *         invalidation by
10905     * @param left The left coordinate of the rectangle to invalidate.
10906     * @param top The top coordinate of the rectangle to invalidate.
10907     * @param right The right coordinate of the rectangle to invalidate.
10908     * @param bottom The bottom coordinate of the rectangle to invalidate.
10909     *
10910     * @see #invalidate(int, int, int, int)
10911     * @see #invalidate(Rect)
10912     * @see #postInvalidate(int, int, int, int)
10913     */
10914    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10915            int right, int bottom) {
10916
10917        // We try only with the AttachInfo because there's no point in invalidating
10918        // if we are not attached to our window
10919        final AttachInfo attachInfo = mAttachInfo;
10920        if (attachInfo != null) {
10921            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10922            info.target = this;
10923            info.left = left;
10924            info.top = top;
10925            info.right = right;
10926            info.bottom = bottom;
10927
10928            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10929        }
10930    }
10931
10932    /**
10933     * <p>Cause an invalidate to happen on the next animation time step, typically the
10934     * next display frame.</p>
10935     *
10936     * <p>This method can be invoked from outside of the UI thread
10937     * only when this View is attached to a window.</p>
10938     *
10939     * @see #invalidate()
10940     */
10941    public void postInvalidateOnAnimation() {
10942        // We try only with the AttachInfo because there's no point in invalidating
10943        // if we are not attached to our window
10944        final AttachInfo attachInfo = mAttachInfo;
10945        if (attachInfo != null) {
10946            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10947        }
10948    }
10949
10950    /**
10951     * <p>Cause an invalidate of the specified area to happen on the next animation
10952     * time step, typically the next display frame.</p>
10953     *
10954     * <p>This method can be invoked from outside of the UI thread
10955     * only when this View is attached to a window.</p>
10956     *
10957     * @param left The left coordinate of the rectangle to invalidate.
10958     * @param top The top coordinate of the rectangle to invalidate.
10959     * @param right The right coordinate of the rectangle to invalidate.
10960     * @param bottom The bottom coordinate of the rectangle to invalidate.
10961     *
10962     * @see #invalidate(int, int, int, int)
10963     * @see #invalidate(Rect)
10964     */
10965    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10966        // We try only with the AttachInfo because there's no point in invalidating
10967        // if we are not attached to our window
10968        final AttachInfo attachInfo = mAttachInfo;
10969        if (attachInfo != null) {
10970            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10971            info.target = this;
10972            info.left = left;
10973            info.top = top;
10974            info.right = right;
10975            info.bottom = bottom;
10976
10977            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10978        }
10979    }
10980
10981    /**
10982     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10983     * This event is sent at most once every
10984     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10985     */
10986    private void postSendViewScrolledAccessibilityEventCallback() {
10987        if (mSendViewScrolledAccessibilityEvent == null) {
10988            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10989        }
10990        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10991            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10992            postDelayed(mSendViewScrolledAccessibilityEvent,
10993                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10994        }
10995    }
10996
10997    /**
10998     * Called by a parent to request that a child update its values for mScrollX
10999     * and mScrollY if necessary. This will typically be done if the child is
11000     * animating a scroll using a {@link android.widget.Scroller Scroller}
11001     * object.
11002     */
11003    public void computeScroll() {
11004    }
11005
11006    /**
11007     * <p>Indicate whether the horizontal edges are faded when the view is
11008     * scrolled horizontally.</p>
11009     *
11010     * @return true if the horizontal edges should are faded on scroll, false
11011     *         otherwise
11012     *
11013     * @see #setHorizontalFadingEdgeEnabled(boolean)
11014     *
11015     * @attr ref android.R.styleable#View_requiresFadingEdge
11016     */
11017    public boolean isHorizontalFadingEdgeEnabled() {
11018        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11019    }
11020
11021    /**
11022     * <p>Define whether the horizontal edges should be faded when this view
11023     * is scrolled horizontally.</p>
11024     *
11025     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11026     *                                    be faded when the view is scrolled
11027     *                                    horizontally
11028     *
11029     * @see #isHorizontalFadingEdgeEnabled()
11030     *
11031     * @attr ref android.R.styleable#View_requiresFadingEdge
11032     */
11033    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11034        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11035            if (horizontalFadingEdgeEnabled) {
11036                initScrollCache();
11037            }
11038
11039            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11040        }
11041    }
11042
11043    /**
11044     * <p>Indicate whether the vertical edges are faded when the view is
11045     * scrolled horizontally.</p>
11046     *
11047     * @return true if the vertical edges should are faded on scroll, false
11048     *         otherwise
11049     *
11050     * @see #setVerticalFadingEdgeEnabled(boolean)
11051     *
11052     * @attr ref android.R.styleable#View_requiresFadingEdge
11053     */
11054    public boolean isVerticalFadingEdgeEnabled() {
11055        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11056    }
11057
11058    /**
11059     * <p>Define whether the vertical edges should be faded when this view
11060     * is scrolled vertically.</p>
11061     *
11062     * @param verticalFadingEdgeEnabled true if the vertical edges should
11063     *                                  be faded when the view is scrolled
11064     *                                  vertically
11065     *
11066     * @see #isVerticalFadingEdgeEnabled()
11067     *
11068     * @attr ref android.R.styleable#View_requiresFadingEdge
11069     */
11070    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11071        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11072            if (verticalFadingEdgeEnabled) {
11073                initScrollCache();
11074            }
11075
11076            mViewFlags ^= FADING_EDGE_VERTICAL;
11077        }
11078    }
11079
11080    /**
11081     * Returns the strength, or intensity, of the top faded edge. The strength is
11082     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11083     * returns 0.0 or 1.0 but no value in between.
11084     *
11085     * Subclasses should override this method to provide a smoother fade transition
11086     * when scrolling occurs.
11087     *
11088     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11089     */
11090    protected float getTopFadingEdgeStrength() {
11091        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11092    }
11093
11094    /**
11095     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11096     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11097     * returns 0.0 or 1.0 but no value in between.
11098     *
11099     * Subclasses should override this method to provide a smoother fade transition
11100     * when scrolling occurs.
11101     *
11102     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11103     */
11104    protected float getBottomFadingEdgeStrength() {
11105        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11106                computeVerticalScrollRange() ? 1.0f : 0.0f;
11107    }
11108
11109    /**
11110     * Returns the strength, or intensity, of the left faded edge. The strength is
11111     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11112     * returns 0.0 or 1.0 but no value in between.
11113     *
11114     * Subclasses should override this method to provide a smoother fade transition
11115     * when scrolling occurs.
11116     *
11117     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11118     */
11119    protected float getLeftFadingEdgeStrength() {
11120        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11121    }
11122
11123    /**
11124     * Returns the strength, or intensity, of the right faded edge. The strength is
11125     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11126     * returns 0.0 or 1.0 but no value in between.
11127     *
11128     * Subclasses should override this method to provide a smoother fade transition
11129     * when scrolling occurs.
11130     *
11131     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11132     */
11133    protected float getRightFadingEdgeStrength() {
11134        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11135                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11136    }
11137
11138    /**
11139     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11140     * scrollbar is not drawn by default.</p>
11141     *
11142     * @return true if the horizontal scrollbar should be painted, false
11143     *         otherwise
11144     *
11145     * @see #setHorizontalScrollBarEnabled(boolean)
11146     */
11147    public boolean isHorizontalScrollBarEnabled() {
11148        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11149    }
11150
11151    /**
11152     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11153     * scrollbar is not drawn by default.</p>
11154     *
11155     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11156     *                                   be painted
11157     *
11158     * @see #isHorizontalScrollBarEnabled()
11159     */
11160    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11161        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11162            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11163            computeOpaqueFlags();
11164            resolvePadding();
11165        }
11166    }
11167
11168    /**
11169     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11170     * scrollbar is not drawn by default.</p>
11171     *
11172     * @return true if the vertical scrollbar should be painted, false
11173     *         otherwise
11174     *
11175     * @see #setVerticalScrollBarEnabled(boolean)
11176     */
11177    public boolean isVerticalScrollBarEnabled() {
11178        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11179    }
11180
11181    /**
11182     * <p>Define whether the vertical scrollbar should be drawn or not. The
11183     * scrollbar is not drawn by default.</p>
11184     *
11185     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11186     *                                 be painted
11187     *
11188     * @see #isVerticalScrollBarEnabled()
11189     */
11190    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11191        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11192            mViewFlags ^= SCROLLBARS_VERTICAL;
11193            computeOpaqueFlags();
11194            resolvePadding();
11195        }
11196    }
11197
11198    /**
11199     * @hide
11200     */
11201    protected void recomputePadding() {
11202        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11203    }
11204
11205    /**
11206     * Define whether scrollbars will fade when the view is not scrolling.
11207     *
11208     * @param fadeScrollbars wheter to enable fading
11209     *
11210     * @attr ref android.R.styleable#View_fadeScrollbars
11211     */
11212    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11213        initScrollCache();
11214        final ScrollabilityCache scrollabilityCache = mScrollCache;
11215        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11216        if (fadeScrollbars) {
11217            scrollabilityCache.state = ScrollabilityCache.OFF;
11218        } else {
11219            scrollabilityCache.state = ScrollabilityCache.ON;
11220        }
11221    }
11222
11223    /**
11224     *
11225     * Returns true if scrollbars will fade when this view is not scrolling
11226     *
11227     * @return true if scrollbar fading is enabled
11228     *
11229     * @attr ref android.R.styleable#View_fadeScrollbars
11230     */
11231    public boolean isScrollbarFadingEnabled() {
11232        return mScrollCache != null && mScrollCache.fadeScrollBars;
11233    }
11234
11235    /**
11236     *
11237     * Returns the delay before scrollbars fade.
11238     *
11239     * @return the delay before scrollbars fade
11240     *
11241     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11242     */
11243    public int getScrollBarDefaultDelayBeforeFade() {
11244        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11245                mScrollCache.scrollBarDefaultDelayBeforeFade;
11246    }
11247
11248    /**
11249     * Define the delay before scrollbars fade.
11250     *
11251     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11252     *
11253     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11254     */
11255    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11256        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11257    }
11258
11259    /**
11260     *
11261     * Returns the scrollbar fade duration.
11262     *
11263     * @return the scrollbar fade duration
11264     *
11265     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11266     */
11267    public int getScrollBarFadeDuration() {
11268        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11269                mScrollCache.scrollBarFadeDuration;
11270    }
11271
11272    /**
11273     * Define the scrollbar fade duration.
11274     *
11275     * @param scrollBarFadeDuration - the scrollbar fade duration
11276     *
11277     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11278     */
11279    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11280        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11281    }
11282
11283    /**
11284     *
11285     * Returns the scrollbar size.
11286     *
11287     * @return the scrollbar size
11288     *
11289     * @attr ref android.R.styleable#View_scrollbarSize
11290     */
11291    public int getScrollBarSize() {
11292        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11293                mScrollCache.scrollBarSize;
11294    }
11295
11296    /**
11297     * Define the scrollbar size.
11298     *
11299     * @param scrollBarSize - the scrollbar size
11300     *
11301     * @attr ref android.R.styleable#View_scrollbarSize
11302     */
11303    public void setScrollBarSize(int scrollBarSize) {
11304        getScrollCache().scrollBarSize = scrollBarSize;
11305    }
11306
11307    /**
11308     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11309     * inset. When inset, they add to the padding of the view. And the scrollbars
11310     * can be drawn inside the padding area or on the edge of the view. For example,
11311     * if a view has a background drawable and you want to draw the scrollbars
11312     * inside the padding specified by the drawable, you can use
11313     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11314     * appear at the edge of the view, ignoring the padding, then you can use
11315     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11316     * @param style the style of the scrollbars. Should be one of
11317     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11318     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11319     * @see #SCROLLBARS_INSIDE_OVERLAY
11320     * @see #SCROLLBARS_INSIDE_INSET
11321     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11322     * @see #SCROLLBARS_OUTSIDE_INSET
11323     *
11324     * @attr ref android.R.styleable#View_scrollbarStyle
11325     */
11326    public void setScrollBarStyle(int style) {
11327        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11328            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11329            computeOpaqueFlags();
11330            resolvePadding();
11331        }
11332    }
11333
11334    /**
11335     * <p>Returns the current scrollbar style.</p>
11336     * @return the current scrollbar style
11337     * @see #SCROLLBARS_INSIDE_OVERLAY
11338     * @see #SCROLLBARS_INSIDE_INSET
11339     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11340     * @see #SCROLLBARS_OUTSIDE_INSET
11341     *
11342     * @attr ref android.R.styleable#View_scrollbarStyle
11343     */
11344    @ViewDebug.ExportedProperty(mapping = {
11345            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11346            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11347            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11348            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11349    })
11350    public int getScrollBarStyle() {
11351        return mViewFlags & SCROLLBARS_STYLE_MASK;
11352    }
11353
11354    /**
11355     * <p>Compute the horizontal range that the horizontal scrollbar
11356     * represents.</p>
11357     *
11358     * <p>The range is expressed in arbitrary units that must be the same as the
11359     * units used by {@link #computeHorizontalScrollExtent()} and
11360     * {@link #computeHorizontalScrollOffset()}.</p>
11361     *
11362     * <p>The default range is the drawing width of this view.</p>
11363     *
11364     * @return the total horizontal range represented by the horizontal
11365     *         scrollbar
11366     *
11367     * @see #computeHorizontalScrollExtent()
11368     * @see #computeHorizontalScrollOffset()
11369     * @see android.widget.ScrollBarDrawable
11370     */
11371    protected int computeHorizontalScrollRange() {
11372        return getWidth();
11373    }
11374
11375    /**
11376     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11377     * within the horizontal range. This value is used to compute the position
11378     * of the thumb within the scrollbar's track.</p>
11379     *
11380     * <p>The range is expressed in arbitrary units that must be the same as the
11381     * units used by {@link #computeHorizontalScrollRange()} and
11382     * {@link #computeHorizontalScrollExtent()}.</p>
11383     *
11384     * <p>The default offset is the scroll offset of this view.</p>
11385     *
11386     * @return the horizontal offset of the scrollbar's thumb
11387     *
11388     * @see #computeHorizontalScrollRange()
11389     * @see #computeHorizontalScrollExtent()
11390     * @see android.widget.ScrollBarDrawable
11391     */
11392    protected int computeHorizontalScrollOffset() {
11393        return mScrollX;
11394    }
11395
11396    /**
11397     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11398     * within the horizontal range. This value is used to compute the length
11399     * of the thumb within the scrollbar's track.</p>
11400     *
11401     * <p>The range is expressed in arbitrary units that must be the same as the
11402     * units used by {@link #computeHorizontalScrollRange()} and
11403     * {@link #computeHorizontalScrollOffset()}.</p>
11404     *
11405     * <p>The default extent is the drawing width of this view.</p>
11406     *
11407     * @return the horizontal extent of the scrollbar's thumb
11408     *
11409     * @see #computeHorizontalScrollRange()
11410     * @see #computeHorizontalScrollOffset()
11411     * @see android.widget.ScrollBarDrawable
11412     */
11413    protected int computeHorizontalScrollExtent() {
11414        return getWidth();
11415    }
11416
11417    /**
11418     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11419     *
11420     * <p>The range is expressed in arbitrary units that must be the same as the
11421     * units used by {@link #computeVerticalScrollExtent()} and
11422     * {@link #computeVerticalScrollOffset()}.</p>
11423     *
11424     * @return the total vertical range represented by the vertical scrollbar
11425     *
11426     * <p>The default range is the drawing height of this view.</p>
11427     *
11428     * @see #computeVerticalScrollExtent()
11429     * @see #computeVerticalScrollOffset()
11430     * @see android.widget.ScrollBarDrawable
11431     */
11432    protected int computeVerticalScrollRange() {
11433        return getHeight();
11434    }
11435
11436    /**
11437     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11438     * within the horizontal range. This value is used to compute the position
11439     * of the thumb within the scrollbar's track.</p>
11440     *
11441     * <p>The range is expressed in arbitrary units that must be the same as the
11442     * units used by {@link #computeVerticalScrollRange()} and
11443     * {@link #computeVerticalScrollExtent()}.</p>
11444     *
11445     * <p>The default offset is the scroll offset of this view.</p>
11446     *
11447     * @return the vertical offset of the scrollbar's thumb
11448     *
11449     * @see #computeVerticalScrollRange()
11450     * @see #computeVerticalScrollExtent()
11451     * @see android.widget.ScrollBarDrawable
11452     */
11453    protected int computeVerticalScrollOffset() {
11454        return mScrollY;
11455    }
11456
11457    /**
11458     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11459     * within the vertical range. This value is used to compute the length
11460     * of the thumb within the scrollbar's track.</p>
11461     *
11462     * <p>The range is expressed in arbitrary units that must be the same as the
11463     * units used by {@link #computeVerticalScrollRange()} and
11464     * {@link #computeVerticalScrollOffset()}.</p>
11465     *
11466     * <p>The default extent is the drawing height of this view.</p>
11467     *
11468     * @return the vertical extent of the scrollbar's thumb
11469     *
11470     * @see #computeVerticalScrollRange()
11471     * @see #computeVerticalScrollOffset()
11472     * @see android.widget.ScrollBarDrawable
11473     */
11474    protected int computeVerticalScrollExtent() {
11475        return getHeight();
11476    }
11477
11478    /**
11479     * Check if this view can be scrolled horizontally in a certain direction.
11480     *
11481     * @param direction Negative to check scrolling left, positive to check scrolling right.
11482     * @return true if this view can be scrolled in the specified direction, false otherwise.
11483     */
11484    public boolean canScrollHorizontally(int direction) {
11485        final int offset = computeHorizontalScrollOffset();
11486        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11487        if (range == 0) return false;
11488        if (direction < 0) {
11489            return offset > 0;
11490        } else {
11491            return offset < range - 1;
11492        }
11493    }
11494
11495    /**
11496     * Check if this view can be scrolled vertically in a certain direction.
11497     *
11498     * @param direction Negative to check scrolling up, positive to check scrolling down.
11499     * @return true if this view can be scrolled in the specified direction, false otherwise.
11500     */
11501    public boolean canScrollVertically(int direction) {
11502        final int offset = computeVerticalScrollOffset();
11503        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11504        if (range == 0) return false;
11505        if (direction < 0) {
11506            return offset > 0;
11507        } else {
11508            return offset < range - 1;
11509        }
11510    }
11511
11512    /**
11513     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11514     * scrollbars are painted only if they have been awakened first.</p>
11515     *
11516     * @param canvas the canvas on which to draw the scrollbars
11517     *
11518     * @see #awakenScrollBars(int)
11519     */
11520    protected final void onDrawScrollBars(Canvas canvas) {
11521        // scrollbars are drawn only when the animation is running
11522        final ScrollabilityCache cache = mScrollCache;
11523        if (cache != null) {
11524
11525            int state = cache.state;
11526
11527            if (state == ScrollabilityCache.OFF) {
11528                return;
11529            }
11530
11531            boolean invalidate = false;
11532
11533            if (state == ScrollabilityCache.FADING) {
11534                // We're fading -- get our fade interpolation
11535                if (cache.interpolatorValues == null) {
11536                    cache.interpolatorValues = new float[1];
11537                }
11538
11539                float[] values = cache.interpolatorValues;
11540
11541                // Stops the animation if we're done
11542                if (cache.scrollBarInterpolator.timeToValues(values) ==
11543                        Interpolator.Result.FREEZE_END) {
11544                    cache.state = ScrollabilityCache.OFF;
11545                } else {
11546                    cache.scrollBar.setAlpha(Math.round(values[0]));
11547                }
11548
11549                // This will make the scroll bars inval themselves after
11550                // drawing. We only want this when we're fading so that
11551                // we prevent excessive redraws
11552                invalidate = true;
11553            } else {
11554                // We're just on -- but we may have been fading before so
11555                // reset alpha
11556                cache.scrollBar.setAlpha(255);
11557            }
11558
11559
11560            final int viewFlags = mViewFlags;
11561
11562            final boolean drawHorizontalScrollBar =
11563                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11564            final boolean drawVerticalScrollBar =
11565                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11566                && !isVerticalScrollBarHidden();
11567
11568            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11569                final int width = mRight - mLeft;
11570                final int height = mBottom - mTop;
11571
11572                final ScrollBarDrawable scrollBar = cache.scrollBar;
11573
11574                final int scrollX = mScrollX;
11575                final int scrollY = mScrollY;
11576                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11577
11578                int left;
11579                int top;
11580                int right;
11581                int bottom;
11582
11583                if (drawHorizontalScrollBar) {
11584                    int size = scrollBar.getSize(false);
11585                    if (size <= 0) {
11586                        size = cache.scrollBarSize;
11587                    }
11588
11589                    scrollBar.setParameters(computeHorizontalScrollRange(),
11590                                            computeHorizontalScrollOffset(),
11591                                            computeHorizontalScrollExtent(), false);
11592                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11593                            getVerticalScrollbarWidth() : 0;
11594                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11595                    left = scrollX + (mPaddingLeft & inside);
11596                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11597                    bottom = top + size;
11598                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11599                    if (invalidate) {
11600                        invalidate(left, top, right, bottom);
11601                    }
11602                }
11603
11604                if (drawVerticalScrollBar) {
11605                    int size = scrollBar.getSize(true);
11606                    if (size <= 0) {
11607                        size = cache.scrollBarSize;
11608                    }
11609
11610                    scrollBar.setParameters(computeVerticalScrollRange(),
11611                                            computeVerticalScrollOffset(),
11612                                            computeVerticalScrollExtent(), true);
11613                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11614                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11615                        verticalScrollbarPosition = isLayoutRtl() ?
11616                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11617                    }
11618                    switch (verticalScrollbarPosition) {
11619                        default:
11620                        case SCROLLBAR_POSITION_RIGHT:
11621                            left = scrollX + width - size - (mUserPaddingRight & inside);
11622                            break;
11623                        case SCROLLBAR_POSITION_LEFT:
11624                            left = scrollX + (mUserPaddingLeft & inside);
11625                            break;
11626                    }
11627                    top = scrollY + (mPaddingTop & inside);
11628                    right = left + size;
11629                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11630                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11631                    if (invalidate) {
11632                        invalidate(left, top, right, bottom);
11633                    }
11634                }
11635            }
11636        }
11637    }
11638
11639    /**
11640     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11641     * FastScroller is visible.
11642     * @return whether to temporarily hide the vertical scrollbar
11643     * @hide
11644     */
11645    protected boolean isVerticalScrollBarHidden() {
11646        return false;
11647    }
11648
11649    /**
11650     * <p>Draw the horizontal scrollbar if
11651     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11652     *
11653     * @param canvas the canvas on which to draw the scrollbar
11654     * @param scrollBar the scrollbar's drawable
11655     *
11656     * @see #isHorizontalScrollBarEnabled()
11657     * @see #computeHorizontalScrollRange()
11658     * @see #computeHorizontalScrollExtent()
11659     * @see #computeHorizontalScrollOffset()
11660     * @see android.widget.ScrollBarDrawable
11661     * @hide
11662     */
11663    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11664            int l, int t, int r, int b) {
11665        scrollBar.setBounds(l, t, r, b);
11666        scrollBar.draw(canvas);
11667    }
11668
11669    /**
11670     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11671     * returns true.</p>
11672     *
11673     * @param canvas the canvas on which to draw the scrollbar
11674     * @param scrollBar the scrollbar's drawable
11675     *
11676     * @see #isVerticalScrollBarEnabled()
11677     * @see #computeVerticalScrollRange()
11678     * @see #computeVerticalScrollExtent()
11679     * @see #computeVerticalScrollOffset()
11680     * @see android.widget.ScrollBarDrawable
11681     * @hide
11682     */
11683    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11684            int l, int t, int r, int b) {
11685        scrollBar.setBounds(l, t, r, b);
11686        scrollBar.draw(canvas);
11687    }
11688
11689    /**
11690     * Implement this to do your drawing.
11691     *
11692     * @param canvas the canvas on which the background will be drawn
11693     */
11694    protected void onDraw(Canvas canvas) {
11695    }
11696
11697    /*
11698     * Caller is responsible for calling requestLayout if necessary.
11699     * (This allows addViewInLayout to not request a new layout.)
11700     */
11701    void assignParent(ViewParent parent) {
11702        if (mParent == null) {
11703            mParent = parent;
11704        } else if (parent == null) {
11705            mParent = null;
11706        } else {
11707            throw new RuntimeException("view " + this + " being added, but"
11708                    + " it already has a parent");
11709        }
11710    }
11711
11712    /**
11713     * This is called when the view is attached to a window.  At this point it
11714     * has a Surface and will start drawing.  Note that this function is
11715     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11716     * however it may be called any time before the first onDraw -- including
11717     * before or after {@link #onMeasure(int, int)}.
11718     *
11719     * @see #onDetachedFromWindow()
11720     */
11721    protected void onAttachedToWindow() {
11722        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11723            mParent.requestTransparentRegion(this);
11724        }
11725
11726        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11727            initialAwakenScrollBars();
11728            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11729        }
11730
11731        jumpDrawablesToCurrentState();
11732
11733        clearAccessibilityFocus();
11734        if (isFocused()) {
11735            InputMethodManager imm = InputMethodManager.peekInstance();
11736            imm.focusIn(this);
11737        }
11738
11739        if (mDisplayList != null) {
11740            mDisplayList.clearDirty();
11741        }
11742    }
11743
11744    /**
11745     * Resolve all RTL related properties.
11746     *
11747     * @hide
11748     */
11749    public void resolveRtlPropertiesIfNeeded() {
11750        if (!needRtlPropertiesResolution()) return;
11751
11752        // Order is important here: LayoutDirection MUST be resolved first
11753        if (!isLayoutDirectionResolved()) {
11754            resolveLayoutDirection();
11755            resolveLayoutParams();
11756        }
11757        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11758        if (!isTextDirectionResolved()) {
11759            resolveTextDirection();
11760        }
11761        if (!isTextAlignmentResolved()) {
11762            resolveTextAlignment();
11763        }
11764        if (!isPaddingResolved()) {
11765            resolvePadding();
11766        }
11767        if (!isDrawablesResolved()) {
11768            resolveDrawables();
11769        }
11770        onRtlPropertiesChanged(getLayoutDirection());
11771    }
11772
11773    /**
11774     * Reset resolution of all RTL related properties.
11775     *
11776     * @hide
11777     */
11778    public void resetRtlProperties() {
11779        resetResolvedLayoutDirection();
11780        resetResolvedTextDirection();
11781        resetResolvedTextAlignment();
11782        resetResolvedPadding();
11783        resetResolvedDrawables();
11784    }
11785
11786    /**
11787     * @see #onScreenStateChanged(int)
11788     */
11789    void dispatchScreenStateChanged(int screenState) {
11790        onScreenStateChanged(screenState);
11791    }
11792
11793    /**
11794     * This method is called whenever the state of the screen this view is
11795     * attached to changes. A state change will usually occurs when the screen
11796     * turns on or off (whether it happens automatically or the user does it
11797     * manually.)
11798     *
11799     * @param screenState The new state of the screen. Can be either
11800     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11801     */
11802    public void onScreenStateChanged(int screenState) {
11803    }
11804
11805    /**
11806     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11807     */
11808    private boolean hasRtlSupport() {
11809        return mContext.getApplicationInfo().hasRtlSupport();
11810    }
11811
11812    /**
11813     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11814     * RTL not supported)
11815     */
11816    private boolean isRtlCompatibilityMode() {
11817        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11818        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11819    }
11820
11821    /**
11822     * @return true if RTL properties need resolution.
11823     */
11824    private boolean needRtlPropertiesResolution() {
11825        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11826    }
11827
11828    /**
11829     * Called when any RTL property (layout direction or text direction or text alignment) has
11830     * been changed.
11831     *
11832     * Subclasses need to override this method to take care of cached information that depends on the
11833     * resolved layout direction, or to inform child views that inherit their layout direction.
11834     *
11835     * The default implementation does nothing.
11836     *
11837     * @param layoutDirection the direction of the layout
11838     *
11839     * @see #LAYOUT_DIRECTION_LTR
11840     * @see #LAYOUT_DIRECTION_RTL
11841     */
11842    public void onRtlPropertiesChanged(int layoutDirection) {
11843    }
11844
11845    /**
11846     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11847     * that the parent directionality can and will be resolved before its children.
11848     *
11849     * @return true if resolution has been done, false otherwise.
11850     *
11851     * @hide
11852     */
11853    public boolean resolveLayoutDirection() {
11854        // Clear any previous layout direction resolution
11855        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11856
11857        if (hasRtlSupport()) {
11858            // Set resolved depending on layout direction
11859            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11860                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11861                case LAYOUT_DIRECTION_INHERIT:
11862                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11863                    // later to get the correct resolved value
11864                    if (!canResolveLayoutDirection()) return false;
11865
11866                    // Parent has not yet resolved, LTR is still the default
11867                    if (!mParent.isLayoutDirectionResolved()) return false;
11868
11869                    if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11870                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11871                    }
11872                    break;
11873                case LAYOUT_DIRECTION_RTL:
11874                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11875                    break;
11876                case LAYOUT_DIRECTION_LOCALE:
11877                    if((LAYOUT_DIRECTION_RTL ==
11878                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11879                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11880                    }
11881                    break;
11882                default:
11883                    // Nothing to do, LTR by default
11884            }
11885        }
11886
11887        // Set to resolved
11888        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11889        return true;
11890    }
11891
11892    /**
11893     * Check if layout direction resolution can be done.
11894     *
11895     * @return true if layout direction resolution can be done otherwise return false.
11896     *
11897     * @hide
11898     */
11899    public boolean canResolveLayoutDirection() {
11900        switch (getRawLayoutDirection()) {
11901            case LAYOUT_DIRECTION_INHERIT:
11902                return (mParent != null) && mParent.canResolveLayoutDirection();
11903            default:
11904                return true;
11905        }
11906    }
11907
11908    /**
11909     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11910     * {@link #onMeasure(int, int)}.
11911     *
11912     * @hide
11913     */
11914    public void resetResolvedLayoutDirection() {
11915        // Reset the current resolved bits
11916        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11917    }
11918
11919    /**
11920     * @return true if the layout direction is inherited.
11921     *
11922     * @hide
11923     */
11924    public boolean isLayoutDirectionInherited() {
11925        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11926    }
11927
11928    /**
11929     * @return true if layout direction has been resolved.
11930     * @hide
11931     */
11932    public boolean isLayoutDirectionResolved() {
11933        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11934    }
11935
11936    /**
11937     * Return if padding has been resolved
11938     *
11939     * @hide
11940     */
11941    boolean isPaddingResolved() {
11942        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11943    }
11944
11945    /**
11946     * Resolve padding depending on layout direction.
11947     *
11948     * @hide
11949     */
11950    public void resolvePadding() {
11951        if (!isRtlCompatibilityMode()) {
11952            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11953            // If start / end padding are defined, they will be resolved (hence overriding) to
11954            // left / right or right / left depending on the resolved layout direction.
11955            // If start / end padding are not defined, use the left / right ones.
11956            int resolvedLayoutDirection = getLayoutDirection();
11957            switch (resolvedLayoutDirection) {
11958                case LAYOUT_DIRECTION_RTL:
11959                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11960                        mUserPaddingRight = mUserPaddingStart;
11961                    } else {
11962                        mUserPaddingRight = mUserPaddingRightInitial;
11963                    }
11964                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11965                        mUserPaddingLeft = mUserPaddingEnd;
11966                    } else {
11967                        mUserPaddingLeft = mUserPaddingLeftInitial;
11968                    }
11969                    break;
11970                case LAYOUT_DIRECTION_LTR:
11971                default:
11972                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11973                        mUserPaddingLeft = mUserPaddingStart;
11974                    } else {
11975                        mUserPaddingLeft = mUserPaddingLeftInitial;
11976                    }
11977                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11978                        mUserPaddingRight = mUserPaddingEnd;
11979                    } else {
11980                        mUserPaddingRight = mUserPaddingRightInitial;
11981                    }
11982            }
11983
11984            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11985
11986            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11987                    mUserPaddingBottom);
11988            onRtlPropertiesChanged(resolvedLayoutDirection);
11989        }
11990
11991        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11992    }
11993
11994    /**
11995     * Reset the resolved layout direction.
11996     *
11997     * @hide
11998     */
11999    public void resetResolvedPadding() {
12000        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12001    }
12002
12003    /**
12004     * This is called when the view is detached from a window.  At this point it
12005     * no longer has a surface for drawing.
12006     *
12007     * @see #onAttachedToWindow()
12008     */
12009    protected void onDetachedFromWindow() {
12010        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12011
12012        removeUnsetPressCallback();
12013        removeLongPressCallback();
12014        removePerformClickCallback();
12015        removeSendViewScrolledAccessibilityEventCallback();
12016
12017        destroyDrawingCache();
12018
12019        destroyLayer(false);
12020
12021        if (mAttachInfo != null) {
12022            if (mDisplayList != null) {
12023                mDisplayList.markDirty();
12024                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12025            }
12026            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12027        } else {
12028            // Should never happen
12029            clearDisplayList();
12030        }
12031
12032        mCurrentAnimation = null;
12033
12034        resetAccessibilityStateChanged();
12035    }
12036
12037    /**
12038     * @return The number of times this view has been attached to a window
12039     */
12040    protected int getWindowAttachCount() {
12041        return mWindowAttachCount;
12042    }
12043
12044    /**
12045     * Retrieve a unique token identifying the window this view is attached to.
12046     * @return Return the window's token for use in
12047     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12048     */
12049    public IBinder getWindowToken() {
12050        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12051    }
12052
12053    /**
12054     * Retrieve the {@link WindowId} for the window this view is
12055     * currently attached to.
12056     */
12057    public WindowId getWindowId() {
12058        if (mAttachInfo == null) {
12059            return null;
12060        }
12061        if (mAttachInfo.mWindowId == null) {
12062            try {
12063                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12064                        mAttachInfo.mWindowToken);
12065                mAttachInfo.mWindowId = new WindowId(
12066                        mAttachInfo.mIWindowId);
12067            } catch (RemoteException e) {
12068            }
12069        }
12070        return mAttachInfo.mWindowId;
12071    }
12072
12073    /**
12074     * Retrieve a unique token identifying the top-level "real" window of
12075     * the window that this view is attached to.  That is, this is like
12076     * {@link #getWindowToken}, except if the window this view in is a panel
12077     * window (attached to another containing window), then the token of
12078     * the containing window is returned instead.
12079     *
12080     * @return Returns the associated window token, either
12081     * {@link #getWindowToken()} or the containing window's token.
12082     */
12083    public IBinder getApplicationWindowToken() {
12084        AttachInfo ai = mAttachInfo;
12085        if (ai != null) {
12086            IBinder appWindowToken = ai.mPanelParentWindowToken;
12087            if (appWindowToken == null) {
12088                appWindowToken = ai.mWindowToken;
12089            }
12090            return appWindowToken;
12091        }
12092        return null;
12093    }
12094
12095    /**
12096     * Gets the logical display to which the view's window has been attached.
12097     *
12098     * @return The logical display, or null if the view is not currently attached to a window.
12099     */
12100    public Display getDisplay() {
12101        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12102    }
12103
12104    /**
12105     * Retrieve private session object this view hierarchy is using to
12106     * communicate with the window manager.
12107     * @return the session object to communicate with the window manager
12108     */
12109    /*package*/ IWindowSession getWindowSession() {
12110        return mAttachInfo != null ? mAttachInfo.mSession : null;
12111    }
12112
12113    /**
12114     * @param info the {@link android.view.View.AttachInfo} to associated with
12115     *        this view
12116     */
12117    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12118        //System.out.println("Attached! " + this);
12119        mAttachInfo = info;
12120        if (mOverlay != null) {
12121            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12122        }
12123        mWindowAttachCount++;
12124        // We will need to evaluate the drawable state at least once.
12125        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12126        if (mFloatingTreeObserver != null) {
12127            info.mTreeObserver.merge(mFloatingTreeObserver);
12128            mFloatingTreeObserver = null;
12129        }
12130        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12131            mAttachInfo.mScrollContainers.add(this);
12132            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12133        }
12134        performCollectViewAttributes(mAttachInfo, visibility);
12135        onAttachedToWindow();
12136
12137        ListenerInfo li = mListenerInfo;
12138        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12139                li != null ? li.mOnAttachStateChangeListeners : null;
12140        if (listeners != null && listeners.size() > 0) {
12141            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12142            // perform the dispatching. The iterator is a safe guard against listeners that
12143            // could mutate the list by calling the various add/remove methods. This prevents
12144            // the array from being modified while we iterate it.
12145            for (OnAttachStateChangeListener listener : listeners) {
12146                listener.onViewAttachedToWindow(this);
12147            }
12148        }
12149
12150        int vis = info.mWindowVisibility;
12151        if (vis != GONE) {
12152            onWindowVisibilityChanged(vis);
12153        }
12154        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12155            // If nobody has evaluated the drawable state yet, then do it now.
12156            refreshDrawableState();
12157        }
12158        needGlobalAttributesUpdate(false);
12159    }
12160
12161    void dispatchDetachedFromWindow() {
12162        AttachInfo info = mAttachInfo;
12163        if (info != null) {
12164            int vis = info.mWindowVisibility;
12165            if (vis != GONE) {
12166                onWindowVisibilityChanged(GONE);
12167            }
12168        }
12169
12170        onDetachedFromWindow();
12171
12172        ListenerInfo li = mListenerInfo;
12173        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12174                li != null ? li.mOnAttachStateChangeListeners : null;
12175        if (listeners != null && listeners.size() > 0) {
12176            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12177            // perform the dispatching. The iterator is a safe guard against listeners that
12178            // could mutate the list by calling the various add/remove methods. This prevents
12179            // the array from being modified while we iterate it.
12180            for (OnAttachStateChangeListener listener : listeners) {
12181                listener.onViewDetachedFromWindow(this);
12182            }
12183        }
12184
12185        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12186            mAttachInfo.mScrollContainers.remove(this);
12187            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12188        }
12189
12190        mAttachInfo = null;
12191        if (mOverlay != null) {
12192            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12193        }
12194    }
12195
12196    /**
12197     * Store this view hierarchy's frozen state into the given container.
12198     *
12199     * @param container The SparseArray in which to save the view's state.
12200     *
12201     * @see #restoreHierarchyState(android.util.SparseArray)
12202     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12203     * @see #onSaveInstanceState()
12204     */
12205    public void saveHierarchyState(SparseArray<Parcelable> container) {
12206        dispatchSaveInstanceState(container);
12207    }
12208
12209    /**
12210     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12211     * this view and its children. May be overridden to modify how freezing happens to a
12212     * view's children; for example, some views may want to not store state for their children.
12213     *
12214     * @param container The SparseArray in which to save the view's state.
12215     *
12216     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12217     * @see #saveHierarchyState(android.util.SparseArray)
12218     * @see #onSaveInstanceState()
12219     */
12220    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12221        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12222            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12223            Parcelable state = onSaveInstanceState();
12224            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12225                throw new IllegalStateException(
12226                        "Derived class did not call super.onSaveInstanceState()");
12227            }
12228            if (state != null) {
12229                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12230                // + ": " + state);
12231                container.put(mID, state);
12232            }
12233        }
12234    }
12235
12236    /**
12237     * Hook allowing a view to generate a representation of its internal state
12238     * that can later be used to create a new instance with that same state.
12239     * This state should only contain information that is not persistent or can
12240     * not be reconstructed later. For example, you will never store your
12241     * current position on screen because that will be computed again when a
12242     * new instance of the view is placed in its view hierarchy.
12243     * <p>
12244     * Some examples of things you may store here: the current cursor position
12245     * in a text view (but usually not the text itself since that is stored in a
12246     * content provider or other persistent storage), the currently selected
12247     * item in a list view.
12248     *
12249     * @return Returns a Parcelable object containing the view's current dynamic
12250     *         state, or null if there is nothing interesting to save. The
12251     *         default implementation returns null.
12252     * @see #onRestoreInstanceState(android.os.Parcelable)
12253     * @see #saveHierarchyState(android.util.SparseArray)
12254     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12255     * @see #setSaveEnabled(boolean)
12256     */
12257    protected Parcelable onSaveInstanceState() {
12258        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12259        return BaseSavedState.EMPTY_STATE;
12260    }
12261
12262    /**
12263     * Restore this view hierarchy's frozen state from the given container.
12264     *
12265     * @param container The SparseArray which holds previously frozen states.
12266     *
12267     * @see #saveHierarchyState(android.util.SparseArray)
12268     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12269     * @see #onRestoreInstanceState(android.os.Parcelable)
12270     */
12271    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12272        dispatchRestoreInstanceState(container);
12273    }
12274
12275    /**
12276     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12277     * state for this view and its children. May be overridden to modify how restoring
12278     * happens to a view's children; for example, some views may want to not store state
12279     * for their children.
12280     *
12281     * @param container The SparseArray which holds previously saved state.
12282     *
12283     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12284     * @see #restoreHierarchyState(android.util.SparseArray)
12285     * @see #onRestoreInstanceState(android.os.Parcelable)
12286     */
12287    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12288        if (mID != NO_ID) {
12289            Parcelable state = container.get(mID);
12290            if (state != null) {
12291                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12292                // + ": " + state);
12293                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12294                onRestoreInstanceState(state);
12295                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12296                    throw new IllegalStateException(
12297                            "Derived class did not call super.onRestoreInstanceState()");
12298                }
12299            }
12300        }
12301    }
12302
12303    /**
12304     * Hook allowing a view to re-apply a representation of its internal state that had previously
12305     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12306     * null state.
12307     *
12308     * @param state The frozen state that had previously been returned by
12309     *        {@link #onSaveInstanceState}.
12310     *
12311     * @see #onSaveInstanceState()
12312     * @see #restoreHierarchyState(android.util.SparseArray)
12313     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12314     */
12315    protected void onRestoreInstanceState(Parcelable state) {
12316        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12317        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12318            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12319                    + "received " + state.getClass().toString() + " instead. This usually happens "
12320                    + "when two views of different type have the same id in the same hierarchy. "
12321                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12322                    + "other views do not use the same id.");
12323        }
12324    }
12325
12326    /**
12327     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12328     *
12329     * @return the drawing start time in milliseconds
12330     */
12331    public long getDrawingTime() {
12332        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12333    }
12334
12335    /**
12336     * <p>Enables or disables the duplication of the parent's state into this view. When
12337     * duplication is enabled, this view gets its drawable state from its parent rather
12338     * than from its own internal properties.</p>
12339     *
12340     * <p>Note: in the current implementation, setting this property to true after the
12341     * view was added to a ViewGroup might have no effect at all. This property should
12342     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12343     *
12344     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12345     * property is enabled, an exception will be thrown.</p>
12346     *
12347     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12348     * parent, these states should not be affected by this method.</p>
12349     *
12350     * @param enabled True to enable duplication of the parent's drawable state, false
12351     *                to disable it.
12352     *
12353     * @see #getDrawableState()
12354     * @see #isDuplicateParentStateEnabled()
12355     */
12356    public void setDuplicateParentStateEnabled(boolean enabled) {
12357        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12358    }
12359
12360    /**
12361     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12362     *
12363     * @return True if this view's drawable state is duplicated from the parent,
12364     *         false otherwise
12365     *
12366     * @see #getDrawableState()
12367     * @see #setDuplicateParentStateEnabled(boolean)
12368     */
12369    public boolean isDuplicateParentStateEnabled() {
12370        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12371    }
12372
12373    /**
12374     * <p>Specifies the type of layer backing this view. The layer can be
12375     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12376     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12377     *
12378     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12379     * instance that controls how the layer is composed on screen. The following
12380     * properties of the paint are taken into account when composing the layer:</p>
12381     * <ul>
12382     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12383     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12384     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12385     * </ul>
12386     *
12387     * <p>If this view has an alpha value set to < 1.0 by calling
12388     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12389     * by this view's alpha value.</p>
12390     *
12391     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12392     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12393     * for more information on when and how to use layers.</p>
12394     *
12395     * @param layerType The type of layer to use with this view, must be one of
12396     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12397     *        {@link #LAYER_TYPE_HARDWARE}
12398     * @param paint The paint used to compose the layer. This argument is optional
12399     *        and can be null. It is ignored when the layer type is
12400     *        {@link #LAYER_TYPE_NONE}
12401     *
12402     * @see #getLayerType()
12403     * @see #LAYER_TYPE_NONE
12404     * @see #LAYER_TYPE_SOFTWARE
12405     * @see #LAYER_TYPE_HARDWARE
12406     * @see #setAlpha(float)
12407     *
12408     * @attr ref android.R.styleable#View_layerType
12409     */
12410    public void setLayerType(int layerType, Paint paint) {
12411        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12412            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12413                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12414        }
12415
12416        if (layerType == mLayerType) {
12417            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12418                mLayerPaint = paint == null ? new Paint() : paint;
12419                invalidateParentCaches();
12420                invalidate(true);
12421            }
12422            return;
12423        }
12424
12425        // Destroy any previous software drawing cache if needed
12426        switch (mLayerType) {
12427            case LAYER_TYPE_HARDWARE:
12428                destroyLayer(false);
12429                // fall through - non-accelerated views may use software layer mechanism instead
12430            case LAYER_TYPE_SOFTWARE:
12431                destroyDrawingCache();
12432                break;
12433            default:
12434                break;
12435        }
12436
12437        mLayerType = layerType;
12438        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12439        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12440        mLocalDirtyRect = layerDisabled ? null : new Rect();
12441
12442        invalidateParentCaches();
12443        invalidate(true);
12444    }
12445
12446    /**
12447     * Updates the {@link Paint} object used with the current layer (used only if the current
12448     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12449     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12450     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12451     * ensure that the view gets redrawn immediately.
12452     *
12453     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12454     * instance that controls how the layer is composed on screen. The following
12455     * properties of the paint are taken into account when composing the layer:</p>
12456     * <ul>
12457     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12458     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12459     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12460     * </ul>
12461     *
12462     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12463     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12464     *
12465     * @param paint The paint used to compose the layer. This argument is optional
12466     *        and can be null. It is ignored when the layer type is
12467     *        {@link #LAYER_TYPE_NONE}
12468     *
12469     * @see #setLayerType(int, android.graphics.Paint)
12470     */
12471    public void setLayerPaint(Paint paint) {
12472        int layerType = getLayerType();
12473        if (layerType != LAYER_TYPE_NONE) {
12474            mLayerPaint = paint == null ? new Paint() : paint;
12475            if (layerType == LAYER_TYPE_HARDWARE) {
12476                HardwareLayer layer = getHardwareLayer();
12477                if (layer != null) {
12478                    layer.setLayerPaint(paint);
12479                }
12480                invalidateViewProperty(false, false);
12481            } else {
12482                invalidate();
12483            }
12484        }
12485    }
12486
12487    /**
12488     * Indicates whether this view has a static layer. A view with layer type
12489     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12490     * dynamic.
12491     */
12492    boolean hasStaticLayer() {
12493        return true;
12494    }
12495
12496    /**
12497     * Indicates what type of layer is currently associated with this view. By default
12498     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12499     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12500     * for more information on the different types of layers.
12501     *
12502     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12503     *         {@link #LAYER_TYPE_HARDWARE}
12504     *
12505     * @see #setLayerType(int, android.graphics.Paint)
12506     * @see #buildLayer()
12507     * @see #LAYER_TYPE_NONE
12508     * @see #LAYER_TYPE_SOFTWARE
12509     * @see #LAYER_TYPE_HARDWARE
12510     */
12511    public int getLayerType() {
12512        return mLayerType;
12513    }
12514
12515    /**
12516     * Forces this view's layer to be created and this view to be rendered
12517     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12518     * invoking this method will have no effect.
12519     *
12520     * This method can for instance be used to render a view into its layer before
12521     * starting an animation. If this view is complex, rendering into the layer
12522     * before starting the animation will avoid skipping frames.
12523     *
12524     * @throws IllegalStateException If this view is not attached to a window
12525     *
12526     * @see #setLayerType(int, android.graphics.Paint)
12527     */
12528    public void buildLayer() {
12529        if (mLayerType == LAYER_TYPE_NONE) return;
12530
12531        if (mAttachInfo == null) {
12532            throw new IllegalStateException("This view must be attached to a window first");
12533        }
12534
12535        switch (mLayerType) {
12536            case LAYER_TYPE_HARDWARE:
12537                if (mAttachInfo.mHardwareRenderer != null &&
12538                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12539                        mAttachInfo.mHardwareRenderer.validate()) {
12540                    getHardwareLayer();
12541                }
12542                break;
12543            case LAYER_TYPE_SOFTWARE:
12544                buildDrawingCache(true);
12545                break;
12546        }
12547    }
12548
12549    /**
12550     * <p>Returns a hardware layer that can be used to draw this view again
12551     * without executing its draw method.</p>
12552     *
12553     * @return A HardwareLayer ready to render, or null if an error occurred.
12554     */
12555    HardwareLayer getHardwareLayer() {
12556        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12557                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12558            return null;
12559        }
12560
12561        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12562
12563        final int width = mRight - mLeft;
12564        final int height = mBottom - mTop;
12565
12566        if (width == 0 || height == 0) {
12567            return null;
12568        }
12569
12570        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12571            if (mHardwareLayer == null) {
12572                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12573                        width, height, isOpaque());
12574                mLocalDirtyRect.set(0, 0, width, height);
12575            } else {
12576                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12577                    if (mHardwareLayer.resize(width, height)) {
12578                        mLocalDirtyRect.set(0, 0, width, height);
12579                    }
12580                }
12581
12582                // This should not be necessary but applications that change
12583                // the parameters of their background drawable without calling
12584                // this.setBackground(Drawable) can leave the view in a bad state
12585                // (for instance isOpaque() returns true, but the background is
12586                // not opaque.)
12587                computeOpaqueFlags();
12588
12589                final boolean opaque = isOpaque();
12590                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12591                    mHardwareLayer.setOpaque(opaque);
12592                    mLocalDirtyRect.set(0, 0, width, height);
12593                }
12594            }
12595
12596            // The layer is not valid if the underlying GPU resources cannot be allocated
12597            if (!mHardwareLayer.isValid()) {
12598                return null;
12599            }
12600
12601            mHardwareLayer.setLayerPaint(mLayerPaint);
12602            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12603            ViewRootImpl viewRoot = getViewRootImpl();
12604            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12605
12606            mLocalDirtyRect.setEmpty();
12607        }
12608
12609        return mHardwareLayer;
12610    }
12611
12612    /**
12613     * Destroys this View's hardware layer if possible.
12614     *
12615     * @return True if the layer was destroyed, false otherwise.
12616     *
12617     * @see #setLayerType(int, android.graphics.Paint)
12618     * @see #LAYER_TYPE_HARDWARE
12619     */
12620    boolean destroyLayer(boolean valid) {
12621        if (mHardwareLayer != null) {
12622            AttachInfo info = mAttachInfo;
12623            if (info != null && info.mHardwareRenderer != null &&
12624                    info.mHardwareRenderer.isEnabled() &&
12625                    (valid || info.mHardwareRenderer.validate())) {
12626                mHardwareLayer.destroy();
12627                mHardwareLayer = null;
12628
12629                if (mDisplayList != null) {
12630                    mDisplayList.reset();
12631                }
12632                invalidate(true);
12633                invalidateParentCaches();
12634            }
12635            return true;
12636        }
12637        return false;
12638    }
12639
12640    /**
12641     * Destroys all hardware rendering resources. This method is invoked
12642     * when the system needs to reclaim resources. Upon execution of this
12643     * method, you should free any OpenGL resources created by the view.
12644     *
12645     * Note: you <strong>must</strong> call
12646     * <code>super.destroyHardwareResources()</code> when overriding
12647     * this method.
12648     *
12649     * @hide
12650     */
12651    protected void destroyHardwareResources() {
12652        destroyLayer(true);
12653    }
12654
12655    /**
12656     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12657     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12658     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12659     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12660     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12661     * null.</p>
12662     *
12663     * <p>Enabling the drawing cache is similar to
12664     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12665     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12666     * drawing cache has no effect on rendering because the system uses a different mechanism
12667     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12668     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12669     * for information on how to enable software and hardware layers.</p>
12670     *
12671     * <p>This API can be used to manually generate
12672     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12673     * {@link #getDrawingCache()}.</p>
12674     *
12675     * @param enabled true to enable the drawing cache, false otherwise
12676     *
12677     * @see #isDrawingCacheEnabled()
12678     * @see #getDrawingCache()
12679     * @see #buildDrawingCache()
12680     * @see #setLayerType(int, android.graphics.Paint)
12681     */
12682    public void setDrawingCacheEnabled(boolean enabled) {
12683        mCachingFailed = false;
12684        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12685    }
12686
12687    /**
12688     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12689     *
12690     * @return true if the drawing cache is enabled
12691     *
12692     * @see #setDrawingCacheEnabled(boolean)
12693     * @see #getDrawingCache()
12694     */
12695    @ViewDebug.ExportedProperty(category = "drawing")
12696    public boolean isDrawingCacheEnabled() {
12697        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12698    }
12699
12700    /**
12701     * Debugging utility which recursively outputs the dirty state of a view and its
12702     * descendants.
12703     *
12704     * @hide
12705     */
12706    @SuppressWarnings({"UnusedDeclaration"})
12707    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12708        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12709                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12710                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12711                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12712        if (clear) {
12713            mPrivateFlags &= clearMask;
12714        }
12715        if (this instanceof ViewGroup) {
12716            ViewGroup parent = (ViewGroup) this;
12717            final int count = parent.getChildCount();
12718            for (int i = 0; i < count; i++) {
12719                final View child = parent.getChildAt(i);
12720                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12721            }
12722        }
12723    }
12724
12725    /**
12726     * This method is used by ViewGroup to cause its children to restore or recreate their
12727     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12728     * to recreate its own display list, which would happen if it went through the normal
12729     * draw/dispatchDraw mechanisms.
12730     *
12731     * @hide
12732     */
12733    protected void dispatchGetDisplayList() {}
12734
12735    /**
12736     * A view that is not attached or hardware accelerated cannot create a display list.
12737     * This method checks these conditions and returns the appropriate result.
12738     *
12739     * @return true if view has the ability to create a display list, false otherwise.
12740     *
12741     * @hide
12742     */
12743    public boolean canHaveDisplayList() {
12744        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12745    }
12746
12747    /**
12748     * @return The {@link HardwareRenderer} associated with that view or null if
12749     *         hardware rendering is not supported or this view is not attached
12750     *         to a window.
12751     *
12752     * @hide
12753     */
12754    public HardwareRenderer getHardwareRenderer() {
12755        if (mAttachInfo != null) {
12756            return mAttachInfo.mHardwareRenderer;
12757        }
12758        return null;
12759    }
12760
12761    /**
12762     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12763     * Otherwise, the same display list will be returned (after having been rendered into
12764     * along the way, depending on the invalidation state of the view).
12765     *
12766     * @param displayList The previous version of this displayList, could be null.
12767     * @param isLayer Whether the requester of the display list is a layer. If so,
12768     * the view will avoid creating a layer inside the resulting display list.
12769     * @return A new or reused DisplayList object.
12770     */
12771    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12772        if (!canHaveDisplayList()) {
12773            return null;
12774        }
12775
12776        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12777                displayList == null || !displayList.isValid() ||
12778                (!isLayer && mRecreateDisplayList))) {
12779            // Don't need to recreate the display list, just need to tell our
12780            // children to restore/recreate theirs
12781            if (displayList != null && displayList.isValid() &&
12782                    !isLayer && !mRecreateDisplayList) {
12783                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12784                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12785                dispatchGetDisplayList();
12786
12787                return displayList;
12788            }
12789
12790            if (!isLayer) {
12791                // If we got here, we're recreating it. Mark it as such to ensure that
12792                // we copy in child display lists into ours in drawChild()
12793                mRecreateDisplayList = true;
12794            }
12795            if (displayList == null) {
12796                final String name = getClass().getSimpleName();
12797                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12798                // If we're creating a new display list, make sure our parent gets invalidated
12799                // since they will need to recreate their display list to account for this
12800                // new child display list.
12801                invalidateParentCaches();
12802            }
12803
12804            boolean caching = false;
12805            int width = mRight - mLeft;
12806            int height = mBottom - mTop;
12807            int layerType = getLayerType();
12808
12809            final HardwareCanvas canvas = displayList.start(width, height);
12810
12811            try {
12812                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12813                    if (layerType == LAYER_TYPE_HARDWARE) {
12814                        final HardwareLayer layer = getHardwareLayer();
12815                        if (layer != null && layer.isValid()) {
12816                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12817                        } else {
12818                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12819                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12820                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12821                        }
12822                        caching = true;
12823                    } else {
12824                        buildDrawingCache(true);
12825                        Bitmap cache = getDrawingCache(true);
12826                        if (cache != null) {
12827                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12828                            caching = true;
12829                        }
12830                    }
12831                } else {
12832
12833                    computeScroll();
12834
12835                    canvas.translate(-mScrollX, -mScrollY);
12836                    if (!isLayer) {
12837                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12838                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12839                    }
12840
12841                    // Fast path for layouts with no backgrounds
12842                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12843                        dispatchDraw(canvas);
12844                        if (mOverlay != null && !mOverlay.isEmpty()) {
12845                            mOverlay.getOverlayView().draw(canvas);
12846                        }
12847                    } else {
12848                        draw(canvas);
12849                    }
12850                }
12851            } finally {
12852                displayList.end();
12853                displayList.setCaching(caching);
12854                if (isLayer) {
12855                    displayList.setLeftTopRightBottom(0, 0, width, height);
12856                } else {
12857                    setDisplayListProperties(displayList);
12858                }
12859            }
12860        } else if (!isLayer) {
12861            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12862            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12863        }
12864
12865        return displayList;
12866    }
12867
12868    /**
12869     * Get the DisplayList for the HardwareLayer
12870     *
12871     * @param layer The HardwareLayer whose DisplayList we want
12872     * @return A DisplayList fopr the specified HardwareLayer
12873     */
12874    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12875        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12876        layer.setDisplayList(displayList);
12877        return displayList;
12878    }
12879
12880
12881    /**
12882     * <p>Returns a display list that can be used to draw this view again
12883     * without executing its draw method.</p>
12884     *
12885     * @return A DisplayList ready to replay, or null if caching is not enabled.
12886     *
12887     * @hide
12888     */
12889    public DisplayList getDisplayList() {
12890        mDisplayList = getDisplayList(mDisplayList, false);
12891        return mDisplayList;
12892    }
12893
12894    private void clearDisplayList() {
12895        if (mDisplayList != null) {
12896            mDisplayList.clear();
12897        }
12898    }
12899
12900    /**
12901     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12902     *
12903     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12904     *
12905     * @see #getDrawingCache(boolean)
12906     */
12907    public Bitmap getDrawingCache() {
12908        return getDrawingCache(false);
12909    }
12910
12911    /**
12912     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12913     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12914     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12915     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12916     * request the drawing cache by calling this method and draw it on screen if the
12917     * returned bitmap is not null.</p>
12918     *
12919     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12920     * this method will create a bitmap of the same size as this view. Because this bitmap
12921     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12922     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12923     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12924     * size than the view. This implies that your application must be able to handle this
12925     * size.</p>
12926     *
12927     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12928     *        the current density of the screen when the application is in compatibility
12929     *        mode.
12930     *
12931     * @return A bitmap representing this view or null if cache is disabled.
12932     *
12933     * @see #setDrawingCacheEnabled(boolean)
12934     * @see #isDrawingCacheEnabled()
12935     * @see #buildDrawingCache(boolean)
12936     * @see #destroyDrawingCache()
12937     */
12938    public Bitmap getDrawingCache(boolean autoScale) {
12939        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12940            return null;
12941        }
12942        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12943            buildDrawingCache(autoScale);
12944        }
12945        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12946    }
12947
12948    /**
12949     * <p>Frees the resources used by the drawing cache. If you call
12950     * {@link #buildDrawingCache()} manually without calling
12951     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12952     * should cleanup the cache with this method afterwards.</p>
12953     *
12954     * @see #setDrawingCacheEnabled(boolean)
12955     * @see #buildDrawingCache()
12956     * @see #getDrawingCache()
12957     */
12958    public void destroyDrawingCache() {
12959        if (mDrawingCache != null) {
12960            mDrawingCache.recycle();
12961            mDrawingCache = null;
12962        }
12963        if (mUnscaledDrawingCache != null) {
12964            mUnscaledDrawingCache.recycle();
12965            mUnscaledDrawingCache = null;
12966        }
12967    }
12968
12969    /**
12970     * Setting a solid background color for the drawing cache's bitmaps will improve
12971     * performance and memory usage. Note, though that this should only be used if this
12972     * view will always be drawn on top of a solid color.
12973     *
12974     * @param color The background color to use for the drawing cache's bitmap
12975     *
12976     * @see #setDrawingCacheEnabled(boolean)
12977     * @see #buildDrawingCache()
12978     * @see #getDrawingCache()
12979     */
12980    public void setDrawingCacheBackgroundColor(int color) {
12981        if (color != mDrawingCacheBackgroundColor) {
12982            mDrawingCacheBackgroundColor = color;
12983            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12984        }
12985    }
12986
12987    /**
12988     * @see #setDrawingCacheBackgroundColor(int)
12989     *
12990     * @return The background color to used for the drawing cache's bitmap
12991     */
12992    public int getDrawingCacheBackgroundColor() {
12993        return mDrawingCacheBackgroundColor;
12994    }
12995
12996    /**
12997     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12998     *
12999     * @see #buildDrawingCache(boolean)
13000     */
13001    public void buildDrawingCache() {
13002        buildDrawingCache(false);
13003    }
13004
13005    /**
13006     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13007     *
13008     * <p>If you call {@link #buildDrawingCache()} manually without calling
13009     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13010     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13011     *
13012     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13013     * this method will create a bitmap of the same size as this view. Because this bitmap
13014     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13015     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13016     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13017     * size than the view. This implies that your application must be able to handle this
13018     * size.</p>
13019     *
13020     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13021     * you do not need the drawing cache bitmap, calling this method will increase memory
13022     * usage and cause the view to be rendered in software once, thus negatively impacting
13023     * performance.</p>
13024     *
13025     * @see #getDrawingCache()
13026     * @see #destroyDrawingCache()
13027     */
13028    public void buildDrawingCache(boolean autoScale) {
13029        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13030                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13031            mCachingFailed = false;
13032
13033            int width = mRight - mLeft;
13034            int height = mBottom - mTop;
13035
13036            final AttachInfo attachInfo = mAttachInfo;
13037            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13038
13039            if (autoScale && scalingRequired) {
13040                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13041                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13042            }
13043
13044            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13045            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13046            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13047
13048            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13049            final long drawingCacheSize =
13050                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13051            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13052                if (width > 0 && height > 0) {
13053                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13054                            + projectedBitmapSize + " bytes, only "
13055                            + drawingCacheSize + " available");
13056                }
13057                destroyDrawingCache();
13058                mCachingFailed = true;
13059                return;
13060            }
13061
13062            boolean clear = true;
13063            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13064
13065            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13066                Bitmap.Config quality;
13067                if (!opaque) {
13068                    // Never pick ARGB_4444 because it looks awful
13069                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13070                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13071                        case DRAWING_CACHE_QUALITY_AUTO:
13072                            quality = Bitmap.Config.ARGB_8888;
13073                            break;
13074                        case DRAWING_CACHE_QUALITY_LOW:
13075                            quality = Bitmap.Config.ARGB_8888;
13076                            break;
13077                        case DRAWING_CACHE_QUALITY_HIGH:
13078                            quality = Bitmap.Config.ARGB_8888;
13079                            break;
13080                        default:
13081                            quality = Bitmap.Config.ARGB_8888;
13082                            break;
13083                    }
13084                } else {
13085                    // Optimization for translucent windows
13086                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13087                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13088                }
13089
13090                // Try to cleanup memory
13091                if (bitmap != null) bitmap.recycle();
13092
13093                try {
13094                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13095                            width, height, quality);
13096                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13097                    if (autoScale) {
13098                        mDrawingCache = bitmap;
13099                    } else {
13100                        mUnscaledDrawingCache = bitmap;
13101                    }
13102                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13103                } catch (OutOfMemoryError e) {
13104                    // If there is not enough memory to create the bitmap cache, just
13105                    // ignore the issue as bitmap caches are not required to draw the
13106                    // view hierarchy
13107                    if (autoScale) {
13108                        mDrawingCache = null;
13109                    } else {
13110                        mUnscaledDrawingCache = null;
13111                    }
13112                    mCachingFailed = true;
13113                    return;
13114                }
13115
13116                clear = drawingCacheBackgroundColor != 0;
13117            }
13118
13119            Canvas canvas;
13120            if (attachInfo != null) {
13121                canvas = attachInfo.mCanvas;
13122                if (canvas == null) {
13123                    canvas = new Canvas();
13124                }
13125                canvas.setBitmap(bitmap);
13126                // Temporarily clobber the cached Canvas in case one of our children
13127                // is also using a drawing cache. Without this, the children would
13128                // steal the canvas by attaching their own bitmap to it and bad, bad
13129                // thing would happen (invisible views, corrupted drawings, etc.)
13130                attachInfo.mCanvas = null;
13131            } else {
13132                // This case should hopefully never or seldom happen
13133                canvas = new Canvas(bitmap);
13134            }
13135
13136            if (clear) {
13137                bitmap.eraseColor(drawingCacheBackgroundColor);
13138            }
13139
13140            computeScroll();
13141            final int restoreCount = canvas.save();
13142
13143            if (autoScale && scalingRequired) {
13144                final float scale = attachInfo.mApplicationScale;
13145                canvas.scale(scale, scale);
13146            }
13147
13148            canvas.translate(-mScrollX, -mScrollY);
13149
13150            mPrivateFlags |= PFLAG_DRAWN;
13151            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13152                    mLayerType != LAYER_TYPE_NONE) {
13153                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13154            }
13155
13156            // Fast path for layouts with no backgrounds
13157            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13158                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13159                dispatchDraw(canvas);
13160                if (mOverlay != null && !mOverlay.isEmpty()) {
13161                    mOverlay.getOverlayView().draw(canvas);
13162                }
13163            } else {
13164                draw(canvas);
13165            }
13166
13167            canvas.restoreToCount(restoreCount);
13168            canvas.setBitmap(null);
13169
13170            if (attachInfo != null) {
13171                // Restore the cached Canvas for our siblings
13172                attachInfo.mCanvas = canvas;
13173            }
13174        }
13175    }
13176
13177    /**
13178     * Create a snapshot of the view into a bitmap.  We should probably make
13179     * some form of this public, but should think about the API.
13180     */
13181    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13182        int width = mRight - mLeft;
13183        int height = mBottom - mTop;
13184
13185        final AttachInfo attachInfo = mAttachInfo;
13186        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13187        width = (int) ((width * scale) + 0.5f);
13188        height = (int) ((height * scale) + 0.5f);
13189
13190        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13191                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13192        if (bitmap == null) {
13193            throw new OutOfMemoryError();
13194        }
13195
13196        Resources resources = getResources();
13197        if (resources != null) {
13198            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13199        }
13200
13201        Canvas canvas;
13202        if (attachInfo != null) {
13203            canvas = attachInfo.mCanvas;
13204            if (canvas == null) {
13205                canvas = new Canvas();
13206            }
13207            canvas.setBitmap(bitmap);
13208            // Temporarily clobber the cached Canvas in case one of our children
13209            // is also using a drawing cache. Without this, the children would
13210            // steal the canvas by attaching their own bitmap to it and bad, bad
13211            // things would happen (invisible views, corrupted drawings, etc.)
13212            attachInfo.mCanvas = null;
13213        } else {
13214            // This case should hopefully never or seldom happen
13215            canvas = new Canvas(bitmap);
13216        }
13217
13218        if ((backgroundColor & 0xff000000) != 0) {
13219            bitmap.eraseColor(backgroundColor);
13220        }
13221
13222        computeScroll();
13223        final int restoreCount = canvas.save();
13224        canvas.scale(scale, scale);
13225        canvas.translate(-mScrollX, -mScrollY);
13226
13227        // Temporarily remove the dirty mask
13228        int flags = mPrivateFlags;
13229        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13230
13231        // Fast path for layouts with no backgrounds
13232        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13233            dispatchDraw(canvas);
13234        } else {
13235            draw(canvas);
13236        }
13237
13238        mPrivateFlags = flags;
13239
13240        canvas.restoreToCount(restoreCount);
13241        canvas.setBitmap(null);
13242
13243        if (attachInfo != null) {
13244            // Restore the cached Canvas for our siblings
13245            attachInfo.mCanvas = canvas;
13246        }
13247
13248        return bitmap;
13249    }
13250
13251    /**
13252     * Indicates whether this View is currently in edit mode. A View is usually
13253     * in edit mode when displayed within a developer tool. For instance, if
13254     * this View is being drawn by a visual user interface builder, this method
13255     * should return true.
13256     *
13257     * Subclasses should check the return value of this method to provide
13258     * different behaviors if their normal behavior might interfere with the
13259     * host environment. For instance: the class spawns a thread in its
13260     * constructor, the drawing code relies on device-specific features, etc.
13261     *
13262     * This method is usually checked in the drawing code of custom widgets.
13263     *
13264     * @return True if this View is in edit mode, false otherwise.
13265     */
13266    public boolean isInEditMode() {
13267        return false;
13268    }
13269
13270    /**
13271     * If the View draws content inside its padding and enables fading edges,
13272     * it needs to support padding offsets. Padding offsets are added to the
13273     * fading edges to extend the length of the fade so that it covers pixels
13274     * drawn inside the padding.
13275     *
13276     * Subclasses of this class should override this method if they need
13277     * to draw content inside the padding.
13278     *
13279     * @return True if padding offset must be applied, false otherwise.
13280     *
13281     * @see #getLeftPaddingOffset()
13282     * @see #getRightPaddingOffset()
13283     * @see #getTopPaddingOffset()
13284     * @see #getBottomPaddingOffset()
13285     *
13286     * @since CURRENT
13287     */
13288    protected boolean isPaddingOffsetRequired() {
13289        return false;
13290    }
13291
13292    /**
13293     * Amount by which to extend the left fading region. Called only when
13294     * {@link #isPaddingOffsetRequired()} returns true.
13295     *
13296     * @return The left padding offset in pixels.
13297     *
13298     * @see #isPaddingOffsetRequired()
13299     *
13300     * @since CURRENT
13301     */
13302    protected int getLeftPaddingOffset() {
13303        return 0;
13304    }
13305
13306    /**
13307     * Amount by which to extend the right fading region. Called only when
13308     * {@link #isPaddingOffsetRequired()} returns true.
13309     *
13310     * @return The right padding offset in pixels.
13311     *
13312     * @see #isPaddingOffsetRequired()
13313     *
13314     * @since CURRENT
13315     */
13316    protected int getRightPaddingOffset() {
13317        return 0;
13318    }
13319
13320    /**
13321     * Amount by which to extend the top fading region. Called only when
13322     * {@link #isPaddingOffsetRequired()} returns true.
13323     *
13324     * @return The top padding offset in pixels.
13325     *
13326     * @see #isPaddingOffsetRequired()
13327     *
13328     * @since CURRENT
13329     */
13330    protected int getTopPaddingOffset() {
13331        return 0;
13332    }
13333
13334    /**
13335     * Amount by which to extend the bottom fading region. Called only when
13336     * {@link #isPaddingOffsetRequired()} returns true.
13337     *
13338     * @return The bottom padding offset in pixels.
13339     *
13340     * @see #isPaddingOffsetRequired()
13341     *
13342     * @since CURRENT
13343     */
13344    protected int getBottomPaddingOffset() {
13345        return 0;
13346    }
13347
13348    /**
13349     * @hide
13350     * @param offsetRequired
13351     */
13352    protected int getFadeTop(boolean offsetRequired) {
13353        int top = mPaddingTop;
13354        if (offsetRequired) top += getTopPaddingOffset();
13355        return top;
13356    }
13357
13358    /**
13359     * @hide
13360     * @param offsetRequired
13361     */
13362    protected int getFadeHeight(boolean offsetRequired) {
13363        int padding = mPaddingTop;
13364        if (offsetRequired) padding += getTopPaddingOffset();
13365        return mBottom - mTop - mPaddingBottom - padding;
13366    }
13367
13368    /**
13369     * <p>Indicates whether this view is attached to a hardware accelerated
13370     * window or not.</p>
13371     *
13372     * <p>Even if this method returns true, it does not mean that every call
13373     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13374     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13375     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13376     * window is hardware accelerated,
13377     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13378     * return false, and this method will return true.</p>
13379     *
13380     * @return True if the view is attached to a window and the window is
13381     *         hardware accelerated; false in any other case.
13382     */
13383    public boolean isHardwareAccelerated() {
13384        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13385    }
13386
13387    /**
13388     * Sets a rectangular area on this view to which the view will be clipped
13389     * it is drawn. Setting the value to null will remove the clip bounds
13390     * and the view will draw normally, using its full bounds.
13391     *
13392     * @param clipBounds The rectangular area, in the local coordinates of
13393     * this view, to which future drawing operations will be clipped.
13394     */
13395    public void setClipBounds(Rect clipBounds) {
13396        mClipBounds = clipBounds;
13397        if (clipBounds != null) {
13398            invalidate(clipBounds);
13399        } else {
13400            invalidate();
13401        }
13402    }
13403
13404    /**
13405     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13406     *
13407     * @return A copy of the current clip bounds if clip bounds are set,
13408     * otherwise null.
13409     */
13410    public Rect getClipBounds() {
13411        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13412    }
13413
13414    /**
13415     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13416     * case of an active Animation being run on the view.
13417     */
13418    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13419            Animation a, boolean scalingRequired) {
13420        Transformation invalidationTransform;
13421        final int flags = parent.mGroupFlags;
13422        final boolean initialized = a.isInitialized();
13423        if (!initialized) {
13424            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13425            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13426            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13427            onAnimationStart();
13428        }
13429
13430        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13431        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13432            if (parent.mInvalidationTransformation == null) {
13433                parent.mInvalidationTransformation = new Transformation();
13434            }
13435            invalidationTransform = parent.mInvalidationTransformation;
13436            a.getTransformation(drawingTime, invalidationTransform, 1f);
13437        } else {
13438            invalidationTransform = parent.mChildTransformation;
13439        }
13440
13441        if (more) {
13442            if (!a.willChangeBounds()) {
13443                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13444                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13445                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13446                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13447                    // The child need to draw an animation, potentially offscreen, so
13448                    // make sure we do not cancel invalidate requests
13449                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13450                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13451                }
13452            } else {
13453                if (parent.mInvalidateRegion == null) {
13454                    parent.mInvalidateRegion = new RectF();
13455                }
13456                final RectF region = parent.mInvalidateRegion;
13457                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13458                        invalidationTransform);
13459
13460                // The child need to draw an animation, potentially offscreen, so
13461                // make sure we do not cancel invalidate requests
13462                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13463
13464                final int left = mLeft + (int) region.left;
13465                final int top = mTop + (int) region.top;
13466                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13467                        top + (int) (region.height() + .5f));
13468            }
13469        }
13470        return more;
13471    }
13472
13473    /**
13474     * This method is called by getDisplayList() when a display list is created or re-rendered.
13475     * It sets or resets the current value of all properties on that display list (resetting is
13476     * necessary when a display list is being re-created, because we need to make sure that
13477     * previously-set transform values
13478     */
13479    void setDisplayListProperties(DisplayList displayList) {
13480        if (displayList != null) {
13481            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13482            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13483            if (mParent instanceof ViewGroup) {
13484                displayList.setClipChildren(
13485                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13486            }
13487            float alpha = 1;
13488            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13489                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13490                ViewGroup parentVG = (ViewGroup) mParent;
13491                final boolean hasTransform =
13492                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13493                if (hasTransform) {
13494                    Transformation transform = parentVG.mChildTransformation;
13495                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13496                    if (transformType != Transformation.TYPE_IDENTITY) {
13497                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13498                            alpha = transform.getAlpha();
13499                        }
13500                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13501                            displayList.setMatrix(transform.getMatrix());
13502                        }
13503                    }
13504                }
13505            }
13506            if (mTransformationInfo != null) {
13507                alpha *= mTransformationInfo.mAlpha;
13508                if (alpha < 1) {
13509                    final int multipliedAlpha = (int) (255 * alpha);
13510                    if (onSetAlpha(multipliedAlpha)) {
13511                        alpha = 1;
13512                    }
13513                }
13514                displayList.setTransformationInfo(alpha,
13515                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13516                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13517                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13518                        mTransformationInfo.mScaleY);
13519                if (mTransformationInfo.mCamera == null) {
13520                    mTransformationInfo.mCamera = new Camera();
13521                    mTransformationInfo.matrix3D = new Matrix();
13522                }
13523                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13524                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13525                    displayList.setPivotX(getPivotX());
13526                    displayList.setPivotY(getPivotY());
13527                }
13528            } else if (alpha < 1) {
13529                displayList.setAlpha(alpha);
13530            }
13531        }
13532    }
13533
13534    /**
13535     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13536     * This draw() method is an implementation detail and is not intended to be overridden or
13537     * to be called from anywhere else other than ViewGroup.drawChild().
13538     */
13539    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13540        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13541        boolean more = false;
13542        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13543        final int flags = parent.mGroupFlags;
13544
13545        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13546            parent.mChildTransformation.clear();
13547            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13548        }
13549
13550        Transformation transformToApply = null;
13551        boolean concatMatrix = false;
13552
13553        boolean scalingRequired = false;
13554        boolean caching;
13555        int layerType = getLayerType();
13556
13557        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13558        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13559                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13560            caching = true;
13561            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13562            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13563        } else {
13564            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13565        }
13566
13567        final Animation a = getAnimation();
13568        if (a != null) {
13569            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13570            concatMatrix = a.willChangeTransformationMatrix();
13571            if (concatMatrix) {
13572                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13573            }
13574            transformToApply = parent.mChildTransformation;
13575        } else {
13576            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13577                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13578                // No longer animating: clear out old animation matrix
13579                mDisplayList.setAnimationMatrix(null);
13580                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13581            }
13582            if (!useDisplayListProperties &&
13583                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13584                final boolean hasTransform =
13585                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13586                if (hasTransform) {
13587                    final int transformType = parent.mChildTransformation.getTransformationType();
13588                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13589                            parent.mChildTransformation : null;
13590                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13591                }
13592            }
13593        }
13594
13595        concatMatrix |= !childHasIdentityMatrix;
13596
13597        // Sets the flag as early as possible to allow draw() implementations
13598        // to call invalidate() successfully when doing animations
13599        mPrivateFlags |= PFLAG_DRAWN;
13600
13601        if (!concatMatrix &&
13602                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13603                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13604                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13605                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13606            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13607            return more;
13608        }
13609        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13610
13611        if (hardwareAccelerated) {
13612            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13613            // retain the flag's value temporarily in the mRecreateDisplayList flag
13614            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13615            mPrivateFlags &= ~PFLAG_INVALIDATED;
13616        }
13617
13618        DisplayList displayList = null;
13619        Bitmap cache = null;
13620        boolean hasDisplayList = false;
13621        if (caching) {
13622            if (!hardwareAccelerated) {
13623                if (layerType != LAYER_TYPE_NONE) {
13624                    layerType = LAYER_TYPE_SOFTWARE;
13625                    buildDrawingCache(true);
13626                }
13627                cache = getDrawingCache(true);
13628            } else {
13629                switch (layerType) {
13630                    case LAYER_TYPE_SOFTWARE:
13631                        if (useDisplayListProperties) {
13632                            hasDisplayList = canHaveDisplayList();
13633                        } else {
13634                            buildDrawingCache(true);
13635                            cache = getDrawingCache(true);
13636                        }
13637                        break;
13638                    case LAYER_TYPE_HARDWARE:
13639                        if (useDisplayListProperties) {
13640                            hasDisplayList = canHaveDisplayList();
13641                        }
13642                        break;
13643                    case LAYER_TYPE_NONE:
13644                        // Delay getting the display list until animation-driven alpha values are
13645                        // set up and possibly passed on to the view
13646                        hasDisplayList = canHaveDisplayList();
13647                        break;
13648                }
13649            }
13650        }
13651        useDisplayListProperties &= hasDisplayList;
13652        if (useDisplayListProperties) {
13653            displayList = getDisplayList();
13654            if (!displayList.isValid()) {
13655                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13656                // to getDisplayList(), the display list will be marked invalid and we should not
13657                // try to use it again.
13658                displayList = null;
13659                hasDisplayList = false;
13660                useDisplayListProperties = false;
13661            }
13662        }
13663
13664        int sx = 0;
13665        int sy = 0;
13666        if (!hasDisplayList) {
13667            computeScroll();
13668            sx = mScrollX;
13669            sy = mScrollY;
13670        }
13671
13672        final boolean hasNoCache = cache == null || hasDisplayList;
13673        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13674                layerType != LAYER_TYPE_HARDWARE;
13675
13676        int restoreTo = -1;
13677        if (!useDisplayListProperties || transformToApply != null) {
13678            restoreTo = canvas.save();
13679        }
13680        if (offsetForScroll) {
13681            canvas.translate(mLeft - sx, mTop - sy);
13682        } else {
13683            if (!useDisplayListProperties) {
13684                canvas.translate(mLeft, mTop);
13685            }
13686            if (scalingRequired) {
13687                if (useDisplayListProperties) {
13688                    // TODO: Might not need this if we put everything inside the DL
13689                    restoreTo = canvas.save();
13690                }
13691                // mAttachInfo cannot be null, otherwise scalingRequired == false
13692                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13693                canvas.scale(scale, scale);
13694            }
13695        }
13696
13697        float alpha = useDisplayListProperties ? 1 : getAlpha();
13698        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13699                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13700            if (transformToApply != null || !childHasIdentityMatrix) {
13701                int transX = 0;
13702                int transY = 0;
13703
13704                if (offsetForScroll) {
13705                    transX = -sx;
13706                    transY = -sy;
13707                }
13708
13709                if (transformToApply != null) {
13710                    if (concatMatrix) {
13711                        if (useDisplayListProperties) {
13712                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13713                        } else {
13714                            // Undo the scroll translation, apply the transformation matrix,
13715                            // then redo the scroll translate to get the correct result.
13716                            canvas.translate(-transX, -transY);
13717                            canvas.concat(transformToApply.getMatrix());
13718                            canvas.translate(transX, transY);
13719                        }
13720                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13721                    }
13722
13723                    float transformAlpha = transformToApply.getAlpha();
13724                    if (transformAlpha < 1) {
13725                        alpha *= transformAlpha;
13726                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13727                    }
13728                }
13729
13730                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13731                    canvas.translate(-transX, -transY);
13732                    canvas.concat(getMatrix());
13733                    canvas.translate(transX, transY);
13734                }
13735            }
13736
13737            // Deal with alpha if it is or used to be <1
13738            if (alpha < 1 ||
13739                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13740                if (alpha < 1) {
13741                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13742                } else {
13743                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13744                }
13745                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13746                if (hasNoCache) {
13747                    final int multipliedAlpha = (int) (255 * alpha);
13748                    if (!onSetAlpha(multipliedAlpha)) {
13749                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13750                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13751                                layerType != LAYER_TYPE_NONE) {
13752                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13753                        }
13754                        if (useDisplayListProperties) {
13755                            displayList.setAlpha(alpha * getAlpha());
13756                        } else  if (layerType == LAYER_TYPE_NONE) {
13757                            final int scrollX = hasDisplayList ? 0 : sx;
13758                            final int scrollY = hasDisplayList ? 0 : sy;
13759                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13760                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13761                        }
13762                    } else {
13763                        // Alpha is handled by the child directly, clobber the layer's alpha
13764                        mPrivateFlags |= PFLAG_ALPHA_SET;
13765                    }
13766                }
13767            }
13768        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13769            onSetAlpha(255);
13770            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13771        }
13772
13773        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13774                !useDisplayListProperties && layerType == LAYER_TYPE_NONE) {
13775            if (offsetForScroll) {
13776                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13777            } else {
13778                if (!scalingRequired || cache == null) {
13779                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13780                } else {
13781                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13782                }
13783            }
13784        }
13785
13786        if (!useDisplayListProperties && hasDisplayList) {
13787            displayList = getDisplayList();
13788            if (!displayList.isValid()) {
13789                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13790                // to getDisplayList(), the display list will be marked invalid and we should not
13791                // try to use it again.
13792                displayList = null;
13793                hasDisplayList = false;
13794            }
13795        }
13796
13797        if (hasNoCache) {
13798            boolean layerRendered = false;
13799            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13800                final HardwareLayer layer = getHardwareLayer();
13801                if (layer != null && layer.isValid()) {
13802                    mLayerPaint.setAlpha((int) (alpha * 255));
13803                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13804                    layerRendered = true;
13805                } else {
13806                    final int scrollX = hasDisplayList ? 0 : sx;
13807                    final int scrollY = hasDisplayList ? 0 : sy;
13808                    canvas.saveLayer(scrollX, scrollY,
13809                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13810                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13811                }
13812            }
13813
13814            if (!layerRendered) {
13815                if (!hasDisplayList) {
13816                    // Fast path for layouts with no backgrounds
13817                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13818                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13819                        dispatchDraw(canvas);
13820                    } else {
13821                        draw(canvas);
13822                    }
13823                } else {
13824                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13825                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13826                }
13827            }
13828        } else if (cache != null) {
13829            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13830            Paint cachePaint;
13831
13832            if (layerType == LAYER_TYPE_NONE) {
13833                cachePaint = parent.mCachePaint;
13834                if (cachePaint == null) {
13835                    cachePaint = new Paint();
13836                    cachePaint.setDither(false);
13837                    parent.mCachePaint = cachePaint;
13838                }
13839                if (alpha < 1) {
13840                    cachePaint.setAlpha((int) (alpha * 255));
13841                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13842                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13843                    cachePaint.setAlpha(255);
13844                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13845                }
13846            } else {
13847                cachePaint = mLayerPaint;
13848                cachePaint.setAlpha((int) (alpha * 255));
13849            }
13850            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13851        }
13852
13853        if (restoreTo >= 0) {
13854            canvas.restoreToCount(restoreTo);
13855        }
13856
13857        if (a != null && !more) {
13858            if (!hardwareAccelerated && !a.getFillAfter()) {
13859                onSetAlpha(255);
13860            }
13861            parent.finishAnimatingView(this, a);
13862        }
13863
13864        if (more && hardwareAccelerated) {
13865            // invalidation is the trigger to recreate display lists, so if we're using
13866            // display lists to render, force an invalidate to allow the animation to
13867            // continue drawing another frame
13868            parent.invalidate(true);
13869            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13870                // alpha animations should cause the child to recreate its display list
13871                invalidate(true);
13872            }
13873        }
13874
13875        mRecreateDisplayList = false;
13876
13877        return more;
13878    }
13879
13880    /**
13881     * Manually render this view (and all of its children) to the given Canvas.
13882     * The view must have already done a full layout before this function is
13883     * called.  When implementing a view, implement
13884     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13885     * If you do need to override this method, call the superclass version.
13886     *
13887     * @param canvas The Canvas to which the View is rendered.
13888     */
13889    public void draw(Canvas canvas) {
13890        if (mClipBounds != null) {
13891            canvas.clipRect(mClipBounds);
13892        }
13893        final int privateFlags = mPrivateFlags;
13894        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13895                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13896        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13897
13898        /*
13899         * Draw traversal performs several drawing steps which must be executed
13900         * in the appropriate order:
13901         *
13902         *      1. Draw the background
13903         *      2. If necessary, save the canvas' layers to prepare for fading
13904         *      3. Draw view's content
13905         *      4. Draw children
13906         *      5. If necessary, draw the fading edges and restore layers
13907         *      6. Draw decorations (scrollbars for instance)
13908         */
13909
13910        // Step 1, draw the background, if needed
13911        int saveCount;
13912
13913        if (!dirtyOpaque) {
13914            final Drawable background = mBackground;
13915            if (background != null) {
13916                final int scrollX = mScrollX;
13917                final int scrollY = mScrollY;
13918
13919                if (mBackgroundSizeChanged) {
13920                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13921                    mBackgroundSizeChanged = false;
13922                }
13923
13924                if ((scrollX | scrollY) == 0) {
13925                    background.draw(canvas);
13926                } else {
13927                    canvas.translate(scrollX, scrollY);
13928                    background.draw(canvas);
13929                    canvas.translate(-scrollX, -scrollY);
13930                }
13931            }
13932        }
13933
13934        // skip step 2 & 5 if possible (common case)
13935        final int viewFlags = mViewFlags;
13936        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13937        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13938        if (!verticalEdges && !horizontalEdges) {
13939            // Step 3, draw the content
13940            if (!dirtyOpaque) onDraw(canvas);
13941
13942            // Step 4, draw the children
13943            dispatchDraw(canvas);
13944
13945            // Step 6, draw decorations (scrollbars)
13946            onDrawScrollBars(canvas);
13947
13948            if (mOverlay != null && !mOverlay.isEmpty()) {
13949                mOverlay.getOverlayView().dispatchDraw(canvas);
13950            }
13951
13952            // we're done...
13953            return;
13954        }
13955
13956        /*
13957         * Here we do the full fledged routine...
13958         * (this is an uncommon case where speed matters less,
13959         * this is why we repeat some of the tests that have been
13960         * done above)
13961         */
13962
13963        boolean drawTop = false;
13964        boolean drawBottom = false;
13965        boolean drawLeft = false;
13966        boolean drawRight = false;
13967
13968        float topFadeStrength = 0.0f;
13969        float bottomFadeStrength = 0.0f;
13970        float leftFadeStrength = 0.0f;
13971        float rightFadeStrength = 0.0f;
13972
13973        // Step 2, save the canvas' layers
13974        int paddingLeft = mPaddingLeft;
13975
13976        final boolean offsetRequired = isPaddingOffsetRequired();
13977        if (offsetRequired) {
13978            paddingLeft += getLeftPaddingOffset();
13979        }
13980
13981        int left = mScrollX + paddingLeft;
13982        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13983        int top = mScrollY + getFadeTop(offsetRequired);
13984        int bottom = top + getFadeHeight(offsetRequired);
13985
13986        if (offsetRequired) {
13987            right += getRightPaddingOffset();
13988            bottom += getBottomPaddingOffset();
13989        }
13990
13991        final ScrollabilityCache scrollabilityCache = mScrollCache;
13992        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13993        int length = (int) fadeHeight;
13994
13995        // clip the fade length if top and bottom fades overlap
13996        // overlapping fades produce odd-looking artifacts
13997        if (verticalEdges && (top + length > bottom - length)) {
13998            length = (bottom - top) / 2;
13999        }
14000
14001        // also clip horizontal fades if necessary
14002        if (horizontalEdges && (left + length > right - length)) {
14003            length = (right - left) / 2;
14004        }
14005
14006        if (verticalEdges) {
14007            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14008            drawTop = topFadeStrength * fadeHeight > 1.0f;
14009            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14010            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14011        }
14012
14013        if (horizontalEdges) {
14014            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14015            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14016            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14017            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14018        }
14019
14020        saveCount = canvas.getSaveCount();
14021
14022        int solidColor = getSolidColor();
14023        if (solidColor == 0) {
14024            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14025
14026            if (drawTop) {
14027                canvas.saveLayer(left, top, right, top + length, null, flags);
14028            }
14029
14030            if (drawBottom) {
14031                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14032            }
14033
14034            if (drawLeft) {
14035                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14036            }
14037
14038            if (drawRight) {
14039                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14040            }
14041        } else {
14042            scrollabilityCache.setFadeColor(solidColor);
14043        }
14044
14045        // Step 3, draw the content
14046        if (!dirtyOpaque) onDraw(canvas);
14047
14048        // Step 4, draw the children
14049        dispatchDraw(canvas);
14050
14051        // Step 5, draw the fade effect and restore layers
14052        final Paint p = scrollabilityCache.paint;
14053        final Matrix matrix = scrollabilityCache.matrix;
14054        final Shader fade = scrollabilityCache.shader;
14055
14056        if (drawTop) {
14057            matrix.setScale(1, fadeHeight * topFadeStrength);
14058            matrix.postTranslate(left, top);
14059            fade.setLocalMatrix(matrix);
14060            canvas.drawRect(left, top, right, top + length, p);
14061        }
14062
14063        if (drawBottom) {
14064            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14065            matrix.postRotate(180);
14066            matrix.postTranslate(left, bottom);
14067            fade.setLocalMatrix(matrix);
14068            canvas.drawRect(left, bottom - length, right, bottom, p);
14069        }
14070
14071        if (drawLeft) {
14072            matrix.setScale(1, fadeHeight * leftFadeStrength);
14073            matrix.postRotate(-90);
14074            matrix.postTranslate(left, top);
14075            fade.setLocalMatrix(matrix);
14076            canvas.drawRect(left, top, left + length, bottom, p);
14077        }
14078
14079        if (drawRight) {
14080            matrix.setScale(1, fadeHeight * rightFadeStrength);
14081            matrix.postRotate(90);
14082            matrix.postTranslate(right, top);
14083            fade.setLocalMatrix(matrix);
14084            canvas.drawRect(right - length, top, right, bottom, p);
14085        }
14086
14087        canvas.restoreToCount(saveCount);
14088
14089        // Step 6, draw decorations (scrollbars)
14090        onDrawScrollBars(canvas);
14091
14092        if (mOverlay != null && !mOverlay.isEmpty()) {
14093            mOverlay.getOverlayView().dispatchDraw(canvas);
14094        }
14095    }
14096
14097    /**
14098     * Returns the overlay for this view, creating it if it does not yet exist.
14099     * Adding drawables to the overlay will cause them to be displayed whenever
14100     * the view itself is redrawn. Objects in the overlay should be actively
14101     * managed: remove them when they should not be displayed anymore. The
14102     * overlay will always have the same size as its host view.
14103     *
14104     * <p>Note: Overlays do not currently work correctly with {@link
14105     * SurfaceView} or {@link TextureView}; contents in overlays for these
14106     * types of views may not display correctly.</p>
14107     *
14108     * @return The ViewOverlay object for this view.
14109     * @see ViewOverlay
14110     */
14111    public ViewOverlay getOverlay() {
14112        if (mOverlay == null) {
14113            mOverlay = new ViewOverlay(mContext, this);
14114        }
14115        return mOverlay;
14116    }
14117
14118    /**
14119     * Override this if your view is known to always be drawn on top of a solid color background,
14120     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14121     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14122     * should be set to 0xFF.
14123     *
14124     * @see #setVerticalFadingEdgeEnabled(boolean)
14125     * @see #setHorizontalFadingEdgeEnabled(boolean)
14126     *
14127     * @return The known solid color background for this view, or 0 if the color may vary
14128     */
14129    @ViewDebug.ExportedProperty(category = "drawing")
14130    public int getSolidColor() {
14131        return 0;
14132    }
14133
14134    /**
14135     * Build a human readable string representation of the specified view flags.
14136     *
14137     * @param flags the view flags to convert to a string
14138     * @return a String representing the supplied flags
14139     */
14140    private static String printFlags(int flags) {
14141        String output = "";
14142        int numFlags = 0;
14143        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14144            output += "TAKES_FOCUS";
14145            numFlags++;
14146        }
14147
14148        switch (flags & VISIBILITY_MASK) {
14149        case INVISIBLE:
14150            if (numFlags > 0) {
14151                output += " ";
14152            }
14153            output += "INVISIBLE";
14154            // USELESS HERE numFlags++;
14155            break;
14156        case GONE:
14157            if (numFlags > 0) {
14158                output += " ";
14159            }
14160            output += "GONE";
14161            // USELESS HERE numFlags++;
14162            break;
14163        default:
14164            break;
14165        }
14166        return output;
14167    }
14168
14169    /**
14170     * Build a human readable string representation of the specified private
14171     * view flags.
14172     *
14173     * @param privateFlags the private view flags to convert to a string
14174     * @return a String representing the supplied flags
14175     */
14176    private static String printPrivateFlags(int privateFlags) {
14177        String output = "";
14178        int numFlags = 0;
14179
14180        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14181            output += "WANTS_FOCUS";
14182            numFlags++;
14183        }
14184
14185        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14186            if (numFlags > 0) {
14187                output += " ";
14188            }
14189            output += "FOCUSED";
14190            numFlags++;
14191        }
14192
14193        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14194            if (numFlags > 0) {
14195                output += " ";
14196            }
14197            output += "SELECTED";
14198            numFlags++;
14199        }
14200
14201        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14202            if (numFlags > 0) {
14203                output += " ";
14204            }
14205            output += "IS_ROOT_NAMESPACE";
14206            numFlags++;
14207        }
14208
14209        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14210            if (numFlags > 0) {
14211                output += " ";
14212            }
14213            output += "HAS_BOUNDS";
14214            numFlags++;
14215        }
14216
14217        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14218            if (numFlags > 0) {
14219                output += " ";
14220            }
14221            output += "DRAWN";
14222            // USELESS HERE numFlags++;
14223        }
14224        return output;
14225    }
14226
14227    /**
14228     * <p>Indicates whether or not this view's layout will be requested during
14229     * the next hierarchy layout pass.</p>
14230     *
14231     * @return true if the layout will be forced during next layout pass
14232     */
14233    public boolean isLayoutRequested() {
14234        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14235    }
14236
14237    /**
14238     * Return true if o is a ViewGroup that is laying out using optical bounds.
14239     * @hide
14240     */
14241    public static boolean isLayoutModeOptical(Object o) {
14242        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14243    }
14244
14245    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14246        Insets parentInsets = mParent instanceof View ?
14247                ((View) mParent).getOpticalInsets() : Insets.NONE;
14248        Insets childInsets = getOpticalInsets();
14249        return setFrame(
14250                left   + parentInsets.left - childInsets.left,
14251                top    + parentInsets.top  - childInsets.top,
14252                right  + parentInsets.left + childInsets.right,
14253                bottom + parentInsets.top  + childInsets.bottom);
14254    }
14255
14256    /**
14257     * Assign a size and position to a view and all of its
14258     * descendants
14259     *
14260     * <p>This is the second phase of the layout mechanism.
14261     * (The first is measuring). In this phase, each parent calls
14262     * layout on all of its children to position them.
14263     * This is typically done using the child measurements
14264     * that were stored in the measure pass().</p>
14265     *
14266     * <p>Derived classes should not override this method.
14267     * Derived classes with children should override
14268     * onLayout. In that method, they should
14269     * call layout on each of their children.</p>
14270     *
14271     * @param l Left position, relative to parent
14272     * @param t Top position, relative to parent
14273     * @param r Right position, relative to parent
14274     * @param b Bottom position, relative to parent
14275     */
14276    @SuppressWarnings({"unchecked"})
14277    public void layout(int l, int t, int r, int b) {
14278        int oldL = mLeft;
14279        int oldT = mTop;
14280        int oldB = mBottom;
14281        int oldR = mRight;
14282        boolean changed = isLayoutModeOptical(mParent) ?
14283                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14284        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14285            onLayout(changed, l, t, r, b);
14286            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14287
14288            ListenerInfo li = mListenerInfo;
14289            if (li != null && li.mOnLayoutChangeListeners != null) {
14290                ArrayList<OnLayoutChangeListener> listenersCopy =
14291                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14292                int numListeners = listenersCopy.size();
14293                for (int i = 0; i < numListeners; ++i) {
14294                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14295                }
14296            }
14297        }
14298        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14299    }
14300
14301    /**
14302     * Called from layout when this view should
14303     * assign a size and position to each of its children.
14304     *
14305     * Derived classes with children should override
14306     * this method and call layout on each of
14307     * their children.
14308     * @param changed This is a new size or position for this view
14309     * @param left Left position, relative to parent
14310     * @param top Top position, relative to parent
14311     * @param right Right position, relative to parent
14312     * @param bottom Bottom position, relative to parent
14313     */
14314    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14315    }
14316
14317    /**
14318     * Assign a size and position to this view.
14319     *
14320     * This is called from layout.
14321     *
14322     * @param left Left position, relative to parent
14323     * @param top Top position, relative to parent
14324     * @param right Right position, relative to parent
14325     * @param bottom Bottom position, relative to parent
14326     * @return true if the new size and position are different than the
14327     *         previous ones
14328     * {@hide}
14329     */
14330    protected boolean setFrame(int left, int top, int right, int bottom) {
14331        boolean changed = false;
14332
14333        if (DBG) {
14334            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14335                    + right + "," + bottom + ")");
14336        }
14337
14338        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14339            changed = true;
14340
14341            // Remember our drawn bit
14342            int drawn = mPrivateFlags & PFLAG_DRAWN;
14343
14344            int oldWidth = mRight - mLeft;
14345            int oldHeight = mBottom - mTop;
14346            int newWidth = right - left;
14347            int newHeight = bottom - top;
14348            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14349
14350            // Invalidate our old position
14351            invalidate(sizeChanged);
14352
14353            mLeft = left;
14354            mTop = top;
14355            mRight = right;
14356            mBottom = bottom;
14357            if (mDisplayList != null) {
14358                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14359            }
14360
14361            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14362
14363
14364            if (sizeChanged) {
14365                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14366                    // A change in dimension means an auto-centered pivot point changes, too
14367                    if (mTransformationInfo != null) {
14368                        mTransformationInfo.mMatrixDirty = true;
14369                    }
14370                }
14371                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14372            }
14373
14374            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14375                // If we are visible, force the DRAWN bit to on so that
14376                // this invalidate will go through (at least to our parent).
14377                // This is because someone may have invalidated this view
14378                // before this call to setFrame came in, thereby clearing
14379                // the DRAWN bit.
14380                mPrivateFlags |= PFLAG_DRAWN;
14381                invalidate(sizeChanged);
14382                // parent display list may need to be recreated based on a change in the bounds
14383                // of any child
14384                invalidateParentCaches();
14385            }
14386
14387            // Reset drawn bit to original value (invalidate turns it off)
14388            mPrivateFlags |= drawn;
14389
14390            mBackgroundSizeChanged = true;
14391        }
14392        return changed;
14393    }
14394
14395    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14396        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14397        if (mOverlay != null) {
14398            mOverlay.getOverlayView().setRight(newWidth);
14399            mOverlay.getOverlayView().setBottom(newHeight);
14400        }
14401    }
14402
14403    /**
14404     * Finalize inflating a view from XML.  This is called as the last phase
14405     * of inflation, after all child views have been added.
14406     *
14407     * <p>Even if the subclass overrides onFinishInflate, they should always be
14408     * sure to call the super method, so that we get called.
14409     */
14410    protected void onFinishInflate() {
14411    }
14412
14413    /**
14414     * Returns the resources associated with this view.
14415     *
14416     * @return Resources object.
14417     */
14418    public Resources getResources() {
14419        return mResources;
14420    }
14421
14422    /**
14423     * Invalidates the specified Drawable.
14424     *
14425     * @param drawable the drawable to invalidate
14426     */
14427    public void invalidateDrawable(Drawable drawable) {
14428        if (verifyDrawable(drawable)) {
14429            final Rect dirty = drawable.getBounds();
14430            final int scrollX = mScrollX;
14431            final int scrollY = mScrollY;
14432
14433            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14434                    dirty.right + scrollX, dirty.bottom + scrollY);
14435        }
14436    }
14437
14438    /**
14439     * Schedules an action on a drawable to occur at a specified time.
14440     *
14441     * @param who the recipient of the action
14442     * @param what the action to run on the drawable
14443     * @param when the time at which the action must occur. Uses the
14444     *        {@link SystemClock#uptimeMillis} timebase.
14445     */
14446    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14447        if (verifyDrawable(who) && what != null) {
14448            final long delay = when - SystemClock.uptimeMillis();
14449            if (mAttachInfo != null) {
14450                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14451                        Choreographer.CALLBACK_ANIMATION, what, who,
14452                        Choreographer.subtractFrameDelay(delay));
14453            } else {
14454                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14455            }
14456        }
14457    }
14458
14459    /**
14460     * Cancels a scheduled action on a drawable.
14461     *
14462     * @param who the recipient of the action
14463     * @param what the action to cancel
14464     */
14465    public void unscheduleDrawable(Drawable who, Runnable what) {
14466        if (verifyDrawable(who) && what != null) {
14467            if (mAttachInfo != null) {
14468                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14469                        Choreographer.CALLBACK_ANIMATION, what, who);
14470            } else {
14471                ViewRootImpl.getRunQueue().removeCallbacks(what);
14472            }
14473        }
14474    }
14475
14476    /**
14477     * Unschedule any events associated with the given Drawable.  This can be
14478     * used when selecting a new Drawable into a view, so that the previous
14479     * one is completely unscheduled.
14480     *
14481     * @param who The Drawable to unschedule.
14482     *
14483     * @see #drawableStateChanged
14484     */
14485    public void unscheduleDrawable(Drawable who) {
14486        if (mAttachInfo != null && who != null) {
14487            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14488                    Choreographer.CALLBACK_ANIMATION, null, who);
14489        }
14490    }
14491
14492    /**
14493     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14494     * that the View directionality can and will be resolved before its Drawables.
14495     *
14496     * Will call {@link View#onResolveDrawables} when resolution is done.
14497     *
14498     * @hide
14499     */
14500    protected void resolveDrawables() {
14501        if (canResolveLayoutDirection()) {
14502            if (mBackground != null) {
14503                mBackground.setLayoutDirection(getLayoutDirection());
14504            }
14505            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14506            onResolveDrawables(getLayoutDirection());
14507        }
14508    }
14509
14510    /**
14511     * Called when layout direction has been resolved.
14512     *
14513     * The default implementation does nothing.
14514     *
14515     * @param layoutDirection The resolved layout direction.
14516     *
14517     * @see #LAYOUT_DIRECTION_LTR
14518     * @see #LAYOUT_DIRECTION_RTL
14519     *
14520     * @hide
14521     */
14522    public void onResolveDrawables(int layoutDirection) {
14523    }
14524
14525    /**
14526     * @hide
14527     */
14528    protected void resetResolvedDrawables() {
14529        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14530    }
14531
14532    private boolean isDrawablesResolved() {
14533        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14534    }
14535
14536    /**
14537     * If your view subclass is displaying its own Drawable objects, it should
14538     * override this function and return true for any Drawable it is
14539     * displaying.  This allows animations for those drawables to be
14540     * scheduled.
14541     *
14542     * <p>Be sure to call through to the super class when overriding this
14543     * function.
14544     *
14545     * @param who The Drawable to verify.  Return true if it is one you are
14546     *            displaying, else return the result of calling through to the
14547     *            super class.
14548     *
14549     * @return boolean If true than the Drawable is being displayed in the
14550     *         view; else false and it is not allowed to animate.
14551     *
14552     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14553     * @see #drawableStateChanged()
14554     */
14555    protected boolean verifyDrawable(Drawable who) {
14556        return who == mBackground;
14557    }
14558
14559    /**
14560     * This function is called whenever the state of the view changes in such
14561     * a way that it impacts the state of drawables being shown.
14562     *
14563     * <p>Be sure to call through to the superclass when overriding this
14564     * function.
14565     *
14566     * @see Drawable#setState(int[])
14567     */
14568    protected void drawableStateChanged() {
14569        Drawable d = mBackground;
14570        if (d != null && d.isStateful()) {
14571            d.setState(getDrawableState());
14572        }
14573    }
14574
14575    /**
14576     * Call this to force a view to update its drawable state. This will cause
14577     * drawableStateChanged to be called on this view. Views that are interested
14578     * in the new state should call getDrawableState.
14579     *
14580     * @see #drawableStateChanged
14581     * @see #getDrawableState
14582     */
14583    public void refreshDrawableState() {
14584        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14585        drawableStateChanged();
14586
14587        ViewParent parent = mParent;
14588        if (parent != null) {
14589            parent.childDrawableStateChanged(this);
14590        }
14591    }
14592
14593    /**
14594     * Return an array of resource IDs of the drawable states representing the
14595     * current state of the view.
14596     *
14597     * @return The current drawable state
14598     *
14599     * @see Drawable#setState(int[])
14600     * @see #drawableStateChanged()
14601     * @see #onCreateDrawableState(int)
14602     */
14603    public final int[] getDrawableState() {
14604        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14605            return mDrawableState;
14606        } else {
14607            mDrawableState = onCreateDrawableState(0);
14608            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14609            return mDrawableState;
14610        }
14611    }
14612
14613    /**
14614     * Generate the new {@link android.graphics.drawable.Drawable} state for
14615     * this view. This is called by the view
14616     * system when the cached Drawable state is determined to be invalid.  To
14617     * retrieve the current state, you should use {@link #getDrawableState}.
14618     *
14619     * @param extraSpace if non-zero, this is the number of extra entries you
14620     * would like in the returned array in which you can place your own
14621     * states.
14622     *
14623     * @return Returns an array holding the current {@link Drawable} state of
14624     * the view.
14625     *
14626     * @see #mergeDrawableStates(int[], int[])
14627     */
14628    protected int[] onCreateDrawableState(int extraSpace) {
14629        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14630                mParent instanceof View) {
14631            return ((View) mParent).onCreateDrawableState(extraSpace);
14632        }
14633
14634        int[] drawableState;
14635
14636        int privateFlags = mPrivateFlags;
14637
14638        int viewStateIndex = 0;
14639        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14640        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14641        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14642        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14643        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14644        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14645        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14646                HardwareRenderer.isAvailable()) {
14647            // This is set if HW acceleration is requested, even if the current
14648            // process doesn't allow it.  This is just to allow app preview
14649            // windows to better match their app.
14650            viewStateIndex |= VIEW_STATE_ACCELERATED;
14651        }
14652        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14653
14654        final int privateFlags2 = mPrivateFlags2;
14655        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14656        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14657
14658        drawableState = VIEW_STATE_SETS[viewStateIndex];
14659
14660        //noinspection ConstantIfStatement
14661        if (false) {
14662            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14663            Log.i("View", toString()
14664                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14665                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14666                    + " fo=" + hasFocus()
14667                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14668                    + " wf=" + hasWindowFocus()
14669                    + ": " + Arrays.toString(drawableState));
14670        }
14671
14672        if (extraSpace == 0) {
14673            return drawableState;
14674        }
14675
14676        final int[] fullState;
14677        if (drawableState != null) {
14678            fullState = new int[drawableState.length + extraSpace];
14679            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14680        } else {
14681            fullState = new int[extraSpace];
14682        }
14683
14684        return fullState;
14685    }
14686
14687    /**
14688     * Merge your own state values in <var>additionalState</var> into the base
14689     * state values <var>baseState</var> that were returned by
14690     * {@link #onCreateDrawableState(int)}.
14691     *
14692     * @param baseState The base state values returned by
14693     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14694     * own additional state values.
14695     *
14696     * @param additionalState The additional state values you would like
14697     * added to <var>baseState</var>; this array is not modified.
14698     *
14699     * @return As a convenience, the <var>baseState</var> array you originally
14700     * passed into the function is returned.
14701     *
14702     * @see #onCreateDrawableState(int)
14703     */
14704    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14705        final int N = baseState.length;
14706        int i = N - 1;
14707        while (i >= 0 && baseState[i] == 0) {
14708            i--;
14709        }
14710        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14711        return baseState;
14712    }
14713
14714    /**
14715     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14716     * on all Drawable objects associated with this view.
14717     */
14718    public void jumpDrawablesToCurrentState() {
14719        if (mBackground != null) {
14720            mBackground.jumpToCurrentState();
14721        }
14722    }
14723
14724    /**
14725     * Sets the background color for this view.
14726     * @param color the color of the background
14727     */
14728    @RemotableViewMethod
14729    public void setBackgroundColor(int color) {
14730        if (mBackground instanceof ColorDrawable) {
14731            ((ColorDrawable) mBackground.mutate()).setColor(color);
14732            computeOpaqueFlags();
14733            mBackgroundResource = 0;
14734        } else {
14735            setBackground(new ColorDrawable(color));
14736        }
14737    }
14738
14739    /**
14740     * Set the background to a given resource. The resource should refer to
14741     * a Drawable object or 0 to remove the background.
14742     * @param resid The identifier of the resource.
14743     *
14744     * @attr ref android.R.styleable#View_background
14745     */
14746    @RemotableViewMethod
14747    public void setBackgroundResource(int resid) {
14748        if (resid != 0 && resid == mBackgroundResource) {
14749            return;
14750        }
14751
14752        Drawable d= null;
14753        if (resid != 0) {
14754            d = mResources.getDrawable(resid);
14755        }
14756        setBackground(d);
14757
14758        mBackgroundResource = resid;
14759    }
14760
14761    /**
14762     * Set the background to a given Drawable, or remove the background. If the
14763     * background has padding, this View's padding is set to the background's
14764     * padding. However, when a background is removed, this View's padding isn't
14765     * touched. If setting the padding is desired, please use
14766     * {@link #setPadding(int, int, int, int)}.
14767     *
14768     * @param background The Drawable to use as the background, or null to remove the
14769     *        background
14770     */
14771    public void setBackground(Drawable background) {
14772        //noinspection deprecation
14773        setBackgroundDrawable(background);
14774    }
14775
14776    /**
14777     * @deprecated use {@link #setBackground(Drawable)} instead
14778     */
14779    @Deprecated
14780    public void setBackgroundDrawable(Drawable background) {
14781        computeOpaqueFlags();
14782
14783        if (background == mBackground) {
14784            return;
14785        }
14786
14787        boolean requestLayout = false;
14788
14789        mBackgroundResource = 0;
14790
14791        /*
14792         * Regardless of whether we're setting a new background or not, we want
14793         * to clear the previous drawable.
14794         */
14795        if (mBackground != null) {
14796            mBackground.setCallback(null);
14797            unscheduleDrawable(mBackground);
14798        }
14799
14800        if (background != null) {
14801            Rect padding = sThreadLocal.get();
14802            if (padding == null) {
14803                padding = new Rect();
14804                sThreadLocal.set(padding);
14805            }
14806            resetResolvedDrawables();
14807            background.setLayoutDirection(getLayoutDirection());
14808            if (background.getPadding(padding)) {
14809                resetResolvedPadding();
14810                switch (background.getLayoutDirection()) {
14811                    case LAYOUT_DIRECTION_RTL:
14812                        mUserPaddingLeftInitial = padding.right;
14813                        mUserPaddingRightInitial = padding.left;
14814                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14815                        break;
14816                    case LAYOUT_DIRECTION_LTR:
14817                    default:
14818                        mUserPaddingLeftInitial = padding.left;
14819                        mUserPaddingRightInitial = padding.right;
14820                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14821                }
14822            }
14823
14824            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14825            // if it has a different minimum size, we should layout again
14826            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14827                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14828                requestLayout = true;
14829            }
14830
14831            background.setCallback(this);
14832            if (background.isStateful()) {
14833                background.setState(getDrawableState());
14834            }
14835            background.setVisible(getVisibility() == VISIBLE, false);
14836            mBackground = background;
14837
14838            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14839                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14840                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14841                requestLayout = true;
14842            }
14843        } else {
14844            /* Remove the background */
14845            mBackground = null;
14846
14847            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14848                /*
14849                 * This view ONLY drew the background before and we're removing
14850                 * the background, so now it won't draw anything
14851                 * (hence we SKIP_DRAW)
14852                 */
14853                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14854                mPrivateFlags |= PFLAG_SKIP_DRAW;
14855            }
14856
14857            /*
14858             * When the background is set, we try to apply its padding to this
14859             * View. When the background is removed, we don't touch this View's
14860             * padding. This is noted in the Javadocs. Hence, we don't need to
14861             * requestLayout(), the invalidate() below is sufficient.
14862             */
14863
14864            // The old background's minimum size could have affected this
14865            // View's layout, so let's requestLayout
14866            requestLayout = true;
14867        }
14868
14869        computeOpaqueFlags();
14870
14871        if (requestLayout) {
14872            requestLayout();
14873        }
14874
14875        mBackgroundSizeChanged = true;
14876        invalidate(true);
14877    }
14878
14879    /**
14880     * Gets the background drawable
14881     *
14882     * @return The drawable used as the background for this view, if any.
14883     *
14884     * @see #setBackground(Drawable)
14885     *
14886     * @attr ref android.R.styleable#View_background
14887     */
14888    public Drawable getBackground() {
14889        return mBackground;
14890    }
14891
14892    /**
14893     * Sets the padding. The view may add on the space required to display
14894     * the scrollbars, depending on the style and visibility of the scrollbars.
14895     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14896     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14897     * from the values set in this call.
14898     *
14899     * @attr ref android.R.styleable#View_padding
14900     * @attr ref android.R.styleable#View_paddingBottom
14901     * @attr ref android.R.styleable#View_paddingLeft
14902     * @attr ref android.R.styleable#View_paddingRight
14903     * @attr ref android.R.styleable#View_paddingTop
14904     * @param left the left padding in pixels
14905     * @param top the top padding in pixels
14906     * @param right the right padding in pixels
14907     * @param bottom the bottom padding in pixels
14908     */
14909    public void setPadding(int left, int top, int right, int bottom) {
14910        resetResolvedPadding();
14911
14912        mUserPaddingStart = UNDEFINED_PADDING;
14913        mUserPaddingEnd = UNDEFINED_PADDING;
14914
14915        mUserPaddingLeftInitial = left;
14916        mUserPaddingRightInitial = right;
14917
14918        internalSetPadding(left, top, right, bottom);
14919    }
14920
14921    /**
14922     * @hide
14923     */
14924    protected void internalSetPadding(int left, int top, int right, int bottom) {
14925        mUserPaddingLeft = left;
14926        mUserPaddingRight = right;
14927        mUserPaddingBottom = bottom;
14928
14929        final int viewFlags = mViewFlags;
14930        boolean changed = false;
14931
14932        // Common case is there are no scroll bars.
14933        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14934            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14935                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14936                        ? 0 : getVerticalScrollbarWidth();
14937                switch (mVerticalScrollbarPosition) {
14938                    case SCROLLBAR_POSITION_DEFAULT:
14939                        if (isLayoutRtl()) {
14940                            left += offset;
14941                        } else {
14942                            right += offset;
14943                        }
14944                        break;
14945                    case SCROLLBAR_POSITION_RIGHT:
14946                        right += offset;
14947                        break;
14948                    case SCROLLBAR_POSITION_LEFT:
14949                        left += offset;
14950                        break;
14951                }
14952            }
14953            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14954                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14955                        ? 0 : getHorizontalScrollbarHeight();
14956            }
14957        }
14958
14959        if (mPaddingLeft != left) {
14960            changed = true;
14961            mPaddingLeft = left;
14962        }
14963        if (mPaddingTop != top) {
14964            changed = true;
14965            mPaddingTop = top;
14966        }
14967        if (mPaddingRight != right) {
14968            changed = true;
14969            mPaddingRight = right;
14970        }
14971        if (mPaddingBottom != bottom) {
14972            changed = true;
14973            mPaddingBottom = bottom;
14974        }
14975
14976        if (changed) {
14977            requestLayout();
14978        }
14979    }
14980
14981    /**
14982     * Sets the relative padding. The view may add on the space required to display
14983     * the scrollbars, depending on the style and visibility of the scrollbars.
14984     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14985     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14986     * from the values set in this call.
14987     *
14988     * @attr ref android.R.styleable#View_padding
14989     * @attr ref android.R.styleable#View_paddingBottom
14990     * @attr ref android.R.styleable#View_paddingStart
14991     * @attr ref android.R.styleable#View_paddingEnd
14992     * @attr ref android.R.styleable#View_paddingTop
14993     * @param start the start padding in pixels
14994     * @param top the top padding in pixels
14995     * @param end the end padding in pixels
14996     * @param bottom the bottom padding in pixels
14997     */
14998    public void setPaddingRelative(int start, int top, int end, int bottom) {
14999        resetResolvedPadding();
15000
15001        mUserPaddingStart = start;
15002        mUserPaddingEnd = end;
15003
15004        switch(getLayoutDirection()) {
15005            case LAYOUT_DIRECTION_RTL:
15006                mUserPaddingLeftInitial = end;
15007                mUserPaddingRightInitial = start;
15008                internalSetPadding(end, top, start, bottom);
15009                break;
15010            case LAYOUT_DIRECTION_LTR:
15011            default:
15012                mUserPaddingLeftInitial = start;
15013                mUserPaddingRightInitial = end;
15014                internalSetPadding(start, top, end, bottom);
15015        }
15016    }
15017
15018    /**
15019     * Returns the top padding of this view.
15020     *
15021     * @return the top padding in pixels
15022     */
15023    public int getPaddingTop() {
15024        return mPaddingTop;
15025    }
15026
15027    /**
15028     * Returns the bottom padding of this view. If there are inset and enabled
15029     * scrollbars, this value may include the space required to display the
15030     * scrollbars as well.
15031     *
15032     * @return the bottom padding in pixels
15033     */
15034    public int getPaddingBottom() {
15035        return mPaddingBottom;
15036    }
15037
15038    /**
15039     * Returns the left padding of this view. If there are inset and enabled
15040     * scrollbars, this value may include the space required to display the
15041     * scrollbars as well.
15042     *
15043     * @return the left padding in pixels
15044     */
15045    public int getPaddingLeft() {
15046        if (!isPaddingResolved()) {
15047            resolvePadding();
15048        }
15049        return mPaddingLeft;
15050    }
15051
15052    /**
15053     * Returns the start padding of this view depending on its resolved layout direction.
15054     * If there are inset and enabled scrollbars, this value may include the space
15055     * required to display the scrollbars as well.
15056     *
15057     * @return the start padding in pixels
15058     */
15059    public int getPaddingStart() {
15060        if (!isPaddingResolved()) {
15061            resolvePadding();
15062        }
15063        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15064                mPaddingRight : mPaddingLeft;
15065    }
15066
15067    /**
15068     * Returns the right padding of this view. If there are inset and enabled
15069     * scrollbars, this value may include the space required to display the
15070     * scrollbars as well.
15071     *
15072     * @return the right padding in pixels
15073     */
15074    public int getPaddingRight() {
15075        if (!isPaddingResolved()) {
15076            resolvePadding();
15077        }
15078        return mPaddingRight;
15079    }
15080
15081    /**
15082     * Returns the end padding of this view depending on its resolved layout direction.
15083     * If there are inset and enabled scrollbars, this value may include the space
15084     * required to display the scrollbars as well.
15085     *
15086     * @return the end padding in pixels
15087     */
15088    public int getPaddingEnd() {
15089        if (!isPaddingResolved()) {
15090            resolvePadding();
15091        }
15092        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15093                mPaddingLeft : mPaddingRight;
15094    }
15095
15096    /**
15097     * Return if the padding as been set thru relative values
15098     * {@link #setPaddingRelative(int, int, int, int)} or thru
15099     * @attr ref android.R.styleable#View_paddingStart or
15100     * @attr ref android.R.styleable#View_paddingEnd
15101     *
15102     * @return true if the padding is relative or false if it is not.
15103     */
15104    public boolean isPaddingRelative() {
15105        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15106    }
15107
15108    Insets computeOpticalInsets() {
15109        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15110    }
15111
15112    /**
15113     * @hide
15114     */
15115    public void resetPaddingToInitialValues() {
15116        if (isRtlCompatibilityMode()) {
15117            mPaddingLeft = mUserPaddingLeftInitial;
15118            mPaddingRight = mUserPaddingRightInitial;
15119            return;
15120        }
15121        if (isLayoutRtl()) {
15122            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15123            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15124        } else {
15125            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15126            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15127        }
15128    }
15129
15130    /**
15131     * @hide
15132     */
15133    public Insets getOpticalInsets() {
15134        if (mLayoutInsets == null) {
15135            mLayoutInsets = computeOpticalInsets();
15136        }
15137        return mLayoutInsets;
15138    }
15139
15140    /**
15141     * Changes the selection state of this view. A view can be selected or not.
15142     * Note that selection is not the same as focus. Views are typically
15143     * selected in the context of an AdapterView like ListView or GridView;
15144     * the selected view is the view that is highlighted.
15145     *
15146     * @param selected true if the view must be selected, false otherwise
15147     */
15148    public void setSelected(boolean selected) {
15149        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15150            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15151            if (!selected) resetPressedState();
15152            invalidate(true);
15153            refreshDrawableState();
15154            dispatchSetSelected(selected);
15155            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
15156                notifyAccessibilityStateChanged();
15157            }
15158        }
15159    }
15160
15161    /**
15162     * Dispatch setSelected to all of this View's children.
15163     *
15164     * @see #setSelected(boolean)
15165     *
15166     * @param selected The new selected state
15167     */
15168    protected void dispatchSetSelected(boolean selected) {
15169    }
15170
15171    /**
15172     * Indicates the selection state of this view.
15173     *
15174     * @return true if the view is selected, false otherwise
15175     */
15176    @ViewDebug.ExportedProperty
15177    public boolean isSelected() {
15178        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15179    }
15180
15181    /**
15182     * Changes the activated state of this view. A view can be activated or not.
15183     * Note that activation is not the same as selection.  Selection is
15184     * a transient property, representing the view (hierarchy) the user is
15185     * currently interacting with.  Activation is a longer-term state that the
15186     * user can move views in and out of.  For example, in a list view with
15187     * single or multiple selection enabled, the views in the current selection
15188     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15189     * here.)  The activated state is propagated down to children of the view it
15190     * is set on.
15191     *
15192     * @param activated true if the view must be activated, false otherwise
15193     */
15194    public void setActivated(boolean activated) {
15195        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15196            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15197            invalidate(true);
15198            refreshDrawableState();
15199            dispatchSetActivated(activated);
15200        }
15201    }
15202
15203    /**
15204     * Dispatch setActivated to all of this View's children.
15205     *
15206     * @see #setActivated(boolean)
15207     *
15208     * @param activated The new activated state
15209     */
15210    protected void dispatchSetActivated(boolean activated) {
15211    }
15212
15213    /**
15214     * Indicates the activation state of this view.
15215     *
15216     * @return true if the view is activated, false otherwise
15217     */
15218    @ViewDebug.ExportedProperty
15219    public boolean isActivated() {
15220        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15221    }
15222
15223    /**
15224     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15225     * observer can be used to get notifications when global events, like
15226     * layout, happen.
15227     *
15228     * The returned ViewTreeObserver observer is not guaranteed to remain
15229     * valid for the lifetime of this View. If the caller of this method keeps
15230     * a long-lived reference to ViewTreeObserver, it should always check for
15231     * the return value of {@link ViewTreeObserver#isAlive()}.
15232     *
15233     * @return The ViewTreeObserver for this view's hierarchy.
15234     */
15235    public ViewTreeObserver getViewTreeObserver() {
15236        if (mAttachInfo != null) {
15237            return mAttachInfo.mTreeObserver;
15238        }
15239        if (mFloatingTreeObserver == null) {
15240            mFloatingTreeObserver = new ViewTreeObserver();
15241        }
15242        return mFloatingTreeObserver;
15243    }
15244
15245    /**
15246     * <p>Finds the topmost view in the current view hierarchy.</p>
15247     *
15248     * @return the topmost view containing this view
15249     */
15250    public View getRootView() {
15251        if (mAttachInfo != null) {
15252            final View v = mAttachInfo.mRootView;
15253            if (v != null) {
15254                return v;
15255            }
15256        }
15257
15258        View parent = this;
15259
15260        while (parent.mParent != null && parent.mParent instanceof View) {
15261            parent = (View) parent.mParent;
15262        }
15263
15264        return parent;
15265    }
15266
15267    /**
15268     * <p>Computes the coordinates of this view on the screen. The argument
15269     * must be an array of two integers. After the method returns, the array
15270     * contains the x and y location in that order.</p>
15271     *
15272     * @param location an array of two integers in which to hold the coordinates
15273     */
15274    public void getLocationOnScreen(int[] location) {
15275        getLocationInWindow(location);
15276
15277        final AttachInfo info = mAttachInfo;
15278        if (info != null) {
15279            location[0] += info.mWindowLeft;
15280            location[1] += info.mWindowTop;
15281        }
15282    }
15283
15284    /**
15285     * <p>Computes the coordinates of this view in its window. The argument
15286     * must be an array of two integers. After the method returns, the array
15287     * contains the x and y location in that order.</p>
15288     *
15289     * @param location an array of two integers in which to hold the coordinates
15290     */
15291    public void getLocationInWindow(int[] location) {
15292        if (location == null || location.length < 2) {
15293            throw new IllegalArgumentException("location must be an array of two integers");
15294        }
15295
15296        if (mAttachInfo == null) {
15297            // When the view is not attached to a window, this method does not make sense
15298            location[0] = location[1] = 0;
15299            return;
15300        }
15301
15302        float[] position = mAttachInfo.mTmpTransformLocation;
15303        position[0] = position[1] = 0.0f;
15304
15305        if (!hasIdentityMatrix()) {
15306            getMatrix().mapPoints(position);
15307        }
15308
15309        position[0] += mLeft;
15310        position[1] += mTop;
15311
15312        ViewParent viewParent = mParent;
15313        while (viewParent instanceof View) {
15314            final View view = (View) viewParent;
15315
15316            position[0] -= view.mScrollX;
15317            position[1] -= view.mScrollY;
15318
15319            if (!view.hasIdentityMatrix()) {
15320                view.getMatrix().mapPoints(position);
15321            }
15322
15323            position[0] += view.mLeft;
15324            position[1] += view.mTop;
15325
15326            viewParent = view.mParent;
15327         }
15328
15329        if (viewParent instanceof ViewRootImpl) {
15330            // *cough*
15331            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15332            position[1] -= vr.mCurScrollY;
15333        }
15334
15335        location[0] = (int) (position[0] + 0.5f);
15336        location[1] = (int) (position[1] + 0.5f);
15337    }
15338
15339    /**
15340     * {@hide}
15341     * @param id the id of the view to be found
15342     * @return the view of the specified id, null if cannot be found
15343     */
15344    protected View findViewTraversal(int id) {
15345        if (id == mID) {
15346            return this;
15347        }
15348        return null;
15349    }
15350
15351    /**
15352     * {@hide}
15353     * @param tag the tag of the view to be found
15354     * @return the view of specified tag, null if cannot be found
15355     */
15356    protected View findViewWithTagTraversal(Object tag) {
15357        if (tag != null && tag.equals(mTag)) {
15358            return this;
15359        }
15360        return null;
15361    }
15362
15363    /**
15364     * {@hide}
15365     * @param predicate The predicate to evaluate.
15366     * @param childToSkip If not null, ignores this child during the recursive traversal.
15367     * @return The first view that matches the predicate or null.
15368     */
15369    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15370        if (predicate.apply(this)) {
15371            return this;
15372        }
15373        return null;
15374    }
15375
15376    /**
15377     * Look for a child view with the given id.  If this view has the given
15378     * id, return this view.
15379     *
15380     * @param id The id to search for.
15381     * @return The view that has the given id in the hierarchy or null
15382     */
15383    public final View findViewById(int id) {
15384        if (id < 0) {
15385            return null;
15386        }
15387        return findViewTraversal(id);
15388    }
15389
15390    /**
15391     * Finds a view by its unuque and stable accessibility id.
15392     *
15393     * @param accessibilityId The searched accessibility id.
15394     * @return The found view.
15395     */
15396    final View findViewByAccessibilityId(int accessibilityId) {
15397        if (accessibilityId < 0) {
15398            return null;
15399        }
15400        return findViewByAccessibilityIdTraversal(accessibilityId);
15401    }
15402
15403    /**
15404     * Performs the traversal to find a view by its unuque and stable accessibility id.
15405     *
15406     * <strong>Note:</strong>This method does not stop at the root namespace
15407     * boundary since the user can touch the screen at an arbitrary location
15408     * potentially crossing the root namespace bounday which will send an
15409     * accessibility event to accessibility services and they should be able
15410     * to obtain the event source. Also accessibility ids are guaranteed to be
15411     * unique in the window.
15412     *
15413     * @param accessibilityId The accessibility id.
15414     * @return The found view.
15415     */
15416    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15417        if (getAccessibilityViewId() == accessibilityId) {
15418            return this;
15419        }
15420        return null;
15421    }
15422
15423    /**
15424     * Look for a child view with the given tag.  If this view has the given
15425     * tag, return this view.
15426     *
15427     * @param tag The tag to search for, using "tag.equals(getTag())".
15428     * @return The View that has the given tag in the hierarchy or null
15429     */
15430    public final View findViewWithTag(Object tag) {
15431        if (tag == null) {
15432            return null;
15433        }
15434        return findViewWithTagTraversal(tag);
15435    }
15436
15437    /**
15438     * {@hide}
15439     * Look for a child view that matches the specified predicate.
15440     * If this view matches the predicate, return this view.
15441     *
15442     * @param predicate The predicate to evaluate.
15443     * @return The first view that matches the predicate or null.
15444     */
15445    public final View findViewByPredicate(Predicate<View> predicate) {
15446        return findViewByPredicateTraversal(predicate, null);
15447    }
15448
15449    /**
15450     * {@hide}
15451     * Look for a child view that matches the specified predicate,
15452     * starting with the specified view and its descendents and then
15453     * recusively searching the ancestors and siblings of that view
15454     * until this view is reached.
15455     *
15456     * This method is useful in cases where the predicate does not match
15457     * a single unique view (perhaps multiple views use the same id)
15458     * and we are trying to find the view that is "closest" in scope to the
15459     * starting view.
15460     *
15461     * @param start The view to start from.
15462     * @param predicate The predicate to evaluate.
15463     * @return The first view that matches the predicate or null.
15464     */
15465    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15466        View childToSkip = null;
15467        for (;;) {
15468            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15469            if (view != null || start == this) {
15470                return view;
15471            }
15472
15473            ViewParent parent = start.getParent();
15474            if (parent == null || !(parent instanceof View)) {
15475                return null;
15476            }
15477
15478            childToSkip = start;
15479            start = (View) parent;
15480        }
15481    }
15482
15483    /**
15484     * Sets the identifier for this view. The identifier does not have to be
15485     * unique in this view's hierarchy. The identifier should be a positive
15486     * number.
15487     *
15488     * @see #NO_ID
15489     * @see #getId()
15490     * @see #findViewById(int)
15491     *
15492     * @param id a number used to identify the view
15493     *
15494     * @attr ref android.R.styleable#View_id
15495     */
15496    public void setId(int id) {
15497        mID = id;
15498        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15499            mID = generateViewId();
15500        }
15501    }
15502
15503    /**
15504     * {@hide}
15505     *
15506     * @param isRoot true if the view belongs to the root namespace, false
15507     *        otherwise
15508     */
15509    public void setIsRootNamespace(boolean isRoot) {
15510        if (isRoot) {
15511            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15512        } else {
15513            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15514        }
15515    }
15516
15517    /**
15518     * {@hide}
15519     *
15520     * @return true if the view belongs to the root namespace, false otherwise
15521     */
15522    public boolean isRootNamespace() {
15523        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15524    }
15525
15526    /**
15527     * Returns this view's identifier.
15528     *
15529     * @return a positive integer used to identify the view or {@link #NO_ID}
15530     *         if the view has no ID
15531     *
15532     * @see #setId(int)
15533     * @see #findViewById(int)
15534     * @attr ref android.R.styleable#View_id
15535     */
15536    @ViewDebug.CapturedViewProperty
15537    public int getId() {
15538        return mID;
15539    }
15540
15541    /**
15542     * Returns this view's tag.
15543     *
15544     * @return the Object stored in this view as a tag
15545     *
15546     * @see #setTag(Object)
15547     * @see #getTag(int)
15548     */
15549    @ViewDebug.ExportedProperty
15550    public Object getTag() {
15551        return mTag;
15552    }
15553
15554    /**
15555     * Sets the tag associated with this view. A tag can be used to mark
15556     * a view in its hierarchy and does not have to be unique within the
15557     * hierarchy. Tags can also be used to store data within a view without
15558     * resorting to another data structure.
15559     *
15560     * @param tag an Object to tag the view with
15561     *
15562     * @see #getTag()
15563     * @see #setTag(int, Object)
15564     */
15565    public void setTag(final Object tag) {
15566        mTag = tag;
15567    }
15568
15569    /**
15570     * Returns the tag associated with this view and the specified key.
15571     *
15572     * @param key The key identifying the tag
15573     *
15574     * @return the Object stored in this view as a tag
15575     *
15576     * @see #setTag(int, Object)
15577     * @see #getTag()
15578     */
15579    public Object getTag(int key) {
15580        if (mKeyedTags != null) return mKeyedTags.get(key);
15581        return null;
15582    }
15583
15584    /**
15585     * Sets a tag associated with this view and a key. A tag can be used
15586     * to mark a view in its hierarchy and does not have to be unique within
15587     * the hierarchy. Tags can also be used to store data within a view
15588     * without resorting to another data structure.
15589     *
15590     * The specified key should be an id declared in the resources of the
15591     * application to ensure it is unique (see the <a
15592     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15593     * Keys identified as belonging to
15594     * the Android framework or not associated with any package will cause
15595     * an {@link IllegalArgumentException} to be thrown.
15596     *
15597     * @param key The key identifying the tag
15598     * @param tag An Object to tag the view with
15599     *
15600     * @throws IllegalArgumentException If they specified key is not valid
15601     *
15602     * @see #setTag(Object)
15603     * @see #getTag(int)
15604     */
15605    public void setTag(int key, final Object tag) {
15606        // If the package id is 0x00 or 0x01, it's either an undefined package
15607        // or a framework id
15608        if ((key >>> 24) < 2) {
15609            throw new IllegalArgumentException("The key must be an application-specific "
15610                    + "resource id.");
15611        }
15612
15613        setKeyedTag(key, tag);
15614    }
15615
15616    /**
15617     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15618     * framework id.
15619     *
15620     * @hide
15621     */
15622    public void setTagInternal(int key, Object tag) {
15623        if ((key >>> 24) != 0x1) {
15624            throw new IllegalArgumentException("The key must be a framework-specific "
15625                    + "resource id.");
15626        }
15627
15628        setKeyedTag(key, tag);
15629    }
15630
15631    private void setKeyedTag(int key, Object tag) {
15632        if (mKeyedTags == null) {
15633            mKeyedTags = new SparseArray<Object>();
15634        }
15635
15636        mKeyedTags.put(key, tag);
15637    }
15638
15639    /**
15640     * Prints information about this view in the log output, with the tag
15641     * {@link #VIEW_LOG_TAG}.
15642     *
15643     * @hide
15644     */
15645    public void debug() {
15646        debug(0);
15647    }
15648
15649    /**
15650     * Prints information about this view in the log output, with the tag
15651     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15652     * indentation defined by the <code>depth</code>.
15653     *
15654     * @param depth the indentation level
15655     *
15656     * @hide
15657     */
15658    protected void debug(int depth) {
15659        String output = debugIndent(depth - 1);
15660
15661        output += "+ " + this;
15662        int id = getId();
15663        if (id != -1) {
15664            output += " (id=" + id + ")";
15665        }
15666        Object tag = getTag();
15667        if (tag != null) {
15668            output += " (tag=" + tag + ")";
15669        }
15670        Log.d(VIEW_LOG_TAG, output);
15671
15672        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15673            output = debugIndent(depth) + " FOCUSED";
15674            Log.d(VIEW_LOG_TAG, output);
15675        }
15676
15677        output = debugIndent(depth);
15678        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15679                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15680                + "} ";
15681        Log.d(VIEW_LOG_TAG, output);
15682
15683        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15684                || mPaddingBottom != 0) {
15685            output = debugIndent(depth);
15686            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15687                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15688            Log.d(VIEW_LOG_TAG, output);
15689        }
15690
15691        output = debugIndent(depth);
15692        output += "mMeasureWidth=" + mMeasuredWidth +
15693                " mMeasureHeight=" + mMeasuredHeight;
15694        Log.d(VIEW_LOG_TAG, output);
15695
15696        output = debugIndent(depth);
15697        if (mLayoutParams == null) {
15698            output += "BAD! no layout params";
15699        } else {
15700            output = mLayoutParams.debug(output);
15701        }
15702        Log.d(VIEW_LOG_TAG, output);
15703
15704        output = debugIndent(depth);
15705        output += "flags={";
15706        output += View.printFlags(mViewFlags);
15707        output += "}";
15708        Log.d(VIEW_LOG_TAG, output);
15709
15710        output = debugIndent(depth);
15711        output += "privateFlags={";
15712        output += View.printPrivateFlags(mPrivateFlags);
15713        output += "}";
15714        Log.d(VIEW_LOG_TAG, output);
15715    }
15716
15717    /**
15718     * Creates a string of whitespaces used for indentation.
15719     *
15720     * @param depth the indentation level
15721     * @return a String containing (depth * 2 + 3) * 2 white spaces
15722     *
15723     * @hide
15724     */
15725    protected static String debugIndent(int depth) {
15726        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15727        for (int i = 0; i < (depth * 2) + 3; i++) {
15728            spaces.append(' ').append(' ');
15729        }
15730        return spaces.toString();
15731    }
15732
15733    /**
15734     * <p>Return the offset of the widget's text baseline from the widget's top
15735     * boundary. If this widget does not support baseline alignment, this
15736     * method returns -1. </p>
15737     *
15738     * @return the offset of the baseline within the widget's bounds or -1
15739     *         if baseline alignment is not supported
15740     */
15741    @ViewDebug.ExportedProperty(category = "layout")
15742    public int getBaseline() {
15743        return -1;
15744    }
15745
15746    /**
15747     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15748     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15749     * a layout pass.
15750     *
15751     * @return whether the view hierarchy is currently undergoing a layout pass
15752     */
15753    public boolean isInLayout() {
15754        ViewRootImpl viewRoot = getViewRootImpl();
15755        return (viewRoot != null && viewRoot.isInLayout());
15756    }
15757
15758    /**
15759     * Call this when something has changed which has invalidated the
15760     * layout of this view. This will schedule a layout pass of the view
15761     * tree. This should not be called while the view hierarchy is currently in a layout
15762     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15763     * end of the current layout pass (and then layout will run again) or after the current
15764     * frame is drawn and the next layout occurs.
15765     *
15766     * <p>Subclasses which override this method should call the superclass method to
15767     * handle possible request-during-layout errors correctly.</p>
15768     */
15769    public void requestLayout() {
15770        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15771            // Only trigger request-during-layout logic if this is the view requesting it,
15772            // not the views in its parent hierarchy
15773            ViewRootImpl viewRoot = getViewRootImpl();
15774            if (viewRoot != null && viewRoot.isInLayout()) {
15775                if (!viewRoot.requestLayoutDuringLayout(this)) {
15776                    return;
15777                }
15778            }
15779            mAttachInfo.mViewRequestingLayout = this;
15780        }
15781
15782        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15783        mPrivateFlags |= PFLAG_INVALIDATED;
15784
15785        if (mParent != null && !mParent.isLayoutRequested()) {
15786            mParent.requestLayout();
15787        }
15788        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15789            mAttachInfo.mViewRequestingLayout = null;
15790        }
15791    }
15792
15793    /**
15794     * Forces this view to be laid out during the next layout pass.
15795     * This method does not call requestLayout() or forceLayout()
15796     * on the parent.
15797     */
15798    public void forceLayout() {
15799        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15800        mPrivateFlags |= PFLAG_INVALIDATED;
15801    }
15802
15803    /**
15804     * <p>
15805     * This is called to find out how big a view should be. The parent
15806     * supplies constraint information in the width and height parameters.
15807     * </p>
15808     *
15809     * <p>
15810     * The actual measurement work of a view is performed in
15811     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15812     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15813     * </p>
15814     *
15815     *
15816     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15817     *        parent
15818     * @param heightMeasureSpec Vertical space requirements as imposed by the
15819     *        parent
15820     *
15821     * @see #onMeasure(int, int)
15822     */
15823    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15824        boolean optical = isLayoutModeOptical(this);
15825        if (optical != isLayoutModeOptical(mParent)) {
15826            Insets insets = getOpticalInsets();
15827            int oWidth  = insets.left + insets.right;
15828            int oHeight = insets.top  + insets.bottom;
15829            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15830            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15831        }
15832        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15833                widthMeasureSpec != mOldWidthMeasureSpec ||
15834                heightMeasureSpec != mOldHeightMeasureSpec) {
15835
15836            // first clears the measured dimension flag
15837            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15838
15839            resolveRtlPropertiesIfNeeded();
15840
15841            // measure ourselves, this should set the measured dimension flag back
15842            onMeasure(widthMeasureSpec, heightMeasureSpec);
15843
15844            // flag not set, setMeasuredDimension() was not invoked, we raise
15845            // an exception to warn the developer
15846            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15847                throw new IllegalStateException("onMeasure() did not set the"
15848                        + " measured dimension by calling"
15849                        + " setMeasuredDimension()");
15850            }
15851
15852            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15853        }
15854
15855        mOldWidthMeasureSpec = widthMeasureSpec;
15856        mOldHeightMeasureSpec = heightMeasureSpec;
15857    }
15858
15859    /**
15860     * <p>
15861     * Measure the view and its content to determine the measured width and the
15862     * measured height. This method is invoked by {@link #measure(int, int)} and
15863     * should be overriden by subclasses to provide accurate and efficient
15864     * measurement of their contents.
15865     * </p>
15866     *
15867     * <p>
15868     * <strong>CONTRACT:</strong> When overriding this method, you
15869     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15870     * measured width and height of this view. Failure to do so will trigger an
15871     * <code>IllegalStateException</code>, thrown by
15872     * {@link #measure(int, int)}. Calling the superclass'
15873     * {@link #onMeasure(int, int)} is a valid use.
15874     * </p>
15875     *
15876     * <p>
15877     * The base class implementation of measure defaults to the background size,
15878     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15879     * override {@link #onMeasure(int, int)} to provide better measurements of
15880     * their content.
15881     * </p>
15882     *
15883     * <p>
15884     * If this method is overridden, it is the subclass's responsibility to make
15885     * sure the measured height and width are at least the view's minimum height
15886     * and width ({@link #getSuggestedMinimumHeight()} and
15887     * {@link #getSuggestedMinimumWidth()}).
15888     * </p>
15889     *
15890     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15891     *                         The requirements are encoded with
15892     *                         {@link android.view.View.MeasureSpec}.
15893     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15894     *                         The requirements are encoded with
15895     *                         {@link android.view.View.MeasureSpec}.
15896     *
15897     * @see #getMeasuredWidth()
15898     * @see #getMeasuredHeight()
15899     * @see #setMeasuredDimension(int, int)
15900     * @see #getSuggestedMinimumHeight()
15901     * @see #getSuggestedMinimumWidth()
15902     * @see android.view.View.MeasureSpec#getMode(int)
15903     * @see android.view.View.MeasureSpec#getSize(int)
15904     */
15905    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15906        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15907                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15908    }
15909
15910    /**
15911     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15912     * measured width and measured height. Failing to do so will trigger an
15913     * exception at measurement time.</p>
15914     *
15915     * @param measuredWidth The measured width of this view.  May be a complex
15916     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15917     * {@link #MEASURED_STATE_TOO_SMALL}.
15918     * @param measuredHeight The measured height of this view.  May be a complex
15919     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15920     * {@link #MEASURED_STATE_TOO_SMALL}.
15921     */
15922    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15923        boolean optical = isLayoutModeOptical(this);
15924        if (optical != isLayoutModeOptical(mParent)) {
15925            Insets insets = getOpticalInsets();
15926            int opticalWidth  = insets.left + insets.right;
15927            int opticalHeight = insets.top  + insets.bottom;
15928
15929            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
15930            measuredHeight += optical ? opticalHeight : -opticalHeight;
15931        }
15932        mMeasuredWidth = measuredWidth;
15933        mMeasuredHeight = measuredHeight;
15934
15935        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15936    }
15937
15938    /**
15939     * Merge two states as returned by {@link #getMeasuredState()}.
15940     * @param curState The current state as returned from a view or the result
15941     * of combining multiple views.
15942     * @param newState The new view state to combine.
15943     * @return Returns a new integer reflecting the combination of the two
15944     * states.
15945     */
15946    public static int combineMeasuredStates(int curState, int newState) {
15947        return curState | newState;
15948    }
15949
15950    /**
15951     * Version of {@link #resolveSizeAndState(int, int, int)}
15952     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15953     */
15954    public static int resolveSize(int size, int measureSpec) {
15955        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15956    }
15957
15958    /**
15959     * Utility to reconcile a desired size and state, with constraints imposed
15960     * by a MeasureSpec.  Will take the desired size, unless a different size
15961     * is imposed by the constraints.  The returned value is a compound integer,
15962     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15963     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15964     * size is smaller than the size the view wants to be.
15965     *
15966     * @param size How big the view wants to be
15967     * @param measureSpec Constraints imposed by the parent
15968     * @return Size information bit mask as defined by
15969     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15970     */
15971    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15972        int result = size;
15973        int specMode = MeasureSpec.getMode(measureSpec);
15974        int specSize =  MeasureSpec.getSize(measureSpec);
15975        switch (specMode) {
15976        case MeasureSpec.UNSPECIFIED:
15977            result = size;
15978            break;
15979        case MeasureSpec.AT_MOST:
15980            if (specSize < size) {
15981                result = specSize | MEASURED_STATE_TOO_SMALL;
15982            } else {
15983                result = size;
15984            }
15985            break;
15986        case MeasureSpec.EXACTLY:
15987            result = specSize;
15988            break;
15989        }
15990        return result | (childMeasuredState&MEASURED_STATE_MASK);
15991    }
15992
15993    /**
15994     * Utility to return a default size. Uses the supplied size if the
15995     * MeasureSpec imposed no constraints. Will get larger if allowed
15996     * by the MeasureSpec.
15997     *
15998     * @param size Default size for this view
15999     * @param measureSpec Constraints imposed by the parent
16000     * @return The size this view should be.
16001     */
16002    public static int getDefaultSize(int size, int measureSpec) {
16003        int result = size;
16004        int specMode = MeasureSpec.getMode(measureSpec);
16005        int specSize = MeasureSpec.getSize(measureSpec);
16006
16007        switch (specMode) {
16008        case MeasureSpec.UNSPECIFIED:
16009            result = size;
16010            break;
16011        case MeasureSpec.AT_MOST:
16012        case MeasureSpec.EXACTLY:
16013            result = specSize;
16014            break;
16015        }
16016        return result;
16017    }
16018
16019    /**
16020     * Returns the suggested minimum height that the view should use. This
16021     * returns the maximum of the view's minimum height
16022     * and the background's minimum height
16023     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16024     * <p>
16025     * When being used in {@link #onMeasure(int, int)}, the caller should still
16026     * ensure the returned height is within the requirements of the parent.
16027     *
16028     * @return The suggested minimum height of the view.
16029     */
16030    protected int getSuggestedMinimumHeight() {
16031        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16032
16033    }
16034
16035    /**
16036     * Returns the suggested minimum width that the view should use. This
16037     * returns the maximum of the view's minimum width)
16038     * and the background's minimum width
16039     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16040     * <p>
16041     * When being used in {@link #onMeasure(int, int)}, the caller should still
16042     * ensure the returned width is within the requirements of the parent.
16043     *
16044     * @return The suggested minimum width of the view.
16045     */
16046    protected int getSuggestedMinimumWidth() {
16047        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16048    }
16049
16050    /**
16051     * Returns the minimum height of the view.
16052     *
16053     * @return the minimum height the view will try to be.
16054     *
16055     * @see #setMinimumHeight(int)
16056     *
16057     * @attr ref android.R.styleable#View_minHeight
16058     */
16059    public int getMinimumHeight() {
16060        return mMinHeight;
16061    }
16062
16063    /**
16064     * Sets the minimum height of the view. It is not guaranteed the view will
16065     * be able to achieve this minimum height (for example, if its parent layout
16066     * constrains it with less available height).
16067     *
16068     * @param minHeight The minimum height the view will try to be.
16069     *
16070     * @see #getMinimumHeight()
16071     *
16072     * @attr ref android.R.styleable#View_minHeight
16073     */
16074    public void setMinimumHeight(int minHeight) {
16075        mMinHeight = minHeight;
16076        requestLayout();
16077    }
16078
16079    /**
16080     * Returns the minimum width of the view.
16081     *
16082     * @return the minimum width the view will try to be.
16083     *
16084     * @see #setMinimumWidth(int)
16085     *
16086     * @attr ref android.R.styleable#View_minWidth
16087     */
16088    public int getMinimumWidth() {
16089        return mMinWidth;
16090    }
16091
16092    /**
16093     * Sets the minimum width of the view. It is not guaranteed the view will
16094     * be able to achieve this minimum width (for example, if its parent layout
16095     * constrains it with less available width).
16096     *
16097     * @param minWidth The minimum width the view will try to be.
16098     *
16099     * @see #getMinimumWidth()
16100     *
16101     * @attr ref android.R.styleable#View_minWidth
16102     */
16103    public void setMinimumWidth(int minWidth) {
16104        mMinWidth = minWidth;
16105        requestLayout();
16106
16107    }
16108
16109    /**
16110     * Get the animation currently associated with this view.
16111     *
16112     * @return The animation that is currently playing or
16113     *         scheduled to play for this view.
16114     */
16115    public Animation getAnimation() {
16116        return mCurrentAnimation;
16117    }
16118
16119    /**
16120     * Start the specified animation now.
16121     *
16122     * @param animation the animation to start now
16123     */
16124    public void startAnimation(Animation animation) {
16125        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16126        setAnimation(animation);
16127        invalidateParentCaches();
16128        invalidate(true);
16129    }
16130
16131    /**
16132     * Cancels any animations for this view.
16133     */
16134    public void clearAnimation() {
16135        if (mCurrentAnimation != null) {
16136            mCurrentAnimation.detach();
16137        }
16138        mCurrentAnimation = null;
16139        invalidateParentIfNeeded();
16140    }
16141
16142    /**
16143     * Sets the next animation to play for this view.
16144     * If you want the animation to play immediately, use
16145     * {@link #startAnimation(android.view.animation.Animation)} instead.
16146     * This method provides allows fine-grained
16147     * control over the start time and invalidation, but you
16148     * must make sure that 1) the animation has a start time set, and
16149     * 2) the view's parent (which controls animations on its children)
16150     * will be invalidated when the animation is supposed to
16151     * start.
16152     *
16153     * @param animation The next animation, or null.
16154     */
16155    public void setAnimation(Animation animation) {
16156        mCurrentAnimation = animation;
16157
16158        if (animation != null) {
16159            // If the screen is off assume the animation start time is now instead of
16160            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16161            // would cause the animation to start when the screen turns back on
16162            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16163                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16164                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16165            }
16166            animation.reset();
16167        }
16168    }
16169
16170    /**
16171     * Invoked by a parent ViewGroup to notify the start of the animation
16172     * currently associated with this view. If you override this method,
16173     * always call super.onAnimationStart();
16174     *
16175     * @see #setAnimation(android.view.animation.Animation)
16176     * @see #getAnimation()
16177     */
16178    protected void onAnimationStart() {
16179        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16180    }
16181
16182    /**
16183     * Invoked by a parent ViewGroup to notify the end of the animation
16184     * currently associated with this view. If you override this method,
16185     * always call super.onAnimationEnd();
16186     *
16187     * @see #setAnimation(android.view.animation.Animation)
16188     * @see #getAnimation()
16189     */
16190    protected void onAnimationEnd() {
16191        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16192    }
16193
16194    /**
16195     * Invoked if there is a Transform that involves alpha. Subclass that can
16196     * draw themselves with the specified alpha should return true, and then
16197     * respect that alpha when their onDraw() is called. If this returns false
16198     * then the view may be redirected to draw into an offscreen buffer to
16199     * fulfill the request, which will look fine, but may be slower than if the
16200     * subclass handles it internally. The default implementation returns false.
16201     *
16202     * @param alpha The alpha (0..255) to apply to the view's drawing
16203     * @return true if the view can draw with the specified alpha.
16204     */
16205    protected boolean onSetAlpha(int alpha) {
16206        return false;
16207    }
16208
16209    /**
16210     * This is used by the RootView to perform an optimization when
16211     * the view hierarchy contains one or several SurfaceView.
16212     * SurfaceView is always considered transparent, but its children are not,
16213     * therefore all View objects remove themselves from the global transparent
16214     * region (passed as a parameter to this function).
16215     *
16216     * @param region The transparent region for this ViewAncestor (window).
16217     *
16218     * @return Returns true if the effective visibility of the view at this
16219     * point is opaque, regardless of the transparent region; returns false
16220     * if it is possible for underlying windows to be seen behind the view.
16221     *
16222     * {@hide}
16223     */
16224    public boolean gatherTransparentRegion(Region region) {
16225        final AttachInfo attachInfo = mAttachInfo;
16226        if (region != null && attachInfo != null) {
16227            final int pflags = mPrivateFlags;
16228            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16229                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16230                // remove it from the transparent region.
16231                final int[] location = attachInfo.mTransparentLocation;
16232                getLocationInWindow(location);
16233                region.op(location[0], location[1], location[0] + mRight - mLeft,
16234                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16235            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16236                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16237                // exists, so we remove the background drawable's non-transparent
16238                // parts from this transparent region.
16239                applyDrawableToTransparentRegion(mBackground, region);
16240            }
16241        }
16242        return true;
16243    }
16244
16245    /**
16246     * Play a sound effect for this view.
16247     *
16248     * <p>The framework will play sound effects for some built in actions, such as
16249     * clicking, but you may wish to play these effects in your widget,
16250     * for instance, for internal navigation.
16251     *
16252     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16253     * {@link #isSoundEffectsEnabled()} is true.
16254     *
16255     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16256     */
16257    public void playSoundEffect(int soundConstant) {
16258        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16259            return;
16260        }
16261        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16262    }
16263
16264    /**
16265     * BZZZTT!!1!
16266     *
16267     * <p>Provide haptic feedback to the user for this view.
16268     *
16269     * <p>The framework will provide haptic feedback for some built in actions,
16270     * such as long presses, but you may wish to provide feedback for your
16271     * own widget.
16272     *
16273     * <p>The feedback will only be performed if
16274     * {@link #isHapticFeedbackEnabled()} is true.
16275     *
16276     * @param feedbackConstant One of the constants defined in
16277     * {@link HapticFeedbackConstants}
16278     */
16279    public boolean performHapticFeedback(int feedbackConstant) {
16280        return performHapticFeedback(feedbackConstant, 0);
16281    }
16282
16283    /**
16284     * BZZZTT!!1!
16285     *
16286     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16287     *
16288     * @param feedbackConstant One of the constants defined in
16289     * {@link HapticFeedbackConstants}
16290     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16291     */
16292    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16293        if (mAttachInfo == null) {
16294            return false;
16295        }
16296        //noinspection SimplifiableIfStatement
16297        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16298                && !isHapticFeedbackEnabled()) {
16299            return false;
16300        }
16301        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16302                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16303    }
16304
16305    /**
16306     * Request that the visibility of the status bar or other screen/window
16307     * decorations be changed.
16308     *
16309     * <p>This method is used to put the over device UI into temporary modes
16310     * where the user's attention is focused more on the application content,
16311     * by dimming or hiding surrounding system affordances.  This is typically
16312     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16313     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16314     * to be placed behind the action bar (and with these flags other system
16315     * affordances) so that smooth transitions between hiding and showing them
16316     * can be done.
16317     *
16318     * <p>Two representative examples of the use of system UI visibility is
16319     * implementing a content browsing application (like a magazine reader)
16320     * and a video playing application.
16321     *
16322     * <p>The first code shows a typical implementation of a View in a content
16323     * browsing application.  In this implementation, the application goes
16324     * into a content-oriented mode by hiding the status bar and action bar,
16325     * and putting the navigation elements into lights out mode.  The user can
16326     * then interact with content while in this mode.  Such an application should
16327     * provide an easy way for the user to toggle out of the mode (such as to
16328     * check information in the status bar or access notifications).  In the
16329     * implementation here, this is done simply by tapping on the content.
16330     *
16331     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16332     *      content}
16333     *
16334     * <p>This second code sample shows a typical implementation of a View
16335     * in a video playing application.  In this situation, while the video is
16336     * playing the application would like to go into a complete full-screen mode,
16337     * to use as much of the display as possible for the video.  When in this state
16338     * the user can not interact with the application; the system intercepts
16339     * touching on the screen to pop the UI out of full screen mode.  See
16340     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16341     *
16342     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16343     *      content}
16344     *
16345     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16346     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16347     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16348     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16349     */
16350    public void setSystemUiVisibility(int visibility) {
16351        if (visibility != mSystemUiVisibility) {
16352            mSystemUiVisibility = visibility;
16353            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16354                mParent.recomputeViewAttributes(this);
16355            }
16356        }
16357    }
16358
16359    /**
16360     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16361     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16362     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16363     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16364     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16365     */
16366    public int getSystemUiVisibility() {
16367        return mSystemUiVisibility;
16368    }
16369
16370    /**
16371     * Returns the current system UI visibility that is currently set for
16372     * the entire window.  This is the combination of the
16373     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16374     * views in the window.
16375     */
16376    public int getWindowSystemUiVisibility() {
16377        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16378    }
16379
16380    /**
16381     * Override to find out when the window's requested system UI visibility
16382     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16383     * This is different from the callbacks recieved through
16384     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16385     * in that this is only telling you about the local request of the window,
16386     * not the actual values applied by the system.
16387     */
16388    public void onWindowSystemUiVisibilityChanged(int visible) {
16389    }
16390
16391    /**
16392     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16393     * the view hierarchy.
16394     */
16395    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16396        onWindowSystemUiVisibilityChanged(visible);
16397    }
16398
16399    /**
16400     * Set a listener to receive callbacks when the visibility of the system bar changes.
16401     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16402     */
16403    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16404        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16405        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16406            mParent.recomputeViewAttributes(this);
16407        }
16408    }
16409
16410    /**
16411     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16412     * the view hierarchy.
16413     */
16414    public void dispatchSystemUiVisibilityChanged(int visibility) {
16415        ListenerInfo li = mListenerInfo;
16416        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16417            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16418                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16419        }
16420    }
16421
16422    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16423        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16424        if (val != mSystemUiVisibility) {
16425            setSystemUiVisibility(val);
16426            return true;
16427        }
16428        return false;
16429    }
16430
16431    /** @hide */
16432    public void setDisabledSystemUiVisibility(int flags) {
16433        if (mAttachInfo != null) {
16434            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16435                mAttachInfo.mDisabledSystemUiVisibility = flags;
16436                if (mParent != null) {
16437                    mParent.recomputeViewAttributes(this);
16438                }
16439            }
16440        }
16441    }
16442
16443    /**
16444     * Creates an image that the system displays during the drag and drop
16445     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16446     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16447     * appearance as the given View. The default also positions the center of the drag shadow
16448     * directly under the touch point. If no View is provided (the constructor with no parameters
16449     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16450     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16451     * default is an invisible drag shadow.
16452     * <p>
16453     * You are not required to use the View you provide to the constructor as the basis of the
16454     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16455     * anything you want as the drag shadow.
16456     * </p>
16457     * <p>
16458     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16459     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16460     *  size and position of the drag shadow. It uses this data to construct a
16461     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16462     *  so that your application can draw the shadow image in the Canvas.
16463     * </p>
16464     *
16465     * <div class="special reference">
16466     * <h3>Developer Guides</h3>
16467     * <p>For a guide to implementing drag and drop features, read the
16468     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16469     * </div>
16470     */
16471    public static class DragShadowBuilder {
16472        private final WeakReference<View> mView;
16473
16474        /**
16475         * Constructs a shadow image builder based on a View. By default, the resulting drag
16476         * shadow will have the same appearance and dimensions as the View, with the touch point
16477         * over the center of the View.
16478         * @param view A View. Any View in scope can be used.
16479         */
16480        public DragShadowBuilder(View view) {
16481            mView = new WeakReference<View>(view);
16482        }
16483
16484        /**
16485         * Construct a shadow builder object with no associated View.  This
16486         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16487         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16488         * to supply the drag shadow's dimensions and appearance without
16489         * reference to any View object. If they are not overridden, then the result is an
16490         * invisible drag shadow.
16491         */
16492        public DragShadowBuilder() {
16493            mView = new WeakReference<View>(null);
16494        }
16495
16496        /**
16497         * Returns the View object that had been passed to the
16498         * {@link #View.DragShadowBuilder(View)}
16499         * constructor.  If that View parameter was {@code null} or if the
16500         * {@link #View.DragShadowBuilder()}
16501         * constructor was used to instantiate the builder object, this method will return
16502         * null.
16503         *
16504         * @return The View object associate with this builder object.
16505         */
16506        @SuppressWarnings({"JavadocReference"})
16507        final public View getView() {
16508            return mView.get();
16509        }
16510
16511        /**
16512         * Provides the metrics for the shadow image. These include the dimensions of
16513         * the shadow image, and the point within that shadow that should
16514         * be centered under the touch location while dragging.
16515         * <p>
16516         * The default implementation sets the dimensions of the shadow to be the
16517         * same as the dimensions of the View itself and centers the shadow under
16518         * the touch point.
16519         * </p>
16520         *
16521         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16522         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16523         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16524         * image.
16525         *
16526         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16527         * shadow image that should be underneath the touch point during the drag and drop
16528         * operation. Your application must set {@link android.graphics.Point#x} to the
16529         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16530         */
16531        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16532            final View view = mView.get();
16533            if (view != null) {
16534                shadowSize.set(view.getWidth(), view.getHeight());
16535                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16536            } else {
16537                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16538            }
16539        }
16540
16541        /**
16542         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16543         * based on the dimensions it received from the
16544         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16545         *
16546         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16547         */
16548        public void onDrawShadow(Canvas canvas) {
16549            final View view = mView.get();
16550            if (view != null) {
16551                view.draw(canvas);
16552            } else {
16553                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16554            }
16555        }
16556    }
16557
16558    /**
16559     * Starts a drag and drop operation. When your application calls this method, it passes a
16560     * {@link android.view.View.DragShadowBuilder} object to the system. The
16561     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16562     * to get metrics for the drag shadow, and then calls the object's
16563     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16564     * <p>
16565     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16566     *  drag events to all the View objects in your application that are currently visible. It does
16567     *  this either by calling the View object's drag listener (an implementation of
16568     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16569     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16570     *  Both are passed a {@link android.view.DragEvent} object that has a
16571     *  {@link android.view.DragEvent#getAction()} value of
16572     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16573     * </p>
16574     * <p>
16575     * Your application can invoke startDrag() on any attached View object. The View object does not
16576     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16577     * be related to the View the user selected for dragging.
16578     * </p>
16579     * @param data A {@link android.content.ClipData} object pointing to the data to be
16580     * transferred by the drag and drop operation.
16581     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16582     * drag shadow.
16583     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16584     * drop operation. This Object is put into every DragEvent object sent by the system during the
16585     * current drag.
16586     * <p>
16587     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16588     * to the target Views. For example, it can contain flags that differentiate between a
16589     * a copy operation and a move operation.
16590     * </p>
16591     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16592     * so the parameter should be set to 0.
16593     * @return {@code true} if the method completes successfully, or
16594     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16595     * do a drag, and so no drag operation is in progress.
16596     */
16597    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16598            Object myLocalState, int flags) {
16599        if (ViewDebug.DEBUG_DRAG) {
16600            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16601        }
16602        boolean okay = false;
16603
16604        Point shadowSize = new Point();
16605        Point shadowTouchPoint = new Point();
16606        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16607
16608        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16609                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16610            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16611        }
16612
16613        if (ViewDebug.DEBUG_DRAG) {
16614            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16615                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16616        }
16617        Surface surface = new Surface();
16618        try {
16619            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16620                    flags, shadowSize.x, shadowSize.y, surface);
16621            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16622                    + " surface=" + surface);
16623            if (token != null) {
16624                Canvas canvas = surface.lockCanvas(null);
16625                try {
16626                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16627                    shadowBuilder.onDrawShadow(canvas);
16628                } finally {
16629                    surface.unlockCanvasAndPost(canvas);
16630                }
16631
16632                final ViewRootImpl root = getViewRootImpl();
16633
16634                // Cache the local state object for delivery with DragEvents
16635                root.setLocalDragState(myLocalState);
16636
16637                // repurpose 'shadowSize' for the last touch point
16638                root.getLastTouchPoint(shadowSize);
16639
16640                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16641                        shadowSize.x, shadowSize.y,
16642                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16643                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16644
16645                // Off and running!  Release our local surface instance; the drag
16646                // shadow surface is now managed by the system process.
16647                surface.release();
16648            }
16649        } catch (Exception e) {
16650            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16651            surface.destroy();
16652        }
16653
16654        return okay;
16655    }
16656
16657    /**
16658     * Handles drag events sent by the system following a call to
16659     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16660     *<p>
16661     * When the system calls this method, it passes a
16662     * {@link android.view.DragEvent} object. A call to
16663     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16664     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16665     * operation.
16666     * @param event The {@link android.view.DragEvent} sent by the system.
16667     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16668     * in DragEvent, indicating the type of drag event represented by this object.
16669     * @return {@code true} if the method was successful, otherwise {@code false}.
16670     * <p>
16671     *  The method should return {@code true} in response to an action type of
16672     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16673     *  operation.
16674     * </p>
16675     * <p>
16676     *  The method should also return {@code true} in response to an action type of
16677     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16678     *  {@code false} if it didn't.
16679     * </p>
16680     */
16681    public boolean onDragEvent(DragEvent event) {
16682        return false;
16683    }
16684
16685    /**
16686     * Detects if this View is enabled and has a drag event listener.
16687     * If both are true, then it calls the drag event listener with the
16688     * {@link android.view.DragEvent} it received. If the drag event listener returns
16689     * {@code true}, then dispatchDragEvent() returns {@code true}.
16690     * <p>
16691     * For all other cases, the method calls the
16692     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16693     * method and returns its result.
16694     * </p>
16695     * <p>
16696     * This ensures that a drag event is always consumed, even if the View does not have a drag
16697     * event listener. However, if the View has a listener and the listener returns true, then
16698     * onDragEvent() is not called.
16699     * </p>
16700     */
16701    public boolean dispatchDragEvent(DragEvent event) {
16702        //noinspection SimplifiableIfStatement
16703        ListenerInfo li = mListenerInfo;
16704        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16705                && li.mOnDragListener.onDrag(this, event)) {
16706            return true;
16707        }
16708        return onDragEvent(event);
16709    }
16710
16711    boolean canAcceptDrag() {
16712        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16713    }
16714
16715    /**
16716     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16717     * it is ever exposed at all.
16718     * @hide
16719     */
16720    public void onCloseSystemDialogs(String reason) {
16721    }
16722
16723    /**
16724     * Given a Drawable whose bounds have been set to draw into this view,
16725     * update a Region being computed for
16726     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16727     * that any non-transparent parts of the Drawable are removed from the
16728     * given transparent region.
16729     *
16730     * @param dr The Drawable whose transparency is to be applied to the region.
16731     * @param region A Region holding the current transparency information,
16732     * where any parts of the region that are set are considered to be
16733     * transparent.  On return, this region will be modified to have the
16734     * transparency information reduced by the corresponding parts of the
16735     * Drawable that are not transparent.
16736     * {@hide}
16737     */
16738    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16739        if (DBG) {
16740            Log.i("View", "Getting transparent region for: " + this);
16741        }
16742        final Region r = dr.getTransparentRegion();
16743        final Rect db = dr.getBounds();
16744        final AttachInfo attachInfo = mAttachInfo;
16745        if (r != null && attachInfo != null) {
16746            final int w = getRight()-getLeft();
16747            final int h = getBottom()-getTop();
16748            if (db.left > 0) {
16749                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16750                r.op(0, 0, db.left, h, Region.Op.UNION);
16751            }
16752            if (db.right < w) {
16753                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16754                r.op(db.right, 0, w, h, Region.Op.UNION);
16755            }
16756            if (db.top > 0) {
16757                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16758                r.op(0, 0, w, db.top, Region.Op.UNION);
16759            }
16760            if (db.bottom < h) {
16761                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16762                r.op(0, db.bottom, w, h, Region.Op.UNION);
16763            }
16764            final int[] location = attachInfo.mTransparentLocation;
16765            getLocationInWindow(location);
16766            r.translate(location[0], location[1]);
16767            region.op(r, Region.Op.INTERSECT);
16768        } else {
16769            region.op(db, Region.Op.DIFFERENCE);
16770        }
16771    }
16772
16773    private void checkForLongClick(int delayOffset) {
16774        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16775            mHasPerformedLongPress = false;
16776
16777            if (mPendingCheckForLongPress == null) {
16778                mPendingCheckForLongPress = new CheckForLongPress();
16779            }
16780            mPendingCheckForLongPress.rememberWindowAttachCount();
16781            postDelayed(mPendingCheckForLongPress,
16782                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16783        }
16784    }
16785
16786    /**
16787     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16788     * LayoutInflater} class, which provides a full range of options for view inflation.
16789     *
16790     * @param context The Context object for your activity or application.
16791     * @param resource The resource ID to inflate
16792     * @param root A view group that will be the parent.  Used to properly inflate the
16793     * layout_* parameters.
16794     * @see LayoutInflater
16795     */
16796    public static View inflate(Context context, int resource, ViewGroup root) {
16797        LayoutInflater factory = LayoutInflater.from(context);
16798        return factory.inflate(resource, root);
16799    }
16800
16801    /**
16802     * Scroll the view with standard behavior for scrolling beyond the normal
16803     * content boundaries. Views that call this method should override
16804     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16805     * results of an over-scroll operation.
16806     *
16807     * Views can use this method to handle any touch or fling-based scrolling.
16808     *
16809     * @param deltaX Change in X in pixels
16810     * @param deltaY Change in Y in pixels
16811     * @param scrollX Current X scroll value in pixels before applying deltaX
16812     * @param scrollY Current Y scroll value in pixels before applying deltaY
16813     * @param scrollRangeX Maximum content scroll range along the X axis
16814     * @param scrollRangeY Maximum content scroll range along the Y axis
16815     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16816     *          along the X axis.
16817     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16818     *          along the Y axis.
16819     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16820     * @return true if scrolling was clamped to an over-scroll boundary along either
16821     *          axis, false otherwise.
16822     */
16823    @SuppressWarnings({"UnusedParameters"})
16824    protected boolean overScrollBy(int deltaX, int deltaY,
16825            int scrollX, int scrollY,
16826            int scrollRangeX, int scrollRangeY,
16827            int maxOverScrollX, int maxOverScrollY,
16828            boolean isTouchEvent) {
16829        final int overScrollMode = mOverScrollMode;
16830        final boolean canScrollHorizontal =
16831                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16832        final boolean canScrollVertical =
16833                computeVerticalScrollRange() > computeVerticalScrollExtent();
16834        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16835                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16836        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16837                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16838
16839        int newScrollX = scrollX + deltaX;
16840        if (!overScrollHorizontal) {
16841            maxOverScrollX = 0;
16842        }
16843
16844        int newScrollY = scrollY + deltaY;
16845        if (!overScrollVertical) {
16846            maxOverScrollY = 0;
16847        }
16848
16849        // Clamp values if at the limits and record
16850        final int left = -maxOverScrollX;
16851        final int right = maxOverScrollX + scrollRangeX;
16852        final int top = -maxOverScrollY;
16853        final int bottom = maxOverScrollY + scrollRangeY;
16854
16855        boolean clampedX = false;
16856        if (newScrollX > right) {
16857            newScrollX = right;
16858            clampedX = true;
16859        } else if (newScrollX < left) {
16860            newScrollX = left;
16861            clampedX = true;
16862        }
16863
16864        boolean clampedY = false;
16865        if (newScrollY > bottom) {
16866            newScrollY = bottom;
16867            clampedY = true;
16868        } else if (newScrollY < top) {
16869            newScrollY = top;
16870            clampedY = true;
16871        }
16872
16873        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16874
16875        return clampedX || clampedY;
16876    }
16877
16878    /**
16879     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16880     * respond to the results of an over-scroll operation.
16881     *
16882     * @param scrollX New X scroll value in pixels
16883     * @param scrollY New Y scroll value in pixels
16884     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16885     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16886     */
16887    protected void onOverScrolled(int scrollX, int scrollY,
16888            boolean clampedX, boolean clampedY) {
16889        // Intentionally empty.
16890    }
16891
16892    /**
16893     * Returns the over-scroll mode for this view. The result will be
16894     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16895     * (allow over-scrolling only if the view content is larger than the container),
16896     * or {@link #OVER_SCROLL_NEVER}.
16897     *
16898     * @return This view's over-scroll mode.
16899     */
16900    public int getOverScrollMode() {
16901        return mOverScrollMode;
16902    }
16903
16904    /**
16905     * Set the over-scroll mode for this view. Valid over-scroll modes are
16906     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16907     * (allow over-scrolling only if the view content is larger than the container),
16908     * or {@link #OVER_SCROLL_NEVER}.
16909     *
16910     * Setting the over-scroll mode of a view will have an effect only if the
16911     * view is capable of scrolling.
16912     *
16913     * @param overScrollMode The new over-scroll mode for this view.
16914     */
16915    public void setOverScrollMode(int overScrollMode) {
16916        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16917                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16918                overScrollMode != OVER_SCROLL_NEVER) {
16919            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16920        }
16921        mOverScrollMode = overScrollMode;
16922    }
16923
16924    /**
16925     * Gets a scale factor that determines the distance the view should scroll
16926     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16927     * @return The vertical scroll scale factor.
16928     * @hide
16929     */
16930    protected float getVerticalScrollFactor() {
16931        if (mVerticalScrollFactor == 0) {
16932            TypedValue outValue = new TypedValue();
16933            if (!mContext.getTheme().resolveAttribute(
16934                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16935                throw new IllegalStateException(
16936                        "Expected theme to define listPreferredItemHeight.");
16937            }
16938            mVerticalScrollFactor = outValue.getDimension(
16939                    mContext.getResources().getDisplayMetrics());
16940        }
16941        return mVerticalScrollFactor;
16942    }
16943
16944    /**
16945     * Gets a scale factor that determines the distance the view should scroll
16946     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16947     * @return The horizontal scroll scale factor.
16948     * @hide
16949     */
16950    protected float getHorizontalScrollFactor() {
16951        // TODO: Should use something else.
16952        return getVerticalScrollFactor();
16953    }
16954
16955    /**
16956     * Return the value specifying the text direction or policy that was set with
16957     * {@link #setTextDirection(int)}.
16958     *
16959     * @return the defined text direction. It can be one of:
16960     *
16961     * {@link #TEXT_DIRECTION_INHERIT},
16962     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16963     * {@link #TEXT_DIRECTION_ANY_RTL},
16964     * {@link #TEXT_DIRECTION_LTR},
16965     * {@link #TEXT_DIRECTION_RTL},
16966     * {@link #TEXT_DIRECTION_LOCALE}
16967     *
16968     * @attr ref android.R.styleable#View_textDirection
16969     *
16970     * @hide
16971     */
16972    @ViewDebug.ExportedProperty(category = "text", mapping = {
16973            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16974            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16975            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16976            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16977            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16978            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16979    })
16980    public int getRawTextDirection() {
16981        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16982    }
16983
16984    /**
16985     * Set the text direction.
16986     *
16987     * @param textDirection the direction to set. Should be one of:
16988     *
16989     * {@link #TEXT_DIRECTION_INHERIT},
16990     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16991     * {@link #TEXT_DIRECTION_ANY_RTL},
16992     * {@link #TEXT_DIRECTION_LTR},
16993     * {@link #TEXT_DIRECTION_RTL},
16994     * {@link #TEXT_DIRECTION_LOCALE}
16995     *
16996     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
16997     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
16998     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
16999     *
17000     * @attr ref android.R.styleable#View_textDirection
17001     */
17002    public void setTextDirection(int textDirection) {
17003        if (getRawTextDirection() != textDirection) {
17004            // Reset the current text direction and the resolved one
17005            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17006            resetResolvedTextDirection();
17007            // Set the new text direction
17008            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17009            // Do resolution
17010            resolveTextDirection();
17011            // Notify change
17012            onRtlPropertiesChanged(getLayoutDirection());
17013            // Refresh
17014            requestLayout();
17015            invalidate(true);
17016        }
17017    }
17018
17019    /**
17020     * Return the resolved text direction.
17021     *
17022     * @return the resolved text direction. Returns one of:
17023     *
17024     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17025     * {@link #TEXT_DIRECTION_ANY_RTL},
17026     * {@link #TEXT_DIRECTION_LTR},
17027     * {@link #TEXT_DIRECTION_RTL},
17028     * {@link #TEXT_DIRECTION_LOCALE}
17029     *
17030     * @attr ref android.R.styleable#View_textDirection
17031     */
17032    @ViewDebug.ExportedProperty(category = "text", mapping = {
17033            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17034            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17035            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17036            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17037            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17038            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17039    })
17040    public int getTextDirection() {
17041        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17042    }
17043
17044    /**
17045     * Resolve the text direction.
17046     *
17047     * @return true if resolution has been done, false otherwise.
17048     *
17049     * @hide
17050     */
17051    public boolean resolveTextDirection() {
17052        // Reset any previous text direction resolution
17053        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17054
17055        if (hasRtlSupport()) {
17056            // Set resolved text direction flag depending on text direction flag
17057            final int textDirection = getRawTextDirection();
17058            switch(textDirection) {
17059                case TEXT_DIRECTION_INHERIT:
17060                    if (!canResolveTextDirection()) {
17061                        // We cannot do the resolution if there is no parent, so use the default one
17062                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17063                        // Resolution will need to happen again later
17064                        return false;
17065                    }
17066
17067                    // Parent has not yet resolved, so we still return the default
17068                    if (!mParent.isTextDirectionResolved()) {
17069                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17070                        // Resolution will need to happen again later
17071                        return false;
17072                    }
17073
17074                    // Set current resolved direction to the same value as the parent's one
17075                    final int parentResolvedDirection = mParent.getTextDirection();
17076                    switch (parentResolvedDirection) {
17077                        case TEXT_DIRECTION_FIRST_STRONG:
17078                        case TEXT_DIRECTION_ANY_RTL:
17079                        case TEXT_DIRECTION_LTR:
17080                        case TEXT_DIRECTION_RTL:
17081                        case TEXT_DIRECTION_LOCALE:
17082                            mPrivateFlags2 |=
17083                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17084                            break;
17085                        default:
17086                            // Default resolved direction is "first strong" heuristic
17087                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17088                    }
17089                    break;
17090                case TEXT_DIRECTION_FIRST_STRONG:
17091                case TEXT_DIRECTION_ANY_RTL:
17092                case TEXT_DIRECTION_LTR:
17093                case TEXT_DIRECTION_RTL:
17094                case TEXT_DIRECTION_LOCALE:
17095                    // Resolved direction is the same as text direction
17096                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17097                    break;
17098                default:
17099                    // Default resolved direction is "first strong" heuristic
17100                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17101            }
17102        } else {
17103            // Default resolved direction is "first strong" heuristic
17104            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17105        }
17106
17107        // Set to resolved
17108        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17109        return true;
17110    }
17111
17112    /**
17113     * Check if text direction resolution can be done.
17114     *
17115     * @return true if text direction resolution can be done otherwise return false.
17116     *
17117     * @hide
17118     */
17119    public boolean canResolveTextDirection() {
17120        switch (getRawTextDirection()) {
17121            case TEXT_DIRECTION_INHERIT:
17122                return (mParent != null) && mParent.canResolveTextDirection();
17123            default:
17124                return true;
17125        }
17126    }
17127
17128    /**
17129     * Reset resolved text direction. Text direction will be resolved during a call to
17130     * {@link #onMeasure(int, int)}.
17131     *
17132     * @hide
17133     */
17134    public void resetResolvedTextDirection() {
17135        // Reset any previous text direction resolution
17136        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17137        // Set to default value
17138        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17139    }
17140
17141    /**
17142     * @return true if text direction is inherited.
17143     *
17144     * @hide
17145     */
17146    public boolean isTextDirectionInherited() {
17147        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17148    }
17149
17150    /**
17151     * @return true if text direction is resolved.
17152     *
17153     * @hide
17154     */
17155    public boolean isTextDirectionResolved() {
17156        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17157    }
17158
17159    /**
17160     * Return the value specifying the text alignment or policy that was set with
17161     * {@link #setTextAlignment(int)}.
17162     *
17163     * @return the defined text alignment. It can be one of:
17164     *
17165     * {@link #TEXT_ALIGNMENT_INHERIT},
17166     * {@link #TEXT_ALIGNMENT_GRAVITY},
17167     * {@link #TEXT_ALIGNMENT_CENTER},
17168     * {@link #TEXT_ALIGNMENT_TEXT_START},
17169     * {@link #TEXT_ALIGNMENT_TEXT_END},
17170     * {@link #TEXT_ALIGNMENT_VIEW_START},
17171     * {@link #TEXT_ALIGNMENT_VIEW_END}
17172     *
17173     * @attr ref android.R.styleable#View_textAlignment
17174     *
17175     * @hide
17176     */
17177    @ViewDebug.ExportedProperty(category = "text", mapping = {
17178            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17179            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17180            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17181            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17182            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17183            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17184            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17185    })
17186    public int getRawTextAlignment() {
17187        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17188    }
17189
17190    /**
17191     * Set the text alignment.
17192     *
17193     * @param textAlignment The text alignment to set. Should be one of
17194     *
17195     * {@link #TEXT_ALIGNMENT_INHERIT},
17196     * {@link #TEXT_ALIGNMENT_GRAVITY},
17197     * {@link #TEXT_ALIGNMENT_CENTER},
17198     * {@link #TEXT_ALIGNMENT_TEXT_START},
17199     * {@link #TEXT_ALIGNMENT_TEXT_END},
17200     * {@link #TEXT_ALIGNMENT_VIEW_START},
17201     * {@link #TEXT_ALIGNMENT_VIEW_END}
17202     *
17203     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17204     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17205     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17206     *
17207     * @attr ref android.R.styleable#View_textAlignment
17208     */
17209    public void setTextAlignment(int textAlignment) {
17210        if (textAlignment != getRawTextAlignment()) {
17211            // Reset the current and resolved text alignment
17212            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17213            resetResolvedTextAlignment();
17214            // Set the new text alignment
17215            mPrivateFlags2 |=
17216                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17217            // Do resolution
17218            resolveTextAlignment();
17219            // Notify change
17220            onRtlPropertiesChanged(getLayoutDirection());
17221            // Refresh
17222            requestLayout();
17223            invalidate(true);
17224        }
17225    }
17226
17227    /**
17228     * Return the resolved text alignment.
17229     *
17230     * @return the resolved text alignment. Returns one of:
17231     *
17232     * {@link #TEXT_ALIGNMENT_GRAVITY},
17233     * {@link #TEXT_ALIGNMENT_CENTER},
17234     * {@link #TEXT_ALIGNMENT_TEXT_START},
17235     * {@link #TEXT_ALIGNMENT_TEXT_END},
17236     * {@link #TEXT_ALIGNMENT_VIEW_START},
17237     * {@link #TEXT_ALIGNMENT_VIEW_END}
17238     *
17239     * @attr ref android.R.styleable#View_textAlignment
17240     */
17241    @ViewDebug.ExportedProperty(category = "text", mapping = {
17242            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17243            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17244            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17245            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17246            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17247            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17248            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17249    })
17250    public int getTextAlignment() {
17251        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17252                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17253    }
17254
17255    /**
17256     * Resolve the text alignment.
17257     *
17258     * @return true if resolution has been done, false otherwise.
17259     *
17260     * @hide
17261     */
17262    public boolean resolveTextAlignment() {
17263        // Reset any previous text alignment resolution
17264        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17265
17266        if (hasRtlSupport()) {
17267            // Set resolved text alignment flag depending on text alignment flag
17268            final int textAlignment = getRawTextAlignment();
17269            switch (textAlignment) {
17270                case TEXT_ALIGNMENT_INHERIT:
17271                    // Check if we can resolve the text alignment
17272                    if (!canResolveTextAlignment()) {
17273                        // We cannot do the resolution if there is no parent so use the default
17274                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17275                        // Resolution will need to happen again later
17276                        return false;
17277                    }
17278
17279                    // Parent has not yet resolved, so we still return the default
17280                    if (!mParent.isTextAlignmentResolved()) {
17281                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17282                        // Resolution will need to happen again later
17283                        return false;
17284                    }
17285
17286                    final int parentResolvedTextAlignment = mParent.getTextAlignment();
17287                    switch (parentResolvedTextAlignment) {
17288                        case TEXT_ALIGNMENT_GRAVITY:
17289                        case TEXT_ALIGNMENT_TEXT_START:
17290                        case TEXT_ALIGNMENT_TEXT_END:
17291                        case TEXT_ALIGNMENT_CENTER:
17292                        case TEXT_ALIGNMENT_VIEW_START:
17293                        case TEXT_ALIGNMENT_VIEW_END:
17294                            // Resolved text alignment is the same as the parent resolved
17295                            // text alignment
17296                            mPrivateFlags2 |=
17297                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17298                            break;
17299                        default:
17300                            // Use default resolved text alignment
17301                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17302                    }
17303                    break;
17304                case TEXT_ALIGNMENT_GRAVITY:
17305                case TEXT_ALIGNMENT_TEXT_START:
17306                case TEXT_ALIGNMENT_TEXT_END:
17307                case TEXT_ALIGNMENT_CENTER:
17308                case TEXT_ALIGNMENT_VIEW_START:
17309                case TEXT_ALIGNMENT_VIEW_END:
17310                    // Resolved text alignment is the same as text alignment
17311                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17312                    break;
17313                default:
17314                    // Use default resolved text alignment
17315                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17316            }
17317        } else {
17318            // Use default resolved text alignment
17319            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17320        }
17321
17322        // Set the resolved
17323        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17324        return true;
17325    }
17326
17327    /**
17328     * Check if text alignment resolution can be done.
17329     *
17330     * @return true if text alignment resolution can be done otherwise return false.
17331     *
17332     * @hide
17333     */
17334    public boolean canResolveTextAlignment() {
17335        switch (getRawTextAlignment()) {
17336            case TEXT_DIRECTION_INHERIT:
17337                return (mParent != null) && mParent.canResolveTextAlignment();
17338            default:
17339                return true;
17340        }
17341    }
17342
17343    /**
17344     * Reset resolved text alignment. Text alignment will be resolved during a call to
17345     * {@link #onMeasure(int, int)}.
17346     *
17347     * @hide
17348     */
17349    public void resetResolvedTextAlignment() {
17350        // Reset any previous text alignment resolution
17351        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17352        // Set to default
17353        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17354    }
17355
17356    /**
17357     * @return true if text alignment is inherited.
17358     *
17359     * @hide
17360     */
17361    public boolean isTextAlignmentInherited() {
17362        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17363    }
17364
17365    /**
17366     * @return true if text alignment is resolved.
17367     *
17368     * @hide
17369     */
17370    public boolean isTextAlignmentResolved() {
17371        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17372    }
17373
17374    /**
17375     * Generate a value suitable for use in {@link #setId(int)}.
17376     * This value will not collide with ID values generated at build time by aapt for R.id.
17377     *
17378     * @return a generated ID value
17379     */
17380    public static int generateViewId() {
17381        for (;;) {
17382            final int result = sNextGeneratedId.get();
17383            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17384            int newValue = result + 1;
17385            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17386            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17387                return result;
17388            }
17389        }
17390    }
17391
17392    //
17393    // Properties
17394    //
17395    /**
17396     * A Property wrapper around the <code>alpha</code> functionality handled by the
17397     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17398     */
17399    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17400        @Override
17401        public void setValue(View object, float value) {
17402            object.setAlpha(value);
17403        }
17404
17405        @Override
17406        public Float get(View object) {
17407            return object.getAlpha();
17408        }
17409    };
17410
17411    /**
17412     * A Property wrapper around the <code>translationX</code> functionality handled by the
17413     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17414     */
17415    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17416        @Override
17417        public void setValue(View object, float value) {
17418            object.setTranslationX(value);
17419        }
17420
17421                @Override
17422        public Float get(View object) {
17423            return object.getTranslationX();
17424        }
17425    };
17426
17427    /**
17428     * A Property wrapper around the <code>translationY</code> functionality handled by the
17429     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17430     */
17431    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17432        @Override
17433        public void setValue(View object, float value) {
17434            object.setTranslationY(value);
17435        }
17436
17437        @Override
17438        public Float get(View object) {
17439            return object.getTranslationY();
17440        }
17441    };
17442
17443    /**
17444     * A Property wrapper around the <code>x</code> functionality handled by the
17445     * {@link View#setX(float)} and {@link View#getX()} methods.
17446     */
17447    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17448        @Override
17449        public void setValue(View object, float value) {
17450            object.setX(value);
17451        }
17452
17453        @Override
17454        public Float get(View object) {
17455            return object.getX();
17456        }
17457    };
17458
17459    /**
17460     * A Property wrapper around the <code>y</code> functionality handled by the
17461     * {@link View#setY(float)} and {@link View#getY()} methods.
17462     */
17463    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17464        @Override
17465        public void setValue(View object, float value) {
17466            object.setY(value);
17467        }
17468
17469        @Override
17470        public Float get(View object) {
17471            return object.getY();
17472        }
17473    };
17474
17475    /**
17476     * A Property wrapper around the <code>rotation</code> functionality handled by the
17477     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17478     */
17479    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17480        @Override
17481        public void setValue(View object, float value) {
17482            object.setRotation(value);
17483        }
17484
17485        @Override
17486        public Float get(View object) {
17487            return object.getRotation();
17488        }
17489    };
17490
17491    /**
17492     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17493     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17494     */
17495    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17496        @Override
17497        public void setValue(View object, float value) {
17498            object.setRotationX(value);
17499        }
17500
17501        @Override
17502        public Float get(View object) {
17503            return object.getRotationX();
17504        }
17505    };
17506
17507    /**
17508     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17509     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17510     */
17511    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17512        @Override
17513        public void setValue(View object, float value) {
17514            object.setRotationY(value);
17515        }
17516
17517        @Override
17518        public Float get(View object) {
17519            return object.getRotationY();
17520        }
17521    };
17522
17523    /**
17524     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17525     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17526     */
17527    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17528        @Override
17529        public void setValue(View object, float value) {
17530            object.setScaleX(value);
17531        }
17532
17533        @Override
17534        public Float get(View object) {
17535            return object.getScaleX();
17536        }
17537    };
17538
17539    /**
17540     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17541     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17542     */
17543    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17544        @Override
17545        public void setValue(View object, float value) {
17546            object.setScaleY(value);
17547        }
17548
17549        @Override
17550        public Float get(View object) {
17551            return object.getScaleY();
17552        }
17553    };
17554
17555    /**
17556     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17557     * Each MeasureSpec represents a requirement for either the width or the height.
17558     * A MeasureSpec is comprised of a size and a mode. There are three possible
17559     * modes:
17560     * <dl>
17561     * <dt>UNSPECIFIED</dt>
17562     * <dd>
17563     * The parent has not imposed any constraint on the child. It can be whatever size
17564     * it wants.
17565     * </dd>
17566     *
17567     * <dt>EXACTLY</dt>
17568     * <dd>
17569     * The parent has determined an exact size for the child. The child is going to be
17570     * given those bounds regardless of how big it wants to be.
17571     * </dd>
17572     *
17573     * <dt>AT_MOST</dt>
17574     * <dd>
17575     * The child can be as large as it wants up to the specified size.
17576     * </dd>
17577     * </dl>
17578     *
17579     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17580     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17581     */
17582    public static class MeasureSpec {
17583        private static final int MODE_SHIFT = 30;
17584        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17585
17586        /**
17587         * Measure specification mode: The parent has not imposed any constraint
17588         * on the child. It can be whatever size it wants.
17589         */
17590        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17591
17592        /**
17593         * Measure specification mode: The parent has determined an exact size
17594         * for the child. The child is going to be given those bounds regardless
17595         * of how big it wants to be.
17596         */
17597        public static final int EXACTLY     = 1 << MODE_SHIFT;
17598
17599        /**
17600         * Measure specification mode: The child can be as large as it wants up
17601         * to the specified size.
17602         */
17603        public static final int AT_MOST     = 2 << MODE_SHIFT;
17604
17605        /**
17606         * Creates a measure specification based on the supplied size and mode.
17607         *
17608         * The mode must always be one of the following:
17609         * <ul>
17610         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17611         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17612         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17613         * </ul>
17614         *
17615         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17616         * implementation was such that the order of arguments did not matter
17617         * and overflow in either value could impact the resulting MeasureSpec.
17618         * {@link android.widget.RelativeLayout} was affected by this bug.
17619         * Apps targeting API levels greater than 17 will get the fixed, more strict
17620         * behavior.</p>
17621         *
17622         * @param size the size of the measure specification
17623         * @param mode the mode of the measure specification
17624         * @return the measure specification based on size and mode
17625         */
17626        public static int makeMeasureSpec(int size, int mode) {
17627            if (sUseBrokenMakeMeasureSpec) {
17628                return size + mode;
17629            } else {
17630                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17631            }
17632        }
17633
17634        /**
17635         * Extracts the mode from the supplied measure specification.
17636         *
17637         * @param measureSpec the measure specification to extract the mode from
17638         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17639         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17640         *         {@link android.view.View.MeasureSpec#EXACTLY}
17641         */
17642        public static int getMode(int measureSpec) {
17643            return (measureSpec & MODE_MASK);
17644        }
17645
17646        /**
17647         * Extracts the size from the supplied measure specification.
17648         *
17649         * @param measureSpec the measure specification to extract the size from
17650         * @return the size in pixels defined in the supplied measure specification
17651         */
17652        public static int getSize(int measureSpec) {
17653            return (measureSpec & ~MODE_MASK);
17654        }
17655
17656        static int adjust(int measureSpec, int delta) {
17657            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17658        }
17659
17660        /**
17661         * Returns a String representation of the specified measure
17662         * specification.
17663         *
17664         * @param measureSpec the measure specification to convert to a String
17665         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17666         */
17667        public static String toString(int measureSpec) {
17668            int mode = getMode(measureSpec);
17669            int size = getSize(measureSpec);
17670
17671            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17672
17673            if (mode == UNSPECIFIED)
17674                sb.append("UNSPECIFIED ");
17675            else if (mode == EXACTLY)
17676                sb.append("EXACTLY ");
17677            else if (mode == AT_MOST)
17678                sb.append("AT_MOST ");
17679            else
17680                sb.append(mode).append(" ");
17681
17682            sb.append(size);
17683            return sb.toString();
17684        }
17685    }
17686
17687    class CheckForLongPress implements Runnable {
17688
17689        private int mOriginalWindowAttachCount;
17690
17691        public void run() {
17692            if (isPressed() && (mParent != null)
17693                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17694                if (performLongClick()) {
17695                    mHasPerformedLongPress = true;
17696                }
17697            }
17698        }
17699
17700        public void rememberWindowAttachCount() {
17701            mOriginalWindowAttachCount = mWindowAttachCount;
17702        }
17703    }
17704
17705    private final class CheckForTap implements Runnable {
17706        public void run() {
17707            mPrivateFlags &= ~PFLAG_PREPRESSED;
17708            setPressed(true);
17709            checkForLongClick(ViewConfiguration.getTapTimeout());
17710        }
17711    }
17712
17713    private final class PerformClick implements Runnable {
17714        public void run() {
17715            performClick();
17716        }
17717    }
17718
17719    /** @hide */
17720    public void hackTurnOffWindowResizeAnim(boolean off) {
17721        mAttachInfo.mTurnOffWindowResizeAnim = off;
17722    }
17723
17724    /**
17725     * This method returns a ViewPropertyAnimator object, which can be used to animate
17726     * specific properties on this View.
17727     *
17728     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17729     */
17730    public ViewPropertyAnimator animate() {
17731        if (mAnimator == null) {
17732            mAnimator = new ViewPropertyAnimator(this);
17733        }
17734        return mAnimator;
17735    }
17736
17737    /**
17738     * Interface definition for a callback to be invoked when a hardware key event is
17739     * dispatched to this view. The callback will be invoked before the key event is
17740     * given to the view. This is only useful for hardware keyboards; a software input
17741     * method has no obligation to trigger this listener.
17742     */
17743    public interface OnKeyListener {
17744        /**
17745         * Called when a hardware key is dispatched to a view. This allows listeners to
17746         * get a chance to respond before the target view.
17747         * <p>Key presses in software keyboards will generally NOT trigger this method,
17748         * although some may elect to do so in some situations. Do not assume a
17749         * software input method has to be key-based; even if it is, it may use key presses
17750         * in a different way than you expect, so there is no way to reliably catch soft
17751         * input key presses.
17752         *
17753         * @param v The view the key has been dispatched to.
17754         * @param keyCode The code for the physical key that was pressed
17755         * @param event The KeyEvent object containing full information about
17756         *        the event.
17757         * @return True if the listener has consumed the event, false otherwise.
17758         */
17759        boolean onKey(View v, int keyCode, KeyEvent event);
17760    }
17761
17762    /**
17763     * Interface definition for a callback to be invoked when a touch event is
17764     * dispatched to this view. The callback will be invoked before the touch
17765     * event is given to the view.
17766     */
17767    public interface OnTouchListener {
17768        /**
17769         * Called when a touch event is dispatched to a view. This allows listeners to
17770         * get a chance to respond before the target view.
17771         *
17772         * @param v The view the touch event has been dispatched to.
17773         * @param event The MotionEvent object containing full information about
17774         *        the event.
17775         * @return True if the listener has consumed the event, false otherwise.
17776         */
17777        boolean onTouch(View v, MotionEvent event);
17778    }
17779
17780    /**
17781     * Interface definition for a callback to be invoked when a hover event is
17782     * dispatched to this view. The callback will be invoked before the hover
17783     * event is given to the view.
17784     */
17785    public interface OnHoverListener {
17786        /**
17787         * Called when a hover event is dispatched to a view. This allows listeners to
17788         * get a chance to respond before the target view.
17789         *
17790         * @param v The view the hover event has been dispatched to.
17791         * @param event The MotionEvent object containing full information about
17792         *        the event.
17793         * @return True if the listener has consumed the event, false otherwise.
17794         */
17795        boolean onHover(View v, MotionEvent event);
17796    }
17797
17798    /**
17799     * Interface definition for a callback to be invoked when a generic motion event is
17800     * dispatched to this view. The callback will be invoked before the generic motion
17801     * event is given to the view.
17802     */
17803    public interface OnGenericMotionListener {
17804        /**
17805         * Called when a generic motion event is dispatched to a view. This allows listeners to
17806         * get a chance to respond before the target view.
17807         *
17808         * @param v The view the generic motion event has been dispatched to.
17809         * @param event The MotionEvent object containing full information about
17810         *        the event.
17811         * @return True if the listener has consumed the event, false otherwise.
17812         */
17813        boolean onGenericMotion(View v, MotionEvent event);
17814    }
17815
17816    /**
17817     * Interface definition for a callback to be invoked when a view has been clicked and held.
17818     */
17819    public interface OnLongClickListener {
17820        /**
17821         * Called when a view has been clicked and held.
17822         *
17823         * @param v The view that was clicked and held.
17824         *
17825         * @return true if the callback consumed the long click, false otherwise.
17826         */
17827        boolean onLongClick(View v);
17828    }
17829
17830    /**
17831     * Interface definition for a callback to be invoked when a drag is being dispatched
17832     * to this view.  The callback will be invoked before the hosting view's own
17833     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17834     * onDrag(event) behavior, it should return 'false' from this callback.
17835     *
17836     * <div class="special reference">
17837     * <h3>Developer Guides</h3>
17838     * <p>For a guide to implementing drag and drop features, read the
17839     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17840     * </div>
17841     */
17842    public interface OnDragListener {
17843        /**
17844         * Called when a drag event is dispatched to a view. This allows listeners
17845         * to get a chance to override base View behavior.
17846         *
17847         * @param v The View that received the drag event.
17848         * @param event The {@link android.view.DragEvent} object for the drag event.
17849         * @return {@code true} if the drag event was handled successfully, or {@code false}
17850         * if the drag event was not handled. Note that {@code false} will trigger the View
17851         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17852         */
17853        boolean onDrag(View v, DragEvent event);
17854    }
17855
17856    /**
17857     * Interface definition for a callback to be invoked when the focus state of
17858     * a view changed.
17859     */
17860    public interface OnFocusChangeListener {
17861        /**
17862         * Called when the focus state of a view has changed.
17863         *
17864         * @param v The view whose state has changed.
17865         * @param hasFocus The new focus state of v.
17866         */
17867        void onFocusChange(View v, boolean hasFocus);
17868    }
17869
17870    /**
17871     * Interface definition for a callback to be invoked when a view is clicked.
17872     */
17873    public interface OnClickListener {
17874        /**
17875         * Called when a view has been clicked.
17876         *
17877         * @param v The view that was clicked.
17878         */
17879        void onClick(View v);
17880    }
17881
17882    /**
17883     * Interface definition for a callback to be invoked when the context menu
17884     * for this view is being built.
17885     */
17886    public interface OnCreateContextMenuListener {
17887        /**
17888         * Called when the context menu for this view is being built. It is not
17889         * safe to hold onto the menu after this method returns.
17890         *
17891         * @param menu The context menu that is being built
17892         * @param v The view for which the context menu is being built
17893         * @param menuInfo Extra information about the item for which the
17894         *            context menu should be shown. This information will vary
17895         *            depending on the class of v.
17896         */
17897        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17898    }
17899
17900    /**
17901     * Interface definition for a callback to be invoked when the status bar changes
17902     * visibility.  This reports <strong>global</strong> changes to the system UI
17903     * state, not what the application is requesting.
17904     *
17905     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17906     */
17907    public interface OnSystemUiVisibilityChangeListener {
17908        /**
17909         * Called when the status bar changes visibility because of a call to
17910         * {@link View#setSystemUiVisibility(int)}.
17911         *
17912         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17913         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17914         * This tells you the <strong>global</strong> state of these UI visibility
17915         * flags, not what your app is currently applying.
17916         */
17917        public void onSystemUiVisibilityChange(int visibility);
17918    }
17919
17920    /**
17921     * Interface definition for a callback to be invoked when this view is attached
17922     * or detached from its window.
17923     */
17924    public interface OnAttachStateChangeListener {
17925        /**
17926         * Called when the view is attached to a window.
17927         * @param v The view that was attached
17928         */
17929        public void onViewAttachedToWindow(View v);
17930        /**
17931         * Called when the view is detached from a window.
17932         * @param v The view that was detached
17933         */
17934        public void onViewDetachedFromWindow(View v);
17935    }
17936
17937    private final class UnsetPressedState implements Runnable {
17938        public void run() {
17939            setPressed(false);
17940        }
17941    }
17942
17943    /**
17944     * Base class for derived classes that want to save and restore their own
17945     * state in {@link android.view.View#onSaveInstanceState()}.
17946     */
17947    public static class BaseSavedState extends AbsSavedState {
17948        /**
17949         * Constructor used when reading from a parcel. Reads the state of the superclass.
17950         *
17951         * @param source
17952         */
17953        public BaseSavedState(Parcel source) {
17954            super(source);
17955        }
17956
17957        /**
17958         * Constructor called by derived classes when creating their SavedState objects
17959         *
17960         * @param superState The state of the superclass of this view
17961         */
17962        public BaseSavedState(Parcelable superState) {
17963            super(superState);
17964        }
17965
17966        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17967                new Parcelable.Creator<BaseSavedState>() {
17968            public BaseSavedState createFromParcel(Parcel in) {
17969                return new BaseSavedState(in);
17970            }
17971
17972            public BaseSavedState[] newArray(int size) {
17973                return new BaseSavedState[size];
17974            }
17975        };
17976    }
17977
17978    /**
17979     * A set of information given to a view when it is attached to its parent
17980     * window.
17981     */
17982    static class AttachInfo {
17983        interface Callbacks {
17984            void playSoundEffect(int effectId);
17985            boolean performHapticFeedback(int effectId, boolean always);
17986        }
17987
17988        /**
17989         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17990         * to a Handler. This class contains the target (View) to invalidate and
17991         * the coordinates of the dirty rectangle.
17992         *
17993         * For performance purposes, this class also implements a pool of up to
17994         * POOL_LIMIT objects that get reused. This reduces memory allocations
17995         * whenever possible.
17996         */
17997        static class InvalidateInfo {
17998            private static final int POOL_LIMIT = 10;
17999
18000            private static final SynchronizedPool<InvalidateInfo> sPool =
18001                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18002
18003            View target;
18004
18005            int left;
18006            int top;
18007            int right;
18008            int bottom;
18009
18010            public static InvalidateInfo obtain() {
18011                InvalidateInfo instance = sPool.acquire();
18012                return (instance != null) ? instance : new InvalidateInfo();
18013            }
18014
18015            public void recycle() {
18016                target = null;
18017                sPool.release(this);
18018            }
18019        }
18020
18021        final IWindowSession mSession;
18022
18023        final IWindow mWindow;
18024
18025        final IBinder mWindowToken;
18026
18027        final Display mDisplay;
18028
18029        final Callbacks mRootCallbacks;
18030
18031        HardwareCanvas mHardwareCanvas;
18032
18033        IWindowId mIWindowId;
18034        WindowId mWindowId;
18035
18036        /**
18037         * The top view of the hierarchy.
18038         */
18039        View mRootView;
18040
18041        IBinder mPanelParentWindowToken;
18042        Surface mSurface;
18043
18044        boolean mHardwareAccelerated;
18045        boolean mHardwareAccelerationRequested;
18046        HardwareRenderer mHardwareRenderer;
18047
18048        boolean mScreenOn;
18049
18050        /**
18051         * Scale factor used by the compatibility mode
18052         */
18053        float mApplicationScale;
18054
18055        /**
18056         * Indicates whether the application is in compatibility mode
18057         */
18058        boolean mScalingRequired;
18059
18060        /**
18061         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18062         */
18063        boolean mTurnOffWindowResizeAnim;
18064
18065        /**
18066         * Left position of this view's window
18067         */
18068        int mWindowLeft;
18069
18070        /**
18071         * Top position of this view's window
18072         */
18073        int mWindowTop;
18074
18075        /**
18076         * Indicates whether views need to use 32-bit drawing caches
18077         */
18078        boolean mUse32BitDrawingCache;
18079
18080        /**
18081         * For windows that are full-screen but using insets to layout inside
18082         * of the screen areas, these are the current insets to appear inside
18083         * the overscan area of the display.
18084         */
18085        final Rect mOverscanInsets = new Rect();
18086
18087        /**
18088         * For windows that are full-screen but using insets to layout inside
18089         * of the screen decorations, these are the current insets for the
18090         * content of the window.
18091         */
18092        final Rect mContentInsets = new Rect();
18093
18094        /**
18095         * For windows that are full-screen but using insets to layout inside
18096         * of the screen decorations, these are the current insets for the
18097         * actual visible parts of the window.
18098         */
18099        final Rect mVisibleInsets = new Rect();
18100
18101        /**
18102         * The internal insets given by this window.  This value is
18103         * supplied by the client (through
18104         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18105         * be given to the window manager when changed to be used in laying
18106         * out windows behind it.
18107         */
18108        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18109                = new ViewTreeObserver.InternalInsetsInfo();
18110
18111        /**
18112         * All views in the window's hierarchy that serve as scroll containers,
18113         * used to determine if the window can be resized or must be panned
18114         * to adjust for a soft input area.
18115         */
18116        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18117
18118        final KeyEvent.DispatcherState mKeyDispatchState
18119                = new KeyEvent.DispatcherState();
18120
18121        /**
18122         * Indicates whether the view's window currently has the focus.
18123         */
18124        boolean mHasWindowFocus;
18125
18126        /**
18127         * The current visibility of the window.
18128         */
18129        int mWindowVisibility;
18130
18131        /**
18132         * Indicates the time at which drawing started to occur.
18133         */
18134        long mDrawingTime;
18135
18136        /**
18137         * Indicates whether or not ignoring the DIRTY_MASK flags.
18138         */
18139        boolean mIgnoreDirtyState;
18140
18141        /**
18142         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18143         * to avoid clearing that flag prematurely.
18144         */
18145        boolean mSetIgnoreDirtyState = false;
18146
18147        /**
18148         * Indicates whether the view's window is currently in touch mode.
18149         */
18150        boolean mInTouchMode;
18151
18152        /**
18153         * Indicates that ViewAncestor should trigger a global layout change
18154         * the next time it performs a traversal
18155         */
18156        boolean mRecomputeGlobalAttributes;
18157
18158        /**
18159         * Always report new attributes at next traversal.
18160         */
18161        boolean mForceReportNewAttributes;
18162
18163        /**
18164         * Set during a traveral if any views want to keep the screen on.
18165         */
18166        boolean mKeepScreenOn;
18167
18168        /**
18169         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18170         */
18171        int mSystemUiVisibility;
18172
18173        /**
18174         * Hack to force certain system UI visibility flags to be cleared.
18175         */
18176        int mDisabledSystemUiVisibility;
18177
18178        /**
18179         * Last global system UI visibility reported by the window manager.
18180         */
18181        int mGlobalSystemUiVisibility;
18182
18183        /**
18184         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18185         * attached.
18186         */
18187        boolean mHasSystemUiListeners;
18188
18189        /**
18190         * Set if the window has requested to extend into the overscan region
18191         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18192         */
18193        boolean mOverscanRequested;
18194
18195        /**
18196         * Set if the visibility of any views has changed.
18197         */
18198        boolean mViewVisibilityChanged;
18199
18200        /**
18201         * Set to true if a view has been scrolled.
18202         */
18203        boolean mViewScrollChanged;
18204
18205        /**
18206         * Global to the view hierarchy used as a temporary for dealing with
18207         * x/y points in the transparent region computations.
18208         */
18209        final int[] mTransparentLocation = new int[2];
18210
18211        /**
18212         * Global to the view hierarchy used as a temporary for dealing with
18213         * x/y points in the ViewGroup.invalidateChild implementation.
18214         */
18215        final int[] mInvalidateChildLocation = new int[2];
18216
18217
18218        /**
18219         * Global to the view hierarchy used as a temporary for dealing with
18220         * x/y location when view is transformed.
18221         */
18222        final float[] mTmpTransformLocation = new float[2];
18223
18224        /**
18225         * The view tree observer used to dispatch global events like
18226         * layout, pre-draw, touch mode change, etc.
18227         */
18228        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18229
18230        /**
18231         * A Canvas used by the view hierarchy to perform bitmap caching.
18232         */
18233        Canvas mCanvas;
18234
18235        /**
18236         * The view root impl.
18237         */
18238        final ViewRootImpl mViewRootImpl;
18239
18240        /**
18241         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18242         * handler can be used to pump events in the UI events queue.
18243         */
18244        final Handler mHandler;
18245
18246        /**
18247         * Temporary for use in computing invalidate rectangles while
18248         * calling up the hierarchy.
18249         */
18250        final Rect mTmpInvalRect = new Rect();
18251
18252        /**
18253         * Temporary for use in computing hit areas with transformed views
18254         */
18255        final RectF mTmpTransformRect = new RectF();
18256
18257        /**
18258         * Temporary for use in transforming invalidation rect
18259         */
18260        final Matrix mTmpMatrix = new Matrix();
18261
18262        /**
18263         * Temporary for use in transforming invalidation rect
18264         */
18265        final Transformation mTmpTransformation = new Transformation();
18266
18267        /**
18268         * Temporary list for use in collecting focusable descendents of a view.
18269         */
18270        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18271
18272        /**
18273         * The id of the window for accessibility purposes.
18274         */
18275        int mAccessibilityWindowId = View.NO_ID;
18276
18277        /**
18278         * Flags related to accessibility processing.
18279         *
18280         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18281         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18282         */
18283        int mAccessibilityFetchFlags;
18284
18285        /**
18286         * The drawable for highlighting accessibility focus.
18287         */
18288        Drawable mAccessibilityFocusDrawable;
18289
18290        /**
18291         * Show where the margins, bounds and layout bounds are for each view.
18292         */
18293        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18294
18295        /**
18296         * Point used to compute visible regions.
18297         */
18298        final Point mPoint = new Point();
18299
18300        /**
18301         * Used to track which View originated a requestLayout() call, used when
18302         * requestLayout() is called during layout.
18303         */
18304        View mViewRequestingLayout;
18305
18306        /**
18307         * Creates a new set of attachment information with the specified
18308         * events handler and thread.
18309         *
18310         * @param handler the events handler the view must use
18311         */
18312        AttachInfo(IWindowSession session, IWindow window, Display display,
18313                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18314            mSession = session;
18315            mWindow = window;
18316            mWindowToken = window.asBinder();
18317            mDisplay = display;
18318            mViewRootImpl = viewRootImpl;
18319            mHandler = handler;
18320            mRootCallbacks = effectPlayer;
18321        }
18322    }
18323
18324    /**
18325     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18326     * is supported. This avoids keeping too many unused fields in most
18327     * instances of View.</p>
18328     */
18329    private static class ScrollabilityCache implements Runnable {
18330
18331        /**
18332         * Scrollbars are not visible
18333         */
18334        public static final int OFF = 0;
18335
18336        /**
18337         * Scrollbars are visible
18338         */
18339        public static final int ON = 1;
18340
18341        /**
18342         * Scrollbars are fading away
18343         */
18344        public static final int FADING = 2;
18345
18346        public boolean fadeScrollBars;
18347
18348        public int fadingEdgeLength;
18349        public int scrollBarDefaultDelayBeforeFade;
18350        public int scrollBarFadeDuration;
18351
18352        public int scrollBarSize;
18353        public ScrollBarDrawable scrollBar;
18354        public float[] interpolatorValues;
18355        public View host;
18356
18357        public final Paint paint;
18358        public final Matrix matrix;
18359        public Shader shader;
18360
18361        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18362
18363        private static final float[] OPAQUE = { 255 };
18364        private static final float[] TRANSPARENT = { 0.0f };
18365
18366        /**
18367         * When fading should start. This time moves into the future every time
18368         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18369         */
18370        public long fadeStartTime;
18371
18372
18373        /**
18374         * The current state of the scrollbars: ON, OFF, or FADING
18375         */
18376        public int state = OFF;
18377
18378        private int mLastColor;
18379
18380        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18381            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18382            scrollBarSize = configuration.getScaledScrollBarSize();
18383            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18384            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18385
18386            paint = new Paint();
18387            matrix = new Matrix();
18388            // use use a height of 1, and then wack the matrix each time we
18389            // actually use it.
18390            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18391            paint.setShader(shader);
18392            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18393
18394            this.host = host;
18395        }
18396
18397        public void setFadeColor(int color) {
18398            if (color != mLastColor) {
18399                mLastColor = color;
18400
18401                if (color != 0) {
18402                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18403                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18404                    paint.setShader(shader);
18405                    // Restore the default transfer mode (src_over)
18406                    paint.setXfermode(null);
18407                } else {
18408                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18409                    paint.setShader(shader);
18410                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18411                }
18412            }
18413        }
18414
18415        public void run() {
18416            long now = AnimationUtils.currentAnimationTimeMillis();
18417            if (now >= fadeStartTime) {
18418
18419                // the animation fades the scrollbars out by changing
18420                // the opacity (alpha) from fully opaque to fully
18421                // transparent
18422                int nextFrame = (int) now;
18423                int framesCount = 0;
18424
18425                Interpolator interpolator = scrollBarInterpolator;
18426
18427                // Start opaque
18428                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18429
18430                // End transparent
18431                nextFrame += scrollBarFadeDuration;
18432                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18433
18434                state = FADING;
18435
18436                // Kick off the fade animation
18437                host.invalidate(true);
18438            }
18439        }
18440    }
18441
18442    /**
18443     * Resuable callback for sending
18444     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18445     */
18446    private class SendViewScrolledAccessibilityEvent implements Runnable {
18447        public volatile boolean mIsPending;
18448
18449        public void run() {
18450            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18451            mIsPending = false;
18452        }
18453    }
18454
18455    /**
18456     * <p>
18457     * This class represents a delegate that can be registered in a {@link View}
18458     * to enhance accessibility support via composition rather via inheritance.
18459     * It is specifically targeted to widget developers that extend basic View
18460     * classes i.e. classes in package android.view, that would like their
18461     * applications to be backwards compatible.
18462     * </p>
18463     * <div class="special reference">
18464     * <h3>Developer Guides</h3>
18465     * <p>For more information about making applications accessible, read the
18466     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18467     * developer guide.</p>
18468     * </div>
18469     * <p>
18470     * A scenario in which a developer would like to use an accessibility delegate
18471     * is overriding a method introduced in a later API version then the minimal API
18472     * version supported by the application. For example, the method
18473     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18474     * in API version 4 when the accessibility APIs were first introduced. If a
18475     * developer would like his application to run on API version 4 devices (assuming
18476     * all other APIs used by the application are version 4 or lower) and take advantage
18477     * of this method, instead of overriding the method which would break the application's
18478     * backwards compatibility, he can override the corresponding method in this
18479     * delegate and register the delegate in the target View if the API version of
18480     * the system is high enough i.e. the API version is same or higher to the API
18481     * version that introduced
18482     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18483     * </p>
18484     * <p>
18485     * Here is an example implementation:
18486     * </p>
18487     * <code><pre><p>
18488     * if (Build.VERSION.SDK_INT >= 14) {
18489     *     // If the API version is equal of higher than the version in
18490     *     // which onInitializeAccessibilityNodeInfo was introduced we
18491     *     // register a delegate with a customized implementation.
18492     *     View view = findViewById(R.id.view_id);
18493     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18494     *         public void onInitializeAccessibilityNodeInfo(View host,
18495     *                 AccessibilityNodeInfo info) {
18496     *             // Let the default implementation populate the info.
18497     *             super.onInitializeAccessibilityNodeInfo(host, info);
18498     *             // Set some other information.
18499     *             info.setEnabled(host.isEnabled());
18500     *         }
18501     *     });
18502     * }
18503     * </code></pre></p>
18504     * <p>
18505     * This delegate contains methods that correspond to the accessibility methods
18506     * in View. If a delegate has been specified the implementation in View hands
18507     * off handling to the corresponding method in this delegate. The default
18508     * implementation the delegate methods behaves exactly as the corresponding
18509     * method in View for the case of no accessibility delegate been set. Hence,
18510     * to customize the behavior of a View method, clients can override only the
18511     * corresponding delegate method without altering the behavior of the rest
18512     * accessibility related methods of the host view.
18513     * </p>
18514     */
18515    public static class AccessibilityDelegate {
18516
18517        /**
18518         * Sends an accessibility event of the given type. If accessibility is not
18519         * enabled this method has no effect.
18520         * <p>
18521         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18522         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18523         * been set.
18524         * </p>
18525         *
18526         * @param host The View hosting the delegate.
18527         * @param eventType The type of the event to send.
18528         *
18529         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18530         */
18531        public void sendAccessibilityEvent(View host, int eventType) {
18532            host.sendAccessibilityEventInternal(eventType);
18533        }
18534
18535        /**
18536         * Performs the specified accessibility action on the view. For
18537         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18538         * <p>
18539         * The default implementation behaves as
18540         * {@link View#performAccessibilityAction(int, Bundle)
18541         *  View#performAccessibilityAction(int, Bundle)} for the case of
18542         *  no accessibility delegate been set.
18543         * </p>
18544         *
18545         * @param action The action to perform.
18546         * @return Whether the action was performed.
18547         *
18548         * @see View#performAccessibilityAction(int, Bundle)
18549         *      View#performAccessibilityAction(int, Bundle)
18550         */
18551        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18552            return host.performAccessibilityActionInternal(action, args);
18553        }
18554
18555        /**
18556         * Sends an accessibility event. This method behaves exactly as
18557         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18558         * empty {@link AccessibilityEvent} and does not perform a check whether
18559         * accessibility is enabled.
18560         * <p>
18561         * The default implementation behaves as
18562         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18563         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18564         * the case of no accessibility delegate been set.
18565         * </p>
18566         *
18567         * @param host The View hosting the delegate.
18568         * @param event The event to send.
18569         *
18570         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18571         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18572         */
18573        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18574            host.sendAccessibilityEventUncheckedInternal(event);
18575        }
18576
18577        /**
18578         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18579         * to its children for adding their text content to the event.
18580         * <p>
18581         * The default implementation behaves as
18582         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18583         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18584         * the case of no accessibility delegate been set.
18585         * </p>
18586         *
18587         * @param host The View hosting the delegate.
18588         * @param event The event.
18589         * @return True if the event population was completed.
18590         *
18591         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18592         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18593         */
18594        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18595            return host.dispatchPopulateAccessibilityEventInternal(event);
18596        }
18597
18598        /**
18599         * Gives a chance to the host View to populate the accessibility event with its
18600         * text content.
18601         * <p>
18602         * The default implementation behaves as
18603         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18604         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18605         * the case of no accessibility delegate been set.
18606         * </p>
18607         *
18608         * @param host The View hosting the delegate.
18609         * @param event The accessibility event which to populate.
18610         *
18611         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18612         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18613         */
18614        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18615            host.onPopulateAccessibilityEventInternal(event);
18616        }
18617
18618        /**
18619         * Initializes an {@link AccessibilityEvent} with information about the
18620         * the host View which is the event source.
18621         * <p>
18622         * The default implementation behaves as
18623         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18624         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18625         * the case of no accessibility delegate been set.
18626         * </p>
18627         *
18628         * @param host The View hosting the delegate.
18629         * @param event The event to initialize.
18630         *
18631         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18632         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18633         */
18634        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18635            host.onInitializeAccessibilityEventInternal(event);
18636        }
18637
18638        /**
18639         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18640         * <p>
18641         * The default implementation behaves as
18642         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18643         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18644         * the case of no accessibility delegate been set.
18645         * </p>
18646         *
18647         * @param host The View hosting the delegate.
18648         * @param info The instance to initialize.
18649         *
18650         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18651         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18652         */
18653        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18654            host.onInitializeAccessibilityNodeInfoInternal(info);
18655        }
18656
18657        /**
18658         * Called when a child of the host View has requested sending an
18659         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18660         * to augment the event.
18661         * <p>
18662         * The default implementation behaves as
18663         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18664         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18665         * the case of no accessibility delegate been set.
18666         * </p>
18667         *
18668         * @param host The View hosting the delegate.
18669         * @param child The child which requests sending the event.
18670         * @param event The event to be sent.
18671         * @return True if the event should be sent
18672         *
18673         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18674         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18675         */
18676        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18677                AccessibilityEvent event) {
18678            return host.onRequestSendAccessibilityEventInternal(child, event);
18679        }
18680
18681        /**
18682         * Gets the provider for managing a virtual view hierarchy rooted at this View
18683         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18684         * that explore the window content.
18685         * <p>
18686         * The default implementation behaves as
18687         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18688         * the case of no accessibility delegate been set.
18689         * </p>
18690         *
18691         * @return The provider.
18692         *
18693         * @see AccessibilityNodeProvider
18694         */
18695        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18696            return null;
18697        }
18698    }
18699
18700    private class MatchIdPredicate implements Predicate<View> {
18701        public int mId;
18702
18703        @Override
18704        public boolean apply(View view) {
18705            return (view.mID == mId);
18706        }
18707    }
18708
18709    private class MatchLabelForPredicate implements Predicate<View> {
18710        private int mLabeledId;
18711
18712        @Override
18713        public boolean apply(View view) {
18714            return (view.mLabelForId == mLabeledId);
18715        }
18716    }
18717
18718    /**
18719     * Dump all private flags in readable format, useful for documentation and
18720     * sanity checking.
18721     */
18722    private static void dumpFlags() {
18723        final HashMap<String, String> found = Maps.newHashMap();
18724        try {
18725            for (Field field : View.class.getDeclaredFields()) {
18726                final int modifiers = field.getModifiers();
18727                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18728                    if (field.getType().equals(int.class)) {
18729                        final int value = field.getInt(null);
18730                        dumpFlag(found, field.getName(), value);
18731                    } else if (field.getType().equals(int[].class)) {
18732                        final int[] values = (int[]) field.get(null);
18733                        for (int i = 0; i < values.length; i++) {
18734                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18735                        }
18736                    }
18737                }
18738            }
18739        } catch (IllegalAccessException e) {
18740            throw new RuntimeException(e);
18741        }
18742
18743        final ArrayList<String> keys = Lists.newArrayList();
18744        keys.addAll(found.keySet());
18745        Collections.sort(keys);
18746        for (String key : keys) {
18747            Log.d(VIEW_LOG_TAG, found.get(key));
18748        }
18749    }
18750
18751    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18752        // Sort flags by prefix, then by bits, always keeping unique keys
18753        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18754        final int prefix = name.indexOf('_');
18755        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18756        final String output = bits + " " + name;
18757        found.put(key, output);
18758    }
18759}
18760