View.java revision 5495c726121737b5565ea58a28efdd6dbc471891
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        clearAccessibilityFocusNoCallbacks();
6621        // Clear the global reference of accessibility focus if this
6622        // view or any of its descendants had accessibility focus.
6623        ViewRootImpl viewRootImpl = getViewRootImpl();
6624        if (viewRootImpl != null) {
6625            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6626            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6627                viewRootImpl.setAccessibilityFocus(null, null);
6628            }
6629        }
6630    }
6631
6632    private void sendAccessibilityHoverEvent(int eventType) {
6633        // Since we are not delivering to a client accessibility events from not
6634        // important views (unless the clinet request that) we need to fire the
6635        // event from the deepest view exposed to the client. As a consequence if
6636        // the user crosses a not exposed view the client will see enter and exit
6637        // of the exposed predecessor followed by and enter and exit of that same
6638        // predecessor when entering and exiting the not exposed descendant. This
6639        // is fine since the client has a clear idea which view is hovered at the
6640        // price of a couple more events being sent. This is a simple and
6641        // working solution.
6642        View source = this;
6643        while (true) {
6644            if (source.includeForAccessibility()) {
6645                source.sendAccessibilityEvent(eventType);
6646                return;
6647            }
6648            ViewParent parent = source.getParent();
6649            if (parent instanceof View) {
6650                source = (View) parent;
6651            } else {
6652                return;
6653            }
6654        }
6655    }
6656
6657    /**
6658     * Clears accessibility focus without calling any callback methods
6659     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6660     * is used for clearing accessibility focus when giving this focus to
6661     * another view.
6662     */
6663    void clearAccessibilityFocusNoCallbacks() {
6664        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6665            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6666            invalidate();
6667            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6668            notifyAccessibilityStateChanged();
6669        }
6670    }
6671
6672    /**
6673     * Call this to try to give focus to a specific view or to one of its
6674     * descendants.
6675     *
6676     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6677     * false), or if it is focusable and it is not focusable in touch mode
6678     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6679     *
6680     * See also {@link #focusSearch(int)}, which is what you call to say that you
6681     * have focus, and you want your parent to look for the next one.
6682     *
6683     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6684     * {@link #FOCUS_DOWN} and <code>null</code>.
6685     *
6686     * @return Whether this view or one of its descendants actually took focus.
6687     */
6688    public final boolean requestFocus() {
6689        return requestFocus(View.FOCUS_DOWN);
6690    }
6691
6692    /**
6693     * Call this to try to give focus to a specific view or to one of its
6694     * descendants and give it a hint about what direction focus is heading.
6695     *
6696     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6697     * false), or if it is focusable and it is not focusable in touch mode
6698     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6699     *
6700     * See also {@link #focusSearch(int)}, which is what you call to say that you
6701     * have focus, and you want your parent to look for the next one.
6702     *
6703     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6704     * <code>null</code> set for the previously focused rectangle.
6705     *
6706     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6707     * @return Whether this view or one of its descendants actually took focus.
6708     */
6709    public final boolean requestFocus(int direction) {
6710        return requestFocus(direction, null);
6711    }
6712
6713    /**
6714     * Call this to try to give focus to a specific view or to one of its descendants
6715     * and give it hints about the direction and a specific rectangle that the focus
6716     * is coming from.  The rectangle can help give larger views a finer grained hint
6717     * about where focus is coming from, and therefore, where to show selection, or
6718     * forward focus change internally.
6719     *
6720     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6721     * false), or if it is focusable and it is not focusable in touch mode
6722     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6723     *
6724     * A View will not take focus if it is not visible.
6725     *
6726     * A View will not take focus if one of its parents has
6727     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6728     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6729     *
6730     * See also {@link #focusSearch(int)}, which is what you call to say that you
6731     * have focus, and you want your parent to look for the next one.
6732     *
6733     * You may wish to override this method if your custom {@link View} has an internal
6734     * {@link View} that it wishes to forward the request to.
6735     *
6736     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6737     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6738     *        to give a finer grained hint about where focus is coming from.  May be null
6739     *        if there is no hint.
6740     * @return Whether this view or one of its descendants actually took focus.
6741     */
6742    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6743        return requestFocusNoSearch(direction, previouslyFocusedRect);
6744    }
6745
6746    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6747        // need to be focusable
6748        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6749                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6750            return false;
6751        }
6752
6753        // need to be focusable in touch mode if in touch mode
6754        if (isInTouchMode() &&
6755            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6756               return false;
6757        }
6758
6759        // need to not have any parents blocking us
6760        if (hasAncestorThatBlocksDescendantFocus()) {
6761            return false;
6762        }
6763
6764        handleFocusGainInternal(direction, previouslyFocusedRect);
6765        return true;
6766    }
6767
6768    /**
6769     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6770     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6771     * touch mode to request focus when they are touched.
6772     *
6773     * @return Whether this view or one of its descendants actually took focus.
6774     *
6775     * @see #isInTouchMode()
6776     *
6777     */
6778    public final boolean requestFocusFromTouch() {
6779        // Leave touch mode if we need to
6780        if (isInTouchMode()) {
6781            ViewRootImpl viewRoot = getViewRootImpl();
6782            if (viewRoot != null) {
6783                viewRoot.ensureTouchMode(false);
6784            }
6785        }
6786        return requestFocus(View.FOCUS_DOWN);
6787    }
6788
6789    /**
6790     * @return Whether any ancestor of this view blocks descendant focus.
6791     */
6792    private boolean hasAncestorThatBlocksDescendantFocus() {
6793        ViewParent ancestor = mParent;
6794        while (ancestor instanceof ViewGroup) {
6795            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6796            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6797                return true;
6798            } else {
6799                ancestor = vgAncestor.getParent();
6800            }
6801        }
6802        return false;
6803    }
6804
6805    /**
6806     * Gets the mode for determining whether this View is important for accessibility
6807     * which is if it fires accessibility events and if it is reported to
6808     * accessibility services that query the screen.
6809     *
6810     * @return The mode for determining whether a View is important for accessibility.
6811     *
6812     * @attr ref android.R.styleable#View_importantForAccessibility
6813     *
6814     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6815     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6816     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6817     */
6818    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6819            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6820            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6821            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6822        })
6823    public int getImportantForAccessibility() {
6824        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6825                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6826    }
6827
6828    /**
6829     * Sets how to determine whether this view is important for accessibility
6830     * which is if it fires accessibility events and if it is reported to
6831     * accessibility services that query the screen.
6832     *
6833     * @param mode How to determine whether this view is important for accessibility.
6834     *
6835     * @attr ref android.R.styleable#View_importantForAccessibility
6836     *
6837     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6838     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6839     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6840     */
6841    public void setImportantForAccessibility(int mode) {
6842        if (mode != getImportantForAccessibility()) {
6843            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6844            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6845                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6846            notifyAccessibilityStateChanged();
6847        }
6848    }
6849
6850    /**
6851     * Gets whether this view should be exposed for accessibility.
6852     *
6853     * @return Whether the view is exposed for accessibility.
6854     *
6855     * @hide
6856     */
6857    public boolean isImportantForAccessibility() {
6858        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6859                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6860        switch (mode) {
6861            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6862                return true;
6863            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6864                return false;
6865            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6866                return isActionableForAccessibility() || hasListenersForAccessibility()
6867                        || getAccessibilityNodeProvider() != null;
6868            default:
6869                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6870                        + mode);
6871        }
6872    }
6873
6874    /**
6875     * Gets the parent for accessibility purposes. Note that the parent for
6876     * accessibility is not necessary the immediate parent. It is the first
6877     * predecessor that is important for accessibility.
6878     *
6879     * @return The parent for accessibility purposes.
6880     */
6881    public ViewParent getParentForAccessibility() {
6882        if (mParent instanceof View) {
6883            View parentView = (View) mParent;
6884            if (parentView.includeForAccessibility()) {
6885                return mParent;
6886            } else {
6887                return mParent.getParentForAccessibility();
6888            }
6889        }
6890        return null;
6891    }
6892
6893    /**
6894     * Adds the children of a given View for accessibility. Since some Views are
6895     * not important for accessibility the children for accessibility are not
6896     * necessarily direct children of the view, rather they are the first level of
6897     * descendants important for accessibility.
6898     *
6899     * @param children The list of children for accessibility.
6900     */
6901    public void addChildrenForAccessibility(ArrayList<View> children) {
6902        if (includeForAccessibility()) {
6903            children.add(this);
6904        }
6905    }
6906
6907    /**
6908     * Whether to regard this view for accessibility. A view is regarded for
6909     * accessibility if it is important for accessibility or the querying
6910     * accessibility service has explicitly requested that view not
6911     * important for accessibility are regarded.
6912     *
6913     * @return Whether to regard the view for accessibility.
6914     *
6915     * @hide
6916     */
6917    public boolean includeForAccessibility() {
6918        if (mAttachInfo != null) {
6919            return (mAttachInfo.mAccessibilityFetchFlags
6920                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6921                    || isImportantForAccessibility();
6922        }
6923        return false;
6924    }
6925
6926    /**
6927     * Returns whether the View is considered actionable from
6928     * accessibility perspective. Such view are important for
6929     * accessibility.
6930     *
6931     * @return True if the view is actionable for accessibility.
6932     *
6933     * @hide
6934     */
6935    public boolean isActionableForAccessibility() {
6936        return (isClickable() || isLongClickable() || isFocusable());
6937    }
6938
6939    /**
6940     * Returns whether the View has registered callbacks wich makes it
6941     * important for accessibility.
6942     *
6943     * @return True if the view is actionable for accessibility.
6944     */
6945    private boolean hasListenersForAccessibility() {
6946        ListenerInfo info = getListenerInfo();
6947        return mTouchDelegate != null || info.mOnKeyListener != null
6948                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6949                || info.mOnHoverListener != null || info.mOnDragListener != null;
6950    }
6951
6952    /**
6953     * Notifies accessibility services that some view's important for
6954     * accessibility state has changed. Note that such notifications
6955     * are made at most once every
6956     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6957     * to avoid unnecessary load to the system. Also once a view has
6958     * made a notifucation this method is a NOP until the notification has
6959     * been sent to clients.
6960     *
6961     * @hide
6962     *
6963     * TODO: Makse sure this method is called for any view state change
6964     *       that is interesting for accessilility purposes.
6965     */
6966    public void notifyAccessibilityStateChanged() {
6967        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6968            return;
6969        }
6970        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6971            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6972            if (mParent != null) {
6973                mParent.childAccessibilityStateChanged(this);
6974            }
6975        }
6976    }
6977
6978    /**
6979     * Reset the state indicating the this view has requested clients
6980     * interested in its accessibility state to be notified.
6981     *
6982     * @hide
6983     */
6984    public void resetAccessibilityStateChanged() {
6985        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6986    }
6987
6988    /**
6989     * Performs the specified accessibility action on the view. For
6990     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6991     * <p>
6992     * If an {@link AccessibilityDelegate} has been specified via calling
6993     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6994     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6995     * is responsible for handling this call.
6996     * </p>
6997     *
6998     * @param action The action to perform.
6999     * @param arguments Optional action arguments.
7000     * @return Whether the action was performed.
7001     */
7002    public boolean performAccessibilityAction(int action, Bundle arguments) {
7003      if (mAccessibilityDelegate != null) {
7004          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7005      } else {
7006          return performAccessibilityActionInternal(action, arguments);
7007      }
7008    }
7009
7010   /**
7011    * @see #performAccessibilityAction(int, Bundle)
7012    *
7013    * Note: Called from the default {@link AccessibilityDelegate}.
7014    */
7015    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7016        switch (action) {
7017            case AccessibilityNodeInfo.ACTION_CLICK: {
7018                if (isClickable()) {
7019                    performClick();
7020                    return true;
7021                }
7022            } break;
7023            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7024                if (isLongClickable()) {
7025                    performLongClick();
7026                    return true;
7027                }
7028            } break;
7029            case AccessibilityNodeInfo.ACTION_FOCUS: {
7030                if (!hasFocus()) {
7031                    // Get out of touch mode since accessibility
7032                    // wants to move focus around.
7033                    getViewRootImpl().ensureTouchMode(false);
7034                    return requestFocus();
7035                }
7036            } break;
7037            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7038                if (hasFocus()) {
7039                    clearFocus();
7040                    return !isFocused();
7041                }
7042            } break;
7043            case AccessibilityNodeInfo.ACTION_SELECT: {
7044                if (!isSelected()) {
7045                    setSelected(true);
7046                    return isSelected();
7047                }
7048            } break;
7049            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7050                if (isSelected()) {
7051                    setSelected(false);
7052                    return !isSelected();
7053                }
7054            } break;
7055            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7056                if (!isAccessibilityFocused()) {
7057                    return requestAccessibilityFocus();
7058                }
7059            } break;
7060            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7061                if (isAccessibilityFocused()) {
7062                    clearAccessibilityFocus();
7063                    return true;
7064                }
7065            } break;
7066            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7067                if (arguments != null) {
7068                    final int granularity = arguments.getInt(
7069                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7070                    final boolean extendSelection = arguments.getBoolean(
7071                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7072                    return traverseAtGranularity(granularity, true, extendSelection);
7073                }
7074            } break;
7075            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7076                if (arguments != null) {
7077                    final int granularity = arguments.getInt(
7078                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7079                    final boolean extendSelection = arguments.getBoolean(
7080                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7081                    return traverseAtGranularity(granularity, false, extendSelection);
7082                }
7083            } break;
7084            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7085                CharSequence text = getIterableTextForAccessibility();
7086                if (text == null) {
7087                    return false;
7088                }
7089                final int start = (arguments != null) ? arguments.getInt(
7090                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7091                final int end = (arguments != null) ? arguments.getInt(
7092                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7093                // Only cursor position can be specified (selection length == 0)
7094                if ((getAccessibilitySelectionStart() != start
7095                        || getAccessibilitySelectionEnd() != end)
7096                        && (start == end)) {
7097                    setAccessibilitySelection(start, end);
7098                    notifyAccessibilityStateChanged();
7099                    return true;
7100                }
7101            } break;
7102        }
7103        return false;
7104    }
7105
7106    private boolean traverseAtGranularity(int granularity, boolean forward,
7107            boolean extendSelection) {
7108        CharSequence text = getIterableTextForAccessibility();
7109        if (text == null || text.length() == 0) {
7110            return false;
7111        }
7112        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7113        if (iterator == null) {
7114            return false;
7115        }
7116        int current = getAccessibilitySelectionEnd();
7117        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7118            current = forward ? 0 : text.length();
7119        }
7120        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7121        if (range == null) {
7122            return false;
7123        }
7124        final int segmentStart = range[0];
7125        final int segmentEnd = range[1];
7126        int selectionStart;
7127        int selectionEnd;
7128        if (extendSelection && isAccessibilitySelectionExtendable()) {
7129            selectionStart = getAccessibilitySelectionStart();
7130            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7131                selectionStart = forward ? segmentStart : segmentEnd;
7132            }
7133            selectionEnd = forward ? segmentEnd : segmentStart;
7134        } else {
7135            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7136        }
7137        setAccessibilitySelection(selectionStart, selectionEnd);
7138        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7139                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7140        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7141        return true;
7142    }
7143
7144    /**
7145     * Gets the text reported for accessibility purposes.
7146     *
7147     * @return The accessibility text.
7148     *
7149     * @hide
7150     */
7151    public CharSequence getIterableTextForAccessibility() {
7152        return getContentDescription();
7153    }
7154
7155    /**
7156     * Gets whether accessibility selection can be extended.
7157     *
7158     * @return If selection is extensible.
7159     *
7160     * @hide
7161     */
7162    public boolean isAccessibilitySelectionExtendable() {
7163        return false;
7164    }
7165
7166    /**
7167     * @hide
7168     */
7169    public int getAccessibilitySelectionStart() {
7170        return mAccessibilityCursorPosition;
7171    }
7172
7173    /**
7174     * @hide
7175     */
7176    public int getAccessibilitySelectionEnd() {
7177        return getAccessibilitySelectionStart();
7178    }
7179
7180    /**
7181     * @hide
7182     */
7183    public void setAccessibilitySelection(int start, int end) {
7184        if (start ==  end && end == mAccessibilityCursorPosition) {
7185            return;
7186        }
7187        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7188            mAccessibilityCursorPosition = start;
7189        } else {
7190            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7191        }
7192        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7193    }
7194
7195    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7196            int fromIndex, int toIndex) {
7197        if (mParent == null) {
7198            return;
7199        }
7200        AccessibilityEvent event = AccessibilityEvent.obtain(
7201                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7202        onInitializeAccessibilityEvent(event);
7203        onPopulateAccessibilityEvent(event);
7204        event.setFromIndex(fromIndex);
7205        event.setToIndex(toIndex);
7206        event.setAction(action);
7207        event.setMovementGranularity(granularity);
7208        mParent.requestSendAccessibilityEvent(this, event);
7209    }
7210
7211    /**
7212     * @hide
7213     */
7214    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7215        switch (granularity) {
7216            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7217                CharSequence text = getIterableTextForAccessibility();
7218                if (text != null && text.length() > 0) {
7219                    CharacterTextSegmentIterator iterator =
7220                        CharacterTextSegmentIterator.getInstance(
7221                                mContext.getResources().getConfiguration().locale);
7222                    iterator.initialize(text.toString());
7223                    return iterator;
7224                }
7225            } break;
7226            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7227                CharSequence text = getIterableTextForAccessibility();
7228                if (text != null && text.length() > 0) {
7229                    WordTextSegmentIterator iterator =
7230                        WordTextSegmentIterator.getInstance(
7231                                mContext.getResources().getConfiguration().locale);
7232                    iterator.initialize(text.toString());
7233                    return iterator;
7234                }
7235            } break;
7236            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7237                CharSequence text = getIterableTextForAccessibility();
7238                if (text != null && text.length() > 0) {
7239                    ParagraphTextSegmentIterator iterator =
7240                        ParagraphTextSegmentIterator.getInstance();
7241                    iterator.initialize(text.toString());
7242                    return iterator;
7243                }
7244            } break;
7245        }
7246        return null;
7247    }
7248
7249    /**
7250     * @hide
7251     */
7252    public void dispatchStartTemporaryDetach() {
7253        clearAccessibilityFocus();
7254        clearDisplayList();
7255
7256        onStartTemporaryDetach();
7257    }
7258
7259    /**
7260     * This is called when a container is going to temporarily detach a child, with
7261     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7262     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7263     * {@link #onDetachedFromWindow()} when the container is done.
7264     */
7265    public void onStartTemporaryDetach() {
7266        removeUnsetPressCallback();
7267        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7268    }
7269
7270    /**
7271     * @hide
7272     */
7273    public void dispatchFinishTemporaryDetach() {
7274        onFinishTemporaryDetach();
7275    }
7276
7277    /**
7278     * Called after {@link #onStartTemporaryDetach} when the container is done
7279     * changing the view.
7280     */
7281    public void onFinishTemporaryDetach() {
7282    }
7283
7284    /**
7285     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7286     * for this view's window.  Returns null if the view is not currently attached
7287     * to the window.  Normally you will not need to use this directly, but
7288     * just use the standard high-level event callbacks like
7289     * {@link #onKeyDown(int, KeyEvent)}.
7290     */
7291    public KeyEvent.DispatcherState getKeyDispatcherState() {
7292        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7293    }
7294
7295    /**
7296     * Dispatch a key event before it is processed by any input method
7297     * associated with the view hierarchy.  This can be used to intercept
7298     * key events in special situations before the IME consumes them; a
7299     * typical example would be handling the BACK key to update the application's
7300     * UI instead of allowing the IME to see it and close itself.
7301     *
7302     * @param event The key event to be dispatched.
7303     * @return True if the event was handled, false otherwise.
7304     */
7305    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7306        return onKeyPreIme(event.getKeyCode(), event);
7307    }
7308
7309    /**
7310     * Dispatch a key event to the next view on the focus path. This path runs
7311     * from the top of the view tree down to the currently focused view. If this
7312     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7313     * the next node down the focus path. This method also fires any key
7314     * listeners.
7315     *
7316     * @param event The key event to be dispatched.
7317     * @return True if the event was handled, false otherwise.
7318     */
7319    public boolean dispatchKeyEvent(KeyEvent event) {
7320        if (mInputEventConsistencyVerifier != null) {
7321            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7322        }
7323
7324        // Give any attached key listener a first crack at the event.
7325        //noinspection SimplifiableIfStatement
7326        ListenerInfo li = mListenerInfo;
7327        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7328                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7329            return true;
7330        }
7331
7332        if (event.dispatch(this, mAttachInfo != null
7333                ? mAttachInfo.mKeyDispatchState : null, this)) {
7334            return true;
7335        }
7336
7337        if (mInputEventConsistencyVerifier != null) {
7338            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7339        }
7340        return false;
7341    }
7342
7343    /**
7344     * Dispatches a key shortcut event.
7345     *
7346     * @param event The key event to be dispatched.
7347     * @return True if the event was handled by the view, false otherwise.
7348     */
7349    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7350        return onKeyShortcut(event.getKeyCode(), event);
7351    }
7352
7353    /**
7354     * Pass the touch screen motion event down to the target view, or this
7355     * view if it is the target.
7356     *
7357     * @param event The motion event to be dispatched.
7358     * @return True if the event was handled by the view, false otherwise.
7359     */
7360    public boolean dispatchTouchEvent(MotionEvent event) {
7361        if (mInputEventConsistencyVerifier != null) {
7362            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7363        }
7364
7365        if (onFilterTouchEventForSecurity(event)) {
7366            //noinspection SimplifiableIfStatement
7367            ListenerInfo li = mListenerInfo;
7368            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7369                    && li.mOnTouchListener.onTouch(this, event)) {
7370                return true;
7371            }
7372
7373            if (onTouchEvent(event)) {
7374                return true;
7375            }
7376        }
7377
7378        if (mInputEventConsistencyVerifier != null) {
7379            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7380        }
7381        return false;
7382    }
7383
7384    /**
7385     * Filter the touch event to apply security policies.
7386     *
7387     * @param event The motion event to be filtered.
7388     * @return True if the event should be dispatched, false if the event should be dropped.
7389     *
7390     * @see #getFilterTouchesWhenObscured
7391     */
7392    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7393        //noinspection RedundantIfStatement
7394        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7395                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7396            // Window is obscured, drop this touch.
7397            return false;
7398        }
7399        return true;
7400    }
7401
7402    /**
7403     * Pass a trackball motion event down to the focused view.
7404     *
7405     * @param event The motion event to be dispatched.
7406     * @return True if the event was handled by the view, false otherwise.
7407     */
7408    public boolean dispatchTrackballEvent(MotionEvent event) {
7409        if (mInputEventConsistencyVerifier != null) {
7410            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7411        }
7412
7413        return onTrackballEvent(event);
7414    }
7415
7416    /**
7417     * Dispatch a generic motion event.
7418     * <p>
7419     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7420     * are delivered to the view under the pointer.  All other generic motion events are
7421     * delivered to the focused view.  Hover events are handled specially and are delivered
7422     * to {@link #onHoverEvent(MotionEvent)}.
7423     * </p>
7424     *
7425     * @param event The motion event to be dispatched.
7426     * @return True if the event was handled by the view, false otherwise.
7427     */
7428    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7429        if (mInputEventConsistencyVerifier != null) {
7430            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7431        }
7432
7433        final int source = event.getSource();
7434        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7435            final int action = event.getAction();
7436            if (action == MotionEvent.ACTION_HOVER_ENTER
7437                    || action == MotionEvent.ACTION_HOVER_MOVE
7438                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7439                if (dispatchHoverEvent(event)) {
7440                    return true;
7441                }
7442            } else if (dispatchGenericPointerEvent(event)) {
7443                return true;
7444            }
7445        } else if (dispatchGenericFocusedEvent(event)) {
7446            return true;
7447        }
7448
7449        if (dispatchGenericMotionEventInternal(event)) {
7450            return true;
7451        }
7452
7453        if (mInputEventConsistencyVerifier != null) {
7454            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7455        }
7456        return false;
7457    }
7458
7459    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7460        //noinspection SimplifiableIfStatement
7461        ListenerInfo li = mListenerInfo;
7462        if (li != null && li.mOnGenericMotionListener != null
7463                && (mViewFlags & ENABLED_MASK) == ENABLED
7464                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7465            return true;
7466        }
7467
7468        if (onGenericMotionEvent(event)) {
7469            return true;
7470        }
7471
7472        if (mInputEventConsistencyVerifier != null) {
7473            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7474        }
7475        return false;
7476    }
7477
7478    /**
7479     * Dispatch a hover event.
7480     * <p>
7481     * Do not call this method directly.
7482     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7483     * </p>
7484     *
7485     * @param event The motion event to be dispatched.
7486     * @return True if the event was handled by the view, false otherwise.
7487     */
7488    protected boolean dispatchHoverEvent(MotionEvent event) {
7489        //noinspection SimplifiableIfStatement
7490        ListenerInfo li = mListenerInfo;
7491        if (li != null && li.mOnHoverListener != null
7492                && (mViewFlags & ENABLED_MASK) == ENABLED
7493                && li.mOnHoverListener.onHover(this, event)) {
7494            return true;
7495        }
7496
7497        return onHoverEvent(event);
7498    }
7499
7500    /**
7501     * Returns true if the view has a child to which it has recently sent
7502     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7503     * it does not have a hovered child, then it must be the innermost hovered view.
7504     * @hide
7505     */
7506    protected boolean hasHoveredChild() {
7507        return false;
7508    }
7509
7510    /**
7511     * Dispatch a generic motion event to the view under the first pointer.
7512     * <p>
7513     * Do not call this method directly.
7514     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7515     * </p>
7516     *
7517     * @param event The motion event to be dispatched.
7518     * @return True if the event was handled by the view, false otherwise.
7519     */
7520    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7521        return false;
7522    }
7523
7524    /**
7525     * Dispatch a generic motion event to the currently focused view.
7526     * <p>
7527     * Do not call this method directly.
7528     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7529     * </p>
7530     *
7531     * @param event The motion event to be dispatched.
7532     * @return True if the event was handled by the view, false otherwise.
7533     */
7534    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7535        return false;
7536    }
7537
7538    /**
7539     * Dispatch a pointer event.
7540     * <p>
7541     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7542     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7543     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7544     * and should not be expected to handle other pointing device features.
7545     * </p>
7546     *
7547     * @param event The motion event to be dispatched.
7548     * @return True if the event was handled by the view, false otherwise.
7549     * @hide
7550     */
7551    public final boolean dispatchPointerEvent(MotionEvent event) {
7552        if (event.isTouchEvent()) {
7553            return dispatchTouchEvent(event);
7554        } else {
7555            return dispatchGenericMotionEvent(event);
7556        }
7557    }
7558
7559    /**
7560     * Called when the window containing this view gains or loses window focus.
7561     * ViewGroups should override to route to their children.
7562     *
7563     * @param hasFocus True if the window containing this view now has focus,
7564     *        false otherwise.
7565     */
7566    public void dispatchWindowFocusChanged(boolean hasFocus) {
7567        onWindowFocusChanged(hasFocus);
7568    }
7569
7570    /**
7571     * Called when the window containing this view gains or loses focus.  Note
7572     * that this is separate from view focus: to receive key events, both
7573     * your view and its window must have focus.  If a window is displayed
7574     * on top of yours that takes input focus, then your own window will lose
7575     * focus but the view focus will remain unchanged.
7576     *
7577     * @param hasWindowFocus True if the window containing this view now has
7578     *        focus, false otherwise.
7579     */
7580    public void onWindowFocusChanged(boolean hasWindowFocus) {
7581        InputMethodManager imm = InputMethodManager.peekInstance();
7582        if (!hasWindowFocus) {
7583            if (isPressed()) {
7584                setPressed(false);
7585            }
7586            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7587                imm.focusOut(this);
7588            }
7589            removeLongPressCallback();
7590            removeTapCallback();
7591            onFocusLost();
7592        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7593            imm.focusIn(this);
7594        }
7595        refreshDrawableState();
7596    }
7597
7598    /**
7599     * Returns true if this view is in a window that currently has window focus.
7600     * Note that this is not the same as the view itself having focus.
7601     *
7602     * @return True if this view is in a window that currently has window focus.
7603     */
7604    public boolean hasWindowFocus() {
7605        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7606    }
7607
7608    /**
7609     * Dispatch a view visibility change down the view hierarchy.
7610     * ViewGroups should override to route to their children.
7611     * @param changedView The view whose visibility changed. Could be 'this' or
7612     * an ancestor view.
7613     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7614     * {@link #INVISIBLE} or {@link #GONE}.
7615     */
7616    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7617        onVisibilityChanged(changedView, visibility);
7618    }
7619
7620    /**
7621     * Called when the visibility of the view or an ancestor of the view is changed.
7622     * @param changedView The view whose visibility changed. Could be 'this' or
7623     * an ancestor view.
7624     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7625     * {@link #INVISIBLE} or {@link #GONE}.
7626     */
7627    protected void onVisibilityChanged(View changedView, int visibility) {
7628        if (visibility == VISIBLE) {
7629            if (mAttachInfo != null) {
7630                initialAwakenScrollBars();
7631            } else {
7632                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7633            }
7634        }
7635    }
7636
7637    /**
7638     * Dispatch a hint about whether this view is displayed. For instance, when
7639     * a View moves out of the screen, it might receives a display hint indicating
7640     * the view is not displayed. Applications should not <em>rely</em> on this hint
7641     * as there is no guarantee that they will receive one.
7642     *
7643     * @param hint A hint about whether or not this view is displayed:
7644     * {@link #VISIBLE} or {@link #INVISIBLE}.
7645     */
7646    public void dispatchDisplayHint(int hint) {
7647        onDisplayHint(hint);
7648    }
7649
7650    /**
7651     * Gives this view a hint about whether is displayed or not. For instance, when
7652     * a View moves out of the screen, it might receives a display hint indicating
7653     * the view is not displayed. Applications should not <em>rely</em> on this hint
7654     * as there is no guarantee that they will receive one.
7655     *
7656     * @param hint A hint about whether or not this view is displayed:
7657     * {@link #VISIBLE} or {@link #INVISIBLE}.
7658     */
7659    protected void onDisplayHint(int hint) {
7660    }
7661
7662    /**
7663     * Dispatch a window visibility change down the view hierarchy.
7664     * ViewGroups should override to route to their children.
7665     *
7666     * @param visibility The new visibility of the window.
7667     *
7668     * @see #onWindowVisibilityChanged(int)
7669     */
7670    public void dispatchWindowVisibilityChanged(int visibility) {
7671        onWindowVisibilityChanged(visibility);
7672    }
7673
7674    /**
7675     * Called when the window containing has change its visibility
7676     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7677     * that this tells you whether or not your window is being made visible
7678     * to the window manager; this does <em>not</em> tell you whether or not
7679     * your window is obscured by other windows on the screen, even if it
7680     * is itself visible.
7681     *
7682     * @param visibility The new visibility of the window.
7683     */
7684    protected void onWindowVisibilityChanged(int visibility) {
7685        if (visibility == VISIBLE) {
7686            initialAwakenScrollBars();
7687        }
7688    }
7689
7690    /**
7691     * Returns the current visibility of the window this view is attached to
7692     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7693     *
7694     * @return Returns the current visibility of the view's window.
7695     */
7696    public int getWindowVisibility() {
7697        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7698    }
7699
7700    /**
7701     * Retrieve the overall visible display size in which the window this view is
7702     * attached to has been positioned in.  This takes into account screen
7703     * decorations above the window, for both cases where the window itself
7704     * is being position inside of them or the window is being placed under
7705     * then and covered insets are used for the window to position its content
7706     * inside.  In effect, this tells you the available area where content can
7707     * be placed and remain visible to users.
7708     *
7709     * <p>This function requires an IPC back to the window manager to retrieve
7710     * the requested information, so should not be used in performance critical
7711     * code like drawing.
7712     *
7713     * @param outRect Filled in with the visible display frame.  If the view
7714     * is not attached to a window, this is simply the raw display size.
7715     */
7716    public void getWindowVisibleDisplayFrame(Rect outRect) {
7717        if (mAttachInfo != null) {
7718            try {
7719                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7720            } catch (RemoteException e) {
7721                return;
7722            }
7723            // XXX This is really broken, and probably all needs to be done
7724            // in the window manager, and we need to know more about whether
7725            // we want the area behind or in front of the IME.
7726            final Rect insets = mAttachInfo.mVisibleInsets;
7727            outRect.left += insets.left;
7728            outRect.top += insets.top;
7729            outRect.right -= insets.right;
7730            outRect.bottom -= insets.bottom;
7731            return;
7732        }
7733        // The view is not attached to a display so we don't have a context.
7734        // Make a best guess about the display size.
7735        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7736        d.getRectSize(outRect);
7737    }
7738
7739    /**
7740     * Dispatch a notification about a resource configuration change down
7741     * the view hierarchy.
7742     * ViewGroups should override to route to their children.
7743     *
7744     * @param newConfig The new resource configuration.
7745     *
7746     * @see #onConfigurationChanged(android.content.res.Configuration)
7747     */
7748    public void dispatchConfigurationChanged(Configuration newConfig) {
7749        onConfigurationChanged(newConfig);
7750    }
7751
7752    /**
7753     * Called when the current configuration of the resources being used
7754     * by the application have changed.  You can use this to decide when
7755     * to reload resources that can changed based on orientation and other
7756     * configuration characterstics.  You only need to use this if you are
7757     * not relying on the normal {@link android.app.Activity} mechanism of
7758     * recreating the activity instance upon a configuration change.
7759     *
7760     * @param newConfig The new resource configuration.
7761     */
7762    protected void onConfigurationChanged(Configuration newConfig) {
7763    }
7764
7765    /**
7766     * Private function to aggregate all per-view attributes in to the view
7767     * root.
7768     */
7769    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7770        performCollectViewAttributes(attachInfo, visibility);
7771    }
7772
7773    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7774        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7775            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7776                attachInfo.mKeepScreenOn = true;
7777            }
7778            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7779            ListenerInfo li = mListenerInfo;
7780            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7781                attachInfo.mHasSystemUiListeners = true;
7782            }
7783        }
7784    }
7785
7786    void needGlobalAttributesUpdate(boolean force) {
7787        final AttachInfo ai = mAttachInfo;
7788        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7789            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7790                    || ai.mHasSystemUiListeners) {
7791                ai.mRecomputeGlobalAttributes = true;
7792            }
7793        }
7794    }
7795
7796    /**
7797     * Returns whether the device is currently in touch mode.  Touch mode is entered
7798     * once the user begins interacting with the device by touch, and affects various
7799     * things like whether focus is always visible to the user.
7800     *
7801     * @return Whether the device is in touch mode.
7802     */
7803    @ViewDebug.ExportedProperty
7804    public boolean isInTouchMode() {
7805        if (mAttachInfo != null) {
7806            return mAttachInfo.mInTouchMode;
7807        } else {
7808            return ViewRootImpl.isInTouchMode();
7809        }
7810    }
7811
7812    /**
7813     * Returns the context the view is running in, through which it can
7814     * access the current theme, resources, etc.
7815     *
7816     * @return The view's Context.
7817     */
7818    @ViewDebug.CapturedViewProperty
7819    public final Context getContext() {
7820        return mContext;
7821    }
7822
7823    /**
7824     * Handle a key event before it is processed by any input method
7825     * associated with the view hierarchy.  This can be used to intercept
7826     * key events in special situations before the IME consumes them; a
7827     * typical example would be handling the BACK key to update the application's
7828     * UI instead of allowing the IME to see it and close itself.
7829     *
7830     * @param keyCode The value in event.getKeyCode().
7831     * @param event Description of the key event.
7832     * @return If you handled the event, return true. If you want to allow the
7833     *         event to be handled by the next receiver, return false.
7834     */
7835    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7836        return false;
7837    }
7838
7839    /**
7840     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7841     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7842     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7843     * is released, if the view is enabled and clickable.
7844     *
7845     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7846     * although some may elect to do so in some situations. Do not rely on this to
7847     * catch software key presses.
7848     *
7849     * @param keyCode A key code that represents the button pressed, from
7850     *                {@link android.view.KeyEvent}.
7851     * @param event   The KeyEvent object that defines the button action.
7852     */
7853    public boolean onKeyDown(int keyCode, KeyEvent event) {
7854        boolean result = false;
7855
7856        switch (keyCode) {
7857            case KeyEvent.KEYCODE_DPAD_CENTER:
7858            case KeyEvent.KEYCODE_ENTER: {
7859                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7860                    return true;
7861                }
7862                // Long clickable items don't necessarily have to be clickable
7863                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7864                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7865                        (event.getRepeatCount() == 0)) {
7866                    setPressed(true);
7867                    checkForLongClick(0);
7868                    return true;
7869                }
7870                break;
7871            }
7872        }
7873        return result;
7874    }
7875
7876    /**
7877     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7878     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7879     * the event).
7880     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7881     * although some may elect to do so in some situations. Do not rely on this to
7882     * catch software key presses.
7883     */
7884    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7885        return false;
7886    }
7887
7888    /**
7889     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7890     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7891     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7892     * {@link KeyEvent#KEYCODE_ENTER} is released.
7893     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7894     * although some may elect to do so in some situations. Do not rely on this to
7895     * catch software key presses.
7896     *
7897     * @param keyCode A key code that represents the button pressed, from
7898     *                {@link android.view.KeyEvent}.
7899     * @param event   The KeyEvent object that defines the button action.
7900     */
7901    public boolean onKeyUp(int keyCode, KeyEvent event) {
7902        boolean result = false;
7903
7904        switch (keyCode) {
7905            case KeyEvent.KEYCODE_DPAD_CENTER:
7906            case KeyEvent.KEYCODE_ENTER: {
7907                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7908                    return true;
7909                }
7910                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7911                    setPressed(false);
7912
7913                    if (!mHasPerformedLongPress) {
7914                        // This is a tap, so remove the longpress check
7915                        removeLongPressCallback();
7916
7917                        result = performClick();
7918                    }
7919                }
7920                break;
7921            }
7922        }
7923        return result;
7924    }
7925
7926    /**
7927     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7928     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7929     * the event).
7930     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7931     * although some may elect to do so in some situations. Do not rely on this to
7932     * catch software key presses.
7933     *
7934     * @param keyCode     A key code that represents the button pressed, from
7935     *                    {@link android.view.KeyEvent}.
7936     * @param repeatCount The number of times the action was made.
7937     * @param event       The KeyEvent object that defines the button action.
7938     */
7939    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7940        return false;
7941    }
7942
7943    /**
7944     * Called on the focused view when a key shortcut event is not handled.
7945     * Override this method to implement local key shortcuts for the View.
7946     * Key shortcuts can also be implemented by setting the
7947     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7948     *
7949     * @param keyCode The value in event.getKeyCode().
7950     * @param event Description of the key event.
7951     * @return If you handled the event, return true. If you want to allow the
7952     *         event to be handled by the next receiver, return false.
7953     */
7954    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7955        return false;
7956    }
7957
7958    /**
7959     * Check whether the called view is a text editor, in which case it
7960     * would make sense to automatically display a soft input window for
7961     * it.  Subclasses should override this if they implement
7962     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7963     * a call on that method would return a non-null InputConnection, and
7964     * they are really a first-class editor that the user would normally
7965     * start typing on when the go into a window containing your view.
7966     *
7967     * <p>The default implementation always returns false.  This does
7968     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7969     * will not be called or the user can not otherwise perform edits on your
7970     * view; it is just a hint to the system that this is not the primary
7971     * purpose of this view.
7972     *
7973     * @return Returns true if this view is a text editor, else false.
7974     */
7975    public boolean onCheckIsTextEditor() {
7976        return false;
7977    }
7978
7979    /**
7980     * Create a new InputConnection for an InputMethod to interact
7981     * with the view.  The default implementation returns null, since it doesn't
7982     * support input methods.  You can override this to implement such support.
7983     * This is only needed for views that take focus and text input.
7984     *
7985     * <p>When implementing this, you probably also want to implement
7986     * {@link #onCheckIsTextEditor()} to indicate you will return a
7987     * non-null InputConnection.
7988     *
7989     * @param outAttrs Fill in with attribute information about the connection.
7990     */
7991    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7992        return null;
7993    }
7994
7995    /**
7996     * Called by the {@link android.view.inputmethod.InputMethodManager}
7997     * when a view who is not the current
7998     * input connection target is trying to make a call on the manager.  The
7999     * default implementation returns false; you can override this to return
8000     * true for certain views if you are performing InputConnection proxying
8001     * to them.
8002     * @param view The View that is making the InputMethodManager call.
8003     * @return Return true to allow the call, false to reject.
8004     */
8005    public boolean checkInputConnectionProxy(View view) {
8006        return false;
8007    }
8008
8009    /**
8010     * Show the context menu for this view. It is not safe to hold on to the
8011     * menu after returning from this method.
8012     *
8013     * You should normally not overload this method. Overload
8014     * {@link #onCreateContextMenu(ContextMenu)} or define an
8015     * {@link OnCreateContextMenuListener} to add items to the context menu.
8016     *
8017     * @param menu The context menu to populate
8018     */
8019    public void createContextMenu(ContextMenu menu) {
8020        ContextMenuInfo menuInfo = getContextMenuInfo();
8021
8022        // Sets the current menu info so all items added to menu will have
8023        // my extra info set.
8024        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8025
8026        onCreateContextMenu(menu);
8027        ListenerInfo li = mListenerInfo;
8028        if (li != null && li.mOnCreateContextMenuListener != null) {
8029            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8030        }
8031
8032        // Clear the extra information so subsequent items that aren't mine don't
8033        // have my extra info.
8034        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8035
8036        if (mParent != null) {
8037            mParent.createContextMenu(menu);
8038        }
8039    }
8040
8041    /**
8042     * Views should implement this if they have extra information to associate
8043     * with the context menu. The return result is supplied as a parameter to
8044     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8045     * callback.
8046     *
8047     * @return Extra information about the item for which the context menu
8048     *         should be shown. This information will vary across different
8049     *         subclasses of View.
8050     */
8051    protected ContextMenuInfo getContextMenuInfo() {
8052        return null;
8053    }
8054
8055    /**
8056     * Views should implement this if the view itself is going to add items to
8057     * the context menu.
8058     *
8059     * @param menu the context menu to populate
8060     */
8061    protected void onCreateContextMenu(ContextMenu menu) {
8062    }
8063
8064    /**
8065     * Implement this method to handle trackball motion events.  The
8066     * <em>relative</em> movement of the trackball since the last event
8067     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8068     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8069     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8070     * they will often be fractional values, representing the more fine-grained
8071     * movement information available from a trackball).
8072     *
8073     * @param event The motion event.
8074     * @return True if the event was handled, false otherwise.
8075     */
8076    public boolean onTrackballEvent(MotionEvent event) {
8077        return false;
8078    }
8079
8080    /**
8081     * Implement this method to handle generic motion events.
8082     * <p>
8083     * Generic motion events describe joystick movements, mouse hovers, track pad
8084     * touches, scroll wheel movements and other input events.  The
8085     * {@link MotionEvent#getSource() source} of the motion event specifies
8086     * the class of input that was received.  Implementations of this method
8087     * must examine the bits in the source before processing the event.
8088     * The following code example shows how this is done.
8089     * </p><p>
8090     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8091     * are delivered to the view under the pointer.  All other generic motion events are
8092     * delivered to the focused view.
8093     * </p>
8094     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8095     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8096     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8097     *             // process the joystick movement...
8098     *             return true;
8099     *         }
8100     *     }
8101     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8102     *         switch (event.getAction()) {
8103     *             case MotionEvent.ACTION_HOVER_MOVE:
8104     *                 // process the mouse hover movement...
8105     *                 return true;
8106     *             case MotionEvent.ACTION_SCROLL:
8107     *                 // process the scroll wheel movement...
8108     *                 return true;
8109     *         }
8110     *     }
8111     *     return super.onGenericMotionEvent(event);
8112     * }</pre>
8113     *
8114     * @param event The generic motion event being processed.
8115     * @return True if the event was handled, false otherwise.
8116     */
8117    public boolean onGenericMotionEvent(MotionEvent event) {
8118        return false;
8119    }
8120
8121    /**
8122     * Implement this method to handle hover events.
8123     * <p>
8124     * This method is called whenever a pointer is hovering into, over, or out of the
8125     * bounds of a view and the view is not currently being touched.
8126     * Hover events are represented as pointer events with action
8127     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8128     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8129     * </p>
8130     * <ul>
8131     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8132     * when the pointer enters the bounds of the view.</li>
8133     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8134     * when the pointer has already entered the bounds of the view and has moved.</li>
8135     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8136     * when the pointer has exited the bounds of the view or when the pointer is
8137     * about to go down due to a button click, tap, or similar user action that
8138     * causes the view to be touched.</li>
8139     * </ul>
8140     * <p>
8141     * The view should implement this method to return true to indicate that it is
8142     * handling the hover event, such as by changing its drawable state.
8143     * </p><p>
8144     * The default implementation calls {@link #setHovered} to update the hovered state
8145     * of the view when a hover enter or hover exit event is received, if the view
8146     * is enabled and is clickable.  The default implementation also sends hover
8147     * accessibility events.
8148     * </p>
8149     *
8150     * @param event The motion event that describes the hover.
8151     * @return True if the view handled the hover event.
8152     *
8153     * @see #isHovered
8154     * @see #setHovered
8155     * @see #onHoverChanged
8156     */
8157    public boolean onHoverEvent(MotionEvent event) {
8158        // The root view may receive hover (or touch) events that are outside the bounds of
8159        // the window.  This code ensures that we only send accessibility events for
8160        // hovers that are actually within the bounds of the root view.
8161        final int action = event.getActionMasked();
8162        if (!mSendingHoverAccessibilityEvents) {
8163            if ((action == MotionEvent.ACTION_HOVER_ENTER
8164                    || action == MotionEvent.ACTION_HOVER_MOVE)
8165                    && !hasHoveredChild()
8166                    && pointInView(event.getX(), event.getY())) {
8167                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8168                mSendingHoverAccessibilityEvents = true;
8169            }
8170        } else {
8171            if (action == MotionEvent.ACTION_HOVER_EXIT
8172                    || (action == MotionEvent.ACTION_MOVE
8173                            && !pointInView(event.getX(), event.getY()))) {
8174                mSendingHoverAccessibilityEvents = false;
8175                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8176                // If the window does not have input focus we take away accessibility
8177                // focus as soon as the user stop hovering over the view.
8178                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8179                    getViewRootImpl().setAccessibilityFocus(null, null);
8180                }
8181            }
8182        }
8183
8184        if (isHoverable()) {
8185            switch (action) {
8186                case MotionEvent.ACTION_HOVER_ENTER:
8187                    setHovered(true);
8188                    break;
8189                case MotionEvent.ACTION_HOVER_EXIT:
8190                    setHovered(false);
8191                    break;
8192            }
8193
8194            // Dispatch the event to onGenericMotionEvent before returning true.
8195            // This is to provide compatibility with existing applications that
8196            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8197            // break because of the new default handling for hoverable views
8198            // in onHoverEvent.
8199            // Note that onGenericMotionEvent will be called by default when
8200            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8201            dispatchGenericMotionEventInternal(event);
8202            // The event was already handled by calling setHovered(), so always
8203            // return true.
8204            return true;
8205        }
8206
8207        return false;
8208    }
8209
8210    /**
8211     * Returns true if the view should handle {@link #onHoverEvent}
8212     * by calling {@link #setHovered} to change its hovered state.
8213     *
8214     * @return True if the view is hoverable.
8215     */
8216    private boolean isHoverable() {
8217        final int viewFlags = mViewFlags;
8218        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8219            return false;
8220        }
8221
8222        return (viewFlags & CLICKABLE) == CLICKABLE
8223                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8224    }
8225
8226    /**
8227     * Returns true if the view is currently hovered.
8228     *
8229     * @return True if the view is currently hovered.
8230     *
8231     * @see #setHovered
8232     * @see #onHoverChanged
8233     */
8234    @ViewDebug.ExportedProperty
8235    public boolean isHovered() {
8236        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8237    }
8238
8239    /**
8240     * Sets whether the view is currently hovered.
8241     * <p>
8242     * Calling this method also changes the drawable state of the view.  This
8243     * enables the view to react to hover by using different drawable resources
8244     * to change its appearance.
8245     * </p><p>
8246     * The {@link #onHoverChanged} method is called when the hovered state changes.
8247     * </p>
8248     *
8249     * @param hovered True if the view is hovered.
8250     *
8251     * @see #isHovered
8252     * @see #onHoverChanged
8253     */
8254    public void setHovered(boolean hovered) {
8255        if (hovered) {
8256            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8257                mPrivateFlags |= PFLAG_HOVERED;
8258                refreshDrawableState();
8259                onHoverChanged(true);
8260            }
8261        } else {
8262            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8263                mPrivateFlags &= ~PFLAG_HOVERED;
8264                refreshDrawableState();
8265                onHoverChanged(false);
8266            }
8267        }
8268    }
8269
8270    /**
8271     * Implement this method to handle hover state changes.
8272     * <p>
8273     * This method is called whenever the hover state changes as a result of a
8274     * call to {@link #setHovered}.
8275     * </p>
8276     *
8277     * @param hovered The current hover state, as returned by {@link #isHovered}.
8278     *
8279     * @see #isHovered
8280     * @see #setHovered
8281     */
8282    public void onHoverChanged(boolean hovered) {
8283    }
8284
8285    /**
8286     * Implement this method to handle touch screen motion events.
8287     *
8288     * @param event The motion event.
8289     * @return True if the event was handled, false otherwise.
8290     */
8291    public boolean onTouchEvent(MotionEvent event) {
8292        final int viewFlags = mViewFlags;
8293
8294        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8295            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8296                setPressed(false);
8297            }
8298            // A disabled view that is clickable still consumes the touch
8299            // events, it just doesn't respond to them.
8300            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8301                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8302        }
8303
8304        if (mTouchDelegate != null) {
8305            if (mTouchDelegate.onTouchEvent(event)) {
8306                return true;
8307            }
8308        }
8309
8310        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8311                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8312            switch (event.getAction()) {
8313                case MotionEvent.ACTION_UP:
8314                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8315                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8316                        // take focus if we don't have it already and we should in
8317                        // touch mode.
8318                        boolean focusTaken = false;
8319                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8320                            focusTaken = requestFocus();
8321                        }
8322
8323                        if (prepressed) {
8324                            // The button is being released before we actually
8325                            // showed it as pressed.  Make it show the pressed
8326                            // state now (before scheduling the click) to ensure
8327                            // the user sees it.
8328                            setPressed(true);
8329                       }
8330
8331                        if (!mHasPerformedLongPress) {
8332                            // This is a tap, so remove the longpress check
8333                            removeLongPressCallback();
8334
8335                            // Only perform take click actions if we were in the pressed state
8336                            if (!focusTaken) {
8337                                // Use a Runnable and post this rather than calling
8338                                // performClick directly. This lets other visual state
8339                                // of the view update before click actions start.
8340                                if (mPerformClick == null) {
8341                                    mPerformClick = new PerformClick();
8342                                }
8343                                if (!post(mPerformClick)) {
8344                                    performClick();
8345                                }
8346                            }
8347                        }
8348
8349                        if (mUnsetPressedState == null) {
8350                            mUnsetPressedState = new UnsetPressedState();
8351                        }
8352
8353                        if (prepressed) {
8354                            postDelayed(mUnsetPressedState,
8355                                    ViewConfiguration.getPressedStateDuration());
8356                        } else if (!post(mUnsetPressedState)) {
8357                            // If the post failed, unpress right now
8358                            mUnsetPressedState.run();
8359                        }
8360                        removeTapCallback();
8361                    }
8362                    break;
8363
8364                case MotionEvent.ACTION_DOWN:
8365                    mHasPerformedLongPress = false;
8366
8367                    if (performButtonActionOnTouchDown(event)) {
8368                        break;
8369                    }
8370
8371                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8372                    boolean isInScrollingContainer = isInScrollingContainer();
8373
8374                    // For views inside a scrolling container, delay the pressed feedback for
8375                    // a short period in case this is a scroll.
8376                    if (isInScrollingContainer) {
8377                        mPrivateFlags |= PFLAG_PREPRESSED;
8378                        if (mPendingCheckForTap == null) {
8379                            mPendingCheckForTap = new CheckForTap();
8380                        }
8381                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8382                    } else {
8383                        // Not inside a scrolling container, so show the feedback right away
8384                        setPressed(true);
8385                        checkForLongClick(0);
8386                    }
8387                    break;
8388
8389                case MotionEvent.ACTION_CANCEL:
8390                    setPressed(false);
8391                    removeTapCallback();
8392                    removeLongPressCallback();
8393                    break;
8394
8395                case MotionEvent.ACTION_MOVE:
8396                    final int x = (int) event.getX();
8397                    final int y = (int) event.getY();
8398
8399                    // Be lenient about moving outside of buttons
8400                    if (!pointInView(x, y, mTouchSlop)) {
8401                        // Outside button
8402                        removeTapCallback();
8403                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8404                            // Remove any future long press/tap checks
8405                            removeLongPressCallback();
8406
8407                            setPressed(false);
8408                        }
8409                    }
8410                    break;
8411            }
8412            return true;
8413        }
8414
8415        return false;
8416    }
8417
8418    /**
8419     * @hide
8420     */
8421    public boolean isInScrollingContainer() {
8422        ViewParent p = getParent();
8423        while (p != null && p instanceof ViewGroup) {
8424            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8425                return true;
8426            }
8427            p = p.getParent();
8428        }
8429        return false;
8430    }
8431
8432    /**
8433     * Remove the longpress detection timer.
8434     */
8435    private void removeLongPressCallback() {
8436        if (mPendingCheckForLongPress != null) {
8437          removeCallbacks(mPendingCheckForLongPress);
8438        }
8439    }
8440
8441    /**
8442     * Remove the pending click action
8443     */
8444    private void removePerformClickCallback() {
8445        if (mPerformClick != null) {
8446            removeCallbacks(mPerformClick);
8447        }
8448    }
8449
8450    /**
8451     * Remove the prepress detection timer.
8452     */
8453    private void removeUnsetPressCallback() {
8454        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8455            setPressed(false);
8456            removeCallbacks(mUnsetPressedState);
8457        }
8458    }
8459
8460    /**
8461     * Remove the tap detection timer.
8462     */
8463    private void removeTapCallback() {
8464        if (mPendingCheckForTap != null) {
8465            mPrivateFlags &= ~PFLAG_PREPRESSED;
8466            removeCallbacks(mPendingCheckForTap);
8467        }
8468    }
8469
8470    /**
8471     * Cancels a pending long press.  Your subclass can use this if you
8472     * want the context menu to come up if the user presses and holds
8473     * at the same place, but you don't want it to come up if they press
8474     * and then move around enough to cause scrolling.
8475     */
8476    public void cancelLongPress() {
8477        removeLongPressCallback();
8478
8479        /*
8480         * The prepressed state handled by the tap callback is a display
8481         * construct, but the tap callback will post a long press callback
8482         * less its own timeout. Remove it here.
8483         */
8484        removeTapCallback();
8485    }
8486
8487    /**
8488     * Remove the pending callback for sending a
8489     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8490     */
8491    private void removeSendViewScrolledAccessibilityEventCallback() {
8492        if (mSendViewScrolledAccessibilityEvent != null) {
8493            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8494            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8495        }
8496    }
8497
8498    /**
8499     * Sets the TouchDelegate for this View.
8500     */
8501    public void setTouchDelegate(TouchDelegate delegate) {
8502        mTouchDelegate = delegate;
8503    }
8504
8505    /**
8506     * Gets the TouchDelegate for this View.
8507     */
8508    public TouchDelegate getTouchDelegate() {
8509        return mTouchDelegate;
8510    }
8511
8512    /**
8513     * Set flags controlling behavior of this view.
8514     *
8515     * @param flags Constant indicating the value which should be set
8516     * @param mask Constant indicating the bit range that should be changed
8517     */
8518    void setFlags(int flags, int mask) {
8519        int old = mViewFlags;
8520        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8521
8522        int changed = mViewFlags ^ old;
8523        if (changed == 0) {
8524            return;
8525        }
8526        int privateFlags = mPrivateFlags;
8527
8528        /* Check if the FOCUSABLE bit has changed */
8529        if (((changed & FOCUSABLE_MASK) != 0) &&
8530                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8531            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8532                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8533                /* Give up focus if we are no longer focusable */
8534                clearFocus();
8535            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8536                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8537                /*
8538                 * Tell the view system that we are now available to take focus
8539                 * if no one else already has it.
8540                 */
8541                if (mParent != null) mParent.focusableViewAvailable(this);
8542            }
8543            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8544                notifyAccessibilityStateChanged();
8545            }
8546        }
8547
8548        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8549            if ((changed & VISIBILITY_MASK) != 0) {
8550                /*
8551                 * If this view is becoming visible, invalidate it in case it changed while
8552                 * it was not visible. Marking it drawn ensures that the invalidation will
8553                 * go through.
8554                 */
8555                mPrivateFlags |= PFLAG_DRAWN;
8556                invalidate(true);
8557
8558                needGlobalAttributesUpdate(true);
8559
8560                // a view becoming visible is worth notifying the parent
8561                // about in case nothing has focus.  even if this specific view
8562                // isn't focusable, it may contain something that is, so let
8563                // the root view try to give this focus if nothing else does.
8564                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8565                    mParent.focusableViewAvailable(this);
8566                }
8567            }
8568        }
8569
8570        /* Check if the GONE bit has changed */
8571        if ((changed & GONE) != 0) {
8572            needGlobalAttributesUpdate(false);
8573            requestLayout();
8574
8575            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8576                if (hasFocus()) clearFocus();
8577                clearAccessibilityFocus();
8578                destroyDrawingCache();
8579                if (mParent instanceof View) {
8580                    // GONE views noop invalidation, so invalidate the parent
8581                    ((View) mParent).invalidate(true);
8582                }
8583                // Mark the view drawn to ensure that it gets invalidated properly the next
8584                // time it is visible and gets invalidated
8585                mPrivateFlags |= PFLAG_DRAWN;
8586            }
8587            if (mAttachInfo != null) {
8588                mAttachInfo.mViewVisibilityChanged = true;
8589            }
8590        }
8591
8592        /* Check if the VISIBLE bit has changed */
8593        if ((changed & INVISIBLE) != 0) {
8594            needGlobalAttributesUpdate(false);
8595            /*
8596             * If this view is becoming invisible, set the DRAWN flag so that
8597             * the next invalidate() will not be skipped.
8598             */
8599            mPrivateFlags |= PFLAG_DRAWN;
8600
8601            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8602                // root view becoming invisible shouldn't clear focus and accessibility focus
8603                if (getRootView() != this) {
8604                    clearFocus();
8605                    clearAccessibilityFocus();
8606                }
8607            }
8608            if (mAttachInfo != null) {
8609                mAttachInfo.mViewVisibilityChanged = true;
8610            }
8611        }
8612
8613        if ((changed & VISIBILITY_MASK) != 0) {
8614            if (mParent instanceof ViewGroup) {
8615                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8616                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8617                ((View) mParent).invalidate(true);
8618            } else if (mParent != null) {
8619                mParent.invalidateChild(this, null);
8620            }
8621            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8622        }
8623
8624        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8625            destroyDrawingCache();
8626        }
8627
8628        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8629            destroyDrawingCache();
8630            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8631            invalidateParentCaches();
8632        }
8633
8634        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8635            destroyDrawingCache();
8636            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8637        }
8638
8639        if ((changed & DRAW_MASK) != 0) {
8640            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8641                if (mBackground != null) {
8642                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8643                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8644                } else {
8645                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8646                }
8647            } else {
8648                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8649            }
8650            requestLayout();
8651            invalidate(true);
8652        }
8653
8654        if ((changed & KEEP_SCREEN_ON) != 0) {
8655            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8656                mParent.recomputeViewAttributes(this);
8657            }
8658        }
8659
8660        if (AccessibilityManager.getInstance(mContext).isEnabled()
8661                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8662                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8663            notifyAccessibilityStateChanged();
8664        }
8665    }
8666
8667    /**
8668     * Change the view's z order in the tree, so it's on top of other sibling
8669     * views. This ordering change may affect layout, if the parent container
8670     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8671     * method should be followed by calls to {@link #requestLayout()} and
8672     * {@link View#invalidate()} on the parent.
8673     *
8674     * @see ViewGroup#bringChildToFront(View)
8675     */
8676    public void bringToFront() {
8677        if (mParent != null) {
8678            mParent.bringChildToFront(this);
8679        }
8680    }
8681
8682    /**
8683     * This is called in response to an internal scroll in this view (i.e., the
8684     * view scrolled its own contents). This is typically as a result of
8685     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8686     * called.
8687     *
8688     * @param l Current horizontal scroll origin.
8689     * @param t Current vertical scroll origin.
8690     * @param oldl Previous horizontal scroll origin.
8691     * @param oldt Previous vertical scroll origin.
8692     */
8693    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8694        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8695            postSendViewScrolledAccessibilityEventCallback();
8696        }
8697
8698        mBackgroundSizeChanged = true;
8699
8700        final AttachInfo ai = mAttachInfo;
8701        if (ai != null) {
8702            ai.mViewScrollChanged = true;
8703        }
8704    }
8705
8706    /**
8707     * Interface definition for a callback to be invoked when the layout bounds of a view
8708     * changes due to layout processing.
8709     */
8710    public interface OnLayoutChangeListener {
8711        /**
8712         * Called when the focus state of a view has changed.
8713         *
8714         * @param v The view whose state has changed.
8715         * @param left The new value of the view's left property.
8716         * @param top The new value of the view's top property.
8717         * @param right The new value of the view's right property.
8718         * @param bottom The new value of the view's bottom property.
8719         * @param oldLeft The previous value of the view's left property.
8720         * @param oldTop The previous value of the view's top property.
8721         * @param oldRight The previous value of the view's right property.
8722         * @param oldBottom The previous value of the view's bottom property.
8723         */
8724        void onLayoutChange(View v, int left, int top, int right, int bottom,
8725            int oldLeft, int oldTop, int oldRight, int oldBottom);
8726    }
8727
8728    /**
8729     * This is called during layout when the size of this view has changed. If
8730     * you were just added to the view hierarchy, you're called with the old
8731     * values of 0.
8732     *
8733     * @param w Current width of this view.
8734     * @param h Current height of this view.
8735     * @param oldw Old width of this view.
8736     * @param oldh Old height of this view.
8737     */
8738    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8739    }
8740
8741    /**
8742     * Called by draw to draw the child views. This may be overridden
8743     * by derived classes to gain control just before its children are drawn
8744     * (but after its own view has been drawn).
8745     * @param canvas the canvas on which to draw the view
8746     */
8747    protected void dispatchDraw(Canvas canvas) {
8748
8749    }
8750
8751    /**
8752     * Gets the parent of this view. Note that the parent is a
8753     * ViewParent and not necessarily a View.
8754     *
8755     * @return Parent of this view.
8756     */
8757    public final ViewParent getParent() {
8758        return mParent;
8759    }
8760
8761    /**
8762     * Set the horizontal scrolled position of your view. This will cause a call to
8763     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8764     * invalidated.
8765     * @param value the x position to scroll to
8766     */
8767    public void setScrollX(int value) {
8768        scrollTo(value, mScrollY);
8769    }
8770
8771    /**
8772     * Set the vertical scrolled position of your view. This will cause a call to
8773     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8774     * invalidated.
8775     * @param value the y position to scroll to
8776     */
8777    public void setScrollY(int value) {
8778        scrollTo(mScrollX, value);
8779    }
8780
8781    /**
8782     * Return the scrolled left position of this view. This is the left edge of
8783     * the displayed part of your view. You do not need to draw any pixels
8784     * farther left, since those are outside of the frame of your view on
8785     * screen.
8786     *
8787     * @return The left edge of the displayed part of your view, in pixels.
8788     */
8789    public final int getScrollX() {
8790        return mScrollX;
8791    }
8792
8793    /**
8794     * Return the scrolled top position of this view. This is the top edge of
8795     * the displayed part of your view. You do not need to draw any pixels above
8796     * it, since those are outside of the frame of your view on screen.
8797     *
8798     * @return The top edge of the displayed part of your view, in pixels.
8799     */
8800    public final int getScrollY() {
8801        return mScrollY;
8802    }
8803
8804    /**
8805     * Return the width of the your view.
8806     *
8807     * @return The width of your view, in pixels.
8808     */
8809    @ViewDebug.ExportedProperty(category = "layout")
8810    public final int getWidth() {
8811        return mRight - mLeft;
8812    }
8813
8814    /**
8815     * Return the height of your view.
8816     *
8817     * @return The height of your view, in pixels.
8818     */
8819    @ViewDebug.ExportedProperty(category = "layout")
8820    public final int getHeight() {
8821        return mBottom - mTop;
8822    }
8823
8824    /**
8825     * Return the visible drawing bounds of your view. Fills in the output
8826     * rectangle with the values from getScrollX(), getScrollY(),
8827     * getWidth(), and getHeight(). These bounds do not account for any
8828     * transformation properties currently set on the view, such as
8829     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8830     *
8831     * @param outRect The (scrolled) drawing bounds of the view.
8832     */
8833    public void getDrawingRect(Rect outRect) {
8834        outRect.left = mScrollX;
8835        outRect.top = mScrollY;
8836        outRect.right = mScrollX + (mRight - mLeft);
8837        outRect.bottom = mScrollY + (mBottom - mTop);
8838    }
8839
8840    /**
8841     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8842     * raw width component (that is the result is masked by
8843     * {@link #MEASURED_SIZE_MASK}).
8844     *
8845     * @return The raw measured width of this view.
8846     */
8847    public final int getMeasuredWidth() {
8848        return mMeasuredWidth & MEASURED_SIZE_MASK;
8849    }
8850
8851    /**
8852     * Return the full width measurement information for this view as computed
8853     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8854     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8855     * This should be used during measurement and layout calculations only. Use
8856     * {@link #getWidth()} to see how wide a view is after layout.
8857     *
8858     * @return The measured width of this view as a bit mask.
8859     */
8860    public final int getMeasuredWidthAndState() {
8861        return mMeasuredWidth;
8862    }
8863
8864    /**
8865     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8866     * raw width component (that is the result is masked by
8867     * {@link #MEASURED_SIZE_MASK}).
8868     *
8869     * @return The raw measured height of this view.
8870     */
8871    public final int getMeasuredHeight() {
8872        return mMeasuredHeight & MEASURED_SIZE_MASK;
8873    }
8874
8875    /**
8876     * Return the full height measurement information for this view as computed
8877     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8878     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8879     * This should be used during measurement and layout calculations only. Use
8880     * {@link #getHeight()} to see how wide a view is after layout.
8881     *
8882     * @return The measured width of this view as a bit mask.
8883     */
8884    public final int getMeasuredHeightAndState() {
8885        return mMeasuredHeight;
8886    }
8887
8888    /**
8889     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8890     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8891     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8892     * and the height component is at the shifted bits
8893     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8894     */
8895    public final int getMeasuredState() {
8896        return (mMeasuredWidth&MEASURED_STATE_MASK)
8897                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8898                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8899    }
8900
8901    /**
8902     * The transform matrix of this view, which is calculated based on the current
8903     * roation, scale, and pivot properties.
8904     *
8905     * @see #getRotation()
8906     * @see #getScaleX()
8907     * @see #getScaleY()
8908     * @see #getPivotX()
8909     * @see #getPivotY()
8910     * @return The current transform matrix for the view
8911     */
8912    public Matrix getMatrix() {
8913        if (mTransformationInfo != null) {
8914            updateMatrix();
8915            return mTransformationInfo.mMatrix;
8916        }
8917        return Matrix.IDENTITY_MATRIX;
8918    }
8919
8920    /**
8921     * Utility function to determine if the value is far enough away from zero to be
8922     * considered non-zero.
8923     * @param value A floating point value to check for zero-ness
8924     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8925     */
8926    private static boolean nonzero(float value) {
8927        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8928    }
8929
8930    /**
8931     * Returns true if the transform matrix is the identity matrix.
8932     * Recomputes the matrix if necessary.
8933     *
8934     * @return True if the transform matrix is the identity matrix, false otherwise.
8935     */
8936    final boolean hasIdentityMatrix() {
8937        if (mTransformationInfo != null) {
8938            updateMatrix();
8939            return mTransformationInfo.mMatrixIsIdentity;
8940        }
8941        return true;
8942    }
8943
8944    void ensureTransformationInfo() {
8945        if (mTransformationInfo == null) {
8946            mTransformationInfo = new TransformationInfo();
8947        }
8948    }
8949
8950    /**
8951     * Recomputes the transform matrix if necessary.
8952     */
8953    private void updateMatrix() {
8954        final TransformationInfo info = mTransformationInfo;
8955        if (info == null) {
8956            return;
8957        }
8958        if (info.mMatrixDirty) {
8959            // transform-related properties have changed since the last time someone
8960            // asked for the matrix; recalculate it with the current values
8961
8962            // Figure out if we need to update the pivot point
8963            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8964                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8965                    info.mPrevWidth = mRight - mLeft;
8966                    info.mPrevHeight = mBottom - mTop;
8967                    info.mPivotX = info.mPrevWidth / 2f;
8968                    info.mPivotY = info.mPrevHeight / 2f;
8969                }
8970            }
8971            info.mMatrix.reset();
8972            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8973                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8974                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8975                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8976            } else {
8977                if (info.mCamera == null) {
8978                    info.mCamera = new Camera();
8979                    info.matrix3D = new Matrix();
8980                }
8981                info.mCamera.save();
8982                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8983                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8984                info.mCamera.getMatrix(info.matrix3D);
8985                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8986                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8987                        info.mPivotY + info.mTranslationY);
8988                info.mMatrix.postConcat(info.matrix3D);
8989                info.mCamera.restore();
8990            }
8991            info.mMatrixDirty = false;
8992            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8993            info.mInverseMatrixDirty = true;
8994        }
8995    }
8996
8997   /**
8998     * Utility method to retrieve the inverse of the current mMatrix property.
8999     * We cache the matrix to avoid recalculating it when transform properties
9000     * have not changed.
9001     *
9002     * @return The inverse of the current matrix of this view.
9003     */
9004    final Matrix getInverseMatrix() {
9005        final TransformationInfo info = mTransformationInfo;
9006        if (info != null) {
9007            updateMatrix();
9008            if (info.mInverseMatrixDirty) {
9009                if (info.mInverseMatrix == null) {
9010                    info.mInverseMatrix = new Matrix();
9011                }
9012                info.mMatrix.invert(info.mInverseMatrix);
9013                info.mInverseMatrixDirty = false;
9014            }
9015            return info.mInverseMatrix;
9016        }
9017        return Matrix.IDENTITY_MATRIX;
9018    }
9019
9020    /**
9021     * Gets the distance along the Z axis from the camera to this view.
9022     *
9023     * @see #setCameraDistance(float)
9024     *
9025     * @return The distance along the Z axis.
9026     */
9027    public float getCameraDistance() {
9028        ensureTransformationInfo();
9029        final float dpi = mResources.getDisplayMetrics().densityDpi;
9030        final TransformationInfo info = mTransformationInfo;
9031        if (info.mCamera == null) {
9032            info.mCamera = new Camera();
9033            info.matrix3D = new Matrix();
9034        }
9035        return -(info.mCamera.getLocationZ() * dpi);
9036    }
9037
9038    /**
9039     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9040     * views are drawn) from the camera to this view. The camera's distance
9041     * affects 3D transformations, for instance rotations around the X and Y
9042     * axis. If the rotationX or rotationY properties are changed and this view is
9043     * large (more than half the size of the screen), it is recommended to always
9044     * use a camera distance that's greater than the height (X axis rotation) or
9045     * the width (Y axis rotation) of this view.</p>
9046     *
9047     * <p>The distance of the camera from the view plane can have an affect on the
9048     * perspective distortion of the view when it is rotated around the x or y axis.
9049     * For example, a large distance will result in a large viewing angle, and there
9050     * will not be much perspective distortion of the view as it rotates. A short
9051     * distance may cause much more perspective distortion upon rotation, and can
9052     * also result in some drawing artifacts if the rotated view ends up partially
9053     * behind the camera (which is why the recommendation is to use a distance at
9054     * least as far as the size of the view, if the view is to be rotated.)</p>
9055     *
9056     * <p>The distance is expressed in "depth pixels." The default distance depends
9057     * on the screen density. For instance, on a medium density display, the
9058     * default distance is 1280. On a high density display, the default distance
9059     * is 1920.</p>
9060     *
9061     * <p>If you want to specify a distance that leads to visually consistent
9062     * results across various densities, use the following formula:</p>
9063     * <pre>
9064     * float scale = context.getResources().getDisplayMetrics().density;
9065     * view.setCameraDistance(distance * scale);
9066     * </pre>
9067     *
9068     * <p>The density scale factor of a high density display is 1.5,
9069     * and 1920 = 1280 * 1.5.</p>
9070     *
9071     * @param distance The distance in "depth pixels", if negative the opposite
9072     *        value is used
9073     *
9074     * @see #setRotationX(float)
9075     * @see #setRotationY(float)
9076     */
9077    public void setCameraDistance(float distance) {
9078        invalidateViewProperty(true, false);
9079
9080        ensureTransformationInfo();
9081        final float dpi = mResources.getDisplayMetrics().densityDpi;
9082        final TransformationInfo info = mTransformationInfo;
9083        if (info.mCamera == null) {
9084            info.mCamera = new Camera();
9085            info.matrix3D = new Matrix();
9086        }
9087
9088        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9089        info.mMatrixDirty = true;
9090
9091        invalidateViewProperty(false, false);
9092        if (mDisplayList != null) {
9093            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9094        }
9095        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9096            // View was rejected last time it was drawn by its parent; this may have changed
9097            invalidateParentIfNeeded();
9098        }
9099    }
9100
9101    /**
9102     * The degrees that the view is rotated around the pivot point.
9103     *
9104     * @see #setRotation(float)
9105     * @see #getPivotX()
9106     * @see #getPivotY()
9107     *
9108     * @return The degrees of rotation.
9109     */
9110    @ViewDebug.ExportedProperty(category = "drawing")
9111    public float getRotation() {
9112        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9113    }
9114
9115    /**
9116     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9117     * result in clockwise rotation.
9118     *
9119     * @param rotation The degrees of rotation.
9120     *
9121     * @see #getRotation()
9122     * @see #getPivotX()
9123     * @see #getPivotY()
9124     * @see #setRotationX(float)
9125     * @see #setRotationY(float)
9126     *
9127     * @attr ref android.R.styleable#View_rotation
9128     */
9129    public void setRotation(float rotation) {
9130        ensureTransformationInfo();
9131        final TransformationInfo info = mTransformationInfo;
9132        if (info.mRotation != rotation) {
9133            // Double-invalidation is necessary to capture view's old and new areas
9134            invalidateViewProperty(true, false);
9135            info.mRotation = rotation;
9136            info.mMatrixDirty = true;
9137            invalidateViewProperty(false, true);
9138            if (mDisplayList != null) {
9139                mDisplayList.setRotation(rotation);
9140            }
9141            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9142                // View was rejected last time it was drawn by its parent; this may have changed
9143                invalidateParentIfNeeded();
9144            }
9145        }
9146    }
9147
9148    /**
9149     * The degrees that the view is rotated around the vertical axis through the pivot point.
9150     *
9151     * @see #getPivotX()
9152     * @see #getPivotY()
9153     * @see #setRotationY(float)
9154     *
9155     * @return The degrees of Y rotation.
9156     */
9157    @ViewDebug.ExportedProperty(category = "drawing")
9158    public float getRotationY() {
9159        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9160    }
9161
9162    /**
9163     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9164     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9165     * down the y axis.
9166     *
9167     * When rotating large views, it is recommended to adjust the camera distance
9168     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9169     *
9170     * @param rotationY The degrees of Y rotation.
9171     *
9172     * @see #getRotationY()
9173     * @see #getPivotX()
9174     * @see #getPivotY()
9175     * @see #setRotation(float)
9176     * @see #setRotationX(float)
9177     * @see #setCameraDistance(float)
9178     *
9179     * @attr ref android.R.styleable#View_rotationY
9180     */
9181    public void setRotationY(float rotationY) {
9182        ensureTransformationInfo();
9183        final TransformationInfo info = mTransformationInfo;
9184        if (info.mRotationY != rotationY) {
9185            invalidateViewProperty(true, false);
9186            info.mRotationY = rotationY;
9187            info.mMatrixDirty = true;
9188            invalidateViewProperty(false, true);
9189            if (mDisplayList != null) {
9190                mDisplayList.setRotationY(rotationY);
9191            }
9192            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9193                // View was rejected last time it was drawn by its parent; this may have changed
9194                invalidateParentIfNeeded();
9195            }
9196        }
9197    }
9198
9199    /**
9200     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9201     *
9202     * @see #getPivotX()
9203     * @see #getPivotY()
9204     * @see #setRotationX(float)
9205     *
9206     * @return The degrees of X rotation.
9207     */
9208    @ViewDebug.ExportedProperty(category = "drawing")
9209    public float getRotationX() {
9210        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9211    }
9212
9213    /**
9214     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9215     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9216     * x axis.
9217     *
9218     * When rotating large views, it is recommended to adjust the camera distance
9219     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9220     *
9221     * @param rotationX The degrees of X rotation.
9222     *
9223     * @see #getRotationX()
9224     * @see #getPivotX()
9225     * @see #getPivotY()
9226     * @see #setRotation(float)
9227     * @see #setRotationY(float)
9228     * @see #setCameraDistance(float)
9229     *
9230     * @attr ref android.R.styleable#View_rotationX
9231     */
9232    public void setRotationX(float rotationX) {
9233        ensureTransformationInfo();
9234        final TransformationInfo info = mTransformationInfo;
9235        if (info.mRotationX != rotationX) {
9236            invalidateViewProperty(true, false);
9237            info.mRotationX = rotationX;
9238            info.mMatrixDirty = true;
9239            invalidateViewProperty(false, true);
9240            if (mDisplayList != null) {
9241                mDisplayList.setRotationX(rotationX);
9242            }
9243            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9244                // View was rejected last time it was drawn by its parent; this may have changed
9245                invalidateParentIfNeeded();
9246            }
9247        }
9248    }
9249
9250    /**
9251     * The amount that the view is scaled in x around the pivot point, as a proportion of
9252     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9253     *
9254     * <p>By default, this is 1.0f.
9255     *
9256     * @see #getPivotX()
9257     * @see #getPivotY()
9258     * @return The scaling factor.
9259     */
9260    @ViewDebug.ExportedProperty(category = "drawing")
9261    public float getScaleX() {
9262        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9263    }
9264
9265    /**
9266     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9267     * the view's unscaled width. A value of 1 means that no scaling is applied.
9268     *
9269     * @param scaleX The scaling factor.
9270     * @see #getPivotX()
9271     * @see #getPivotY()
9272     *
9273     * @attr ref android.R.styleable#View_scaleX
9274     */
9275    public void setScaleX(float scaleX) {
9276        ensureTransformationInfo();
9277        final TransformationInfo info = mTransformationInfo;
9278        if (info.mScaleX != scaleX) {
9279            invalidateViewProperty(true, false);
9280            info.mScaleX = scaleX;
9281            info.mMatrixDirty = true;
9282            invalidateViewProperty(false, true);
9283            if (mDisplayList != null) {
9284                mDisplayList.setScaleX(scaleX);
9285            }
9286            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9287                // View was rejected last time it was drawn by its parent; this may have changed
9288                invalidateParentIfNeeded();
9289            }
9290        }
9291    }
9292
9293    /**
9294     * The amount that the view is scaled in y around the pivot point, as a proportion of
9295     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9296     *
9297     * <p>By default, this is 1.0f.
9298     *
9299     * @see #getPivotX()
9300     * @see #getPivotY()
9301     * @return The scaling factor.
9302     */
9303    @ViewDebug.ExportedProperty(category = "drawing")
9304    public float getScaleY() {
9305        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9306    }
9307
9308    /**
9309     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9310     * the view's unscaled width. A value of 1 means that no scaling is applied.
9311     *
9312     * @param scaleY The scaling factor.
9313     * @see #getPivotX()
9314     * @see #getPivotY()
9315     *
9316     * @attr ref android.R.styleable#View_scaleY
9317     */
9318    public void setScaleY(float scaleY) {
9319        ensureTransformationInfo();
9320        final TransformationInfo info = mTransformationInfo;
9321        if (info.mScaleY != scaleY) {
9322            invalidateViewProperty(true, false);
9323            info.mScaleY = scaleY;
9324            info.mMatrixDirty = true;
9325            invalidateViewProperty(false, true);
9326            if (mDisplayList != null) {
9327                mDisplayList.setScaleY(scaleY);
9328            }
9329            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9330                // View was rejected last time it was drawn by its parent; this may have changed
9331                invalidateParentIfNeeded();
9332            }
9333        }
9334    }
9335
9336    /**
9337     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9338     * and {@link #setScaleX(float) scaled}.
9339     *
9340     * @see #getRotation()
9341     * @see #getScaleX()
9342     * @see #getScaleY()
9343     * @see #getPivotY()
9344     * @return The x location of the pivot point.
9345     *
9346     * @attr ref android.R.styleable#View_transformPivotX
9347     */
9348    @ViewDebug.ExportedProperty(category = "drawing")
9349    public float getPivotX() {
9350        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9351    }
9352
9353    /**
9354     * Sets the x location of the point around which the view is
9355     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9356     * By default, the pivot point is centered on the object.
9357     * Setting this property disables this behavior and causes the view to use only the
9358     * explicitly set pivotX and pivotY values.
9359     *
9360     * @param pivotX The x location of the pivot point.
9361     * @see #getRotation()
9362     * @see #getScaleX()
9363     * @see #getScaleY()
9364     * @see #getPivotY()
9365     *
9366     * @attr ref android.R.styleable#View_transformPivotX
9367     */
9368    public void setPivotX(float pivotX) {
9369        ensureTransformationInfo();
9370        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9371        final TransformationInfo info = mTransformationInfo;
9372        if (info.mPivotX != pivotX) {
9373            invalidateViewProperty(true, false);
9374            info.mPivotX = pivotX;
9375            info.mMatrixDirty = true;
9376            invalidateViewProperty(false, true);
9377            if (mDisplayList != null) {
9378                mDisplayList.setPivotX(pivotX);
9379            }
9380            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9381                // View was rejected last time it was drawn by its parent; this may have changed
9382                invalidateParentIfNeeded();
9383            }
9384        }
9385    }
9386
9387    /**
9388     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9389     * and {@link #setScaleY(float) scaled}.
9390     *
9391     * @see #getRotation()
9392     * @see #getScaleX()
9393     * @see #getScaleY()
9394     * @see #getPivotY()
9395     * @return The y location of the pivot point.
9396     *
9397     * @attr ref android.R.styleable#View_transformPivotY
9398     */
9399    @ViewDebug.ExportedProperty(category = "drawing")
9400    public float getPivotY() {
9401        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9402    }
9403
9404    /**
9405     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9406     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9407     * Setting this property disables this behavior and causes the view to use only the
9408     * explicitly set pivotX and pivotY values.
9409     *
9410     * @param pivotY The y location of the pivot point.
9411     * @see #getRotation()
9412     * @see #getScaleX()
9413     * @see #getScaleY()
9414     * @see #getPivotY()
9415     *
9416     * @attr ref android.R.styleable#View_transformPivotY
9417     */
9418    public void setPivotY(float pivotY) {
9419        ensureTransformationInfo();
9420        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9421        final TransformationInfo info = mTransformationInfo;
9422        if (info.mPivotY != pivotY) {
9423            invalidateViewProperty(true, false);
9424            info.mPivotY = pivotY;
9425            info.mMatrixDirty = true;
9426            invalidateViewProperty(false, true);
9427            if (mDisplayList != null) {
9428                mDisplayList.setPivotY(pivotY);
9429            }
9430            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9431                // View was rejected last time it was drawn by its parent; this may have changed
9432                invalidateParentIfNeeded();
9433            }
9434        }
9435    }
9436
9437    /**
9438     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9439     * completely transparent and 1 means the view is completely opaque.
9440     *
9441     * <p>By default this is 1.0f.
9442     * @return The opacity of the view.
9443     */
9444    @ViewDebug.ExportedProperty(category = "drawing")
9445    public float getAlpha() {
9446        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9447    }
9448
9449    /**
9450     * Returns whether this View has content which overlaps. This function, intended to be
9451     * overridden by specific View types, is an optimization when alpha is set on a view. If
9452     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9453     * and then composited it into place, which can be expensive. If the view has no overlapping
9454     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9455     * An example of overlapping rendering is a TextView with a background image, such as a
9456     * Button. An example of non-overlapping rendering is a TextView with no background, or
9457     * an ImageView with only the foreground image. The default implementation returns true;
9458     * subclasses should override if they have cases which can be optimized.
9459     *
9460     * @return true if the content in this view might overlap, false otherwise.
9461     */
9462    public boolean hasOverlappingRendering() {
9463        return true;
9464    }
9465
9466    /**
9467     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9468     * completely transparent and 1 means the view is completely opaque.</p>
9469     *
9470     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9471     * performance implications, especially for large views. It is best to use the alpha property
9472     * sparingly and transiently, as in the case of fading animations.</p>
9473     *
9474     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9475     * strongly recommended for performance reasons to either override
9476     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9477     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9478     *
9479     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9480     * responsible for applying the opacity itself.</p>
9481     *
9482     * <p>Note that if the view is backed by a
9483     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9484     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9485     * 1.0 will supercede the alpha of the layer paint.</p>
9486     *
9487     * @param alpha The opacity of the view.
9488     *
9489     * @see #hasOverlappingRendering()
9490     * @see #setLayerType(int, android.graphics.Paint)
9491     *
9492     * @attr ref android.R.styleable#View_alpha
9493     */
9494    public void setAlpha(float alpha) {
9495        ensureTransformationInfo();
9496        if (mTransformationInfo.mAlpha != alpha) {
9497            mTransformationInfo.mAlpha = alpha;
9498            if (onSetAlpha((int) (alpha * 255))) {
9499                mPrivateFlags |= PFLAG_ALPHA_SET;
9500                // subclass is handling alpha - don't optimize rendering cache invalidation
9501                invalidateParentCaches();
9502                invalidate(true);
9503            } else {
9504                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9505                invalidateViewProperty(true, false);
9506                if (mDisplayList != null) {
9507                    mDisplayList.setAlpha(alpha);
9508                }
9509            }
9510        }
9511    }
9512
9513    /**
9514     * Faster version of setAlpha() which performs the same steps except there are
9515     * no calls to invalidate(). The caller of this function should perform proper invalidation
9516     * on the parent and this object. The return value indicates whether the subclass handles
9517     * alpha (the return value for onSetAlpha()).
9518     *
9519     * @param alpha The new value for the alpha property
9520     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9521     *         the new value for the alpha property is different from the old value
9522     */
9523    boolean setAlphaNoInvalidation(float alpha) {
9524        ensureTransformationInfo();
9525        if (mTransformationInfo.mAlpha != alpha) {
9526            mTransformationInfo.mAlpha = alpha;
9527            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9528            if (subclassHandlesAlpha) {
9529                mPrivateFlags |= PFLAG_ALPHA_SET;
9530                return true;
9531            } else {
9532                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9533                if (mDisplayList != null) {
9534                    mDisplayList.setAlpha(alpha);
9535                }
9536            }
9537        }
9538        return false;
9539    }
9540
9541    /**
9542     * Top position of this view relative to its parent.
9543     *
9544     * @return The top of this view, in pixels.
9545     */
9546    @ViewDebug.CapturedViewProperty
9547    public final int getTop() {
9548        return mTop;
9549    }
9550
9551    /**
9552     * Sets the top position of this view relative to its parent. This method is meant to be called
9553     * by the layout system and should not generally be called otherwise, because the property
9554     * may be changed at any time by the layout.
9555     *
9556     * @param top The top of this view, in pixels.
9557     */
9558    public final void setTop(int top) {
9559        if (top != mTop) {
9560            updateMatrix();
9561            final boolean matrixIsIdentity = mTransformationInfo == null
9562                    || mTransformationInfo.mMatrixIsIdentity;
9563            if (matrixIsIdentity) {
9564                if (mAttachInfo != null) {
9565                    int minTop;
9566                    int yLoc;
9567                    if (top < mTop) {
9568                        minTop = top;
9569                        yLoc = top - mTop;
9570                    } else {
9571                        minTop = mTop;
9572                        yLoc = 0;
9573                    }
9574                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9575                }
9576            } else {
9577                // Double-invalidation is necessary to capture view's old and new areas
9578                invalidate(true);
9579            }
9580
9581            int width = mRight - mLeft;
9582            int oldHeight = mBottom - mTop;
9583
9584            mTop = top;
9585            if (mDisplayList != null) {
9586                mDisplayList.setTop(mTop);
9587            }
9588
9589            sizeChange(width, mBottom - mTop, width, oldHeight);
9590
9591            if (!matrixIsIdentity) {
9592                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9593                    // A change in dimension means an auto-centered pivot point changes, too
9594                    mTransformationInfo.mMatrixDirty = true;
9595                }
9596                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9597                invalidate(true);
9598            }
9599            mBackgroundSizeChanged = true;
9600            invalidateParentIfNeeded();
9601            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9602                // View was rejected last time it was drawn by its parent; this may have changed
9603                invalidateParentIfNeeded();
9604            }
9605        }
9606    }
9607
9608    /**
9609     * Bottom position of this view relative to its parent.
9610     *
9611     * @return The bottom of this view, in pixels.
9612     */
9613    @ViewDebug.CapturedViewProperty
9614    public final int getBottom() {
9615        return mBottom;
9616    }
9617
9618    /**
9619     * True if this view has changed since the last time being drawn.
9620     *
9621     * @return The dirty state of this view.
9622     */
9623    public boolean isDirty() {
9624        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9625    }
9626
9627    /**
9628     * Sets the bottom position of this view relative to its parent. This method is meant to be
9629     * called by the layout system and should not generally be called otherwise, because the
9630     * property may be changed at any time by the layout.
9631     *
9632     * @param bottom The bottom of this view, in pixels.
9633     */
9634    public final void setBottom(int bottom) {
9635        if (bottom != mBottom) {
9636            updateMatrix();
9637            final boolean matrixIsIdentity = mTransformationInfo == null
9638                    || mTransformationInfo.mMatrixIsIdentity;
9639            if (matrixIsIdentity) {
9640                if (mAttachInfo != null) {
9641                    int maxBottom;
9642                    if (bottom < mBottom) {
9643                        maxBottom = mBottom;
9644                    } else {
9645                        maxBottom = bottom;
9646                    }
9647                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9648                }
9649            } else {
9650                // Double-invalidation is necessary to capture view's old and new areas
9651                invalidate(true);
9652            }
9653
9654            int width = mRight - mLeft;
9655            int oldHeight = mBottom - mTop;
9656
9657            mBottom = bottom;
9658            if (mDisplayList != null) {
9659                mDisplayList.setBottom(mBottom);
9660            }
9661
9662            sizeChange(width, mBottom - mTop, width, oldHeight);
9663
9664            if (!matrixIsIdentity) {
9665                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9666                    // A change in dimension means an auto-centered pivot point changes, too
9667                    mTransformationInfo.mMatrixDirty = true;
9668                }
9669                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9670                invalidate(true);
9671            }
9672            mBackgroundSizeChanged = true;
9673            invalidateParentIfNeeded();
9674            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9675                // View was rejected last time it was drawn by its parent; this may have changed
9676                invalidateParentIfNeeded();
9677            }
9678        }
9679    }
9680
9681    /**
9682     * Left position of this view relative to its parent.
9683     *
9684     * @return The left edge of this view, in pixels.
9685     */
9686    @ViewDebug.CapturedViewProperty
9687    public final int getLeft() {
9688        return mLeft;
9689    }
9690
9691    /**
9692     * Sets the left position of this view relative to its parent. This method is meant to be called
9693     * by the layout system and should not generally be called otherwise, because the property
9694     * may be changed at any time by the layout.
9695     *
9696     * @param left The bottom of this view, in pixels.
9697     */
9698    public final void setLeft(int left) {
9699        if (left != mLeft) {
9700            updateMatrix();
9701            final boolean matrixIsIdentity = mTransformationInfo == null
9702                    || mTransformationInfo.mMatrixIsIdentity;
9703            if (matrixIsIdentity) {
9704                if (mAttachInfo != null) {
9705                    int minLeft;
9706                    int xLoc;
9707                    if (left < mLeft) {
9708                        minLeft = left;
9709                        xLoc = left - mLeft;
9710                    } else {
9711                        minLeft = mLeft;
9712                        xLoc = 0;
9713                    }
9714                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9715                }
9716            } else {
9717                // Double-invalidation is necessary to capture view's old and new areas
9718                invalidate(true);
9719            }
9720
9721            int oldWidth = mRight - mLeft;
9722            int height = mBottom - mTop;
9723
9724            mLeft = left;
9725            if (mDisplayList != null) {
9726                mDisplayList.setLeft(left);
9727            }
9728
9729            sizeChange(mRight - mLeft, height, oldWidth, height);
9730
9731            if (!matrixIsIdentity) {
9732                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9733                    // A change in dimension means an auto-centered pivot point changes, too
9734                    mTransformationInfo.mMatrixDirty = true;
9735                }
9736                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9737                invalidate(true);
9738            }
9739            mBackgroundSizeChanged = true;
9740            invalidateParentIfNeeded();
9741            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9742                // View was rejected last time it was drawn by its parent; this may have changed
9743                invalidateParentIfNeeded();
9744            }
9745        }
9746    }
9747
9748    /**
9749     * Right position of this view relative to its parent.
9750     *
9751     * @return The right edge of this view, in pixels.
9752     */
9753    @ViewDebug.CapturedViewProperty
9754    public final int getRight() {
9755        return mRight;
9756    }
9757
9758    /**
9759     * Sets the right position of this view relative to its parent. This method is meant to be called
9760     * by the layout system and should not generally be called otherwise, because the property
9761     * may be changed at any time by the layout.
9762     *
9763     * @param right The bottom of this view, in pixels.
9764     */
9765    public final void setRight(int right) {
9766        if (right != mRight) {
9767            updateMatrix();
9768            final boolean matrixIsIdentity = mTransformationInfo == null
9769                    || mTransformationInfo.mMatrixIsIdentity;
9770            if (matrixIsIdentity) {
9771                if (mAttachInfo != null) {
9772                    int maxRight;
9773                    if (right < mRight) {
9774                        maxRight = mRight;
9775                    } else {
9776                        maxRight = right;
9777                    }
9778                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9779                }
9780            } else {
9781                // Double-invalidation is necessary to capture view's old and new areas
9782                invalidate(true);
9783            }
9784
9785            int oldWidth = mRight - mLeft;
9786            int height = mBottom - mTop;
9787
9788            mRight = right;
9789            if (mDisplayList != null) {
9790                mDisplayList.setRight(mRight);
9791            }
9792
9793            sizeChange(mRight - mLeft, height, oldWidth, height);
9794
9795            if (!matrixIsIdentity) {
9796                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9797                    // A change in dimension means an auto-centered pivot point changes, too
9798                    mTransformationInfo.mMatrixDirty = true;
9799                }
9800                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9801                invalidate(true);
9802            }
9803            mBackgroundSizeChanged = true;
9804            invalidateParentIfNeeded();
9805            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9806                // View was rejected last time it was drawn by its parent; this may have changed
9807                invalidateParentIfNeeded();
9808            }
9809        }
9810    }
9811
9812    /**
9813     * The visual x position of this view, in pixels. This is equivalent to the
9814     * {@link #setTranslationX(float) translationX} property plus the current
9815     * {@link #getLeft() left} property.
9816     *
9817     * @return The visual x position of this view, in pixels.
9818     */
9819    @ViewDebug.ExportedProperty(category = "drawing")
9820    public float getX() {
9821        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9822    }
9823
9824    /**
9825     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9826     * {@link #setTranslationX(float) translationX} property to be the difference between
9827     * the x value passed in and the current {@link #getLeft() left} property.
9828     *
9829     * @param x The visual x position of this view, in pixels.
9830     */
9831    public void setX(float x) {
9832        setTranslationX(x - mLeft);
9833    }
9834
9835    /**
9836     * The visual y position of this view, in pixels. This is equivalent to the
9837     * {@link #setTranslationY(float) translationY} property plus the current
9838     * {@link #getTop() top} property.
9839     *
9840     * @return The visual y position of this view, in pixels.
9841     */
9842    @ViewDebug.ExportedProperty(category = "drawing")
9843    public float getY() {
9844        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9845    }
9846
9847    /**
9848     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9849     * {@link #setTranslationY(float) translationY} property to be the difference between
9850     * the y value passed in and the current {@link #getTop() top} property.
9851     *
9852     * @param y The visual y position of this view, in pixels.
9853     */
9854    public void setY(float y) {
9855        setTranslationY(y - mTop);
9856    }
9857
9858
9859    /**
9860     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9861     * This position is post-layout, in addition to wherever the object's
9862     * layout placed it.
9863     *
9864     * @return The horizontal position of this view relative to its left position, in pixels.
9865     */
9866    @ViewDebug.ExportedProperty(category = "drawing")
9867    public float getTranslationX() {
9868        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9869    }
9870
9871    /**
9872     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9873     * This effectively positions the object post-layout, in addition to wherever the object's
9874     * layout placed it.
9875     *
9876     * @param translationX The horizontal position of this view relative to its left position,
9877     * in pixels.
9878     *
9879     * @attr ref android.R.styleable#View_translationX
9880     */
9881    public void setTranslationX(float translationX) {
9882        ensureTransformationInfo();
9883        final TransformationInfo info = mTransformationInfo;
9884        if (info.mTranslationX != translationX) {
9885            // Double-invalidation is necessary to capture view's old and new areas
9886            invalidateViewProperty(true, false);
9887            info.mTranslationX = translationX;
9888            info.mMatrixDirty = true;
9889            invalidateViewProperty(false, true);
9890            if (mDisplayList != null) {
9891                mDisplayList.setTranslationX(translationX);
9892            }
9893            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9894                // View was rejected last time it was drawn by its parent; this may have changed
9895                invalidateParentIfNeeded();
9896            }
9897        }
9898    }
9899
9900    /**
9901     * The horizontal location of this view relative to its {@link #getTop() top} position.
9902     * This position is post-layout, in addition to wherever the object's
9903     * layout placed it.
9904     *
9905     * @return The vertical position of this view relative to its top position,
9906     * in pixels.
9907     */
9908    @ViewDebug.ExportedProperty(category = "drawing")
9909    public float getTranslationY() {
9910        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9911    }
9912
9913    /**
9914     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9915     * This effectively positions the object post-layout, in addition to wherever the object's
9916     * layout placed it.
9917     *
9918     * @param translationY The vertical position of this view relative to its top position,
9919     * in pixels.
9920     *
9921     * @attr ref android.R.styleable#View_translationY
9922     */
9923    public void setTranslationY(float translationY) {
9924        ensureTransformationInfo();
9925        final TransformationInfo info = mTransformationInfo;
9926        if (info.mTranslationY != translationY) {
9927            invalidateViewProperty(true, false);
9928            info.mTranslationY = translationY;
9929            info.mMatrixDirty = true;
9930            invalidateViewProperty(false, true);
9931            if (mDisplayList != null) {
9932                mDisplayList.setTranslationY(translationY);
9933            }
9934            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9935                // View was rejected last time it was drawn by its parent; this may have changed
9936                invalidateParentIfNeeded();
9937            }
9938        }
9939    }
9940
9941    /**
9942     * Hit rectangle in parent's coordinates
9943     *
9944     * @param outRect The hit rectangle of the view.
9945     */
9946    public void getHitRect(Rect outRect) {
9947        updateMatrix();
9948        final TransformationInfo info = mTransformationInfo;
9949        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9950            outRect.set(mLeft, mTop, mRight, mBottom);
9951        } else {
9952            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9953            tmpRect.set(0, 0, getWidth(), getHeight());
9954            info.mMatrix.mapRect(tmpRect);
9955            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9956                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9957        }
9958    }
9959
9960    /**
9961     * Determines whether the given point, in local coordinates is inside the view.
9962     */
9963    /*package*/ final boolean pointInView(float localX, float localY) {
9964        return localX >= 0 && localX < (mRight - mLeft)
9965                && localY >= 0 && localY < (mBottom - mTop);
9966    }
9967
9968    /**
9969     * Utility method to determine whether the given point, in local coordinates,
9970     * is inside the view, where the area of the view is expanded by the slop factor.
9971     * This method is called while processing touch-move events to determine if the event
9972     * is still within the view.
9973     */
9974    private boolean pointInView(float localX, float localY, float slop) {
9975        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9976                localY < ((mBottom - mTop) + slop);
9977    }
9978
9979    /**
9980     * When a view has focus and the user navigates away from it, the next view is searched for
9981     * starting from the rectangle filled in by this method.
9982     *
9983     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
9984     * of the view.  However, if your view maintains some idea of internal selection,
9985     * such as a cursor, or a selected row or column, you should override this method and
9986     * fill in a more specific rectangle.
9987     *
9988     * @param r The rectangle to fill in, in this view's coordinates.
9989     */
9990    public void getFocusedRect(Rect r) {
9991        getDrawingRect(r);
9992    }
9993
9994    /**
9995     * If some part of this view is not clipped by any of its parents, then
9996     * return that area in r in global (root) coordinates. To convert r to local
9997     * coordinates (without taking possible View rotations into account), offset
9998     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9999     * If the view is completely clipped or translated out, return false.
10000     *
10001     * @param r If true is returned, r holds the global coordinates of the
10002     *        visible portion of this view.
10003     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10004     *        between this view and its root. globalOffet may be null.
10005     * @return true if r is non-empty (i.e. part of the view is visible at the
10006     *         root level.
10007     */
10008    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10009        int width = mRight - mLeft;
10010        int height = mBottom - mTop;
10011        if (width > 0 && height > 0) {
10012            r.set(0, 0, width, height);
10013            if (globalOffset != null) {
10014                globalOffset.set(-mScrollX, -mScrollY);
10015            }
10016            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10017        }
10018        return false;
10019    }
10020
10021    public final boolean getGlobalVisibleRect(Rect r) {
10022        return getGlobalVisibleRect(r, null);
10023    }
10024
10025    public final boolean getLocalVisibleRect(Rect r) {
10026        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10027        if (getGlobalVisibleRect(r, offset)) {
10028            r.offset(-offset.x, -offset.y); // make r local
10029            return true;
10030        }
10031        return false;
10032    }
10033
10034    /**
10035     * Offset this view's vertical location by the specified number of pixels.
10036     *
10037     * @param offset the number of pixels to offset the view by
10038     */
10039    public void offsetTopAndBottom(int offset) {
10040        if (offset != 0) {
10041            updateMatrix();
10042            final boolean matrixIsIdentity = mTransformationInfo == null
10043                    || mTransformationInfo.mMatrixIsIdentity;
10044            if (matrixIsIdentity) {
10045                if (mDisplayList != null) {
10046                    invalidateViewProperty(false, false);
10047                } else {
10048                    final ViewParent p = mParent;
10049                    if (p != null && mAttachInfo != null) {
10050                        final Rect r = mAttachInfo.mTmpInvalRect;
10051                        int minTop;
10052                        int maxBottom;
10053                        int yLoc;
10054                        if (offset < 0) {
10055                            minTop = mTop + offset;
10056                            maxBottom = mBottom;
10057                            yLoc = offset;
10058                        } else {
10059                            minTop = mTop;
10060                            maxBottom = mBottom + offset;
10061                            yLoc = 0;
10062                        }
10063                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10064                        p.invalidateChild(this, r);
10065                    }
10066                }
10067            } else {
10068                invalidateViewProperty(false, false);
10069            }
10070
10071            mTop += offset;
10072            mBottom += offset;
10073            if (mDisplayList != null) {
10074                mDisplayList.offsetTopAndBottom(offset);
10075                invalidateViewProperty(false, false);
10076            } else {
10077                if (!matrixIsIdentity) {
10078                    invalidateViewProperty(false, true);
10079                }
10080                invalidateParentIfNeeded();
10081            }
10082        }
10083    }
10084
10085    /**
10086     * Offset this view's horizontal location by the specified amount of pixels.
10087     *
10088     * @param offset the number of pixels to offset the view by
10089     */
10090    public void offsetLeftAndRight(int offset) {
10091        if (offset != 0) {
10092            updateMatrix();
10093            final boolean matrixIsIdentity = mTransformationInfo == null
10094                    || mTransformationInfo.mMatrixIsIdentity;
10095            if (matrixIsIdentity) {
10096                if (mDisplayList != null) {
10097                    invalidateViewProperty(false, false);
10098                } else {
10099                    final ViewParent p = mParent;
10100                    if (p != null && mAttachInfo != null) {
10101                        final Rect r = mAttachInfo.mTmpInvalRect;
10102                        int minLeft;
10103                        int maxRight;
10104                        if (offset < 0) {
10105                            minLeft = mLeft + offset;
10106                            maxRight = mRight;
10107                        } else {
10108                            minLeft = mLeft;
10109                            maxRight = mRight + offset;
10110                        }
10111                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10112                        p.invalidateChild(this, r);
10113                    }
10114                }
10115            } else {
10116                invalidateViewProperty(false, false);
10117            }
10118
10119            mLeft += offset;
10120            mRight += offset;
10121            if (mDisplayList != null) {
10122                mDisplayList.offsetLeftAndRight(offset);
10123                invalidateViewProperty(false, false);
10124            } else {
10125                if (!matrixIsIdentity) {
10126                    invalidateViewProperty(false, true);
10127                }
10128                invalidateParentIfNeeded();
10129            }
10130        }
10131    }
10132
10133    /**
10134     * Get the LayoutParams associated with this view. All views should have
10135     * layout parameters. These supply parameters to the <i>parent</i> of this
10136     * view specifying how it should be arranged. There are many subclasses of
10137     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10138     * of ViewGroup that are responsible for arranging their children.
10139     *
10140     * This method may return null if this View is not attached to a parent
10141     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10142     * was not invoked successfully. When a View is attached to a parent
10143     * ViewGroup, this method must not return null.
10144     *
10145     * @return The LayoutParams associated with this view, or null if no
10146     *         parameters have been set yet
10147     */
10148    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10149    public ViewGroup.LayoutParams getLayoutParams() {
10150        return mLayoutParams;
10151    }
10152
10153    /**
10154     * Set the layout parameters associated with this view. These supply
10155     * parameters to the <i>parent</i> of this view specifying how it should be
10156     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10157     * correspond to the different subclasses of ViewGroup that are responsible
10158     * for arranging their children.
10159     *
10160     * @param params The layout parameters for this view, cannot be null
10161     */
10162    public void setLayoutParams(ViewGroup.LayoutParams params) {
10163        if (params == null) {
10164            throw new NullPointerException("Layout parameters cannot be null");
10165        }
10166        mLayoutParams = params;
10167        resolveLayoutParams();
10168        if (mParent instanceof ViewGroup) {
10169            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10170        }
10171        requestLayout();
10172    }
10173
10174    /**
10175     * Resolve the layout parameters depending on the resolved layout direction
10176     *
10177     * @hide
10178     */
10179    public void resolveLayoutParams() {
10180        if (mLayoutParams != null) {
10181            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10182        }
10183    }
10184
10185    /**
10186     * Set the scrolled position of your view. This will cause a call to
10187     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10188     * invalidated.
10189     * @param x the x position to scroll to
10190     * @param y the y position to scroll to
10191     */
10192    public void scrollTo(int x, int y) {
10193        if (mScrollX != x || mScrollY != y) {
10194            int oldX = mScrollX;
10195            int oldY = mScrollY;
10196            mScrollX = x;
10197            mScrollY = y;
10198            invalidateParentCaches();
10199            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10200            if (!awakenScrollBars()) {
10201                postInvalidateOnAnimation();
10202            }
10203        }
10204    }
10205
10206    /**
10207     * Move the scrolled position of your view. This will cause a call to
10208     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10209     * invalidated.
10210     * @param x the amount of pixels to scroll by horizontally
10211     * @param y the amount of pixels to scroll by vertically
10212     */
10213    public void scrollBy(int x, int y) {
10214        scrollTo(mScrollX + x, mScrollY + y);
10215    }
10216
10217    /**
10218     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10219     * animation to fade the scrollbars out after a default delay. If a subclass
10220     * provides animated scrolling, the start delay should equal the duration
10221     * of the scrolling animation.</p>
10222     *
10223     * <p>The animation starts only if at least one of the scrollbars is
10224     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10225     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10226     * this method returns true, and false otherwise. If the animation is
10227     * started, this method calls {@link #invalidate()}; in that case the
10228     * caller should not call {@link #invalidate()}.</p>
10229     *
10230     * <p>This method should be invoked every time a subclass directly updates
10231     * the scroll parameters.</p>
10232     *
10233     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10234     * and {@link #scrollTo(int, int)}.</p>
10235     *
10236     * @return true if the animation is played, false otherwise
10237     *
10238     * @see #awakenScrollBars(int)
10239     * @see #scrollBy(int, int)
10240     * @see #scrollTo(int, int)
10241     * @see #isHorizontalScrollBarEnabled()
10242     * @see #isVerticalScrollBarEnabled()
10243     * @see #setHorizontalScrollBarEnabled(boolean)
10244     * @see #setVerticalScrollBarEnabled(boolean)
10245     */
10246    protected boolean awakenScrollBars() {
10247        return mScrollCache != null &&
10248                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10249    }
10250
10251    /**
10252     * Trigger the scrollbars to draw.
10253     * This method differs from awakenScrollBars() only in its default duration.
10254     * initialAwakenScrollBars() will show the scroll bars for longer than
10255     * usual to give the user more of a chance to notice them.
10256     *
10257     * @return true if the animation is played, false otherwise.
10258     */
10259    private boolean initialAwakenScrollBars() {
10260        return mScrollCache != null &&
10261                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10262    }
10263
10264    /**
10265     * <p>
10266     * Trigger the scrollbars to draw. When invoked this method starts an
10267     * animation to fade the scrollbars out after a fixed delay. If a subclass
10268     * provides animated scrolling, the start delay should equal the duration of
10269     * the scrolling animation.
10270     * </p>
10271     *
10272     * <p>
10273     * The animation starts only if at least one of the scrollbars is enabled,
10274     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10275     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10276     * this method returns true, and false otherwise. If the animation is
10277     * started, this method calls {@link #invalidate()}; in that case the caller
10278     * should not call {@link #invalidate()}.
10279     * </p>
10280     *
10281     * <p>
10282     * This method should be invoked everytime a subclass directly updates the
10283     * scroll parameters.
10284     * </p>
10285     *
10286     * @param startDelay the delay, in milliseconds, after which the animation
10287     *        should start; when the delay is 0, the animation starts
10288     *        immediately
10289     * @return true if the animation is played, false otherwise
10290     *
10291     * @see #scrollBy(int, int)
10292     * @see #scrollTo(int, int)
10293     * @see #isHorizontalScrollBarEnabled()
10294     * @see #isVerticalScrollBarEnabled()
10295     * @see #setHorizontalScrollBarEnabled(boolean)
10296     * @see #setVerticalScrollBarEnabled(boolean)
10297     */
10298    protected boolean awakenScrollBars(int startDelay) {
10299        return awakenScrollBars(startDelay, true);
10300    }
10301
10302    /**
10303     * <p>
10304     * Trigger the scrollbars to draw. When invoked this method starts an
10305     * animation to fade the scrollbars out after a fixed delay. If a subclass
10306     * provides animated scrolling, the start delay should equal the duration of
10307     * the scrolling animation.
10308     * </p>
10309     *
10310     * <p>
10311     * The animation starts only if at least one of the scrollbars is enabled,
10312     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10313     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10314     * this method returns true, and false otherwise. If the animation is
10315     * started, this method calls {@link #invalidate()} if the invalidate parameter
10316     * is set to true; in that case the caller
10317     * should not call {@link #invalidate()}.
10318     * </p>
10319     *
10320     * <p>
10321     * This method should be invoked everytime a subclass directly updates the
10322     * scroll parameters.
10323     * </p>
10324     *
10325     * @param startDelay the delay, in milliseconds, after which the animation
10326     *        should start; when the delay is 0, the animation starts
10327     *        immediately
10328     *
10329     * @param invalidate Wheter this method should call invalidate
10330     *
10331     * @return true if the animation is played, false otherwise
10332     *
10333     * @see #scrollBy(int, int)
10334     * @see #scrollTo(int, int)
10335     * @see #isHorizontalScrollBarEnabled()
10336     * @see #isVerticalScrollBarEnabled()
10337     * @see #setHorizontalScrollBarEnabled(boolean)
10338     * @see #setVerticalScrollBarEnabled(boolean)
10339     */
10340    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10341        final ScrollabilityCache scrollCache = mScrollCache;
10342
10343        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10344            return false;
10345        }
10346
10347        if (scrollCache.scrollBar == null) {
10348            scrollCache.scrollBar = new ScrollBarDrawable();
10349        }
10350
10351        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10352
10353            if (invalidate) {
10354                // Invalidate to show the scrollbars
10355                postInvalidateOnAnimation();
10356            }
10357
10358            if (scrollCache.state == ScrollabilityCache.OFF) {
10359                // FIXME: this is copied from WindowManagerService.
10360                // We should get this value from the system when it
10361                // is possible to do so.
10362                final int KEY_REPEAT_FIRST_DELAY = 750;
10363                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10364            }
10365
10366            // Tell mScrollCache when we should start fading. This may
10367            // extend the fade start time if one was already scheduled
10368            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10369            scrollCache.fadeStartTime = fadeStartTime;
10370            scrollCache.state = ScrollabilityCache.ON;
10371
10372            // Schedule our fader to run, unscheduling any old ones first
10373            if (mAttachInfo != null) {
10374                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10375                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10376            }
10377
10378            return true;
10379        }
10380
10381        return false;
10382    }
10383
10384    /**
10385     * Do not invalidate views which are not visible and which are not running an animation. They
10386     * will not get drawn and they should not set dirty flags as if they will be drawn
10387     */
10388    private boolean skipInvalidate() {
10389        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10390                (!(mParent instanceof ViewGroup) ||
10391                        !((ViewGroup) mParent).isViewTransitioning(this));
10392    }
10393    /**
10394     * Mark the area defined by dirty as needing to be drawn. If the view is
10395     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10396     * in the future. This must be called from a UI thread. To call from a non-UI
10397     * thread, call {@link #postInvalidate()}.
10398     *
10399     * WARNING: This method is destructive to dirty.
10400     * @param dirty the rectangle representing the bounds of the dirty region
10401     */
10402    public void invalidate(Rect dirty) {
10403        if (skipInvalidate()) {
10404            return;
10405        }
10406        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10407                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10408                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10409            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10410            mPrivateFlags |= PFLAG_INVALIDATED;
10411            mPrivateFlags |= PFLAG_DIRTY;
10412            final ViewParent p = mParent;
10413            final AttachInfo ai = mAttachInfo;
10414            //noinspection PointlessBooleanExpression,ConstantConditions
10415            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10416                if (p != null && ai != null && ai.mHardwareAccelerated) {
10417                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10418                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10419                    p.invalidateChild(this, null);
10420                    return;
10421                }
10422            }
10423            if (p != null && ai != null) {
10424                final int scrollX = mScrollX;
10425                final int scrollY = mScrollY;
10426                final Rect r = ai.mTmpInvalRect;
10427                r.set(dirty.left - scrollX, dirty.top - scrollY,
10428                        dirty.right - scrollX, dirty.bottom - scrollY);
10429                mParent.invalidateChild(this, r);
10430            }
10431        }
10432    }
10433
10434    /**
10435     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10436     * The coordinates of the dirty rect are relative to the view.
10437     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10438     * will be called at some point in the future. This must be called from
10439     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10440     * @param l the left position of the dirty region
10441     * @param t the top position of the dirty region
10442     * @param r the right position of the dirty region
10443     * @param b the bottom position of the dirty region
10444     */
10445    public void invalidate(int l, int t, int r, int b) {
10446        if (skipInvalidate()) {
10447            return;
10448        }
10449        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10450                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10451                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10452            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10453            mPrivateFlags |= PFLAG_INVALIDATED;
10454            mPrivateFlags |= PFLAG_DIRTY;
10455            final ViewParent p = mParent;
10456            final AttachInfo ai = mAttachInfo;
10457            //noinspection PointlessBooleanExpression,ConstantConditions
10458            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10459                if (p != null && ai != null && ai.mHardwareAccelerated) {
10460                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10461                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10462                    p.invalidateChild(this, null);
10463                    return;
10464                }
10465            }
10466            if (p != null && ai != null && l < r && t < b) {
10467                final int scrollX = mScrollX;
10468                final int scrollY = mScrollY;
10469                final Rect tmpr = ai.mTmpInvalRect;
10470                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10471                p.invalidateChild(this, tmpr);
10472            }
10473        }
10474    }
10475
10476    /**
10477     * Invalidate the whole view. If the view is visible,
10478     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10479     * the future. This must be called from a UI thread. To call from a non-UI thread,
10480     * call {@link #postInvalidate()}.
10481     */
10482    public void invalidate() {
10483        invalidate(true);
10484    }
10485
10486    /**
10487     * This is where the invalidate() work actually happens. A full invalidate()
10488     * causes the drawing cache to be invalidated, but this function can be called with
10489     * invalidateCache set to false to skip that invalidation step for cases that do not
10490     * need it (for example, a component that remains at the same dimensions with the same
10491     * content).
10492     *
10493     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10494     * well. This is usually true for a full invalidate, but may be set to false if the
10495     * View's contents or dimensions have not changed.
10496     */
10497    void invalidate(boolean invalidateCache) {
10498        if (skipInvalidate()) {
10499            return;
10500        }
10501        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10502                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10503                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10504            mLastIsOpaque = isOpaque();
10505            mPrivateFlags &= ~PFLAG_DRAWN;
10506            mPrivateFlags |= PFLAG_DIRTY;
10507            if (invalidateCache) {
10508                mPrivateFlags |= PFLAG_INVALIDATED;
10509                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10510            }
10511            final AttachInfo ai = mAttachInfo;
10512            final ViewParent p = mParent;
10513            //noinspection PointlessBooleanExpression,ConstantConditions
10514            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10515                if (p != null && ai != null && ai.mHardwareAccelerated) {
10516                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10517                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10518                    p.invalidateChild(this, null);
10519                    return;
10520                }
10521            }
10522
10523            if (p != null && ai != null) {
10524                final Rect r = ai.mTmpInvalRect;
10525                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10526                // Don't call invalidate -- we don't want to internally scroll
10527                // our own bounds
10528                p.invalidateChild(this, r);
10529            }
10530        }
10531    }
10532
10533    /**
10534     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10535     * set any flags or handle all of the cases handled by the default invalidation methods.
10536     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10537     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10538     * walk up the hierarchy, transforming the dirty rect as necessary.
10539     *
10540     * The method also handles normal invalidation logic if display list properties are not
10541     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10542     * backup approach, to handle these cases used in the various property-setting methods.
10543     *
10544     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10545     * are not being used in this view
10546     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10547     * list properties are not being used in this view
10548     */
10549    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10550        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10551            if (invalidateParent) {
10552                invalidateParentCaches();
10553            }
10554            if (forceRedraw) {
10555                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10556            }
10557            invalidate(false);
10558        } else {
10559            final AttachInfo ai = mAttachInfo;
10560            final ViewParent p = mParent;
10561            if (p != null && ai != null) {
10562                final Rect r = ai.mTmpInvalRect;
10563                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10564                if (mParent instanceof ViewGroup) {
10565                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10566                } else {
10567                    mParent.invalidateChild(this, r);
10568                }
10569            }
10570        }
10571    }
10572
10573    /**
10574     * Utility method to transform a given Rect by the current matrix of this view.
10575     */
10576    void transformRect(final Rect rect) {
10577        if (!getMatrix().isIdentity()) {
10578            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10579            boundingRect.set(rect);
10580            getMatrix().mapRect(boundingRect);
10581            rect.set((int) Math.floor(boundingRect.left),
10582                    (int) Math.floor(boundingRect.top),
10583                    (int) Math.ceil(boundingRect.right),
10584                    (int) Math.ceil(boundingRect.bottom));
10585        }
10586    }
10587
10588    /**
10589     * Used to indicate that the parent of this view should clear its caches. This functionality
10590     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10591     * which is necessary when various parent-managed properties of the view change, such as
10592     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10593     * clears the parent caches and does not causes an invalidate event.
10594     *
10595     * @hide
10596     */
10597    protected void invalidateParentCaches() {
10598        if (mParent instanceof View) {
10599            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10600        }
10601    }
10602
10603    /**
10604     * Used to indicate that the parent of this view should be invalidated. This functionality
10605     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10606     * which is necessary when various parent-managed properties of the view change, such as
10607     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10608     * an invalidation event to the parent.
10609     *
10610     * @hide
10611     */
10612    protected void invalidateParentIfNeeded() {
10613        if (isHardwareAccelerated() && mParent instanceof View) {
10614            ((View) mParent).invalidate(true);
10615        }
10616    }
10617
10618    /**
10619     * Indicates whether this View is opaque. An opaque View guarantees that it will
10620     * draw all the pixels overlapping its bounds using a fully opaque color.
10621     *
10622     * Subclasses of View should override this method whenever possible to indicate
10623     * whether an instance is opaque. Opaque Views are treated in a special way by
10624     * the View hierarchy, possibly allowing it to perform optimizations during
10625     * invalidate/draw passes.
10626     *
10627     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10628     */
10629    @ViewDebug.ExportedProperty(category = "drawing")
10630    public boolean isOpaque() {
10631        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10632                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10633    }
10634
10635    /**
10636     * @hide
10637     */
10638    protected void computeOpaqueFlags() {
10639        // Opaque if:
10640        //   - Has a background
10641        //   - Background is opaque
10642        //   - Doesn't have scrollbars or scrollbars overlay
10643
10644        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10645            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10646        } else {
10647            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10648        }
10649
10650        final int flags = mViewFlags;
10651        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10652                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10653                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10654            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10655        } else {
10656            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10657        }
10658    }
10659
10660    /**
10661     * @hide
10662     */
10663    protected boolean hasOpaqueScrollbars() {
10664        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10665    }
10666
10667    /**
10668     * @return A handler associated with the thread running the View. This
10669     * handler can be used to pump events in the UI events queue.
10670     */
10671    public Handler getHandler() {
10672        if (mAttachInfo != null) {
10673            return mAttachInfo.mHandler;
10674        }
10675        return null;
10676    }
10677
10678    /**
10679     * Gets the view root associated with the View.
10680     * @return The view root, or null if none.
10681     * @hide
10682     */
10683    public ViewRootImpl getViewRootImpl() {
10684        if (mAttachInfo != null) {
10685            return mAttachInfo.mViewRootImpl;
10686        }
10687        return null;
10688    }
10689
10690    /**
10691     * <p>Causes the Runnable to be added to the message queue.
10692     * The runnable will be run on the user interface thread.</p>
10693     *
10694     * @param action The Runnable that will be executed.
10695     *
10696     * @return Returns true if the Runnable was successfully placed in to the
10697     *         message queue.  Returns false on failure, usually because the
10698     *         looper processing the message queue is exiting.
10699     *
10700     * @see #postDelayed
10701     * @see #removeCallbacks
10702     */
10703    public boolean post(Runnable action) {
10704        final AttachInfo attachInfo = mAttachInfo;
10705        if (attachInfo != null) {
10706            return attachInfo.mHandler.post(action);
10707        }
10708        // Assume that post will succeed later
10709        ViewRootImpl.getRunQueue().post(action);
10710        return true;
10711    }
10712
10713    /**
10714     * <p>Causes the Runnable to be added to the message queue, to be run
10715     * after the specified amount of time elapses.
10716     * The runnable will be run on the user interface thread.</p>
10717     *
10718     * @param action The Runnable that will be executed.
10719     * @param delayMillis The delay (in milliseconds) until the Runnable
10720     *        will be executed.
10721     *
10722     * @return true if the Runnable was successfully placed in to the
10723     *         message queue.  Returns false on failure, usually because the
10724     *         looper processing the message queue is exiting.  Note that a
10725     *         result of true does not mean the Runnable will be processed --
10726     *         if the looper is quit before the delivery time of the message
10727     *         occurs then the message will be dropped.
10728     *
10729     * @see #post
10730     * @see #removeCallbacks
10731     */
10732    public boolean postDelayed(Runnable action, long delayMillis) {
10733        final AttachInfo attachInfo = mAttachInfo;
10734        if (attachInfo != null) {
10735            return attachInfo.mHandler.postDelayed(action, delayMillis);
10736        }
10737        // Assume that post will succeed later
10738        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10739        return true;
10740    }
10741
10742    /**
10743     * <p>Causes the Runnable to execute on the next animation time step.
10744     * The runnable will be run on the user interface thread.</p>
10745     *
10746     * @param action The Runnable that will be executed.
10747     *
10748     * @see #postOnAnimationDelayed
10749     * @see #removeCallbacks
10750     */
10751    public void postOnAnimation(Runnable action) {
10752        final AttachInfo attachInfo = mAttachInfo;
10753        if (attachInfo != null) {
10754            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10755                    Choreographer.CALLBACK_ANIMATION, action, null);
10756        } else {
10757            // Assume that post will succeed later
10758            ViewRootImpl.getRunQueue().post(action);
10759        }
10760    }
10761
10762    /**
10763     * <p>Causes the Runnable to execute on the next animation time step,
10764     * after the specified amount of time elapses.
10765     * The runnable will be run on the user interface thread.</p>
10766     *
10767     * @param action The Runnable that will be executed.
10768     * @param delayMillis The delay (in milliseconds) until the Runnable
10769     *        will be executed.
10770     *
10771     * @see #postOnAnimation
10772     * @see #removeCallbacks
10773     */
10774    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10775        final AttachInfo attachInfo = mAttachInfo;
10776        if (attachInfo != null) {
10777            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10778                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10779        } else {
10780            // Assume that post will succeed later
10781            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10782        }
10783    }
10784
10785    /**
10786     * <p>Removes the specified Runnable from the message queue.</p>
10787     *
10788     * @param action The Runnable to remove from the message handling queue
10789     *
10790     * @return true if this view could ask the Handler to remove the Runnable,
10791     *         false otherwise. When the returned value is true, the Runnable
10792     *         may or may not have been actually removed from the message queue
10793     *         (for instance, if the Runnable was not in the queue already.)
10794     *
10795     * @see #post
10796     * @see #postDelayed
10797     * @see #postOnAnimation
10798     * @see #postOnAnimationDelayed
10799     */
10800    public boolean removeCallbacks(Runnable action) {
10801        if (action != null) {
10802            final AttachInfo attachInfo = mAttachInfo;
10803            if (attachInfo != null) {
10804                attachInfo.mHandler.removeCallbacks(action);
10805                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10806                        Choreographer.CALLBACK_ANIMATION, action, null);
10807            } else {
10808                // Assume that post will succeed later
10809                ViewRootImpl.getRunQueue().removeCallbacks(action);
10810            }
10811        }
10812        return true;
10813    }
10814
10815    /**
10816     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10817     * Use this to invalidate the View from a non-UI thread.</p>
10818     *
10819     * <p>This method can be invoked from outside of the UI thread
10820     * only when this View is attached to a window.</p>
10821     *
10822     * @see #invalidate()
10823     * @see #postInvalidateDelayed(long)
10824     */
10825    public void postInvalidate() {
10826        postInvalidateDelayed(0);
10827    }
10828
10829    /**
10830     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10831     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10832     *
10833     * <p>This method can be invoked from outside of the UI thread
10834     * only when this View is attached to a window.</p>
10835     *
10836     * @param left The left coordinate of the rectangle to invalidate.
10837     * @param top The top coordinate of the rectangle to invalidate.
10838     * @param right The right coordinate of the rectangle to invalidate.
10839     * @param bottom The bottom coordinate of the rectangle to invalidate.
10840     *
10841     * @see #invalidate(int, int, int, int)
10842     * @see #invalidate(Rect)
10843     * @see #postInvalidateDelayed(long, int, int, int, int)
10844     */
10845    public void postInvalidate(int left, int top, int right, int bottom) {
10846        postInvalidateDelayed(0, left, top, right, bottom);
10847    }
10848
10849    /**
10850     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10851     * loop. Waits for the specified amount of time.</p>
10852     *
10853     * <p>This method can be invoked from outside of the UI thread
10854     * only when this View is attached to a window.</p>
10855     *
10856     * @param delayMilliseconds the duration in milliseconds to delay the
10857     *         invalidation by
10858     *
10859     * @see #invalidate()
10860     * @see #postInvalidate()
10861     */
10862    public void postInvalidateDelayed(long delayMilliseconds) {
10863        // We try only with the AttachInfo because there's no point in invalidating
10864        // if we are not attached to our window
10865        final AttachInfo attachInfo = mAttachInfo;
10866        if (attachInfo != null) {
10867            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10868        }
10869    }
10870
10871    /**
10872     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10873     * through the event loop. Waits for the specified amount of time.</p>
10874     *
10875     * <p>This method can be invoked from outside of the UI thread
10876     * only when this View is attached to a window.</p>
10877     *
10878     * @param delayMilliseconds the duration in milliseconds to delay the
10879     *         invalidation by
10880     * @param left The left coordinate of the rectangle to invalidate.
10881     * @param top The top coordinate of the rectangle to invalidate.
10882     * @param right The right coordinate of the rectangle to invalidate.
10883     * @param bottom The bottom coordinate of the rectangle to invalidate.
10884     *
10885     * @see #invalidate(int, int, int, int)
10886     * @see #invalidate(Rect)
10887     * @see #postInvalidate(int, int, int, int)
10888     */
10889    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10890            int right, int bottom) {
10891
10892        // We try only with the AttachInfo because there's no point in invalidating
10893        // if we are not attached to our window
10894        final AttachInfo attachInfo = mAttachInfo;
10895        if (attachInfo != null) {
10896            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10897            info.target = this;
10898            info.left = left;
10899            info.top = top;
10900            info.right = right;
10901            info.bottom = bottom;
10902
10903            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10904        }
10905    }
10906
10907    /**
10908     * <p>Cause an invalidate to happen on the next animation time step, typically the
10909     * next display frame.</p>
10910     *
10911     * <p>This method can be invoked from outside of the UI thread
10912     * only when this View is attached to a window.</p>
10913     *
10914     * @see #invalidate()
10915     */
10916    public void postInvalidateOnAnimation() {
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            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10922        }
10923    }
10924
10925    /**
10926     * <p>Cause an invalidate of the specified area to happen on the next animation
10927     * time step, typically the next display frame.</p>
10928     *
10929     * <p>This method can be invoked from outside of the UI thread
10930     * only when this View is attached to a window.</p>
10931     *
10932     * @param left The left coordinate of the rectangle to invalidate.
10933     * @param top The top coordinate of the rectangle to invalidate.
10934     * @param right The right coordinate of the rectangle to invalidate.
10935     * @param bottom The bottom coordinate of the rectangle to invalidate.
10936     *
10937     * @see #invalidate(int, int, int, int)
10938     * @see #invalidate(Rect)
10939     */
10940    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10941        // We try only with the AttachInfo because there's no point in invalidating
10942        // if we are not attached to our window
10943        final AttachInfo attachInfo = mAttachInfo;
10944        if (attachInfo != null) {
10945            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10946            info.target = this;
10947            info.left = left;
10948            info.top = top;
10949            info.right = right;
10950            info.bottom = bottom;
10951
10952            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10953        }
10954    }
10955
10956    /**
10957     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10958     * This event is sent at most once every
10959     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10960     */
10961    private void postSendViewScrolledAccessibilityEventCallback() {
10962        if (mSendViewScrolledAccessibilityEvent == null) {
10963            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10964        }
10965        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10966            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10967            postDelayed(mSendViewScrolledAccessibilityEvent,
10968                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10969        }
10970    }
10971
10972    /**
10973     * Called by a parent to request that a child update its values for mScrollX
10974     * and mScrollY if necessary. This will typically be done if the child is
10975     * animating a scroll using a {@link android.widget.Scroller Scroller}
10976     * object.
10977     */
10978    public void computeScroll() {
10979    }
10980
10981    /**
10982     * <p>Indicate whether the horizontal edges are faded when the view is
10983     * scrolled horizontally.</p>
10984     *
10985     * @return true if the horizontal edges should are faded on scroll, false
10986     *         otherwise
10987     *
10988     * @see #setHorizontalFadingEdgeEnabled(boolean)
10989     *
10990     * @attr ref android.R.styleable#View_requiresFadingEdge
10991     */
10992    public boolean isHorizontalFadingEdgeEnabled() {
10993        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10994    }
10995
10996    /**
10997     * <p>Define whether the horizontal edges should be faded when this view
10998     * is scrolled horizontally.</p>
10999     *
11000     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11001     *                                    be faded when the view is scrolled
11002     *                                    horizontally
11003     *
11004     * @see #isHorizontalFadingEdgeEnabled()
11005     *
11006     * @attr ref android.R.styleable#View_requiresFadingEdge
11007     */
11008    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11009        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11010            if (horizontalFadingEdgeEnabled) {
11011                initScrollCache();
11012            }
11013
11014            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11015        }
11016    }
11017
11018    /**
11019     * <p>Indicate whether the vertical edges are faded when the view is
11020     * scrolled horizontally.</p>
11021     *
11022     * @return true if the vertical edges should are faded on scroll, false
11023     *         otherwise
11024     *
11025     * @see #setVerticalFadingEdgeEnabled(boolean)
11026     *
11027     * @attr ref android.R.styleable#View_requiresFadingEdge
11028     */
11029    public boolean isVerticalFadingEdgeEnabled() {
11030        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11031    }
11032
11033    /**
11034     * <p>Define whether the vertical edges should be faded when this view
11035     * is scrolled vertically.</p>
11036     *
11037     * @param verticalFadingEdgeEnabled true if the vertical edges should
11038     *                                  be faded when the view is scrolled
11039     *                                  vertically
11040     *
11041     * @see #isVerticalFadingEdgeEnabled()
11042     *
11043     * @attr ref android.R.styleable#View_requiresFadingEdge
11044     */
11045    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11046        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11047            if (verticalFadingEdgeEnabled) {
11048                initScrollCache();
11049            }
11050
11051            mViewFlags ^= FADING_EDGE_VERTICAL;
11052        }
11053    }
11054
11055    /**
11056     * Returns the strength, or intensity, of the top faded edge. The strength is
11057     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11058     * returns 0.0 or 1.0 but no value in between.
11059     *
11060     * Subclasses should override this method to provide a smoother fade transition
11061     * when scrolling occurs.
11062     *
11063     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11064     */
11065    protected float getTopFadingEdgeStrength() {
11066        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11067    }
11068
11069    /**
11070     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11071     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11072     * returns 0.0 or 1.0 but no value in between.
11073     *
11074     * Subclasses should override this method to provide a smoother fade transition
11075     * when scrolling occurs.
11076     *
11077     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11078     */
11079    protected float getBottomFadingEdgeStrength() {
11080        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11081                computeVerticalScrollRange() ? 1.0f : 0.0f;
11082    }
11083
11084    /**
11085     * Returns the strength, or intensity, of the left faded edge. The strength is
11086     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11087     * returns 0.0 or 1.0 but no value in between.
11088     *
11089     * Subclasses should override this method to provide a smoother fade transition
11090     * when scrolling occurs.
11091     *
11092     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11093     */
11094    protected float getLeftFadingEdgeStrength() {
11095        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11096    }
11097
11098    /**
11099     * Returns the strength, or intensity, of the right faded edge. The strength is
11100     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11101     * returns 0.0 or 1.0 but no value in between.
11102     *
11103     * Subclasses should override this method to provide a smoother fade transition
11104     * when scrolling occurs.
11105     *
11106     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11107     */
11108    protected float getRightFadingEdgeStrength() {
11109        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11110                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11111    }
11112
11113    /**
11114     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11115     * scrollbar is not drawn by default.</p>
11116     *
11117     * @return true if the horizontal scrollbar should be painted, false
11118     *         otherwise
11119     *
11120     * @see #setHorizontalScrollBarEnabled(boolean)
11121     */
11122    public boolean isHorizontalScrollBarEnabled() {
11123        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11124    }
11125
11126    /**
11127     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11128     * scrollbar is not drawn by default.</p>
11129     *
11130     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11131     *                                   be painted
11132     *
11133     * @see #isHorizontalScrollBarEnabled()
11134     */
11135    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11136        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11137            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11138            computeOpaqueFlags();
11139            resolvePadding();
11140        }
11141    }
11142
11143    /**
11144     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11145     * scrollbar is not drawn by default.</p>
11146     *
11147     * @return true if the vertical scrollbar should be painted, false
11148     *         otherwise
11149     *
11150     * @see #setVerticalScrollBarEnabled(boolean)
11151     */
11152    public boolean isVerticalScrollBarEnabled() {
11153        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11154    }
11155
11156    /**
11157     * <p>Define whether the vertical scrollbar should be drawn or not. The
11158     * scrollbar is not drawn by default.</p>
11159     *
11160     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11161     *                                 be painted
11162     *
11163     * @see #isVerticalScrollBarEnabled()
11164     */
11165    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11166        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11167            mViewFlags ^= SCROLLBARS_VERTICAL;
11168            computeOpaqueFlags();
11169            resolvePadding();
11170        }
11171    }
11172
11173    /**
11174     * @hide
11175     */
11176    protected void recomputePadding() {
11177        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11178    }
11179
11180    /**
11181     * Define whether scrollbars will fade when the view is not scrolling.
11182     *
11183     * @param fadeScrollbars wheter to enable fading
11184     *
11185     * @attr ref android.R.styleable#View_fadeScrollbars
11186     */
11187    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11188        initScrollCache();
11189        final ScrollabilityCache scrollabilityCache = mScrollCache;
11190        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11191        if (fadeScrollbars) {
11192            scrollabilityCache.state = ScrollabilityCache.OFF;
11193        } else {
11194            scrollabilityCache.state = ScrollabilityCache.ON;
11195        }
11196    }
11197
11198    /**
11199     *
11200     * Returns true if scrollbars will fade when this view is not scrolling
11201     *
11202     * @return true if scrollbar fading is enabled
11203     *
11204     * @attr ref android.R.styleable#View_fadeScrollbars
11205     */
11206    public boolean isScrollbarFadingEnabled() {
11207        return mScrollCache != null && mScrollCache.fadeScrollBars;
11208    }
11209
11210    /**
11211     *
11212     * Returns the delay before scrollbars fade.
11213     *
11214     * @return the delay before scrollbars fade
11215     *
11216     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11217     */
11218    public int getScrollBarDefaultDelayBeforeFade() {
11219        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11220                mScrollCache.scrollBarDefaultDelayBeforeFade;
11221    }
11222
11223    /**
11224     * Define the delay before scrollbars fade.
11225     *
11226     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11227     *
11228     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11229     */
11230    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11231        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11232    }
11233
11234    /**
11235     *
11236     * Returns the scrollbar fade duration.
11237     *
11238     * @return the scrollbar fade duration
11239     *
11240     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11241     */
11242    public int getScrollBarFadeDuration() {
11243        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11244                mScrollCache.scrollBarFadeDuration;
11245    }
11246
11247    /**
11248     * Define the scrollbar fade duration.
11249     *
11250     * @param scrollBarFadeDuration - the scrollbar fade duration
11251     *
11252     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11253     */
11254    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11255        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11256    }
11257
11258    /**
11259     *
11260     * Returns the scrollbar size.
11261     *
11262     * @return the scrollbar size
11263     *
11264     * @attr ref android.R.styleable#View_scrollbarSize
11265     */
11266    public int getScrollBarSize() {
11267        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11268                mScrollCache.scrollBarSize;
11269    }
11270
11271    /**
11272     * Define the scrollbar size.
11273     *
11274     * @param scrollBarSize - the scrollbar size
11275     *
11276     * @attr ref android.R.styleable#View_scrollbarSize
11277     */
11278    public void setScrollBarSize(int scrollBarSize) {
11279        getScrollCache().scrollBarSize = scrollBarSize;
11280    }
11281
11282    /**
11283     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11284     * inset. When inset, they add to the padding of the view. And the scrollbars
11285     * can be drawn inside the padding area or on the edge of the view. For example,
11286     * if a view has a background drawable and you want to draw the scrollbars
11287     * inside the padding specified by the drawable, you can use
11288     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11289     * appear at the edge of the view, ignoring the padding, then you can use
11290     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11291     * @param style the style of the scrollbars. Should be one of
11292     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11293     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11294     * @see #SCROLLBARS_INSIDE_OVERLAY
11295     * @see #SCROLLBARS_INSIDE_INSET
11296     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11297     * @see #SCROLLBARS_OUTSIDE_INSET
11298     *
11299     * @attr ref android.R.styleable#View_scrollbarStyle
11300     */
11301    public void setScrollBarStyle(int style) {
11302        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11303            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11304            computeOpaqueFlags();
11305            resolvePadding();
11306        }
11307    }
11308
11309    /**
11310     * <p>Returns the current scrollbar style.</p>
11311     * @return the current scrollbar style
11312     * @see #SCROLLBARS_INSIDE_OVERLAY
11313     * @see #SCROLLBARS_INSIDE_INSET
11314     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11315     * @see #SCROLLBARS_OUTSIDE_INSET
11316     *
11317     * @attr ref android.R.styleable#View_scrollbarStyle
11318     */
11319    @ViewDebug.ExportedProperty(mapping = {
11320            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11321            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11322            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11323            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11324    })
11325    public int getScrollBarStyle() {
11326        return mViewFlags & SCROLLBARS_STYLE_MASK;
11327    }
11328
11329    /**
11330     * <p>Compute the horizontal range that the horizontal scrollbar
11331     * represents.</p>
11332     *
11333     * <p>The range is expressed in arbitrary units that must be the same as the
11334     * units used by {@link #computeHorizontalScrollExtent()} and
11335     * {@link #computeHorizontalScrollOffset()}.</p>
11336     *
11337     * <p>The default range is the drawing width of this view.</p>
11338     *
11339     * @return the total horizontal range represented by the horizontal
11340     *         scrollbar
11341     *
11342     * @see #computeHorizontalScrollExtent()
11343     * @see #computeHorizontalScrollOffset()
11344     * @see android.widget.ScrollBarDrawable
11345     */
11346    protected int computeHorizontalScrollRange() {
11347        return getWidth();
11348    }
11349
11350    /**
11351     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11352     * within the horizontal range. This value is used to compute the position
11353     * of the thumb within the scrollbar's track.</p>
11354     *
11355     * <p>The range is expressed in arbitrary units that must be the same as the
11356     * units used by {@link #computeHorizontalScrollRange()} and
11357     * {@link #computeHorizontalScrollExtent()}.</p>
11358     *
11359     * <p>The default offset is the scroll offset of this view.</p>
11360     *
11361     * @return the horizontal offset of the scrollbar's thumb
11362     *
11363     * @see #computeHorizontalScrollRange()
11364     * @see #computeHorizontalScrollExtent()
11365     * @see android.widget.ScrollBarDrawable
11366     */
11367    protected int computeHorizontalScrollOffset() {
11368        return mScrollX;
11369    }
11370
11371    /**
11372     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11373     * within the horizontal range. This value is used to compute the length
11374     * of the thumb within the scrollbar's track.</p>
11375     *
11376     * <p>The range is expressed in arbitrary units that must be the same as the
11377     * units used by {@link #computeHorizontalScrollRange()} and
11378     * {@link #computeHorizontalScrollOffset()}.</p>
11379     *
11380     * <p>The default extent is the drawing width of this view.</p>
11381     *
11382     * @return the horizontal extent of the scrollbar's thumb
11383     *
11384     * @see #computeHorizontalScrollRange()
11385     * @see #computeHorizontalScrollOffset()
11386     * @see android.widget.ScrollBarDrawable
11387     */
11388    protected int computeHorizontalScrollExtent() {
11389        return getWidth();
11390    }
11391
11392    /**
11393     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11394     *
11395     * <p>The range is expressed in arbitrary units that must be the same as the
11396     * units used by {@link #computeVerticalScrollExtent()} and
11397     * {@link #computeVerticalScrollOffset()}.</p>
11398     *
11399     * @return the total vertical range represented by the vertical scrollbar
11400     *
11401     * <p>The default range is the drawing height of this view.</p>
11402     *
11403     * @see #computeVerticalScrollExtent()
11404     * @see #computeVerticalScrollOffset()
11405     * @see android.widget.ScrollBarDrawable
11406     */
11407    protected int computeVerticalScrollRange() {
11408        return getHeight();
11409    }
11410
11411    /**
11412     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11413     * within the horizontal range. This value is used to compute the position
11414     * of the thumb within the scrollbar's track.</p>
11415     *
11416     * <p>The range is expressed in arbitrary units that must be the same as the
11417     * units used by {@link #computeVerticalScrollRange()} and
11418     * {@link #computeVerticalScrollExtent()}.</p>
11419     *
11420     * <p>The default offset is the scroll offset of this view.</p>
11421     *
11422     * @return the vertical offset of the scrollbar's thumb
11423     *
11424     * @see #computeVerticalScrollRange()
11425     * @see #computeVerticalScrollExtent()
11426     * @see android.widget.ScrollBarDrawable
11427     */
11428    protected int computeVerticalScrollOffset() {
11429        return mScrollY;
11430    }
11431
11432    /**
11433     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11434     * within the vertical range. This value is used to compute the length
11435     * of the thumb within the scrollbar's track.</p>
11436     *
11437     * <p>The range is expressed in arbitrary units that must be the same as the
11438     * units used by {@link #computeVerticalScrollRange()} and
11439     * {@link #computeVerticalScrollOffset()}.</p>
11440     *
11441     * <p>The default extent is the drawing height of this view.</p>
11442     *
11443     * @return the vertical extent of the scrollbar's thumb
11444     *
11445     * @see #computeVerticalScrollRange()
11446     * @see #computeVerticalScrollOffset()
11447     * @see android.widget.ScrollBarDrawable
11448     */
11449    protected int computeVerticalScrollExtent() {
11450        return getHeight();
11451    }
11452
11453    /**
11454     * Check if this view can be scrolled horizontally in a certain direction.
11455     *
11456     * @param direction Negative to check scrolling left, positive to check scrolling right.
11457     * @return true if this view can be scrolled in the specified direction, false otherwise.
11458     */
11459    public boolean canScrollHorizontally(int direction) {
11460        final int offset = computeHorizontalScrollOffset();
11461        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11462        if (range == 0) return false;
11463        if (direction < 0) {
11464            return offset > 0;
11465        } else {
11466            return offset < range - 1;
11467        }
11468    }
11469
11470    /**
11471     * Check if this view can be scrolled vertically in a certain direction.
11472     *
11473     * @param direction Negative to check scrolling up, positive to check scrolling down.
11474     * @return true if this view can be scrolled in the specified direction, false otherwise.
11475     */
11476    public boolean canScrollVertically(int direction) {
11477        final int offset = computeVerticalScrollOffset();
11478        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11479        if (range == 0) return false;
11480        if (direction < 0) {
11481            return offset > 0;
11482        } else {
11483            return offset < range - 1;
11484        }
11485    }
11486
11487    /**
11488     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11489     * scrollbars are painted only if they have been awakened first.</p>
11490     *
11491     * @param canvas the canvas on which to draw the scrollbars
11492     *
11493     * @see #awakenScrollBars(int)
11494     */
11495    protected final void onDrawScrollBars(Canvas canvas) {
11496        // scrollbars are drawn only when the animation is running
11497        final ScrollabilityCache cache = mScrollCache;
11498        if (cache != null) {
11499
11500            int state = cache.state;
11501
11502            if (state == ScrollabilityCache.OFF) {
11503                return;
11504            }
11505
11506            boolean invalidate = false;
11507
11508            if (state == ScrollabilityCache.FADING) {
11509                // We're fading -- get our fade interpolation
11510                if (cache.interpolatorValues == null) {
11511                    cache.interpolatorValues = new float[1];
11512                }
11513
11514                float[] values = cache.interpolatorValues;
11515
11516                // Stops the animation if we're done
11517                if (cache.scrollBarInterpolator.timeToValues(values) ==
11518                        Interpolator.Result.FREEZE_END) {
11519                    cache.state = ScrollabilityCache.OFF;
11520                } else {
11521                    cache.scrollBar.setAlpha(Math.round(values[0]));
11522                }
11523
11524                // This will make the scroll bars inval themselves after
11525                // drawing. We only want this when we're fading so that
11526                // we prevent excessive redraws
11527                invalidate = true;
11528            } else {
11529                // We're just on -- but we may have been fading before so
11530                // reset alpha
11531                cache.scrollBar.setAlpha(255);
11532            }
11533
11534
11535            final int viewFlags = mViewFlags;
11536
11537            final boolean drawHorizontalScrollBar =
11538                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11539            final boolean drawVerticalScrollBar =
11540                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11541                && !isVerticalScrollBarHidden();
11542
11543            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11544                final int width = mRight - mLeft;
11545                final int height = mBottom - mTop;
11546
11547                final ScrollBarDrawable scrollBar = cache.scrollBar;
11548
11549                final int scrollX = mScrollX;
11550                final int scrollY = mScrollY;
11551                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11552
11553                int left;
11554                int top;
11555                int right;
11556                int bottom;
11557
11558                if (drawHorizontalScrollBar) {
11559                    int size = scrollBar.getSize(false);
11560                    if (size <= 0) {
11561                        size = cache.scrollBarSize;
11562                    }
11563
11564                    scrollBar.setParameters(computeHorizontalScrollRange(),
11565                                            computeHorizontalScrollOffset(),
11566                                            computeHorizontalScrollExtent(), false);
11567                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11568                            getVerticalScrollbarWidth() : 0;
11569                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11570                    left = scrollX + (mPaddingLeft & inside);
11571                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11572                    bottom = top + size;
11573                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11574                    if (invalidate) {
11575                        invalidate(left, top, right, bottom);
11576                    }
11577                }
11578
11579                if (drawVerticalScrollBar) {
11580                    int size = scrollBar.getSize(true);
11581                    if (size <= 0) {
11582                        size = cache.scrollBarSize;
11583                    }
11584
11585                    scrollBar.setParameters(computeVerticalScrollRange(),
11586                                            computeVerticalScrollOffset(),
11587                                            computeVerticalScrollExtent(), true);
11588                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11589                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11590                        verticalScrollbarPosition = isLayoutRtl() ?
11591                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11592                    }
11593                    switch (verticalScrollbarPosition) {
11594                        default:
11595                        case SCROLLBAR_POSITION_RIGHT:
11596                            left = scrollX + width - size - (mUserPaddingRight & inside);
11597                            break;
11598                        case SCROLLBAR_POSITION_LEFT:
11599                            left = scrollX + (mUserPaddingLeft & inside);
11600                            break;
11601                    }
11602                    top = scrollY + (mPaddingTop & inside);
11603                    right = left + size;
11604                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11605                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11606                    if (invalidate) {
11607                        invalidate(left, top, right, bottom);
11608                    }
11609                }
11610            }
11611        }
11612    }
11613
11614    /**
11615     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11616     * FastScroller is visible.
11617     * @return whether to temporarily hide the vertical scrollbar
11618     * @hide
11619     */
11620    protected boolean isVerticalScrollBarHidden() {
11621        return false;
11622    }
11623
11624    /**
11625     * <p>Draw the horizontal scrollbar if
11626     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11627     *
11628     * @param canvas the canvas on which to draw the scrollbar
11629     * @param scrollBar the scrollbar's drawable
11630     *
11631     * @see #isHorizontalScrollBarEnabled()
11632     * @see #computeHorizontalScrollRange()
11633     * @see #computeHorizontalScrollExtent()
11634     * @see #computeHorizontalScrollOffset()
11635     * @see android.widget.ScrollBarDrawable
11636     * @hide
11637     */
11638    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11639            int l, int t, int r, int b) {
11640        scrollBar.setBounds(l, t, r, b);
11641        scrollBar.draw(canvas);
11642    }
11643
11644    /**
11645     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11646     * returns true.</p>
11647     *
11648     * @param canvas the canvas on which to draw the scrollbar
11649     * @param scrollBar the scrollbar's drawable
11650     *
11651     * @see #isVerticalScrollBarEnabled()
11652     * @see #computeVerticalScrollRange()
11653     * @see #computeVerticalScrollExtent()
11654     * @see #computeVerticalScrollOffset()
11655     * @see android.widget.ScrollBarDrawable
11656     * @hide
11657     */
11658    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11659            int l, int t, int r, int b) {
11660        scrollBar.setBounds(l, t, r, b);
11661        scrollBar.draw(canvas);
11662    }
11663
11664    /**
11665     * Implement this to do your drawing.
11666     *
11667     * @param canvas the canvas on which the background will be drawn
11668     */
11669    protected void onDraw(Canvas canvas) {
11670    }
11671
11672    /*
11673     * Caller is responsible for calling requestLayout if necessary.
11674     * (This allows addViewInLayout to not request a new layout.)
11675     */
11676    void assignParent(ViewParent parent) {
11677        if (mParent == null) {
11678            mParent = parent;
11679        } else if (parent == null) {
11680            mParent = null;
11681        } else {
11682            throw new RuntimeException("view " + this + " being added, but"
11683                    + " it already has a parent");
11684        }
11685    }
11686
11687    /**
11688     * This is called when the view is attached to a window.  At this point it
11689     * has a Surface and will start drawing.  Note that this function is
11690     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11691     * however it may be called any time before the first onDraw -- including
11692     * before or after {@link #onMeasure(int, int)}.
11693     *
11694     * @see #onDetachedFromWindow()
11695     */
11696    protected void onAttachedToWindow() {
11697        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11698            mParent.requestTransparentRegion(this);
11699        }
11700
11701        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11702            initialAwakenScrollBars();
11703            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11704        }
11705
11706        jumpDrawablesToCurrentState();
11707
11708        clearAccessibilityFocus();
11709        if (isFocused()) {
11710            InputMethodManager imm = InputMethodManager.peekInstance();
11711            imm.focusIn(this);
11712        }
11713
11714        if (mDisplayList != null) {
11715            mDisplayList.clearDirty();
11716        }
11717    }
11718
11719    /**
11720     * Resolve all RTL related properties.
11721     *
11722     * @return true if resolution of RTL properties has been done
11723     *
11724     * @hide
11725     */
11726    public boolean resolveRtlPropertiesIfNeeded() {
11727        if (!needRtlPropertiesResolution()) return false;
11728
11729        // Order is important here: LayoutDirection MUST be resolved first
11730        if (!isLayoutDirectionResolved()) {
11731            resolveLayoutDirection();
11732            resolveLayoutParams();
11733        }
11734        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11735        if (!isTextDirectionResolved()) {
11736            resolveTextDirection();
11737        }
11738        if (!isTextAlignmentResolved()) {
11739            resolveTextAlignment();
11740        }
11741        if (!isPaddingResolved()) {
11742            resolvePadding();
11743        }
11744        if (!isDrawablesResolved()) {
11745            resolveDrawables();
11746        }
11747        onRtlPropertiesChanged(getLayoutDirection());
11748        return true;
11749    }
11750
11751    /**
11752     * Reset resolution of all RTL related properties.
11753     *
11754     * @hide
11755     */
11756    public void resetRtlProperties() {
11757        resetResolvedLayoutDirection();
11758        resetResolvedTextDirection();
11759        resetResolvedTextAlignment();
11760        resetResolvedPadding();
11761        resetResolvedDrawables();
11762    }
11763
11764    /**
11765     * @see #onScreenStateChanged(int)
11766     */
11767    void dispatchScreenStateChanged(int screenState) {
11768        onScreenStateChanged(screenState);
11769    }
11770
11771    /**
11772     * This method is called whenever the state of the screen this view is
11773     * attached to changes. A state change will usually occurs when the screen
11774     * turns on or off (whether it happens automatically or the user does it
11775     * manually.)
11776     *
11777     * @param screenState The new state of the screen. Can be either
11778     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11779     */
11780    public void onScreenStateChanged(int screenState) {
11781    }
11782
11783    /**
11784     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11785     */
11786    private boolean hasRtlSupport() {
11787        return mContext.getApplicationInfo().hasRtlSupport();
11788    }
11789
11790    /**
11791     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11792     * RTL not supported)
11793     */
11794    private boolean isRtlCompatibilityMode() {
11795        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11796        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11797    }
11798
11799    /**
11800     * @return true if RTL properties need resolution.
11801     *
11802     */
11803    private boolean needRtlPropertiesResolution() {
11804        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11805    }
11806
11807    /**
11808     * Called when any RTL property (layout direction or text direction or text alignment) has
11809     * been changed.
11810     *
11811     * Subclasses need to override this method to take care of cached information that depends on the
11812     * resolved layout direction, or to inform child views that inherit their layout direction.
11813     *
11814     * The default implementation does nothing.
11815     *
11816     * @param layoutDirection the direction of the layout
11817     *
11818     * @see #LAYOUT_DIRECTION_LTR
11819     * @see #LAYOUT_DIRECTION_RTL
11820     */
11821    public void onRtlPropertiesChanged(int layoutDirection) {
11822    }
11823
11824    /**
11825     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11826     * that the parent directionality can and will be resolved before its children.
11827     *
11828     * @return true if resolution has been done, false otherwise.
11829     *
11830     * @hide
11831     */
11832    public boolean resolveLayoutDirection() {
11833        // Clear any previous layout direction resolution
11834        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11835
11836        if (hasRtlSupport()) {
11837            // Set resolved depending on layout direction
11838            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11839                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11840                case LAYOUT_DIRECTION_INHERIT:
11841                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11842                    // later to get the correct resolved value
11843                    if (!canResolveLayoutDirection()) return false;
11844
11845                    // Parent has not yet resolved, LTR is still the default
11846                    if (!mParent.isLayoutDirectionResolved()) return false;
11847
11848                    if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11849                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11850                    }
11851                    break;
11852                case LAYOUT_DIRECTION_RTL:
11853                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11854                    break;
11855                case LAYOUT_DIRECTION_LOCALE:
11856                    if((LAYOUT_DIRECTION_RTL ==
11857                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11858                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11859                    }
11860                    break;
11861                default:
11862                    // Nothing to do, LTR by default
11863            }
11864        }
11865
11866        // Set to resolved
11867        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11868        return true;
11869    }
11870
11871    /**
11872     * Check if layout direction resolution can be done.
11873     *
11874     * @return true if layout direction resolution can be done otherwise return false.
11875     *
11876     * @hide
11877     */
11878    public boolean canResolveLayoutDirection() {
11879        switch (getRawLayoutDirection()) {
11880            case LAYOUT_DIRECTION_INHERIT:
11881                return (mParent != null) && mParent.canResolveLayoutDirection();
11882            default:
11883                return true;
11884        }
11885    }
11886
11887    /**
11888     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11889     * {@link #onMeasure(int, int)}.
11890     *
11891     * @hide
11892     */
11893    public void resetResolvedLayoutDirection() {
11894        // Reset the current resolved bits
11895        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11896    }
11897
11898    /**
11899     * @return true if the layout direction is inherited.
11900     *
11901     * @hide
11902     */
11903    public boolean isLayoutDirectionInherited() {
11904        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11905    }
11906
11907    /**
11908     * @return true if layout direction has been resolved.
11909     * @hide
11910     */
11911    public boolean isLayoutDirectionResolved() {
11912        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11913    }
11914
11915    /**
11916     * Return if padding has been resolved
11917     *
11918     * @hide
11919     */
11920    boolean isPaddingResolved() {
11921        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11922    }
11923
11924    /**
11925     * Resolve padding depending on layout direction.
11926     *
11927     * @hide
11928     */
11929    public void resolvePadding() {
11930        if (!isRtlCompatibilityMode()) {
11931            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11932            // If start / end padding are defined, they will be resolved (hence overriding) to
11933            // left / right or right / left depending on the resolved layout direction.
11934            // If start / end padding are not defined, use the left / right ones.
11935            int resolvedLayoutDirection = getLayoutDirection();
11936            switch (resolvedLayoutDirection) {
11937                case LAYOUT_DIRECTION_RTL:
11938                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11939                        mUserPaddingRight = mUserPaddingStart;
11940                    } else {
11941                        mUserPaddingRight = mUserPaddingRightInitial;
11942                    }
11943                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11944                        mUserPaddingLeft = mUserPaddingEnd;
11945                    } else {
11946                        mUserPaddingLeft = mUserPaddingLeftInitial;
11947                    }
11948                    break;
11949                case LAYOUT_DIRECTION_LTR:
11950                default:
11951                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11952                        mUserPaddingLeft = mUserPaddingStart;
11953                    } else {
11954                        mUserPaddingLeft = mUserPaddingLeftInitial;
11955                    }
11956                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11957                        mUserPaddingRight = mUserPaddingEnd;
11958                    } else {
11959                        mUserPaddingRight = mUserPaddingRightInitial;
11960                    }
11961            }
11962
11963            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11964
11965            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11966                    mUserPaddingBottom);
11967            onRtlPropertiesChanged(resolvedLayoutDirection);
11968        }
11969
11970        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11971    }
11972
11973    /**
11974     * Reset the resolved layout direction.
11975     *
11976     * @hide
11977     */
11978    public void resetResolvedPadding() {
11979        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11980    }
11981
11982    /**
11983     * This is called when the view is detached from a window.  At this point it
11984     * no longer has a surface for drawing.
11985     *
11986     * @see #onAttachedToWindow()
11987     */
11988    protected void onDetachedFromWindow() {
11989        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
11990
11991        removeUnsetPressCallback();
11992        removeLongPressCallback();
11993        removePerformClickCallback();
11994        removeSendViewScrolledAccessibilityEventCallback();
11995
11996        destroyDrawingCache();
11997
11998        destroyLayer(false);
11999
12000        if (mAttachInfo != null) {
12001            if (mDisplayList != null) {
12002                mDisplayList.markDirty();
12003                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12004            }
12005            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12006        } else {
12007            // Should never happen
12008            clearDisplayList();
12009        }
12010
12011        mCurrentAnimation = null;
12012
12013        resetAccessibilityStateChanged();
12014    }
12015
12016    /**
12017     * @return The number of times this view has been attached to a window
12018     */
12019    protected int getWindowAttachCount() {
12020        return mWindowAttachCount;
12021    }
12022
12023    /**
12024     * Retrieve a unique token identifying the window this view is attached to.
12025     * @return Return the window's token for use in
12026     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12027     */
12028    public IBinder getWindowToken() {
12029        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12030    }
12031
12032    /**
12033     * Retrieve the {@link WindowId} for the window this view is
12034     * currently attached to.
12035     */
12036    public WindowId getWindowId() {
12037        if (mAttachInfo == null) {
12038            return null;
12039        }
12040        if (mAttachInfo.mWindowId == null) {
12041            try {
12042                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12043                        mAttachInfo.mWindowToken);
12044                mAttachInfo.mWindowId = new WindowId(
12045                        mAttachInfo.mIWindowId);
12046            } catch (RemoteException e) {
12047            }
12048        }
12049        return mAttachInfo.mWindowId;
12050    }
12051
12052    /**
12053     * Retrieve a unique token identifying the top-level "real" window of
12054     * the window that this view is attached to.  That is, this is like
12055     * {@link #getWindowToken}, except if the window this view in is a panel
12056     * window (attached to another containing window), then the token of
12057     * the containing window is returned instead.
12058     *
12059     * @return Returns the associated window token, either
12060     * {@link #getWindowToken()} or the containing window's token.
12061     */
12062    public IBinder getApplicationWindowToken() {
12063        AttachInfo ai = mAttachInfo;
12064        if (ai != null) {
12065            IBinder appWindowToken = ai.mPanelParentWindowToken;
12066            if (appWindowToken == null) {
12067                appWindowToken = ai.mWindowToken;
12068            }
12069            return appWindowToken;
12070        }
12071        return null;
12072    }
12073
12074    /**
12075     * Gets the logical display to which the view's window has been attached.
12076     *
12077     * @return The logical display, or null if the view is not currently attached to a window.
12078     */
12079    public Display getDisplay() {
12080        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12081    }
12082
12083    /**
12084     * Retrieve private session object this view hierarchy is using to
12085     * communicate with the window manager.
12086     * @return the session object to communicate with the window manager
12087     */
12088    /*package*/ IWindowSession getWindowSession() {
12089        return mAttachInfo != null ? mAttachInfo.mSession : null;
12090    }
12091
12092    /**
12093     * @param info the {@link android.view.View.AttachInfo} to associated with
12094     *        this view
12095     */
12096    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12097        //System.out.println("Attached! " + this);
12098        mAttachInfo = info;
12099        if (mOverlay != null) {
12100            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12101        }
12102        mWindowAttachCount++;
12103        // We will need to evaluate the drawable state at least once.
12104        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12105        if (mFloatingTreeObserver != null) {
12106            info.mTreeObserver.merge(mFloatingTreeObserver);
12107            mFloatingTreeObserver = null;
12108        }
12109        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12110            mAttachInfo.mScrollContainers.add(this);
12111            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12112        }
12113        performCollectViewAttributes(mAttachInfo, visibility);
12114        onAttachedToWindow();
12115
12116        ListenerInfo li = mListenerInfo;
12117        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12118                li != null ? li.mOnAttachStateChangeListeners : null;
12119        if (listeners != null && listeners.size() > 0) {
12120            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12121            // perform the dispatching. The iterator is a safe guard against listeners that
12122            // could mutate the list by calling the various add/remove methods. This prevents
12123            // the array from being modified while we iterate it.
12124            for (OnAttachStateChangeListener listener : listeners) {
12125                listener.onViewAttachedToWindow(this);
12126            }
12127        }
12128
12129        int vis = info.mWindowVisibility;
12130        if (vis != GONE) {
12131            onWindowVisibilityChanged(vis);
12132        }
12133        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12134            // If nobody has evaluated the drawable state yet, then do it now.
12135            refreshDrawableState();
12136        }
12137        needGlobalAttributesUpdate(false);
12138    }
12139
12140    void dispatchDetachedFromWindow() {
12141        AttachInfo info = mAttachInfo;
12142        if (info != null) {
12143            int vis = info.mWindowVisibility;
12144            if (vis != GONE) {
12145                onWindowVisibilityChanged(GONE);
12146            }
12147        }
12148
12149        onDetachedFromWindow();
12150
12151        ListenerInfo li = mListenerInfo;
12152        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12153                li != null ? li.mOnAttachStateChangeListeners : null;
12154        if (listeners != null && listeners.size() > 0) {
12155            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12156            // perform the dispatching. The iterator is a safe guard against listeners that
12157            // could mutate the list by calling the various add/remove methods. This prevents
12158            // the array from being modified while we iterate it.
12159            for (OnAttachStateChangeListener listener : listeners) {
12160                listener.onViewDetachedFromWindow(this);
12161            }
12162        }
12163
12164        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12165            mAttachInfo.mScrollContainers.remove(this);
12166            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12167        }
12168
12169        mAttachInfo = null;
12170        if (mOverlay != null) {
12171            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12172        }
12173    }
12174
12175    /**
12176     * Store this view hierarchy's frozen state into the given container.
12177     *
12178     * @param container The SparseArray in which to save the view's state.
12179     *
12180     * @see #restoreHierarchyState(android.util.SparseArray)
12181     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12182     * @see #onSaveInstanceState()
12183     */
12184    public void saveHierarchyState(SparseArray<Parcelable> container) {
12185        dispatchSaveInstanceState(container);
12186    }
12187
12188    /**
12189     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12190     * this view and its children. May be overridden to modify how freezing happens to a
12191     * view's children; for example, some views may want to not store state for their children.
12192     *
12193     * @param container The SparseArray in which to save the view's state.
12194     *
12195     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12196     * @see #saveHierarchyState(android.util.SparseArray)
12197     * @see #onSaveInstanceState()
12198     */
12199    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12200        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12201            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12202            Parcelable state = onSaveInstanceState();
12203            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12204                throw new IllegalStateException(
12205                        "Derived class did not call super.onSaveInstanceState()");
12206            }
12207            if (state != null) {
12208                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12209                // + ": " + state);
12210                container.put(mID, state);
12211            }
12212        }
12213    }
12214
12215    /**
12216     * Hook allowing a view to generate a representation of its internal state
12217     * that can later be used to create a new instance with that same state.
12218     * This state should only contain information that is not persistent or can
12219     * not be reconstructed later. For example, you will never store your
12220     * current position on screen because that will be computed again when a
12221     * new instance of the view is placed in its view hierarchy.
12222     * <p>
12223     * Some examples of things you may store here: the current cursor position
12224     * in a text view (but usually not the text itself since that is stored in a
12225     * content provider or other persistent storage), the currently selected
12226     * item in a list view.
12227     *
12228     * @return Returns a Parcelable object containing the view's current dynamic
12229     *         state, or null if there is nothing interesting to save. The
12230     *         default implementation returns null.
12231     * @see #onRestoreInstanceState(android.os.Parcelable)
12232     * @see #saveHierarchyState(android.util.SparseArray)
12233     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12234     * @see #setSaveEnabled(boolean)
12235     */
12236    protected Parcelable onSaveInstanceState() {
12237        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12238        return BaseSavedState.EMPTY_STATE;
12239    }
12240
12241    /**
12242     * Restore this view hierarchy's frozen state from the given container.
12243     *
12244     * @param container The SparseArray which holds previously frozen states.
12245     *
12246     * @see #saveHierarchyState(android.util.SparseArray)
12247     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12248     * @see #onRestoreInstanceState(android.os.Parcelable)
12249     */
12250    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12251        dispatchRestoreInstanceState(container);
12252    }
12253
12254    /**
12255     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12256     * state for this view and its children. May be overridden to modify how restoring
12257     * happens to a view's children; for example, some views may want to not store state
12258     * for their children.
12259     *
12260     * @param container The SparseArray which holds previously saved state.
12261     *
12262     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12263     * @see #restoreHierarchyState(android.util.SparseArray)
12264     * @see #onRestoreInstanceState(android.os.Parcelable)
12265     */
12266    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12267        if (mID != NO_ID) {
12268            Parcelable state = container.get(mID);
12269            if (state != null) {
12270                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12271                // + ": " + state);
12272                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12273                onRestoreInstanceState(state);
12274                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12275                    throw new IllegalStateException(
12276                            "Derived class did not call super.onRestoreInstanceState()");
12277                }
12278            }
12279        }
12280    }
12281
12282    /**
12283     * Hook allowing a view to re-apply a representation of its internal state that had previously
12284     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12285     * null state.
12286     *
12287     * @param state The frozen state that had previously been returned by
12288     *        {@link #onSaveInstanceState}.
12289     *
12290     * @see #onSaveInstanceState()
12291     * @see #restoreHierarchyState(android.util.SparseArray)
12292     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12293     */
12294    protected void onRestoreInstanceState(Parcelable state) {
12295        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12296        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12297            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12298                    + "received " + state.getClass().toString() + " instead. This usually happens "
12299                    + "when two views of different type have the same id in the same hierarchy. "
12300                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12301                    + "other views do not use the same id.");
12302        }
12303    }
12304
12305    /**
12306     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12307     *
12308     * @return the drawing start time in milliseconds
12309     */
12310    public long getDrawingTime() {
12311        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12312    }
12313
12314    /**
12315     * <p>Enables or disables the duplication of the parent's state into this view. When
12316     * duplication is enabled, this view gets its drawable state from its parent rather
12317     * than from its own internal properties.</p>
12318     *
12319     * <p>Note: in the current implementation, setting this property to true after the
12320     * view was added to a ViewGroup might have no effect at all. This property should
12321     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12322     *
12323     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12324     * property is enabled, an exception will be thrown.</p>
12325     *
12326     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12327     * parent, these states should not be affected by this method.</p>
12328     *
12329     * @param enabled True to enable duplication of the parent's drawable state, false
12330     *                to disable it.
12331     *
12332     * @see #getDrawableState()
12333     * @see #isDuplicateParentStateEnabled()
12334     */
12335    public void setDuplicateParentStateEnabled(boolean enabled) {
12336        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12337    }
12338
12339    /**
12340     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12341     *
12342     * @return True if this view's drawable state is duplicated from the parent,
12343     *         false otherwise
12344     *
12345     * @see #getDrawableState()
12346     * @see #setDuplicateParentStateEnabled(boolean)
12347     */
12348    public boolean isDuplicateParentStateEnabled() {
12349        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12350    }
12351
12352    /**
12353     * <p>Specifies the type of layer backing this view. The layer can be
12354     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12355     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12356     *
12357     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12358     * instance that controls how the layer is composed on screen. The following
12359     * properties of the paint are taken into account when composing the layer:</p>
12360     * <ul>
12361     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12362     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12363     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12364     * </ul>
12365     *
12366     * <p>If this view has an alpha value set to < 1.0 by calling
12367     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12368     * by this view's alpha value.</p>
12369     *
12370     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12371     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12372     * for more information on when and how to use layers.</p>
12373     *
12374     * @param layerType The type of layer to use with this view, must be one of
12375     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12376     *        {@link #LAYER_TYPE_HARDWARE}
12377     * @param paint The paint used to compose the layer. This argument is optional
12378     *        and can be null. It is ignored when the layer type is
12379     *        {@link #LAYER_TYPE_NONE}
12380     *
12381     * @see #getLayerType()
12382     * @see #LAYER_TYPE_NONE
12383     * @see #LAYER_TYPE_SOFTWARE
12384     * @see #LAYER_TYPE_HARDWARE
12385     * @see #setAlpha(float)
12386     *
12387     * @attr ref android.R.styleable#View_layerType
12388     */
12389    public void setLayerType(int layerType, Paint paint) {
12390        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12391            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12392                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12393        }
12394
12395        if (layerType == mLayerType) {
12396            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12397                mLayerPaint = paint == null ? new Paint() : paint;
12398                invalidateParentCaches();
12399                invalidate(true);
12400            }
12401            return;
12402        }
12403
12404        // Destroy any previous software drawing cache if needed
12405        switch (mLayerType) {
12406            case LAYER_TYPE_HARDWARE:
12407                destroyLayer(false);
12408                // fall through - non-accelerated views may use software layer mechanism instead
12409            case LAYER_TYPE_SOFTWARE:
12410                destroyDrawingCache();
12411                break;
12412            default:
12413                break;
12414        }
12415
12416        mLayerType = layerType;
12417        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12418        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12419        mLocalDirtyRect = layerDisabled ? null : new Rect();
12420
12421        invalidateParentCaches();
12422        invalidate(true);
12423    }
12424
12425    /**
12426     * Updates the {@link Paint} object used with the current layer (used only if the current
12427     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12428     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12429     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12430     * ensure that the view gets redrawn immediately.
12431     *
12432     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12433     * instance that controls how the layer is composed on screen. The following
12434     * properties of the paint are taken into account when composing the layer:</p>
12435     * <ul>
12436     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12437     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12438     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12439     * </ul>
12440     *
12441     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12442     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12443     *
12444     * @param paint The paint used to compose the layer. This argument is optional
12445     *        and can be null. It is ignored when the layer type is
12446     *        {@link #LAYER_TYPE_NONE}
12447     *
12448     * @see #setLayerType(int, android.graphics.Paint)
12449     */
12450    public void setLayerPaint(Paint paint) {
12451        int layerType = getLayerType();
12452        if (layerType != LAYER_TYPE_NONE) {
12453            mLayerPaint = paint == null ? new Paint() : paint;
12454            if (layerType == LAYER_TYPE_HARDWARE) {
12455                HardwareLayer layer = getHardwareLayer();
12456                if (layer != null) {
12457                    layer.setLayerPaint(paint);
12458                }
12459                invalidateViewProperty(false, false);
12460            } else {
12461                invalidate();
12462            }
12463        }
12464    }
12465
12466    /**
12467     * Indicates whether this view has a static layer. A view with layer type
12468     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12469     * dynamic.
12470     */
12471    boolean hasStaticLayer() {
12472        return true;
12473    }
12474
12475    /**
12476     * Indicates what type of layer is currently associated with this view. By default
12477     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12478     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12479     * for more information on the different types of layers.
12480     *
12481     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12482     *         {@link #LAYER_TYPE_HARDWARE}
12483     *
12484     * @see #setLayerType(int, android.graphics.Paint)
12485     * @see #buildLayer()
12486     * @see #LAYER_TYPE_NONE
12487     * @see #LAYER_TYPE_SOFTWARE
12488     * @see #LAYER_TYPE_HARDWARE
12489     */
12490    public int getLayerType() {
12491        return mLayerType;
12492    }
12493
12494    /**
12495     * Forces this view's layer to be created and this view to be rendered
12496     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12497     * invoking this method will have no effect.
12498     *
12499     * This method can for instance be used to render a view into its layer before
12500     * starting an animation. If this view is complex, rendering into the layer
12501     * before starting the animation will avoid skipping frames.
12502     *
12503     * @throws IllegalStateException If this view is not attached to a window
12504     *
12505     * @see #setLayerType(int, android.graphics.Paint)
12506     */
12507    public void buildLayer() {
12508        if (mLayerType == LAYER_TYPE_NONE) return;
12509
12510        if (mAttachInfo == null) {
12511            throw new IllegalStateException("This view must be attached to a window first");
12512        }
12513
12514        switch (mLayerType) {
12515            case LAYER_TYPE_HARDWARE:
12516                if (mAttachInfo.mHardwareRenderer != null &&
12517                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12518                        mAttachInfo.mHardwareRenderer.validate()) {
12519                    getHardwareLayer();
12520                }
12521                break;
12522            case LAYER_TYPE_SOFTWARE:
12523                buildDrawingCache(true);
12524                break;
12525        }
12526    }
12527
12528    /**
12529     * <p>Returns a hardware layer that can be used to draw this view again
12530     * without executing its draw method.</p>
12531     *
12532     * @return A HardwareLayer ready to render, or null if an error occurred.
12533     */
12534    HardwareLayer getHardwareLayer() {
12535        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12536                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12537            return null;
12538        }
12539
12540        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12541
12542        final int width = mRight - mLeft;
12543        final int height = mBottom - mTop;
12544
12545        if (width == 0 || height == 0) {
12546            return null;
12547        }
12548
12549        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12550            if (mHardwareLayer == null) {
12551                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12552                        width, height, isOpaque());
12553                mLocalDirtyRect.set(0, 0, width, height);
12554            } else {
12555                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12556                    if (mHardwareLayer.resize(width, height)) {
12557                        mLocalDirtyRect.set(0, 0, width, height);
12558                    }
12559                }
12560
12561                // This should not be necessary but applications that change
12562                // the parameters of their background drawable without calling
12563                // this.setBackground(Drawable) can leave the view in a bad state
12564                // (for instance isOpaque() returns true, but the background is
12565                // not opaque.)
12566                computeOpaqueFlags();
12567
12568                final boolean opaque = isOpaque();
12569                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12570                    mHardwareLayer.setOpaque(opaque);
12571                    mLocalDirtyRect.set(0, 0, width, height);
12572                }
12573            }
12574
12575            // The layer is not valid if the underlying GPU resources cannot be allocated
12576            if (!mHardwareLayer.isValid()) {
12577                return null;
12578            }
12579
12580            mHardwareLayer.setLayerPaint(mLayerPaint);
12581            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12582            ViewRootImpl viewRoot = getViewRootImpl();
12583            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12584
12585            mLocalDirtyRect.setEmpty();
12586        }
12587
12588        return mHardwareLayer;
12589    }
12590
12591    /**
12592     * Destroys this View's hardware layer if possible.
12593     *
12594     * @return True if the layer was destroyed, false otherwise.
12595     *
12596     * @see #setLayerType(int, android.graphics.Paint)
12597     * @see #LAYER_TYPE_HARDWARE
12598     */
12599    boolean destroyLayer(boolean valid) {
12600        if (mHardwareLayer != null) {
12601            AttachInfo info = mAttachInfo;
12602            if (info != null && info.mHardwareRenderer != null &&
12603                    info.mHardwareRenderer.isEnabled() &&
12604                    (valid || info.mHardwareRenderer.validate())) {
12605                mHardwareLayer.destroy();
12606                mHardwareLayer = null;
12607
12608                if (mDisplayList != null) {
12609                    mDisplayList.reset();
12610                }
12611                invalidate(true);
12612                invalidateParentCaches();
12613            }
12614            return true;
12615        }
12616        return false;
12617    }
12618
12619    /**
12620     * Destroys all hardware rendering resources. This method is invoked
12621     * when the system needs to reclaim resources. Upon execution of this
12622     * method, you should free any OpenGL resources created by the view.
12623     *
12624     * Note: you <strong>must</strong> call
12625     * <code>super.destroyHardwareResources()</code> when overriding
12626     * this method.
12627     *
12628     * @hide
12629     */
12630    protected void destroyHardwareResources() {
12631        destroyLayer(true);
12632    }
12633
12634    /**
12635     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12636     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12637     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12638     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12639     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12640     * null.</p>
12641     *
12642     * <p>Enabling the drawing cache is similar to
12643     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12644     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12645     * drawing cache has no effect on rendering because the system uses a different mechanism
12646     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12647     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12648     * for information on how to enable software and hardware layers.</p>
12649     *
12650     * <p>This API can be used to manually generate
12651     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12652     * {@link #getDrawingCache()}.</p>
12653     *
12654     * @param enabled true to enable the drawing cache, false otherwise
12655     *
12656     * @see #isDrawingCacheEnabled()
12657     * @see #getDrawingCache()
12658     * @see #buildDrawingCache()
12659     * @see #setLayerType(int, android.graphics.Paint)
12660     */
12661    public void setDrawingCacheEnabled(boolean enabled) {
12662        mCachingFailed = false;
12663        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12664    }
12665
12666    /**
12667     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12668     *
12669     * @return true if the drawing cache is enabled
12670     *
12671     * @see #setDrawingCacheEnabled(boolean)
12672     * @see #getDrawingCache()
12673     */
12674    @ViewDebug.ExportedProperty(category = "drawing")
12675    public boolean isDrawingCacheEnabled() {
12676        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12677    }
12678
12679    /**
12680     * Debugging utility which recursively outputs the dirty state of a view and its
12681     * descendants.
12682     *
12683     * @hide
12684     */
12685    @SuppressWarnings({"UnusedDeclaration"})
12686    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12687        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12688                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12689                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12690                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12691        if (clear) {
12692            mPrivateFlags &= clearMask;
12693        }
12694        if (this instanceof ViewGroup) {
12695            ViewGroup parent = (ViewGroup) this;
12696            final int count = parent.getChildCount();
12697            for (int i = 0; i < count; i++) {
12698                final View child = parent.getChildAt(i);
12699                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12700            }
12701        }
12702    }
12703
12704    /**
12705     * This method is used by ViewGroup to cause its children to restore or recreate their
12706     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12707     * to recreate its own display list, which would happen if it went through the normal
12708     * draw/dispatchDraw mechanisms.
12709     *
12710     * @hide
12711     */
12712    protected void dispatchGetDisplayList() {}
12713
12714    /**
12715     * A view that is not attached or hardware accelerated cannot create a display list.
12716     * This method checks these conditions and returns the appropriate result.
12717     *
12718     * @return true if view has the ability to create a display list, false otherwise.
12719     *
12720     * @hide
12721     */
12722    public boolean canHaveDisplayList() {
12723        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12724    }
12725
12726    /**
12727     * @return The {@link HardwareRenderer} associated with that view or null if
12728     *         hardware rendering is not supported or this view is not attached
12729     *         to a window.
12730     *
12731     * @hide
12732     */
12733    public HardwareRenderer getHardwareRenderer() {
12734        if (mAttachInfo != null) {
12735            return mAttachInfo.mHardwareRenderer;
12736        }
12737        return null;
12738    }
12739
12740    /**
12741     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12742     * Otherwise, the same display list will be returned (after having been rendered into
12743     * along the way, depending on the invalidation state of the view).
12744     *
12745     * @param displayList The previous version of this displayList, could be null.
12746     * @param isLayer Whether the requester of the display list is a layer. If so,
12747     * the view will avoid creating a layer inside the resulting display list.
12748     * @return A new or reused DisplayList object.
12749     */
12750    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12751        if (!canHaveDisplayList()) {
12752            return null;
12753        }
12754
12755        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12756                displayList == null || !displayList.isValid() ||
12757                (!isLayer && mRecreateDisplayList))) {
12758            // Don't need to recreate the display list, just need to tell our
12759            // children to restore/recreate theirs
12760            if (displayList != null && displayList.isValid() &&
12761                    !isLayer && !mRecreateDisplayList) {
12762                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12763                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12764                dispatchGetDisplayList();
12765
12766                return displayList;
12767            }
12768
12769            if (!isLayer) {
12770                // If we got here, we're recreating it. Mark it as such to ensure that
12771                // we copy in child display lists into ours in drawChild()
12772                mRecreateDisplayList = true;
12773            }
12774            if (displayList == null) {
12775                final String name = getClass().getSimpleName();
12776                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12777                // If we're creating a new display list, make sure our parent gets invalidated
12778                // since they will need to recreate their display list to account for this
12779                // new child display list.
12780                invalidateParentCaches();
12781            }
12782
12783            boolean caching = false;
12784            int width = mRight - mLeft;
12785            int height = mBottom - mTop;
12786            int layerType = getLayerType();
12787
12788            final HardwareCanvas canvas = displayList.start(width, height);
12789
12790            try {
12791                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12792                    if (layerType == LAYER_TYPE_HARDWARE) {
12793                        final HardwareLayer layer = getHardwareLayer();
12794                        if (layer != null && layer.isValid()) {
12795                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12796                        } else {
12797                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12798                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12799                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12800                        }
12801                        caching = true;
12802                    } else {
12803                        buildDrawingCache(true);
12804                        Bitmap cache = getDrawingCache(true);
12805                        if (cache != null) {
12806                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12807                            caching = true;
12808                        }
12809                    }
12810                } else {
12811
12812                    computeScroll();
12813
12814                    canvas.translate(-mScrollX, -mScrollY);
12815                    if (!isLayer) {
12816                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12817                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12818                    }
12819
12820                    // Fast path for layouts with no backgrounds
12821                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12822                        dispatchDraw(canvas);
12823                        if (mOverlay != null && !mOverlay.isEmpty()) {
12824                            mOverlay.getOverlayView().draw(canvas);
12825                        }
12826                    } else {
12827                        draw(canvas);
12828                    }
12829                }
12830            } finally {
12831                displayList.end();
12832                displayList.setCaching(caching);
12833                if (isLayer) {
12834                    displayList.setLeftTopRightBottom(0, 0, width, height);
12835                } else {
12836                    setDisplayListProperties(displayList);
12837                }
12838            }
12839        } else if (!isLayer) {
12840            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12841            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12842        }
12843
12844        return displayList;
12845    }
12846
12847    /**
12848     * Get the DisplayList for the HardwareLayer
12849     *
12850     * @param layer The HardwareLayer whose DisplayList we want
12851     * @return A DisplayList fopr the specified HardwareLayer
12852     */
12853    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12854        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12855        layer.setDisplayList(displayList);
12856        return displayList;
12857    }
12858
12859
12860    /**
12861     * <p>Returns a display list that can be used to draw this view again
12862     * without executing its draw method.</p>
12863     *
12864     * @return A DisplayList ready to replay, or null if caching is not enabled.
12865     *
12866     * @hide
12867     */
12868    public DisplayList getDisplayList() {
12869        mDisplayList = getDisplayList(mDisplayList, false);
12870        return mDisplayList;
12871    }
12872
12873    private void clearDisplayList() {
12874        if (mDisplayList != null) {
12875            mDisplayList.clear();
12876        }
12877    }
12878
12879    /**
12880     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12881     *
12882     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12883     *
12884     * @see #getDrawingCache(boolean)
12885     */
12886    public Bitmap getDrawingCache() {
12887        return getDrawingCache(false);
12888    }
12889
12890    /**
12891     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12892     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12893     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12894     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12895     * request the drawing cache by calling this method and draw it on screen if the
12896     * returned bitmap is not null.</p>
12897     *
12898     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12899     * this method will create a bitmap of the same size as this view. Because this bitmap
12900     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12901     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12902     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12903     * size than the view. This implies that your application must be able to handle this
12904     * size.</p>
12905     *
12906     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12907     *        the current density of the screen when the application is in compatibility
12908     *        mode.
12909     *
12910     * @return A bitmap representing this view or null if cache is disabled.
12911     *
12912     * @see #setDrawingCacheEnabled(boolean)
12913     * @see #isDrawingCacheEnabled()
12914     * @see #buildDrawingCache(boolean)
12915     * @see #destroyDrawingCache()
12916     */
12917    public Bitmap getDrawingCache(boolean autoScale) {
12918        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12919            return null;
12920        }
12921        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12922            buildDrawingCache(autoScale);
12923        }
12924        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12925    }
12926
12927    /**
12928     * <p>Frees the resources used by the drawing cache. If you call
12929     * {@link #buildDrawingCache()} manually without calling
12930     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12931     * should cleanup the cache with this method afterwards.</p>
12932     *
12933     * @see #setDrawingCacheEnabled(boolean)
12934     * @see #buildDrawingCache()
12935     * @see #getDrawingCache()
12936     */
12937    public void destroyDrawingCache() {
12938        if (mDrawingCache != null) {
12939            mDrawingCache.recycle();
12940            mDrawingCache = null;
12941        }
12942        if (mUnscaledDrawingCache != null) {
12943            mUnscaledDrawingCache.recycle();
12944            mUnscaledDrawingCache = null;
12945        }
12946    }
12947
12948    /**
12949     * Setting a solid background color for the drawing cache's bitmaps will improve
12950     * performance and memory usage. Note, though that this should only be used if this
12951     * view will always be drawn on top of a solid color.
12952     *
12953     * @param color The background color to use for the drawing cache's bitmap
12954     *
12955     * @see #setDrawingCacheEnabled(boolean)
12956     * @see #buildDrawingCache()
12957     * @see #getDrawingCache()
12958     */
12959    public void setDrawingCacheBackgroundColor(int color) {
12960        if (color != mDrawingCacheBackgroundColor) {
12961            mDrawingCacheBackgroundColor = color;
12962            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12963        }
12964    }
12965
12966    /**
12967     * @see #setDrawingCacheBackgroundColor(int)
12968     *
12969     * @return The background color to used for the drawing cache's bitmap
12970     */
12971    public int getDrawingCacheBackgroundColor() {
12972        return mDrawingCacheBackgroundColor;
12973    }
12974
12975    /**
12976     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12977     *
12978     * @see #buildDrawingCache(boolean)
12979     */
12980    public void buildDrawingCache() {
12981        buildDrawingCache(false);
12982    }
12983
12984    /**
12985     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12986     *
12987     * <p>If you call {@link #buildDrawingCache()} manually without calling
12988     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12989     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12990     *
12991     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12992     * this method will create a bitmap of the same size as this view. Because this bitmap
12993     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12994     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12995     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12996     * size than the view. This implies that your application must be able to handle this
12997     * size.</p>
12998     *
12999     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13000     * you do not need the drawing cache bitmap, calling this method will increase memory
13001     * usage and cause the view to be rendered in software once, thus negatively impacting
13002     * performance.</p>
13003     *
13004     * @see #getDrawingCache()
13005     * @see #destroyDrawingCache()
13006     */
13007    public void buildDrawingCache(boolean autoScale) {
13008        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13009                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13010            mCachingFailed = false;
13011
13012            int width = mRight - mLeft;
13013            int height = mBottom - mTop;
13014
13015            final AttachInfo attachInfo = mAttachInfo;
13016            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13017
13018            if (autoScale && scalingRequired) {
13019                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13020                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13021            }
13022
13023            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13024            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13025            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13026
13027            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13028            final long drawingCacheSize =
13029                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13030            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13031                if (width > 0 && height > 0) {
13032                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13033                            + projectedBitmapSize + " bytes, only "
13034                            + drawingCacheSize + " available");
13035                }
13036                destroyDrawingCache();
13037                mCachingFailed = true;
13038                return;
13039            }
13040
13041            boolean clear = true;
13042            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13043
13044            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13045                Bitmap.Config quality;
13046                if (!opaque) {
13047                    // Never pick ARGB_4444 because it looks awful
13048                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13049                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13050                        case DRAWING_CACHE_QUALITY_AUTO:
13051                            quality = Bitmap.Config.ARGB_8888;
13052                            break;
13053                        case DRAWING_CACHE_QUALITY_LOW:
13054                            quality = Bitmap.Config.ARGB_8888;
13055                            break;
13056                        case DRAWING_CACHE_QUALITY_HIGH:
13057                            quality = Bitmap.Config.ARGB_8888;
13058                            break;
13059                        default:
13060                            quality = Bitmap.Config.ARGB_8888;
13061                            break;
13062                    }
13063                } else {
13064                    // Optimization for translucent windows
13065                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13066                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13067                }
13068
13069                // Try to cleanup memory
13070                if (bitmap != null) bitmap.recycle();
13071
13072                try {
13073                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13074                            width, height, quality);
13075                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13076                    if (autoScale) {
13077                        mDrawingCache = bitmap;
13078                    } else {
13079                        mUnscaledDrawingCache = bitmap;
13080                    }
13081                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13082                } catch (OutOfMemoryError e) {
13083                    // If there is not enough memory to create the bitmap cache, just
13084                    // ignore the issue as bitmap caches are not required to draw the
13085                    // view hierarchy
13086                    if (autoScale) {
13087                        mDrawingCache = null;
13088                    } else {
13089                        mUnscaledDrawingCache = null;
13090                    }
13091                    mCachingFailed = true;
13092                    return;
13093                }
13094
13095                clear = drawingCacheBackgroundColor != 0;
13096            }
13097
13098            Canvas canvas;
13099            if (attachInfo != null) {
13100                canvas = attachInfo.mCanvas;
13101                if (canvas == null) {
13102                    canvas = new Canvas();
13103                }
13104                canvas.setBitmap(bitmap);
13105                // Temporarily clobber the cached Canvas in case one of our children
13106                // is also using a drawing cache. Without this, the children would
13107                // steal the canvas by attaching their own bitmap to it and bad, bad
13108                // thing would happen (invisible views, corrupted drawings, etc.)
13109                attachInfo.mCanvas = null;
13110            } else {
13111                // This case should hopefully never or seldom happen
13112                canvas = new Canvas(bitmap);
13113            }
13114
13115            if (clear) {
13116                bitmap.eraseColor(drawingCacheBackgroundColor);
13117            }
13118
13119            computeScroll();
13120            final int restoreCount = canvas.save();
13121
13122            if (autoScale && scalingRequired) {
13123                final float scale = attachInfo.mApplicationScale;
13124                canvas.scale(scale, scale);
13125            }
13126
13127            canvas.translate(-mScrollX, -mScrollY);
13128
13129            mPrivateFlags |= PFLAG_DRAWN;
13130            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13131                    mLayerType != LAYER_TYPE_NONE) {
13132                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13133            }
13134
13135            // Fast path for layouts with no backgrounds
13136            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13137                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13138                dispatchDraw(canvas);
13139                if (mOverlay != null && !mOverlay.isEmpty()) {
13140                    mOverlay.getOverlayView().draw(canvas);
13141                }
13142            } else {
13143                draw(canvas);
13144            }
13145
13146            canvas.restoreToCount(restoreCount);
13147            canvas.setBitmap(null);
13148
13149            if (attachInfo != null) {
13150                // Restore the cached Canvas for our siblings
13151                attachInfo.mCanvas = canvas;
13152            }
13153        }
13154    }
13155
13156    /**
13157     * Create a snapshot of the view into a bitmap.  We should probably make
13158     * some form of this public, but should think about the API.
13159     */
13160    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13161        int width = mRight - mLeft;
13162        int height = mBottom - mTop;
13163
13164        final AttachInfo attachInfo = mAttachInfo;
13165        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13166        width = (int) ((width * scale) + 0.5f);
13167        height = (int) ((height * scale) + 0.5f);
13168
13169        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13170                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13171        if (bitmap == null) {
13172            throw new OutOfMemoryError();
13173        }
13174
13175        Resources resources = getResources();
13176        if (resources != null) {
13177            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13178        }
13179
13180        Canvas canvas;
13181        if (attachInfo != null) {
13182            canvas = attachInfo.mCanvas;
13183            if (canvas == null) {
13184                canvas = new Canvas();
13185            }
13186            canvas.setBitmap(bitmap);
13187            // Temporarily clobber the cached Canvas in case one of our children
13188            // is also using a drawing cache. Without this, the children would
13189            // steal the canvas by attaching their own bitmap to it and bad, bad
13190            // things would happen (invisible views, corrupted drawings, etc.)
13191            attachInfo.mCanvas = null;
13192        } else {
13193            // This case should hopefully never or seldom happen
13194            canvas = new Canvas(bitmap);
13195        }
13196
13197        if ((backgroundColor & 0xff000000) != 0) {
13198            bitmap.eraseColor(backgroundColor);
13199        }
13200
13201        computeScroll();
13202        final int restoreCount = canvas.save();
13203        canvas.scale(scale, scale);
13204        canvas.translate(-mScrollX, -mScrollY);
13205
13206        // Temporarily remove the dirty mask
13207        int flags = mPrivateFlags;
13208        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13209
13210        // Fast path for layouts with no backgrounds
13211        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13212            dispatchDraw(canvas);
13213        } else {
13214            draw(canvas);
13215        }
13216
13217        mPrivateFlags = flags;
13218
13219        canvas.restoreToCount(restoreCount);
13220        canvas.setBitmap(null);
13221
13222        if (attachInfo != null) {
13223            // Restore the cached Canvas for our siblings
13224            attachInfo.mCanvas = canvas;
13225        }
13226
13227        return bitmap;
13228    }
13229
13230    /**
13231     * Indicates whether this View is currently in edit mode. A View is usually
13232     * in edit mode when displayed within a developer tool. For instance, if
13233     * this View is being drawn by a visual user interface builder, this method
13234     * should return true.
13235     *
13236     * Subclasses should check the return value of this method to provide
13237     * different behaviors if their normal behavior might interfere with the
13238     * host environment. For instance: the class spawns a thread in its
13239     * constructor, the drawing code relies on device-specific features, etc.
13240     *
13241     * This method is usually checked in the drawing code of custom widgets.
13242     *
13243     * @return True if this View is in edit mode, false otherwise.
13244     */
13245    public boolean isInEditMode() {
13246        return false;
13247    }
13248
13249    /**
13250     * If the View draws content inside its padding and enables fading edges,
13251     * it needs to support padding offsets. Padding offsets are added to the
13252     * fading edges to extend the length of the fade so that it covers pixels
13253     * drawn inside the padding.
13254     *
13255     * Subclasses of this class should override this method if they need
13256     * to draw content inside the padding.
13257     *
13258     * @return True if padding offset must be applied, false otherwise.
13259     *
13260     * @see #getLeftPaddingOffset()
13261     * @see #getRightPaddingOffset()
13262     * @see #getTopPaddingOffset()
13263     * @see #getBottomPaddingOffset()
13264     *
13265     * @since CURRENT
13266     */
13267    protected boolean isPaddingOffsetRequired() {
13268        return false;
13269    }
13270
13271    /**
13272     * Amount by which to extend the left fading region. Called only when
13273     * {@link #isPaddingOffsetRequired()} returns true.
13274     *
13275     * @return The left padding offset in pixels.
13276     *
13277     * @see #isPaddingOffsetRequired()
13278     *
13279     * @since CURRENT
13280     */
13281    protected int getLeftPaddingOffset() {
13282        return 0;
13283    }
13284
13285    /**
13286     * Amount by which to extend the right fading region. Called only when
13287     * {@link #isPaddingOffsetRequired()} returns true.
13288     *
13289     * @return The right padding offset in pixels.
13290     *
13291     * @see #isPaddingOffsetRequired()
13292     *
13293     * @since CURRENT
13294     */
13295    protected int getRightPaddingOffset() {
13296        return 0;
13297    }
13298
13299    /**
13300     * Amount by which to extend the top fading region. Called only when
13301     * {@link #isPaddingOffsetRequired()} returns true.
13302     *
13303     * @return The top padding offset in pixels.
13304     *
13305     * @see #isPaddingOffsetRequired()
13306     *
13307     * @since CURRENT
13308     */
13309    protected int getTopPaddingOffset() {
13310        return 0;
13311    }
13312
13313    /**
13314     * Amount by which to extend the bottom fading region. Called only when
13315     * {@link #isPaddingOffsetRequired()} returns true.
13316     *
13317     * @return The bottom padding offset in pixels.
13318     *
13319     * @see #isPaddingOffsetRequired()
13320     *
13321     * @since CURRENT
13322     */
13323    protected int getBottomPaddingOffset() {
13324        return 0;
13325    }
13326
13327    /**
13328     * @hide
13329     * @param offsetRequired
13330     */
13331    protected int getFadeTop(boolean offsetRequired) {
13332        int top = mPaddingTop;
13333        if (offsetRequired) top += getTopPaddingOffset();
13334        return top;
13335    }
13336
13337    /**
13338     * @hide
13339     * @param offsetRequired
13340     */
13341    protected int getFadeHeight(boolean offsetRequired) {
13342        int padding = mPaddingTop;
13343        if (offsetRequired) padding += getTopPaddingOffset();
13344        return mBottom - mTop - mPaddingBottom - padding;
13345    }
13346
13347    /**
13348     * <p>Indicates whether this view is attached to a hardware accelerated
13349     * window or not.</p>
13350     *
13351     * <p>Even if this method returns true, it does not mean that every call
13352     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13353     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13354     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13355     * window is hardware accelerated,
13356     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13357     * return false, and this method will return true.</p>
13358     *
13359     * @return True if the view is attached to a window and the window is
13360     *         hardware accelerated; false in any other case.
13361     */
13362    public boolean isHardwareAccelerated() {
13363        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13364    }
13365
13366    /**
13367     * Sets a rectangular area on this view to which the view will be clipped
13368     * when it is drawn. Setting the value to null will remove the clip bounds
13369     * and the view will draw normally, using its full bounds.
13370     *
13371     * @param clipBounds The rectangular area, in the local coordinates of
13372     * this view, to which future drawing operations will be clipped.
13373     */
13374    public void setClipBounds(Rect clipBounds) {
13375        if (clipBounds != null) {
13376            if (clipBounds.equals(mClipBounds)) {
13377                return;
13378            }
13379            if (mClipBounds == null) {
13380                invalidate();
13381                mClipBounds = new Rect(clipBounds);
13382            } else {
13383                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13384                        Math.min(mClipBounds.top, clipBounds.top),
13385                        Math.max(mClipBounds.right, clipBounds.right),
13386                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13387                mClipBounds.set(clipBounds);
13388            }
13389        } else {
13390            if (mClipBounds != null) {
13391                invalidate();
13392                mClipBounds = null;
13393            }
13394        }
13395    }
13396
13397    /**
13398     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13399     *
13400     * @return A copy of the current clip bounds if clip bounds are set,
13401     * otherwise null.
13402     */
13403    public Rect getClipBounds() {
13404        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13405    }
13406
13407    /**
13408     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13409     * case of an active Animation being run on the view.
13410     */
13411    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13412            Animation a, boolean scalingRequired) {
13413        Transformation invalidationTransform;
13414        final int flags = parent.mGroupFlags;
13415        final boolean initialized = a.isInitialized();
13416        if (!initialized) {
13417            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13418            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13419            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13420            onAnimationStart();
13421        }
13422
13423        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13424        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13425            if (parent.mInvalidationTransformation == null) {
13426                parent.mInvalidationTransformation = new Transformation();
13427            }
13428            invalidationTransform = parent.mInvalidationTransformation;
13429            a.getTransformation(drawingTime, invalidationTransform, 1f);
13430        } else {
13431            invalidationTransform = parent.mChildTransformation;
13432        }
13433
13434        if (more) {
13435            if (!a.willChangeBounds()) {
13436                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13437                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13438                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13439                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13440                    // The child need to draw an animation, potentially offscreen, so
13441                    // make sure we do not cancel invalidate requests
13442                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13443                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13444                }
13445            } else {
13446                if (parent.mInvalidateRegion == null) {
13447                    parent.mInvalidateRegion = new RectF();
13448                }
13449                final RectF region = parent.mInvalidateRegion;
13450                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13451                        invalidationTransform);
13452
13453                // The child need to draw an animation, potentially offscreen, so
13454                // make sure we do not cancel invalidate requests
13455                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13456
13457                final int left = mLeft + (int) region.left;
13458                final int top = mTop + (int) region.top;
13459                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13460                        top + (int) (region.height() + .5f));
13461            }
13462        }
13463        return more;
13464    }
13465
13466    /**
13467     * This method is called by getDisplayList() when a display list is created or re-rendered.
13468     * It sets or resets the current value of all properties on that display list (resetting is
13469     * necessary when a display list is being re-created, because we need to make sure that
13470     * previously-set transform values
13471     */
13472    void setDisplayListProperties(DisplayList displayList) {
13473        if (displayList != null) {
13474            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13475            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13476            if (mParent instanceof ViewGroup) {
13477                displayList.setClipToBounds(
13478                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13479            }
13480            float alpha = 1;
13481            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13482                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13483                ViewGroup parentVG = (ViewGroup) mParent;
13484                final boolean hasTransform =
13485                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13486                if (hasTransform) {
13487                    Transformation transform = parentVG.mChildTransformation;
13488                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13489                    if (transformType != Transformation.TYPE_IDENTITY) {
13490                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13491                            alpha = transform.getAlpha();
13492                        }
13493                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13494                            displayList.setMatrix(transform.getMatrix());
13495                        }
13496                    }
13497                }
13498            }
13499            if (mTransformationInfo != null) {
13500                alpha *= mTransformationInfo.mAlpha;
13501                if (alpha < 1) {
13502                    final int multipliedAlpha = (int) (255 * alpha);
13503                    if (onSetAlpha(multipliedAlpha)) {
13504                        alpha = 1;
13505                    }
13506                }
13507                displayList.setTransformationInfo(alpha,
13508                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13509                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13510                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13511                        mTransformationInfo.mScaleY);
13512                if (mTransformationInfo.mCamera == null) {
13513                    mTransformationInfo.mCamera = new Camera();
13514                    mTransformationInfo.matrix3D = new Matrix();
13515                }
13516                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13517                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13518                    displayList.setPivotX(getPivotX());
13519                    displayList.setPivotY(getPivotY());
13520                }
13521            } else if (alpha < 1) {
13522                displayList.setAlpha(alpha);
13523            }
13524        }
13525    }
13526
13527    /**
13528     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13529     * This draw() method is an implementation detail and is not intended to be overridden or
13530     * to be called from anywhere else other than ViewGroup.drawChild().
13531     */
13532    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13533        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13534        boolean more = false;
13535        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13536        final int flags = parent.mGroupFlags;
13537
13538        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13539            parent.mChildTransformation.clear();
13540            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13541        }
13542
13543        Transformation transformToApply = null;
13544        boolean concatMatrix = false;
13545
13546        boolean scalingRequired = false;
13547        boolean caching;
13548        int layerType = getLayerType();
13549
13550        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13551        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13552                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13553            caching = true;
13554            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13555            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13556        } else {
13557            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13558        }
13559
13560        final Animation a = getAnimation();
13561        if (a != null) {
13562            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13563            concatMatrix = a.willChangeTransformationMatrix();
13564            if (concatMatrix) {
13565                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13566            }
13567            transformToApply = parent.mChildTransformation;
13568        } else {
13569            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13570                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13571                // No longer animating: clear out old animation matrix
13572                mDisplayList.setAnimationMatrix(null);
13573                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13574            }
13575            if (!useDisplayListProperties &&
13576                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13577                final boolean hasTransform =
13578                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13579                if (hasTransform) {
13580                    final int transformType = parent.mChildTransformation.getTransformationType();
13581                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13582                            parent.mChildTransformation : null;
13583                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13584                }
13585            }
13586        }
13587
13588        concatMatrix |= !childHasIdentityMatrix;
13589
13590        // Sets the flag as early as possible to allow draw() implementations
13591        // to call invalidate() successfully when doing animations
13592        mPrivateFlags |= PFLAG_DRAWN;
13593
13594        if (!concatMatrix &&
13595                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13596                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13597                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13598                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13599            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13600            return more;
13601        }
13602        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13603
13604        if (hardwareAccelerated) {
13605            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13606            // retain the flag's value temporarily in the mRecreateDisplayList flag
13607            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13608            mPrivateFlags &= ~PFLAG_INVALIDATED;
13609        }
13610
13611        DisplayList displayList = null;
13612        Bitmap cache = null;
13613        boolean hasDisplayList = false;
13614        if (caching) {
13615            if (!hardwareAccelerated) {
13616                if (layerType != LAYER_TYPE_NONE) {
13617                    layerType = LAYER_TYPE_SOFTWARE;
13618                    buildDrawingCache(true);
13619                }
13620                cache = getDrawingCache(true);
13621            } else {
13622                switch (layerType) {
13623                    case LAYER_TYPE_SOFTWARE:
13624                        if (useDisplayListProperties) {
13625                            hasDisplayList = canHaveDisplayList();
13626                        } else {
13627                            buildDrawingCache(true);
13628                            cache = getDrawingCache(true);
13629                        }
13630                        break;
13631                    case LAYER_TYPE_HARDWARE:
13632                        if (useDisplayListProperties) {
13633                            hasDisplayList = canHaveDisplayList();
13634                        }
13635                        break;
13636                    case LAYER_TYPE_NONE:
13637                        // Delay getting the display list until animation-driven alpha values are
13638                        // set up and possibly passed on to the view
13639                        hasDisplayList = canHaveDisplayList();
13640                        break;
13641                }
13642            }
13643        }
13644        useDisplayListProperties &= hasDisplayList;
13645        if (useDisplayListProperties) {
13646            displayList = getDisplayList();
13647            if (!displayList.isValid()) {
13648                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13649                // to getDisplayList(), the display list will be marked invalid and we should not
13650                // try to use it again.
13651                displayList = null;
13652                hasDisplayList = false;
13653                useDisplayListProperties = false;
13654            }
13655        }
13656
13657        int sx = 0;
13658        int sy = 0;
13659        if (!hasDisplayList) {
13660            computeScroll();
13661            sx = mScrollX;
13662            sy = mScrollY;
13663        }
13664
13665        final boolean hasNoCache = cache == null || hasDisplayList;
13666        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13667                layerType != LAYER_TYPE_HARDWARE;
13668
13669        int restoreTo = -1;
13670        if (!useDisplayListProperties || transformToApply != null) {
13671            restoreTo = canvas.save();
13672        }
13673        if (offsetForScroll) {
13674            canvas.translate(mLeft - sx, mTop - sy);
13675        } else {
13676            if (!useDisplayListProperties) {
13677                canvas.translate(mLeft, mTop);
13678            }
13679            if (scalingRequired) {
13680                if (useDisplayListProperties) {
13681                    // TODO: Might not need this if we put everything inside the DL
13682                    restoreTo = canvas.save();
13683                }
13684                // mAttachInfo cannot be null, otherwise scalingRequired == false
13685                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13686                canvas.scale(scale, scale);
13687            }
13688        }
13689
13690        float alpha = useDisplayListProperties ? 1 : getAlpha();
13691        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13692                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13693            if (transformToApply != null || !childHasIdentityMatrix) {
13694                int transX = 0;
13695                int transY = 0;
13696
13697                if (offsetForScroll) {
13698                    transX = -sx;
13699                    transY = -sy;
13700                }
13701
13702                if (transformToApply != null) {
13703                    if (concatMatrix) {
13704                        if (useDisplayListProperties) {
13705                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13706                        } else {
13707                            // Undo the scroll translation, apply the transformation matrix,
13708                            // then redo the scroll translate to get the correct result.
13709                            canvas.translate(-transX, -transY);
13710                            canvas.concat(transformToApply.getMatrix());
13711                            canvas.translate(transX, transY);
13712                        }
13713                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13714                    }
13715
13716                    float transformAlpha = transformToApply.getAlpha();
13717                    if (transformAlpha < 1) {
13718                        alpha *= transformAlpha;
13719                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13720                    }
13721                }
13722
13723                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13724                    canvas.translate(-transX, -transY);
13725                    canvas.concat(getMatrix());
13726                    canvas.translate(transX, transY);
13727                }
13728            }
13729
13730            // Deal with alpha if it is or used to be <1
13731            if (alpha < 1 ||
13732                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13733                if (alpha < 1) {
13734                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13735                } else {
13736                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13737                }
13738                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13739                if (hasNoCache) {
13740                    final int multipliedAlpha = (int) (255 * alpha);
13741                    if (!onSetAlpha(multipliedAlpha)) {
13742                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13743                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13744                                layerType != LAYER_TYPE_NONE) {
13745                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13746                        }
13747                        if (useDisplayListProperties) {
13748                            displayList.setAlpha(alpha * getAlpha());
13749                        } else  if (layerType == LAYER_TYPE_NONE) {
13750                            final int scrollX = hasDisplayList ? 0 : sx;
13751                            final int scrollY = hasDisplayList ? 0 : sy;
13752                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13753                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13754                        }
13755                    } else {
13756                        // Alpha is handled by the child directly, clobber the layer's alpha
13757                        mPrivateFlags |= PFLAG_ALPHA_SET;
13758                    }
13759                }
13760            }
13761        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13762            onSetAlpha(255);
13763            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13764        }
13765
13766        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13767                !useDisplayListProperties && cache == null) {
13768            if (offsetForScroll) {
13769                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13770            } else {
13771                if (!scalingRequired || cache == null) {
13772                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13773                } else {
13774                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13775                }
13776            }
13777        }
13778
13779        if (!useDisplayListProperties && hasDisplayList) {
13780            displayList = getDisplayList();
13781            if (!displayList.isValid()) {
13782                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13783                // to getDisplayList(), the display list will be marked invalid and we should not
13784                // try to use it again.
13785                displayList = null;
13786                hasDisplayList = false;
13787            }
13788        }
13789
13790        if (hasNoCache) {
13791            boolean layerRendered = false;
13792            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13793                final HardwareLayer layer = getHardwareLayer();
13794                if (layer != null && layer.isValid()) {
13795                    mLayerPaint.setAlpha((int) (alpha * 255));
13796                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13797                    layerRendered = true;
13798                } else {
13799                    final int scrollX = hasDisplayList ? 0 : sx;
13800                    final int scrollY = hasDisplayList ? 0 : sy;
13801                    canvas.saveLayer(scrollX, scrollY,
13802                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13803                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13804                }
13805            }
13806
13807            if (!layerRendered) {
13808                if (!hasDisplayList) {
13809                    // Fast path for layouts with no backgrounds
13810                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13811                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13812                        dispatchDraw(canvas);
13813                    } else {
13814                        draw(canvas);
13815                    }
13816                } else {
13817                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13818                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13819                }
13820            }
13821        } else if (cache != null) {
13822            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13823            Paint cachePaint;
13824
13825            if (layerType == LAYER_TYPE_NONE) {
13826                cachePaint = parent.mCachePaint;
13827                if (cachePaint == null) {
13828                    cachePaint = new Paint();
13829                    cachePaint.setDither(false);
13830                    parent.mCachePaint = cachePaint;
13831                }
13832                if (alpha < 1) {
13833                    cachePaint.setAlpha((int) (alpha * 255));
13834                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13835                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13836                    cachePaint.setAlpha(255);
13837                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13838                }
13839            } else {
13840                cachePaint = mLayerPaint;
13841                cachePaint.setAlpha((int) (alpha * 255));
13842            }
13843            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13844        }
13845
13846        if (restoreTo >= 0) {
13847            canvas.restoreToCount(restoreTo);
13848        }
13849
13850        if (a != null && !more) {
13851            if (!hardwareAccelerated && !a.getFillAfter()) {
13852                onSetAlpha(255);
13853            }
13854            parent.finishAnimatingView(this, a);
13855        }
13856
13857        if (more && hardwareAccelerated) {
13858            // invalidation is the trigger to recreate display lists, so if we're using
13859            // display lists to render, force an invalidate to allow the animation to
13860            // continue drawing another frame
13861            parent.invalidate(true);
13862            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13863                // alpha animations should cause the child to recreate its display list
13864                invalidate(true);
13865            }
13866        }
13867
13868        mRecreateDisplayList = false;
13869
13870        return more;
13871    }
13872
13873    /**
13874     * Manually render this view (and all of its children) to the given Canvas.
13875     * The view must have already done a full layout before this function is
13876     * called.  When implementing a view, implement
13877     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13878     * If you do need to override this method, call the superclass version.
13879     *
13880     * @param canvas The Canvas to which the View is rendered.
13881     */
13882    public void draw(Canvas canvas) {
13883        if (mClipBounds != null) {
13884            canvas.clipRect(mClipBounds);
13885        }
13886        final int privateFlags = mPrivateFlags;
13887        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13888                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13889        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13890
13891        /*
13892         * Draw traversal performs several drawing steps which must be executed
13893         * in the appropriate order:
13894         *
13895         *      1. Draw the background
13896         *      2. If necessary, save the canvas' layers to prepare for fading
13897         *      3. Draw view's content
13898         *      4. Draw children
13899         *      5. If necessary, draw the fading edges and restore layers
13900         *      6. Draw decorations (scrollbars for instance)
13901         */
13902
13903        // Step 1, draw the background, if needed
13904        int saveCount;
13905
13906        if (!dirtyOpaque) {
13907            final Drawable background = mBackground;
13908            if (background != null) {
13909                final int scrollX = mScrollX;
13910                final int scrollY = mScrollY;
13911
13912                if (mBackgroundSizeChanged) {
13913                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13914                    mBackgroundSizeChanged = false;
13915                }
13916
13917                if ((scrollX | scrollY) == 0) {
13918                    background.draw(canvas);
13919                } else {
13920                    canvas.translate(scrollX, scrollY);
13921                    background.draw(canvas);
13922                    canvas.translate(-scrollX, -scrollY);
13923                }
13924            }
13925        }
13926
13927        // skip step 2 & 5 if possible (common case)
13928        final int viewFlags = mViewFlags;
13929        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13930        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13931        if (!verticalEdges && !horizontalEdges) {
13932            // Step 3, draw the content
13933            if (!dirtyOpaque) onDraw(canvas);
13934
13935            // Step 4, draw the children
13936            dispatchDraw(canvas);
13937
13938            // Step 6, draw decorations (scrollbars)
13939            onDrawScrollBars(canvas);
13940
13941            if (mOverlay != null && !mOverlay.isEmpty()) {
13942                mOverlay.getOverlayView().dispatchDraw(canvas);
13943            }
13944
13945            // we're done...
13946            return;
13947        }
13948
13949        /*
13950         * Here we do the full fledged routine...
13951         * (this is an uncommon case where speed matters less,
13952         * this is why we repeat some of the tests that have been
13953         * done above)
13954         */
13955
13956        boolean drawTop = false;
13957        boolean drawBottom = false;
13958        boolean drawLeft = false;
13959        boolean drawRight = false;
13960
13961        float topFadeStrength = 0.0f;
13962        float bottomFadeStrength = 0.0f;
13963        float leftFadeStrength = 0.0f;
13964        float rightFadeStrength = 0.0f;
13965
13966        // Step 2, save the canvas' layers
13967        int paddingLeft = mPaddingLeft;
13968
13969        final boolean offsetRequired = isPaddingOffsetRequired();
13970        if (offsetRequired) {
13971            paddingLeft += getLeftPaddingOffset();
13972        }
13973
13974        int left = mScrollX + paddingLeft;
13975        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13976        int top = mScrollY + getFadeTop(offsetRequired);
13977        int bottom = top + getFadeHeight(offsetRequired);
13978
13979        if (offsetRequired) {
13980            right += getRightPaddingOffset();
13981            bottom += getBottomPaddingOffset();
13982        }
13983
13984        final ScrollabilityCache scrollabilityCache = mScrollCache;
13985        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13986        int length = (int) fadeHeight;
13987
13988        // clip the fade length if top and bottom fades overlap
13989        // overlapping fades produce odd-looking artifacts
13990        if (verticalEdges && (top + length > bottom - length)) {
13991            length = (bottom - top) / 2;
13992        }
13993
13994        // also clip horizontal fades if necessary
13995        if (horizontalEdges && (left + length > right - length)) {
13996            length = (right - left) / 2;
13997        }
13998
13999        if (verticalEdges) {
14000            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14001            drawTop = topFadeStrength * fadeHeight > 1.0f;
14002            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14003            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14004        }
14005
14006        if (horizontalEdges) {
14007            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14008            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14009            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14010            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14011        }
14012
14013        saveCount = canvas.getSaveCount();
14014
14015        int solidColor = getSolidColor();
14016        if (solidColor == 0) {
14017            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14018
14019            if (drawTop) {
14020                canvas.saveLayer(left, top, right, top + length, null, flags);
14021            }
14022
14023            if (drawBottom) {
14024                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14025            }
14026
14027            if (drawLeft) {
14028                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14029            }
14030
14031            if (drawRight) {
14032                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14033            }
14034        } else {
14035            scrollabilityCache.setFadeColor(solidColor);
14036        }
14037
14038        // Step 3, draw the content
14039        if (!dirtyOpaque) onDraw(canvas);
14040
14041        // Step 4, draw the children
14042        dispatchDraw(canvas);
14043
14044        // Step 5, draw the fade effect and restore layers
14045        final Paint p = scrollabilityCache.paint;
14046        final Matrix matrix = scrollabilityCache.matrix;
14047        final Shader fade = scrollabilityCache.shader;
14048
14049        if (drawTop) {
14050            matrix.setScale(1, fadeHeight * topFadeStrength);
14051            matrix.postTranslate(left, top);
14052            fade.setLocalMatrix(matrix);
14053            canvas.drawRect(left, top, right, top + length, p);
14054        }
14055
14056        if (drawBottom) {
14057            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14058            matrix.postRotate(180);
14059            matrix.postTranslate(left, bottom);
14060            fade.setLocalMatrix(matrix);
14061            canvas.drawRect(left, bottom - length, right, bottom, p);
14062        }
14063
14064        if (drawLeft) {
14065            matrix.setScale(1, fadeHeight * leftFadeStrength);
14066            matrix.postRotate(-90);
14067            matrix.postTranslate(left, top);
14068            fade.setLocalMatrix(matrix);
14069            canvas.drawRect(left, top, left + length, bottom, p);
14070        }
14071
14072        if (drawRight) {
14073            matrix.setScale(1, fadeHeight * rightFadeStrength);
14074            matrix.postRotate(90);
14075            matrix.postTranslate(right, top);
14076            fade.setLocalMatrix(matrix);
14077            canvas.drawRect(right - length, top, right, bottom, p);
14078        }
14079
14080        canvas.restoreToCount(saveCount);
14081
14082        // Step 6, draw decorations (scrollbars)
14083        onDrawScrollBars(canvas);
14084
14085        if (mOverlay != null && !mOverlay.isEmpty()) {
14086            mOverlay.getOverlayView().dispatchDraw(canvas);
14087        }
14088    }
14089
14090    /**
14091     * Returns the overlay for this view, creating it if it does not yet exist.
14092     * Adding drawables to the overlay will cause them to be displayed whenever
14093     * the view itself is redrawn. Objects in the overlay should be actively
14094     * managed: remove them when they should not be displayed anymore. The
14095     * overlay will always have the same size as its host view.
14096     *
14097     * <p>Note: Overlays do not currently work correctly with {@link
14098     * SurfaceView} or {@link TextureView}; contents in overlays for these
14099     * types of views may not display correctly.</p>
14100     *
14101     * @return The ViewOverlay object for this view.
14102     * @see ViewOverlay
14103     */
14104    public ViewOverlay getOverlay() {
14105        if (mOverlay == null) {
14106            mOverlay = new ViewOverlay(mContext, this);
14107        }
14108        return mOverlay;
14109    }
14110
14111    /**
14112     * Override this if your view is known to always be drawn on top of a solid color background,
14113     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14114     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14115     * should be set to 0xFF.
14116     *
14117     * @see #setVerticalFadingEdgeEnabled(boolean)
14118     * @see #setHorizontalFadingEdgeEnabled(boolean)
14119     *
14120     * @return The known solid color background for this view, or 0 if the color may vary
14121     */
14122    @ViewDebug.ExportedProperty(category = "drawing")
14123    public int getSolidColor() {
14124        return 0;
14125    }
14126
14127    /**
14128     * Build a human readable string representation of the specified view flags.
14129     *
14130     * @param flags the view flags to convert to a string
14131     * @return a String representing the supplied flags
14132     */
14133    private static String printFlags(int flags) {
14134        String output = "";
14135        int numFlags = 0;
14136        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14137            output += "TAKES_FOCUS";
14138            numFlags++;
14139        }
14140
14141        switch (flags & VISIBILITY_MASK) {
14142        case INVISIBLE:
14143            if (numFlags > 0) {
14144                output += " ";
14145            }
14146            output += "INVISIBLE";
14147            // USELESS HERE numFlags++;
14148            break;
14149        case GONE:
14150            if (numFlags > 0) {
14151                output += " ";
14152            }
14153            output += "GONE";
14154            // USELESS HERE numFlags++;
14155            break;
14156        default:
14157            break;
14158        }
14159        return output;
14160    }
14161
14162    /**
14163     * Build a human readable string representation of the specified private
14164     * view flags.
14165     *
14166     * @param privateFlags the private view flags to convert to a string
14167     * @return a String representing the supplied flags
14168     */
14169    private static String printPrivateFlags(int privateFlags) {
14170        String output = "";
14171        int numFlags = 0;
14172
14173        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14174            output += "WANTS_FOCUS";
14175            numFlags++;
14176        }
14177
14178        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14179            if (numFlags > 0) {
14180                output += " ";
14181            }
14182            output += "FOCUSED";
14183            numFlags++;
14184        }
14185
14186        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14187            if (numFlags > 0) {
14188                output += " ";
14189            }
14190            output += "SELECTED";
14191            numFlags++;
14192        }
14193
14194        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14195            if (numFlags > 0) {
14196                output += " ";
14197            }
14198            output += "IS_ROOT_NAMESPACE";
14199            numFlags++;
14200        }
14201
14202        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14203            if (numFlags > 0) {
14204                output += " ";
14205            }
14206            output += "HAS_BOUNDS";
14207            numFlags++;
14208        }
14209
14210        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14211            if (numFlags > 0) {
14212                output += " ";
14213            }
14214            output += "DRAWN";
14215            // USELESS HERE numFlags++;
14216        }
14217        return output;
14218    }
14219
14220    /**
14221     * <p>Indicates whether or not this view's layout will be requested during
14222     * the next hierarchy layout pass.</p>
14223     *
14224     * @return true if the layout will be forced during next layout pass
14225     */
14226    public boolean isLayoutRequested() {
14227        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14228    }
14229
14230    /**
14231     * Return true if o is a ViewGroup that is laying out using optical bounds.
14232     * @hide
14233     */
14234    public static boolean isLayoutModeOptical(Object o) {
14235        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14236    }
14237
14238    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14239        Insets parentInsets = mParent instanceof View ?
14240                ((View) mParent).getOpticalInsets() : Insets.NONE;
14241        Insets childInsets = getOpticalInsets();
14242        return setFrame(
14243                left   + parentInsets.left - childInsets.left,
14244                top    + parentInsets.top  - childInsets.top,
14245                right  + parentInsets.left + childInsets.right,
14246                bottom + parentInsets.top  + childInsets.bottom);
14247    }
14248
14249    /**
14250     * Assign a size and position to a view and all of its
14251     * descendants
14252     *
14253     * <p>This is the second phase of the layout mechanism.
14254     * (The first is measuring). In this phase, each parent calls
14255     * layout on all of its children to position them.
14256     * This is typically done using the child measurements
14257     * that were stored in the measure pass().</p>
14258     *
14259     * <p>Derived classes should not override this method.
14260     * Derived classes with children should override
14261     * onLayout. In that method, they should
14262     * call layout on each of their children.</p>
14263     *
14264     * @param l Left position, relative to parent
14265     * @param t Top position, relative to parent
14266     * @param r Right position, relative to parent
14267     * @param b Bottom position, relative to parent
14268     */
14269    @SuppressWarnings({"unchecked"})
14270    public void layout(int l, int t, int r, int b) {
14271        int oldL = mLeft;
14272        int oldT = mTop;
14273        int oldB = mBottom;
14274        int oldR = mRight;
14275        boolean changed = isLayoutModeOptical(mParent) ?
14276                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14277        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14278            onLayout(changed, l, t, r, b);
14279            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14280
14281            ListenerInfo li = mListenerInfo;
14282            if (li != null && li.mOnLayoutChangeListeners != null) {
14283                ArrayList<OnLayoutChangeListener> listenersCopy =
14284                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14285                int numListeners = listenersCopy.size();
14286                for (int i = 0; i < numListeners; ++i) {
14287                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14288                }
14289            }
14290        }
14291        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14292    }
14293
14294    /**
14295     * Called from layout when this view should
14296     * assign a size and position to each of its children.
14297     *
14298     * Derived classes with children should override
14299     * this method and call layout on each of
14300     * their children.
14301     * @param changed This is a new size or position for this view
14302     * @param left Left position, relative to parent
14303     * @param top Top position, relative to parent
14304     * @param right Right position, relative to parent
14305     * @param bottom Bottom position, relative to parent
14306     */
14307    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14308    }
14309
14310    /**
14311     * Assign a size and position to this view.
14312     *
14313     * This is called from layout.
14314     *
14315     * @param left Left position, relative to parent
14316     * @param top Top position, relative to parent
14317     * @param right Right position, relative to parent
14318     * @param bottom Bottom position, relative to parent
14319     * @return true if the new size and position are different than the
14320     *         previous ones
14321     * {@hide}
14322     */
14323    protected boolean setFrame(int left, int top, int right, int bottom) {
14324        boolean changed = false;
14325
14326        if (DBG) {
14327            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14328                    + right + "," + bottom + ")");
14329        }
14330
14331        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14332            changed = true;
14333
14334            // Remember our drawn bit
14335            int drawn = mPrivateFlags & PFLAG_DRAWN;
14336
14337            int oldWidth = mRight - mLeft;
14338            int oldHeight = mBottom - mTop;
14339            int newWidth = right - left;
14340            int newHeight = bottom - top;
14341            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14342
14343            // Invalidate our old position
14344            invalidate(sizeChanged);
14345
14346            mLeft = left;
14347            mTop = top;
14348            mRight = right;
14349            mBottom = bottom;
14350            if (mDisplayList != null) {
14351                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14352            }
14353
14354            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14355
14356
14357            if (sizeChanged) {
14358                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14359                    // A change in dimension means an auto-centered pivot point changes, too
14360                    if (mTransformationInfo != null) {
14361                        mTransformationInfo.mMatrixDirty = true;
14362                    }
14363                }
14364                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14365            }
14366
14367            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14368                // If we are visible, force the DRAWN bit to on so that
14369                // this invalidate will go through (at least to our parent).
14370                // This is because someone may have invalidated this view
14371                // before this call to setFrame came in, thereby clearing
14372                // the DRAWN bit.
14373                mPrivateFlags |= PFLAG_DRAWN;
14374                invalidate(sizeChanged);
14375                // parent display list may need to be recreated based on a change in the bounds
14376                // of any child
14377                invalidateParentCaches();
14378            }
14379
14380            // Reset drawn bit to original value (invalidate turns it off)
14381            mPrivateFlags |= drawn;
14382
14383            mBackgroundSizeChanged = true;
14384        }
14385        return changed;
14386    }
14387
14388    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14389        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14390        if (mOverlay != null) {
14391            mOverlay.getOverlayView().setRight(newWidth);
14392            mOverlay.getOverlayView().setBottom(newHeight);
14393        }
14394    }
14395
14396    /**
14397     * Finalize inflating a view from XML.  This is called as the last phase
14398     * of inflation, after all child views have been added.
14399     *
14400     * <p>Even if the subclass overrides onFinishInflate, they should always be
14401     * sure to call the super method, so that we get called.
14402     */
14403    protected void onFinishInflate() {
14404    }
14405
14406    /**
14407     * Returns the resources associated with this view.
14408     *
14409     * @return Resources object.
14410     */
14411    public Resources getResources() {
14412        return mResources;
14413    }
14414
14415    /**
14416     * Invalidates the specified Drawable.
14417     *
14418     * @param drawable the drawable to invalidate
14419     */
14420    public void invalidateDrawable(Drawable drawable) {
14421        if (verifyDrawable(drawable)) {
14422            final Rect dirty = drawable.getBounds();
14423            final int scrollX = mScrollX;
14424            final int scrollY = mScrollY;
14425
14426            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14427                    dirty.right + scrollX, dirty.bottom + scrollY);
14428        }
14429    }
14430
14431    /**
14432     * Schedules an action on a drawable to occur at a specified time.
14433     *
14434     * @param who the recipient of the action
14435     * @param what the action to run on the drawable
14436     * @param when the time at which the action must occur. Uses the
14437     *        {@link SystemClock#uptimeMillis} timebase.
14438     */
14439    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14440        if (verifyDrawable(who) && what != null) {
14441            final long delay = when - SystemClock.uptimeMillis();
14442            if (mAttachInfo != null) {
14443                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14444                        Choreographer.CALLBACK_ANIMATION, what, who,
14445                        Choreographer.subtractFrameDelay(delay));
14446            } else {
14447                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14448            }
14449        }
14450    }
14451
14452    /**
14453     * Cancels a scheduled action on a drawable.
14454     *
14455     * @param who the recipient of the action
14456     * @param what the action to cancel
14457     */
14458    public void unscheduleDrawable(Drawable who, Runnable what) {
14459        if (verifyDrawable(who) && what != null) {
14460            if (mAttachInfo != null) {
14461                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14462                        Choreographer.CALLBACK_ANIMATION, what, who);
14463            } else {
14464                ViewRootImpl.getRunQueue().removeCallbacks(what);
14465            }
14466        }
14467    }
14468
14469    /**
14470     * Unschedule any events associated with the given Drawable.  This can be
14471     * used when selecting a new Drawable into a view, so that the previous
14472     * one is completely unscheduled.
14473     *
14474     * @param who The Drawable to unschedule.
14475     *
14476     * @see #drawableStateChanged
14477     */
14478    public void unscheduleDrawable(Drawable who) {
14479        if (mAttachInfo != null && who != null) {
14480            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14481                    Choreographer.CALLBACK_ANIMATION, null, who);
14482        }
14483    }
14484
14485    /**
14486     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14487     * that the View directionality can and will be resolved before its Drawables.
14488     *
14489     * Will call {@link View#onResolveDrawables} when resolution is done.
14490     *
14491     * @hide
14492     */
14493    protected void resolveDrawables() {
14494        if (canResolveLayoutDirection()) {
14495            if (mBackground != null) {
14496                mBackground.setLayoutDirection(getLayoutDirection());
14497            }
14498            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14499            onResolveDrawables(getLayoutDirection());
14500        }
14501    }
14502
14503    /**
14504     * Called when layout direction has been resolved.
14505     *
14506     * The default implementation does nothing.
14507     *
14508     * @param layoutDirection The resolved layout direction.
14509     *
14510     * @see #LAYOUT_DIRECTION_LTR
14511     * @see #LAYOUT_DIRECTION_RTL
14512     *
14513     * @hide
14514     */
14515    public void onResolveDrawables(int layoutDirection) {
14516    }
14517
14518    /**
14519     * @hide
14520     */
14521    protected void resetResolvedDrawables() {
14522        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14523    }
14524
14525    private boolean isDrawablesResolved() {
14526        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14527    }
14528
14529    /**
14530     * If your view subclass is displaying its own Drawable objects, it should
14531     * override this function and return true for any Drawable it is
14532     * displaying.  This allows animations for those drawables to be
14533     * scheduled.
14534     *
14535     * <p>Be sure to call through to the super class when overriding this
14536     * function.
14537     *
14538     * @param who The Drawable to verify.  Return true if it is one you are
14539     *            displaying, else return the result of calling through to the
14540     *            super class.
14541     *
14542     * @return boolean If true than the Drawable is being displayed in the
14543     *         view; else false and it is not allowed to animate.
14544     *
14545     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14546     * @see #drawableStateChanged()
14547     */
14548    protected boolean verifyDrawable(Drawable who) {
14549        return who == mBackground;
14550    }
14551
14552    /**
14553     * This function is called whenever the state of the view changes in such
14554     * a way that it impacts the state of drawables being shown.
14555     *
14556     * <p>Be sure to call through to the superclass when overriding this
14557     * function.
14558     *
14559     * @see Drawable#setState(int[])
14560     */
14561    protected void drawableStateChanged() {
14562        Drawable d = mBackground;
14563        if (d != null && d.isStateful()) {
14564            d.setState(getDrawableState());
14565        }
14566    }
14567
14568    /**
14569     * Call this to force a view to update its drawable state. This will cause
14570     * drawableStateChanged to be called on this view. Views that are interested
14571     * in the new state should call getDrawableState.
14572     *
14573     * @see #drawableStateChanged
14574     * @see #getDrawableState
14575     */
14576    public void refreshDrawableState() {
14577        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14578        drawableStateChanged();
14579
14580        ViewParent parent = mParent;
14581        if (parent != null) {
14582            parent.childDrawableStateChanged(this);
14583        }
14584    }
14585
14586    /**
14587     * Return an array of resource IDs of the drawable states representing the
14588     * current state of the view.
14589     *
14590     * @return The current drawable state
14591     *
14592     * @see Drawable#setState(int[])
14593     * @see #drawableStateChanged()
14594     * @see #onCreateDrawableState(int)
14595     */
14596    public final int[] getDrawableState() {
14597        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14598            return mDrawableState;
14599        } else {
14600            mDrawableState = onCreateDrawableState(0);
14601            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14602            return mDrawableState;
14603        }
14604    }
14605
14606    /**
14607     * Generate the new {@link android.graphics.drawable.Drawable} state for
14608     * this view. This is called by the view
14609     * system when the cached Drawable state is determined to be invalid.  To
14610     * retrieve the current state, you should use {@link #getDrawableState}.
14611     *
14612     * @param extraSpace if non-zero, this is the number of extra entries you
14613     * would like in the returned array in which you can place your own
14614     * states.
14615     *
14616     * @return Returns an array holding the current {@link Drawable} state of
14617     * the view.
14618     *
14619     * @see #mergeDrawableStates(int[], int[])
14620     */
14621    protected int[] onCreateDrawableState(int extraSpace) {
14622        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14623                mParent instanceof View) {
14624            return ((View) mParent).onCreateDrawableState(extraSpace);
14625        }
14626
14627        int[] drawableState;
14628
14629        int privateFlags = mPrivateFlags;
14630
14631        int viewStateIndex = 0;
14632        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14633        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14634        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14635        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14636        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14637        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14638        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14639                HardwareRenderer.isAvailable()) {
14640            // This is set if HW acceleration is requested, even if the current
14641            // process doesn't allow it.  This is just to allow app preview
14642            // windows to better match their app.
14643            viewStateIndex |= VIEW_STATE_ACCELERATED;
14644        }
14645        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14646
14647        final int privateFlags2 = mPrivateFlags2;
14648        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14649        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14650
14651        drawableState = VIEW_STATE_SETS[viewStateIndex];
14652
14653        //noinspection ConstantIfStatement
14654        if (false) {
14655            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14656            Log.i("View", toString()
14657                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14658                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14659                    + " fo=" + hasFocus()
14660                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14661                    + " wf=" + hasWindowFocus()
14662                    + ": " + Arrays.toString(drawableState));
14663        }
14664
14665        if (extraSpace == 0) {
14666            return drawableState;
14667        }
14668
14669        final int[] fullState;
14670        if (drawableState != null) {
14671            fullState = new int[drawableState.length + extraSpace];
14672            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14673        } else {
14674            fullState = new int[extraSpace];
14675        }
14676
14677        return fullState;
14678    }
14679
14680    /**
14681     * Merge your own state values in <var>additionalState</var> into the base
14682     * state values <var>baseState</var> that were returned by
14683     * {@link #onCreateDrawableState(int)}.
14684     *
14685     * @param baseState The base state values returned by
14686     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14687     * own additional state values.
14688     *
14689     * @param additionalState The additional state values you would like
14690     * added to <var>baseState</var>; this array is not modified.
14691     *
14692     * @return As a convenience, the <var>baseState</var> array you originally
14693     * passed into the function is returned.
14694     *
14695     * @see #onCreateDrawableState(int)
14696     */
14697    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14698        final int N = baseState.length;
14699        int i = N - 1;
14700        while (i >= 0 && baseState[i] == 0) {
14701            i--;
14702        }
14703        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14704        return baseState;
14705    }
14706
14707    /**
14708     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14709     * on all Drawable objects associated with this view.
14710     */
14711    public void jumpDrawablesToCurrentState() {
14712        if (mBackground != null) {
14713            mBackground.jumpToCurrentState();
14714        }
14715    }
14716
14717    /**
14718     * Sets the background color for this view.
14719     * @param color the color of the background
14720     */
14721    @RemotableViewMethod
14722    public void setBackgroundColor(int color) {
14723        if (mBackground instanceof ColorDrawable) {
14724            ((ColorDrawable) mBackground.mutate()).setColor(color);
14725            computeOpaqueFlags();
14726            mBackgroundResource = 0;
14727        } else {
14728            setBackground(new ColorDrawable(color));
14729        }
14730    }
14731
14732    /**
14733     * Set the background to a given resource. The resource should refer to
14734     * a Drawable object or 0 to remove the background.
14735     * @param resid The identifier of the resource.
14736     *
14737     * @attr ref android.R.styleable#View_background
14738     */
14739    @RemotableViewMethod
14740    public void setBackgroundResource(int resid) {
14741        if (resid != 0 && resid == mBackgroundResource) {
14742            return;
14743        }
14744
14745        Drawable d= null;
14746        if (resid != 0) {
14747            d = mResources.getDrawable(resid);
14748        }
14749        setBackground(d);
14750
14751        mBackgroundResource = resid;
14752    }
14753
14754    /**
14755     * Set the background to a given Drawable, or remove the background. If the
14756     * background has padding, this View's padding is set to the background's
14757     * padding. However, when a background is removed, this View's padding isn't
14758     * touched. If setting the padding is desired, please use
14759     * {@link #setPadding(int, int, int, int)}.
14760     *
14761     * @param background The Drawable to use as the background, or null to remove the
14762     *        background
14763     */
14764    public void setBackground(Drawable background) {
14765        //noinspection deprecation
14766        setBackgroundDrawable(background);
14767    }
14768
14769    /**
14770     * @deprecated use {@link #setBackground(Drawable)} instead
14771     */
14772    @Deprecated
14773    public void setBackgroundDrawable(Drawable background) {
14774        computeOpaqueFlags();
14775
14776        if (background == mBackground) {
14777            return;
14778        }
14779
14780        boolean requestLayout = false;
14781
14782        mBackgroundResource = 0;
14783
14784        /*
14785         * Regardless of whether we're setting a new background or not, we want
14786         * to clear the previous drawable.
14787         */
14788        if (mBackground != null) {
14789            mBackground.setCallback(null);
14790            unscheduleDrawable(mBackground);
14791        }
14792
14793        if (background != null) {
14794            Rect padding = sThreadLocal.get();
14795            if (padding == null) {
14796                padding = new Rect();
14797                sThreadLocal.set(padding);
14798            }
14799            resetResolvedDrawables();
14800            background.setLayoutDirection(getLayoutDirection());
14801            if (background.getPadding(padding)) {
14802                resetResolvedPadding();
14803                switch (background.getLayoutDirection()) {
14804                    case LAYOUT_DIRECTION_RTL:
14805                        mUserPaddingLeftInitial = padding.right;
14806                        mUserPaddingRightInitial = padding.left;
14807                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14808                        break;
14809                    case LAYOUT_DIRECTION_LTR:
14810                    default:
14811                        mUserPaddingLeftInitial = padding.left;
14812                        mUserPaddingRightInitial = padding.right;
14813                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14814                }
14815            }
14816
14817            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14818            // if it has a different minimum size, we should layout again
14819            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14820                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14821                requestLayout = true;
14822            }
14823
14824            background.setCallback(this);
14825            if (background.isStateful()) {
14826                background.setState(getDrawableState());
14827            }
14828            background.setVisible(getVisibility() == VISIBLE, false);
14829            mBackground = background;
14830
14831            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14832                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14833                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14834                requestLayout = true;
14835            }
14836        } else {
14837            /* Remove the background */
14838            mBackground = null;
14839
14840            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14841                /*
14842                 * This view ONLY drew the background before and we're removing
14843                 * the background, so now it won't draw anything
14844                 * (hence we SKIP_DRAW)
14845                 */
14846                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14847                mPrivateFlags |= PFLAG_SKIP_DRAW;
14848            }
14849
14850            /*
14851             * When the background is set, we try to apply its padding to this
14852             * View. When the background is removed, we don't touch this View's
14853             * padding. This is noted in the Javadocs. Hence, we don't need to
14854             * requestLayout(), the invalidate() below is sufficient.
14855             */
14856
14857            // The old background's minimum size could have affected this
14858            // View's layout, so let's requestLayout
14859            requestLayout = true;
14860        }
14861
14862        computeOpaqueFlags();
14863
14864        if (requestLayout) {
14865            requestLayout();
14866        }
14867
14868        mBackgroundSizeChanged = true;
14869        invalidate(true);
14870    }
14871
14872    /**
14873     * Gets the background drawable
14874     *
14875     * @return The drawable used as the background for this view, if any.
14876     *
14877     * @see #setBackground(Drawable)
14878     *
14879     * @attr ref android.R.styleable#View_background
14880     */
14881    public Drawable getBackground() {
14882        return mBackground;
14883    }
14884
14885    /**
14886     * Sets the padding. The view may add on the space required to display
14887     * the scrollbars, depending on the style and visibility of the scrollbars.
14888     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14889     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14890     * from the values set in this call.
14891     *
14892     * @attr ref android.R.styleable#View_padding
14893     * @attr ref android.R.styleable#View_paddingBottom
14894     * @attr ref android.R.styleable#View_paddingLeft
14895     * @attr ref android.R.styleable#View_paddingRight
14896     * @attr ref android.R.styleable#View_paddingTop
14897     * @param left the left padding in pixels
14898     * @param top the top padding in pixels
14899     * @param right the right padding in pixels
14900     * @param bottom the bottom padding in pixels
14901     */
14902    public void setPadding(int left, int top, int right, int bottom) {
14903        resetResolvedPadding();
14904
14905        mUserPaddingStart = UNDEFINED_PADDING;
14906        mUserPaddingEnd = UNDEFINED_PADDING;
14907
14908        mUserPaddingLeftInitial = left;
14909        mUserPaddingRightInitial = right;
14910
14911        internalSetPadding(left, top, right, bottom);
14912    }
14913
14914    /**
14915     * @hide
14916     */
14917    protected void internalSetPadding(int left, int top, int right, int bottom) {
14918        mUserPaddingLeft = left;
14919        mUserPaddingRight = right;
14920        mUserPaddingBottom = bottom;
14921
14922        final int viewFlags = mViewFlags;
14923        boolean changed = false;
14924
14925        // Common case is there are no scroll bars.
14926        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14927            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14928                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14929                        ? 0 : getVerticalScrollbarWidth();
14930                switch (mVerticalScrollbarPosition) {
14931                    case SCROLLBAR_POSITION_DEFAULT:
14932                        if (isLayoutRtl()) {
14933                            left += offset;
14934                        } else {
14935                            right += offset;
14936                        }
14937                        break;
14938                    case SCROLLBAR_POSITION_RIGHT:
14939                        right += offset;
14940                        break;
14941                    case SCROLLBAR_POSITION_LEFT:
14942                        left += offset;
14943                        break;
14944                }
14945            }
14946            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14947                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14948                        ? 0 : getHorizontalScrollbarHeight();
14949            }
14950        }
14951
14952        if (mPaddingLeft != left) {
14953            changed = true;
14954            mPaddingLeft = left;
14955        }
14956        if (mPaddingTop != top) {
14957            changed = true;
14958            mPaddingTop = top;
14959        }
14960        if (mPaddingRight != right) {
14961            changed = true;
14962            mPaddingRight = right;
14963        }
14964        if (mPaddingBottom != bottom) {
14965            changed = true;
14966            mPaddingBottom = bottom;
14967        }
14968
14969        if (changed) {
14970            requestLayout();
14971        }
14972    }
14973
14974    /**
14975     * Sets the relative padding. The view may add on the space required to display
14976     * the scrollbars, depending on the style and visibility of the scrollbars.
14977     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14978     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14979     * from the values set in this call.
14980     *
14981     * @attr ref android.R.styleable#View_padding
14982     * @attr ref android.R.styleable#View_paddingBottom
14983     * @attr ref android.R.styleable#View_paddingStart
14984     * @attr ref android.R.styleable#View_paddingEnd
14985     * @attr ref android.R.styleable#View_paddingTop
14986     * @param start the start padding in pixels
14987     * @param top the top padding in pixels
14988     * @param end the end padding in pixels
14989     * @param bottom the bottom padding in pixels
14990     */
14991    public void setPaddingRelative(int start, int top, int end, int bottom) {
14992        resetResolvedPadding();
14993
14994        mUserPaddingStart = start;
14995        mUserPaddingEnd = end;
14996
14997        switch(getLayoutDirection()) {
14998            case LAYOUT_DIRECTION_RTL:
14999                mUserPaddingLeftInitial = end;
15000                mUserPaddingRightInitial = start;
15001                internalSetPadding(end, top, start, bottom);
15002                break;
15003            case LAYOUT_DIRECTION_LTR:
15004            default:
15005                mUserPaddingLeftInitial = start;
15006                mUserPaddingRightInitial = end;
15007                internalSetPadding(start, top, end, bottom);
15008        }
15009    }
15010
15011    /**
15012     * Returns the top padding of this view.
15013     *
15014     * @return the top padding in pixels
15015     */
15016    public int getPaddingTop() {
15017        return mPaddingTop;
15018    }
15019
15020    /**
15021     * Returns the bottom padding of this view. If there are inset and enabled
15022     * scrollbars, this value may include the space required to display the
15023     * scrollbars as well.
15024     *
15025     * @return the bottom padding in pixels
15026     */
15027    public int getPaddingBottom() {
15028        return mPaddingBottom;
15029    }
15030
15031    /**
15032     * Returns the left padding of this view. If there are inset and enabled
15033     * scrollbars, this value may include the space required to display the
15034     * scrollbars as well.
15035     *
15036     * @return the left padding in pixels
15037     */
15038    public int getPaddingLeft() {
15039        if (!isPaddingResolved()) {
15040            resolvePadding();
15041        }
15042        return mPaddingLeft;
15043    }
15044
15045    /**
15046     * Returns the start padding of this view depending on its resolved layout direction.
15047     * If there are inset and enabled scrollbars, this value may include the space
15048     * required to display the scrollbars as well.
15049     *
15050     * @return the start padding in pixels
15051     */
15052    public int getPaddingStart() {
15053        if (!isPaddingResolved()) {
15054            resolvePadding();
15055        }
15056        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15057                mPaddingRight : mPaddingLeft;
15058    }
15059
15060    /**
15061     * Returns the right padding of this view. If there are inset and enabled
15062     * scrollbars, this value may include the space required to display the
15063     * scrollbars as well.
15064     *
15065     * @return the right padding in pixels
15066     */
15067    public int getPaddingRight() {
15068        if (!isPaddingResolved()) {
15069            resolvePadding();
15070        }
15071        return mPaddingRight;
15072    }
15073
15074    /**
15075     * Returns the end padding of this view depending on its resolved layout direction.
15076     * If there are inset and enabled scrollbars, this value may include the space
15077     * required to display the scrollbars as well.
15078     *
15079     * @return the end padding in pixels
15080     */
15081    public int getPaddingEnd() {
15082        if (!isPaddingResolved()) {
15083            resolvePadding();
15084        }
15085        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15086                mPaddingLeft : mPaddingRight;
15087    }
15088
15089    /**
15090     * Return if the padding as been set thru relative values
15091     * {@link #setPaddingRelative(int, int, int, int)} or thru
15092     * @attr ref android.R.styleable#View_paddingStart or
15093     * @attr ref android.R.styleable#View_paddingEnd
15094     *
15095     * @return true if the padding is relative or false if it is not.
15096     */
15097    public boolean isPaddingRelative() {
15098        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15099    }
15100
15101    Insets computeOpticalInsets() {
15102        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15103    }
15104
15105    /**
15106     * @hide
15107     */
15108    public void resetPaddingToInitialValues() {
15109        if (isRtlCompatibilityMode()) {
15110            mPaddingLeft = mUserPaddingLeftInitial;
15111            mPaddingRight = mUserPaddingRightInitial;
15112            return;
15113        }
15114        if (isLayoutRtl()) {
15115            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15116            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15117        } else {
15118            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15119            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15120        }
15121    }
15122
15123    /**
15124     * @hide
15125     */
15126    public Insets getOpticalInsets() {
15127        if (mLayoutInsets == null) {
15128            mLayoutInsets = computeOpticalInsets();
15129        }
15130        return mLayoutInsets;
15131    }
15132
15133    /**
15134     * Changes the selection state of this view. A view can be selected or not.
15135     * Note that selection is not the same as focus. Views are typically
15136     * selected in the context of an AdapterView like ListView or GridView;
15137     * the selected view is the view that is highlighted.
15138     *
15139     * @param selected true if the view must be selected, false otherwise
15140     */
15141    public void setSelected(boolean selected) {
15142        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15143            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15144            if (!selected) resetPressedState();
15145            invalidate(true);
15146            refreshDrawableState();
15147            dispatchSetSelected(selected);
15148            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
15149                notifyAccessibilityStateChanged();
15150            }
15151        }
15152    }
15153
15154    /**
15155     * Dispatch setSelected to all of this View's children.
15156     *
15157     * @see #setSelected(boolean)
15158     *
15159     * @param selected The new selected state
15160     */
15161    protected void dispatchSetSelected(boolean selected) {
15162    }
15163
15164    /**
15165     * Indicates the selection state of this view.
15166     *
15167     * @return true if the view is selected, false otherwise
15168     */
15169    @ViewDebug.ExportedProperty
15170    public boolean isSelected() {
15171        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15172    }
15173
15174    /**
15175     * Changes the activated state of this view. A view can be activated or not.
15176     * Note that activation is not the same as selection.  Selection is
15177     * a transient property, representing the view (hierarchy) the user is
15178     * currently interacting with.  Activation is a longer-term state that the
15179     * user can move views in and out of.  For example, in a list view with
15180     * single or multiple selection enabled, the views in the current selection
15181     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15182     * here.)  The activated state is propagated down to children of the view it
15183     * is set on.
15184     *
15185     * @param activated true if the view must be activated, false otherwise
15186     */
15187    public void setActivated(boolean activated) {
15188        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15189            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15190            invalidate(true);
15191            refreshDrawableState();
15192            dispatchSetActivated(activated);
15193        }
15194    }
15195
15196    /**
15197     * Dispatch setActivated to all of this View's children.
15198     *
15199     * @see #setActivated(boolean)
15200     *
15201     * @param activated The new activated state
15202     */
15203    protected void dispatchSetActivated(boolean activated) {
15204    }
15205
15206    /**
15207     * Indicates the activation state of this view.
15208     *
15209     * @return true if the view is activated, false otherwise
15210     */
15211    @ViewDebug.ExportedProperty
15212    public boolean isActivated() {
15213        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15214    }
15215
15216    /**
15217     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15218     * observer can be used to get notifications when global events, like
15219     * layout, happen.
15220     *
15221     * The returned ViewTreeObserver observer is not guaranteed to remain
15222     * valid for the lifetime of this View. If the caller of this method keeps
15223     * a long-lived reference to ViewTreeObserver, it should always check for
15224     * the return value of {@link ViewTreeObserver#isAlive()}.
15225     *
15226     * @return The ViewTreeObserver for this view's hierarchy.
15227     */
15228    public ViewTreeObserver getViewTreeObserver() {
15229        if (mAttachInfo != null) {
15230            return mAttachInfo.mTreeObserver;
15231        }
15232        if (mFloatingTreeObserver == null) {
15233            mFloatingTreeObserver = new ViewTreeObserver();
15234        }
15235        return mFloatingTreeObserver;
15236    }
15237
15238    /**
15239     * <p>Finds the topmost view in the current view hierarchy.</p>
15240     *
15241     * @return the topmost view containing this view
15242     */
15243    public View getRootView() {
15244        if (mAttachInfo != null) {
15245            final View v = mAttachInfo.mRootView;
15246            if (v != null) {
15247                return v;
15248            }
15249        }
15250
15251        View parent = this;
15252
15253        while (parent.mParent != null && parent.mParent instanceof View) {
15254            parent = (View) parent.mParent;
15255        }
15256
15257        return parent;
15258    }
15259
15260    /**
15261     * <p>Computes the coordinates of this view on the screen. The argument
15262     * must be an array of two integers. After the method returns, the array
15263     * contains the x and y location in that order.</p>
15264     *
15265     * @param location an array of two integers in which to hold the coordinates
15266     */
15267    public void getLocationOnScreen(int[] location) {
15268        getLocationInWindow(location);
15269
15270        final AttachInfo info = mAttachInfo;
15271        if (info != null) {
15272            location[0] += info.mWindowLeft;
15273            location[1] += info.mWindowTop;
15274        }
15275    }
15276
15277    /**
15278     * <p>Computes the coordinates of this view in its window. The argument
15279     * must be an array of two integers. After the method returns, the array
15280     * contains the x and y location in that order.</p>
15281     *
15282     * @param location an array of two integers in which to hold the coordinates
15283     */
15284    public void getLocationInWindow(int[] location) {
15285        if (location == null || location.length < 2) {
15286            throw new IllegalArgumentException("location must be an array of two integers");
15287        }
15288
15289        if (mAttachInfo == null) {
15290            // When the view is not attached to a window, this method does not make sense
15291            location[0] = location[1] = 0;
15292            return;
15293        }
15294
15295        float[] position = mAttachInfo.mTmpTransformLocation;
15296        position[0] = position[1] = 0.0f;
15297
15298        if (!hasIdentityMatrix()) {
15299            getMatrix().mapPoints(position);
15300        }
15301
15302        position[0] += mLeft;
15303        position[1] += mTop;
15304
15305        ViewParent viewParent = mParent;
15306        while (viewParent instanceof View) {
15307            final View view = (View) viewParent;
15308
15309            position[0] -= view.mScrollX;
15310            position[1] -= view.mScrollY;
15311
15312            if (!view.hasIdentityMatrix()) {
15313                view.getMatrix().mapPoints(position);
15314            }
15315
15316            position[0] += view.mLeft;
15317            position[1] += view.mTop;
15318
15319            viewParent = view.mParent;
15320         }
15321
15322        if (viewParent instanceof ViewRootImpl) {
15323            // *cough*
15324            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15325            position[1] -= vr.mCurScrollY;
15326        }
15327
15328        location[0] = (int) (position[0] + 0.5f);
15329        location[1] = (int) (position[1] + 0.5f);
15330    }
15331
15332    /**
15333     * {@hide}
15334     * @param id the id of the view to be found
15335     * @return the view of the specified id, null if cannot be found
15336     */
15337    protected View findViewTraversal(int id) {
15338        if (id == mID) {
15339            return this;
15340        }
15341        return null;
15342    }
15343
15344    /**
15345     * {@hide}
15346     * @param tag the tag of the view to be found
15347     * @return the view of specified tag, null if cannot be found
15348     */
15349    protected View findViewWithTagTraversal(Object tag) {
15350        if (tag != null && tag.equals(mTag)) {
15351            return this;
15352        }
15353        return null;
15354    }
15355
15356    /**
15357     * {@hide}
15358     * @param predicate The predicate to evaluate.
15359     * @param childToSkip If not null, ignores this child during the recursive traversal.
15360     * @return The first view that matches the predicate or null.
15361     */
15362    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15363        if (predicate.apply(this)) {
15364            return this;
15365        }
15366        return null;
15367    }
15368
15369    /**
15370     * Look for a child view with the given id.  If this view has the given
15371     * id, return this view.
15372     *
15373     * @param id The id to search for.
15374     * @return The view that has the given id in the hierarchy or null
15375     */
15376    public final View findViewById(int id) {
15377        if (id < 0) {
15378            return null;
15379        }
15380        return findViewTraversal(id);
15381    }
15382
15383    /**
15384     * Finds a view by its unuque and stable accessibility id.
15385     *
15386     * @param accessibilityId The searched accessibility id.
15387     * @return The found view.
15388     */
15389    final View findViewByAccessibilityId(int accessibilityId) {
15390        if (accessibilityId < 0) {
15391            return null;
15392        }
15393        return findViewByAccessibilityIdTraversal(accessibilityId);
15394    }
15395
15396    /**
15397     * Performs the traversal to find a view by its unuque and stable accessibility id.
15398     *
15399     * <strong>Note:</strong>This method does not stop at the root namespace
15400     * boundary since the user can touch the screen at an arbitrary location
15401     * potentially crossing the root namespace bounday which will send an
15402     * accessibility event to accessibility services and they should be able
15403     * to obtain the event source. Also accessibility ids are guaranteed to be
15404     * unique in the window.
15405     *
15406     * @param accessibilityId The accessibility id.
15407     * @return The found view.
15408     *
15409     * @hide
15410     */
15411    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15412        if (getAccessibilityViewId() == accessibilityId) {
15413            return this;
15414        }
15415        return null;
15416    }
15417
15418    /**
15419     * Look for a child view with the given tag.  If this view has the given
15420     * tag, return this view.
15421     *
15422     * @param tag The tag to search for, using "tag.equals(getTag())".
15423     * @return The View that has the given tag in the hierarchy or null
15424     */
15425    public final View findViewWithTag(Object tag) {
15426        if (tag == null) {
15427            return null;
15428        }
15429        return findViewWithTagTraversal(tag);
15430    }
15431
15432    /**
15433     * {@hide}
15434     * Look for a child view that matches the specified predicate.
15435     * If this view matches the predicate, return this view.
15436     *
15437     * @param predicate The predicate to evaluate.
15438     * @return The first view that matches the predicate or null.
15439     */
15440    public final View findViewByPredicate(Predicate<View> predicate) {
15441        return findViewByPredicateTraversal(predicate, null);
15442    }
15443
15444    /**
15445     * {@hide}
15446     * Look for a child view that matches the specified predicate,
15447     * starting with the specified view and its descendents and then
15448     * recusively searching the ancestors and siblings of that view
15449     * until this view is reached.
15450     *
15451     * This method is useful in cases where the predicate does not match
15452     * a single unique view (perhaps multiple views use the same id)
15453     * and we are trying to find the view that is "closest" in scope to the
15454     * starting view.
15455     *
15456     * @param start The view to start from.
15457     * @param predicate The predicate to evaluate.
15458     * @return The first view that matches the predicate or null.
15459     */
15460    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15461        View childToSkip = null;
15462        for (;;) {
15463            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15464            if (view != null || start == this) {
15465                return view;
15466            }
15467
15468            ViewParent parent = start.getParent();
15469            if (parent == null || !(parent instanceof View)) {
15470                return null;
15471            }
15472
15473            childToSkip = start;
15474            start = (View) parent;
15475        }
15476    }
15477
15478    /**
15479     * Sets the identifier for this view. The identifier does not have to be
15480     * unique in this view's hierarchy. The identifier should be a positive
15481     * number.
15482     *
15483     * @see #NO_ID
15484     * @see #getId()
15485     * @see #findViewById(int)
15486     *
15487     * @param id a number used to identify the view
15488     *
15489     * @attr ref android.R.styleable#View_id
15490     */
15491    public void setId(int id) {
15492        mID = id;
15493        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15494            mID = generateViewId();
15495        }
15496    }
15497
15498    /**
15499     * {@hide}
15500     *
15501     * @param isRoot true if the view belongs to the root namespace, false
15502     *        otherwise
15503     */
15504    public void setIsRootNamespace(boolean isRoot) {
15505        if (isRoot) {
15506            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15507        } else {
15508            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15509        }
15510    }
15511
15512    /**
15513     * {@hide}
15514     *
15515     * @return true if the view belongs to the root namespace, false otherwise
15516     */
15517    public boolean isRootNamespace() {
15518        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15519    }
15520
15521    /**
15522     * Returns this view's identifier.
15523     *
15524     * @return a positive integer used to identify the view or {@link #NO_ID}
15525     *         if the view has no ID
15526     *
15527     * @see #setId(int)
15528     * @see #findViewById(int)
15529     * @attr ref android.R.styleable#View_id
15530     */
15531    @ViewDebug.CapturedViewProperty
15532    public int getId() {
15533        return mID;
15534    }
15535
15536    /**
15537     * Returns this view's tag.
15538     *
15539     * @return the Object stored in this view as a tag
15540     *
15541     * @see #setTag(Object)
15542     * @see #getTag(int)
15543     */
15544    @ViewDebug.ExportedProperty
15545    public Object getTag() {
15546        return mTag;
15547    }
15548
15549    /**
15550     * Sets the tag associated with this view. A tag can be used to mark
15551     * a view in its hierarchy and does not have to be unique within the
15552     * hierarchy. Tags can also be used to store data within a view without
15553     * resorting to another data structure.
15554     *
15555     * @param tag an Object to tag the view with
15556     *
15557     * @see #getTag()
15558     * @see #setTag(int, Object)
15559     */
15560    public void setTag(final Object tag) {
15561        mTag = tag;
15562    }
15563
15564    /**
15565     * Returns the tag associated with this view and the specified key.
15566     *
15567     * @param key The key identifying the tag
15568     *
15569     * @return the Object stored in this view as a tag
15570     *
15571     * @see #setTag(int, Object)
15572     * @see #getTag()
15573     */
15574    public Object getTag(int key) {
15575        if (mKeyedTags != null) return mKeyedTags.get(key);
15576        return null;
15577    }
15578
15579    /**
15580     * Sets a tag associated with this view and a key. A tag can be used
15581     * to mark a view in its hierarchy and does not have to be unique within
15582     * the hierarchy. Tags can also be used to store data within a view
15583     * without resorting to another data structure.
15584     *
15585     * The specified key should be an id declared in the resources of the
15586     * application to ensure it is unique (see the <a
15587     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15588     * Keys identified as belonging to
15589     * the Android framework or not associated with any package will cause
15590     * an {@link IllegalArgumentException} to be thrown.
15591     *
15592     * @param key The key identifying the tag
15593     * @param tag An Object to tag the view with
15594     *
15595     * @throws IllegalArgumentException If they specified key is not valid
15596     *
15597     * @see #setTag(Object)
15598     * @see #getTag(int)
15599     */
15600    public void setTag(int key, final Object tag) {
15601        // If the package id is 0x00 or 0x01, it's either an undefined package
15602        // or a framework id
15603        if ((key >>> 24) < 2) {
15604            throw new IllegalArgumentException("The key must be an application-specific "
15605                    + "resource id.");
15606        }
15607
15608        setKeyedTag(key, tag);
15609    }
15610
15611    /**
15612     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15613     * framework id.
15614     *
15615     * @hide
15616     */
15617    public void setTagInternal(int key, Object tag) {
15618        if ((key >>> 24) != 0x1) {
15619            throw new IllegalArgumentException("The key must be a framework-specific "
15620                    + "resource id.");
15621        }
15622
15623        setKeyedTag(key, tag);
15624    }
15625
15626    private void setKeyedTag(int key, Object tag) {
15627        if (mKeyedTags == null) {
15628            mKeyedTags = new SparseArray<Object>();
15629        }
15630
15631        mKeyedTags.put(key, tag);
15632    }
15633
15634    /**
15635     * Prints information about this view in the log output, with the tag
15636     * {@link #VIEW_LOG_TAG}.
15637     *
15638     * @hide
15639     */
15640    public void debug() {
15641        debug(0);
15642    }
15643
15644    /**
15645     * Prints information about this view in the log output, with the tag
15646     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15647     * indentation defined by the <code>depth</code>.
15648     *
15649     * @param depth the indentation level
15650     *
15651     * @hide
15652     */
15653    protected void debug(int depth) {
15654        String output = debugIndent(depth - 1);
15655
15656        output += "+ " + this;
15657        int id = getId();
15658        if (id != -1) {
15659            output += " (id=" + id + ")";
15660        }
15661        Object tag = getTag();
15662        if (tag != null) {
15663            output += " (tag=" + tag + ")";
15664        }
15665        Log.d(VIEW_LOG_TAG, output);
15666
15667        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15668            output = debugIndent(depth) + " FOCUSED";
15669            Log.d(VIEW_LOG_TAG, output);
15670        }
15671
15672        output = debugIndent(depth);
15673        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15674                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15675                + "} ";
15676        Log.d(VIEW_LOG_TAG, output);
15677
15678        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15679                || mPaddingBottom != 0) {
15680            output = debugIndent(depth);
15681            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15682                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15683            Log.d(VIEW_LOG_TAG, output);
15684        }
15685
15686        output = debugIndent(depth);
15687        output += "mMeasureWidth=" + mMeasuredWidth +
15688                " mMeasureHeight=" + mMeasuredHeight;
15689        Log.d(VIEW_LOG_TAG, output);
15690
15691        output = debugIndent(depth);
15692        if (mLayoutParams == null) {
15693            output += "BAD! no layout params";
15694        } else {
15695            output = mLayoutParams.debug(output);
15696        }
15697        Log.d(VIEW_LOG_TAG, output);
15698
15699        output = debugIndent(depth);
15700        output += "flags={";
15701        output += View.printFlags(mViewFlags);
15702        output += "}";
15703        Log.d(VIEW_LOG_TAG, output);
15704
15705        output = debugIndent(depth);
15706        output += "privateFlags={";
15707        output += View.printPrivateFlags(mPrivateFlags);
15708        output += "}";
15709        Log.d(VIEW_LOG_TAG, output);
15710    }
15711
15712    /**
15713     * Creates a string of whitespaces used for indentation.
15714     *
15715     * @param depth the indentation level
15716     * @return a String containing (depth * 2 + 3) * 2 white spaces
15717     *
15718     * @hide
15719     */
15720    protected static String debugIndent(int depth) {
15721        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15722        for (int i = 0; i < (depth * 2) + 3; i++) {
15723            spaces.append(' ').append(' ');
15724        }
15725        return spaces.toString();
15726    }
15727
15728    /**
15729     * <p>Return the offset of the widget's text baseline from the widget's top
15730     * boundary. If this widget does not support baseline alignment, this
15731     * method returns -1. </p>
15732     *
15733     * @return the offset of the baseline within the widget's bounds or -1
15734     *         if baseline alignment is not supported
15735     */
15736    @ViewDebug.ExportedProperty(category = "layout")
15737    public int getBaseline() {
15738        return -1;
15739    }
15740
15741    /**
15742     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15743     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15744     * a layout pass.
15745     *
15746     * @return whether the view hierarchy is currently undergoing a layout pass
15747     */
15748    public boolean isInLayout() {
15749        ViewRootImpl viewRoot = getViewRootImpl();
15750        return (viewRoot != null && viewRoot.isInLayout());
15751    }
15752
15753    /**
15754     * Call this when something has changed which has invalidated the
15755     * layout of this view. This will schedule a layout pass of the view
15756     * tree. This should not be called while the view hierarchy is currently in a layout
15757     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15758     * end of the current layout pass (and then layout will run again) or after the current
15759     * frame is drawn and the next layout occurs.
15760     *
15761     * <p>Subclasses which override this method should call the superclass method to
15762     * handle possible request-during-layout errors correctly.</p>
15763     */
15764    public void requestLayout() {
15765        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15766            // Only trigger request-during-layout logic if this is the view requesting it,
15767            // not the views in its parent hierarchy
15768            ViewRootImpl viewRoot = getViewRootImpl();
15769            if (viewRoot != null && viewRoot.isInLayout()) {
15770                if (!viewRoot.requestLayoutDuringLayout(this)) {
15771                    return;
15772                }
15773            }
15774            mAttachInfo.mViewRequestingLayout = this;
15775        }
15776
15777        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15778        mPrivateFlags |= PFLAG_INVALIDATED;
15779
15780        if (mParent != null && !mParent.isLayoutRequested()) {
15781            mParent.requestLayout();
15782        }
15783        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15784            mAttachInfo.mViewRequestingLayout = null;
15785        }
15786    }
15787
15788    /**
15789     * Forces this view to be laid out during the next layout pass.
15790     * This method does not call requestLayout() or forceLayout()
15791     * on the parent.
15792     */
15793    public void forceLayout() {
15794        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15795        mPrivateFlags |= PFLAG_INVALIDATED;
15796    }
15797
15798    /**
15799     * <p>
15800     * This is called to find out how big a view should be. The parent
15801     * supplies constraint information in the width and height parameters.
15802     * </p>
15803     *
15804     * <p>
15805     * The actual measurement work of a view is performed in
15806     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15807     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15808     * </p>
15809     *
15810     *
15811     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15812     *        parent
15813     * @param heightMeasureSpec Vertical space requirements as imposed by the
15814     *        parent
15815     *
15816     * @see #onMeasure(int, int)
15817     */
15818    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15819        boolean optical = isLayoutModeOptical(this);
15820        if (optical != isLayoutModeOptical(mParent)) {
15821            Insets insets = getOpticalInsets();
15822            int oWidth  = insets.left + insets.right;
15823            int oHeight = insets.top  + insets.bottom;
15824            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15825            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15826        }
15827        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15828                widthMeasureSpec != mOldWidthMeasureSpec ||
15829                heightMeasureSpec != mOldHeightMeasureSpec) {
15830
15831            // first clears the measured dimension flag
15832            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15833
15834            resolveRtlPropertiesIfNeeded();
15835
15836            // measure ourselves, this should set the measured dimension flag back
15837            onMeasure(widthMeasureSpec, heightMeasureSpec);
15838
15839            // flag not set, setMeasuredDimension() was not invoked, we raise
15840            // an exception to warn the developer
15841            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15842                throw new IllegalStateException("onMeasure() did not set the"
15843                        + " measured dimension by calling"
15844                        + " setMeasuredDimension()");
15845            }
15846
15847            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15848        }
15849
15850        mOldWidthMeasureSpec = widthMeasureSpec;
15851        mOldHeightMeasureSpec = heightMeasureSpec;
15852    }
15853
15854    /**
15855     * <p>
15856     * Measure the view and its content to determine the measured width and the
15857     * measured height. This method is invoked by {@link #measure(int, int)} and
15858     * should be overriden by subclasses to provide accurate and efficient
15859     * measurement of their contents.
15860     * </p>
15861     *
15862     * <p>
15863     * <strong>CONTRACT:</strong> When overriding this method, you
15864     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15865     * measured width and height of this view. Failure to do so will trigger an
15866     * <code>IllegalStateException</code>, thrown by
15867     * {@link #measure(int, int)}. Calling the superclass'
15868     * {@link #onMeasure(int, int)} is a valid use.
15869     * </p>
15870     *
15871     * <p>
15872     * The base class implementation of measure defaults to the background size,
15873     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15874     * override {@link #onMeasure(int, int)} to provide better measurements of
15875     * their content.
15876     * </p>
15877     *
15878     * <p>
15879     * If this method is overridden, it is the subclass's responsibility to make
15880     * sure the measured height and width are at least the view's minimum height
15881     * and width ({@link #getSuggestedMinimumHeight()} and
15882     * {@link #getSuggestedMinimumWidth()}).
15883     * </p>
15884     *
15885     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15886     *                         The requirements are encoded with
15887     *                         {@link android.view.View.MeasureSpec}.
15888     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15889     *                         The requirements are encoded with
15890     *                         {@link android.view.View.MeasureSpec}.
15891     *
15892     * @see #getMeasuredWidth()
15893     * @see #getMeasuredHeight()
15894     * @see #setMeasuredDimension(int, int)
15895     * @see #getSuggestedMinimumHeight()
15896     * @see #getSuggestedMinimumWidth()
15897     * @see android.view.View.MeasureSpec#getMode(int)
15898     * @see android.view.View.MeasureSpec#getSize(int)
15899     */
15900    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15901        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15902                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15903    }
15904
15905    /**
15906     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15907     * measured width and measured height. Failing to do so will trigger an
15908     * exception at measurement time.</p>
15909     *
15910     * @param measuredWidth The measured width of this view.  May be a complex
15911     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15912     * {@link #MEASURED_STATE_TOO_SMALL}.
15913     * @param measuredHeight The measured height of this view.  May be a complex
15914     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15915     * {@link #MEASURED_STATE_TOO_SMALL}.
15916     */
15917    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15918        boolean optical = isLayoutModeOptical(this);
15919        if (optical != isLayoutModeOptical(mParent)) {
15920            Insets insets = getOpticalInsets();
15921            int opticalWidth  = insets.left + insets.right;
15922            int opticalHeight = insets.top  + insets.bottom;
15923
15924            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
15925            measuredHeight += optical ? opticalHeight : -opticalHeight;
15926        }
15927        mMeasuredWidth = measuredWidth;
15928        mMeasuredHeight = measuredHeight;
15929
15930        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15931    }
15932
15933    /**
15934     * Merge two states as returned by {@link #getMeasuredState()}.
15935     * @param curState The current state as returned from a view or the result
15936     * of combining multiple views.
15937     * @param newState The new view state to combine.
15938     * @return Returns a new integer reflecting the combination of the two
15939     * states.
15940     */
15941    public static int combineMeasuredStates(int curState, int newState) {
15942        return curState | newState;
15943    }
15944
15945    /**
15946     * Version of {@link #resolveSizeAndState(int, int, int)}
15947     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15948     */
15949    public static int resolveSize(int size, int measureSpec) {
15950        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15951    }
15952
15953    /**
15954     * Utility to reconcile a desired size and state, with constraints imposed
15955     * by a MeasureSpec.  Will take the desired size, unless a different size
15956     * is imposed by the constraints.  The returned value is a compound integer,
15957     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15958     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15959     * size is smaller than the size the view wants to be.
15960     *
15961     * @param size How big the view wants to be
15962     * @param measureSpec Constraints imposed by the parent
15963     * @return Size information bit mask as defined by
15964     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15965     */
15966    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15967        int result = size;
15968        int specMode = MeasureSpec.getMode(measureSpec);
15969        int specSize =  MeasureSpec.getSize(measureSpec);
15970        switch (specMode) {
15971        case MeasureSpec.UNSPECIFIED:
15972            result = size;
15973            break;
15974        case MeasureSpec.AT_MOST:
15975            if (specSize < size) {
15976                result = specSize | MEASURED_STATE_TOO_SMALL;
15977            } else {
15978                result = size;
15979            }
15980            break;
15981        case MeasureSpec.EXACTLY:
15982            result = specSize;
15983            break;
15984        }
15985        return result | (childMeasuredState&MEASURED_STATE_MASK);
15986    }
15987
15988    /**
15989     * Utility to return a default size. Uses the supplied size if the
15990     * MeasureSpec imposed no constraints. Will get larger if allowed
15991     * by the MeasureSpec.
15992     *
15993     * @param size Default size for this view
15994     * @param measureSpec Constraints imposed by the parent
15995     * @return The size this view should be.
15996     */
15997    public static int getDefaultSize(int size, int measureSpec) {
15998        int result = size;
15999        int specMode = MeasureSpec.getMode(measureSpec);
16000        int specSize = MeasureSpec.getSize(measureSpec);
16001
16002        switch (specMode) {
16003        case MeasureSpec.UNSPECIFIED:
16004            result = size;
16005            break;
16006        case MeasureSpec.AT_MOST:
16007        case MeasureSpec.EXACTLY:
16008            result = specSize;
16009            break;
16010        }
16011        return result;
16012    }
16013
16014    /**
16015     * Returns the suggested minimum height that the view should use. This
16016     * returns the maximum of the view's minimum height
16017     * and the background's minimum height
16018     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16019     * <p>
16020     * When being used in {@link #onMeasure(int, int)}, the caller should still
16021     * ensure the returned height is within the requirements of the parent.
16022     *
16023     * @return The suggested minimum height of the view.
16024     */
16025    protected int getSuggestedMinimumHeight() {
16026        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16027
16028    }
16029
16030    /**
16031     * Returns the suggested minimum width that the view should use. This
16032     * returns the maximum of the view's minimum width)
16033     * and the background's minimum width
16034     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16035     * <p>
16036     * When being used in {@link #onMeasure(int, int)}, the caller should still
16037     * ensure the returned width is within the requirements of the parent.
16038     *
16039     * @return The suggested minimum width of the view.
16040     */
16041    protected int getSuggestedMinimumWidth() {
16042        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16043    }
16044
16045    /**
16046     * Returns the minimum height of the view.
16047     *
16048     * @return the minimum height the view will try to be.
16049     *
16050     * @see #setMinimumHeight(int)
16051     *
16052     * @attr ref android.R.styleable#View_minHeight
16053     */
16054    public int getMinimumHeight() {
16055        return mMinHeight;
16056    }
16057
16058    /**
16059     * Sets the minimum height of the view. It is not guaranteed the view will
16060     * be able to achieve this minimum height (for example, if its parent layout
16061     * constrains it with less available height).
16062     *
16063     * @param minHeight The minimum height the view will try to be.
16064     *
16065     * @see #getMinimumHeight()
16066     *
16067     * @attr ref android.R.styleable#View_minHeight
16068     */
16069    public void setMinimumHeight(int minHeight) {
16070        mMinHeight = minHeight;
16071        requestLayout();
16072    }
16073
16074    /**
16075     * Returns the minimum width of the view.
16076     *
16077     * @return the minimum width the view will try to be.
16078     *
16079     * @see #setMinimumWidth(int)
16080     *
16081     * @attr ref android.R.styleable#View_minWidth
16082     */
16083    public int getMinimumWidth() {
16084        return mMinWidth;
16085    }
16086
16087    /**
16088     * Sets the minimum width of the view. It is not guaranteed the view will
16089     * be able to achieve this minimum width (for example, if its parent layout
16090     * constrains it with less available width).
16091     *
16092     * @param minWidth The minimum width the view will try to be.
16093     *
16094     * @see #getMinimumWidth()
16095     *
16096     * @attr ref android.R.styleable#View_minWidth
16097     */
16098    public void setMinimumWidth(int minWidth) {
16099        mMinWidth = minWidth;
16100        requestLayout();
16101
16102    }
16103
16104    /**
16105     * Get the animation currently associated with this view.
16106     *
16107     * @return The animation that is currently playing or
16108     *         scheduled to play for this view.
16109     */
16110    public Animation getAnimation() {
16111        return mCurrentAnimation;
16112    }
16113
16114    /**
16115     * Start the specified animation now.
16116     *
16117     * @param animation the animation to start now
16118     */
16119    public void startAnimation(Animation animation) {
16120        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16121        setAnimation(animation);
16122        invalidateParentCaches();
16123        invalidate(true);
16124    }
16125
16126    /**
16127     * Cancels any animations for this view.
16128     */
16129    public void clearAnimation() {
16130        if (mCurrentAnimation != null) {
16131            mCurrentAnimation.detach();
16132        }
16133        mCurrentAnimation = null;
16134        invalidateParentIfNeeded();
16135    }
16136
16137    /**
16138     * Sets the next animation to play for this view.
16139     * If you want the animation to play immediately, use
16140     * {@link #startAnimation(android.view.animation.Animation)} instead.
16141     * This method provides allows fine-grained
16142     * control over the start time and invalidation, but you
16143     * must make sure that 1) the animation has a start time set, and
16144     * 2) the view's parent (which controls animations on its children)
16145     * will be invalidated when the animation is supposed to
16146     * start.
16147     *
16148     * @param animation The next animation, or null.
16149     */
16150    public void setAnimation(Animation animation) {
16151        mCurrentAnimation = animation;
16152
16153        if (animation != null) {
16154            // If the screen is off assume the animation start time is now instead of
16155            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16156            // would cause the animation to start when the screen turns back on
16157            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16158                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16159                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16160            }
16161            animation.reset();
16162        }
16163    }
16164
16165    /**
16166     * Invoked by a parent ViewGroup to notify the start of the animation
16167     * currently associated with this view. If you override this method,
16168     * always call super.onAnimationStart();
16169     *
16170     * @see #setAnimation(android.view.animation.Animation)
16171     * @see #getAnimation()
16172     */
16173    protected void onAnimationStart() {
16174        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16175    }
16176
16177    /**
16178     * Invoked by a parent ViewGroup to notify the end of the animation
16179     * currently associated with this view. If you override this method,
16180     * always call super.onAnimationEnd();
16181     *
16182     * @see #setAnimation(android.view.animation.Animation)
16183     * @see #getAnimation()
16184     */
16185    protected void onAnimationEnd() {
16186        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16187    }
16188
16189    /**
16190     * Invoked if there is a Transform that involves alpha. Subclass that can
16191     * draw themselves with the specified alpha should return true, and then
16192     * respect that alpha when their onDraw() is called. If this returns false
16193     * then the view may be redirected to draw into an offscreen buffer to
16194     * fulfill the request, which will look fine, but may be slower than if the
16195     * subclass handles it internally. The default implementation returns false.
16196     *
16197     * @param alpha The alpha (0..255) to apply to the view's drawing
16198     * @return true if the view can draw with the specified alpha.
16199     */
16200    protected boolean onSetAlpha(int alpha) {
16201        return false;
16202    }
16203
16204    /**
16205     * This is used by the RootView to perform an optimization when
16206     * the view hierarchy contains one or several SurfaceView.
16207     * SurfaceView is always considered transparent, but its children are not,
16208     * therefore all View objects remove themselves from the global transparent
16209     * region (passed as a parameter to this function).
16210     *
16211     * @param region The transparent region for this ViewAncestor (window).
16212     *
16213     * @return Returns true if the effective visibility of the view at this
16214     * point is opaque, regardless of the transparent region; returns false
16215     * if it is possible for underlying windows to be seen behind the view.
16216     *
16217     * {@hide}
16218     */
16219    public boolean gatherTransparentRegion(Region region) {
16220        final AttachInfo attachInfo = mAttachInfo;
16221        if (region != null && attachInfo != null) {
16222            final int pflags = mPrivateFlags;
16223            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16224                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16225                // remove it from the transparent region.
16226                final int[] location = attachInfo.mTransparentLocation;
16227                getLocationInWindow(location);
16228                region.op(location[0], location[1], location[0] + mRight - mLeft,
16229                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16230            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16231                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16232                // exists, so we remove the background drawable's non-transparent
16233                // parts from this transparent region.
16234                applyDrawableToTransparentRegion(mBackground, region);
16235            }
16236        }
16237        return true;
16238    }
16239
16240    /**
16241     * Play a sound effect for this view.
16242     *
16243     * <p>The framework will play sound effects for some built in actions, such as
16244     * clicking, but you may wish to play these effects in your widget,
16245     * for instance, for internal navigation.
16246     *
16247     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16248     * {@link #isSoundEffectsEnabled()} is true.
16249     *
16250     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16251     */
16252    public void playSoundEffect(int soundConstant) {
16253        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16254            return;
16255        }
16256        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16257    }
16258
16259    /**
16260     * BZZZTT!!1!
16261     *
16262     * <p>Provide haptic feedback to the user for this view.
16263     *
16264     * <p>The framework will provide haptic feedback for some built in actions,
16265     * such as long presses, but you may wish to provide feedback for your
16266     * own widget.
16267     *
16268     * <p>The feedback will only be performed if
16269     * {@link #isHapticFeedbackEnabled()} is true.
16270     *
16271     * @param feedbackConstant One of the constants defined in
16272     * {@link HapticFeedbackConstants}
16273     */
16274    public boolean performHapticFeedback(int feedbackConstant) {
16275        return performHapticFeedback(feedbackConstant, 0);
16276    }
16277
16278    /**
16279     * BZZZTT!!1!
16280     *
16281     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16282     *
16283     * @param feedbackConstant One of the constants defined in
16284     * {@link HapticFeedbackConstants}
16285     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16286     */
16287    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16288        if (mAttachInfo == null) {
16289            return false;
16290        }
16291        //noinspection SimplifiableIfStatement
16292        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16293                && !isHapticFeedbackEnabled()) {
16294            return false;
16295        }
16296        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16297                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16298    }
16299
16300    /**
16301     * Request that the visibility of the status bar or other screen/window
16302     * decorations be changed.
16303     *
16304     * <p>This method is used to put the over device UI into temporary modes
16305     * where the user's attention is focused more on the application content,
16306     * by dimming or hiding surrounding system affordances.  This is typically
16307     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16308     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16309     * to be placed behind the action bar (and with these flags other system
16310     * affordances) so that smooth transitions between hiding and showing them
16311     * can be done.
16312     *
16313     * <p>Two representative examples of the use of system UI visibility is
16314     * implementing a content browsing application (like a magazine reader)
16315     * and a video playing application.
16316     *
16317     * <p>The first code shows a typical implementation of a View in a content
16318     * browsing application.  In this implementation, the application goes
16319     * into a content-oriented mode by hiding the status bar and action bar,
16320     * and putting the navigation elements into lights out mode.  The user can
16321     * then interact with content while in this mode.  Such an application should
16322     * provide an easy way for the user to toggle out of the mode (such as to
16323     * check information in the status bar or access notifications).  In the
16324     * implementation here, this is done simply by tapping on the content.
16325     *
16326     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16327     *      content}
16328     *
16329     * <p>This second code sample shows a typical implementation of a View
16330     * in a video playing application.  In this situation, while the video is
16331     * playing the application would like to go into a complete full-screen mode,
16332     * to use as much of the display as possible for the video.  When in this state
16333     * the user can not interact with the application; the system intercepts
16334     * touching on the screen to pop the UI out of full screen mode.  See
16335     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16336     *
16337     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16338     *      content}
16339     *
16340     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16341     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16342     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16343     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16344     */
16345    public void setSystemUiVisibility(int visibility) {
16346        if (visibility != mSystemUiVisibility) {
16347            mSystemUiVisibility = visibility;
16348            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16349                mParent.recomputeViewAttributes(this);
16350            }
16351        }
16352    }
16353
16354    /**
16355     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16356     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16357     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16358     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16359     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16360     */
16361    public int getSystemUiVisibility() {
16362        return mSystemUiVisibility;
16363    }
16364
16365    /**
16366     * Returns the current system UI visibility that is currently set for
16367     * the entire window.  This is the combination of the
16368     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16369     * views in the window.
16370     */
16371    public int getWindowSystemUiVisibility() {
16372        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16373    }
16374
16375    /**
16376     * Override to find out when the window's requested system UI visibility
16377     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16378     * This is different from the callbacks recieved through
16379     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16380     * in that this is only telling you about the local request of the window,
16381     * not the actual values applied by the system.
16382     */
16383    public void onWindowSystemUiVisibilityChanged(int visible) {
16384    }
16385
16386    /**
16387     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16388     * the view hierarchy.
16389     */
16390    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16391        onWindowSystemUiVisibilityChanged(visible);
16392    }
16393
16394    /**
16395     * Set a listener to receive callbacks when the visibility of the system bar changes.
16396     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16397     */
16398    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16399        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16400        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16401            mParent.recomputeViewAttributes(this);
16402        }
16403    }
16404
16405    /**
16406     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16407     * the view hierarchy.
16408     */
16409    public void dispatchSystemUiVisibilityChanged(int visibility) {
16410        ListenerInfo li = mListenerInfo;
16411        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16412            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16413                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16414        }
16415    }
16416
16417    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16418        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16419        if (val != mSystemUiVisibility) {
16420            setSystemUiVisibility(val);
16421            return true;
16422        }
16423        return false;
16424    }
16425
16426    /** @hide */
16427    public void setDisabledSystemUiVisibility(int flags) {
16428        if (mAttachInfo != null) {
16429            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16430                mAttachInfo.mDisabledSystemUiVisibility = flags;
16431                if (mParent != null) {
16432                    mParent.recomputeViewAttributes(this);
16433                }
16434            }
16435        }
16436    }
16437
16438    /**
16439     * Creates an image that the system displays during the drag and drop
16440     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16441     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16442     * appearance as the given View. The default also positions the center of the drag shadow
16443     * directly under the touch point. If no View is provided (the constructor with no parameters
16444     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16445     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16446     * default is an invisible drag shadow.
16447     * <p>
16448     * You are not required to use the View you provide to the constructor as the basis of the
16449     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16450     * anything you want as the drag shadow.
16451     * </p>
16452     * <p>
16453     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16454     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16455     *  size and position of the drag shadow. It uses this data to construct a
16456     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16457     *  so that your application can draw the shadow image in the Canvas.
16458     * </p>
16459     *
16460     * <div class="special reference">
16461     * <h3>Developer Guides</h3>
16462     * <p>For a guide to implementing drag and drop features, read the
16463     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16464     * </div>
16465     */
16466    public static class DragShadowBuilder {
16467        private final WeakReference<View> mView;
16468
16469        /**
16470         * Constructs a shadow image builder based on a View. By default, the resulting drag
16471         * shadow will have the same appearance and dimensions as the View, with the touch point
16472         * over the center of the View.
16473         * @param view A View. Any View in scope can be used.
16474         */
16475        public DragShadowBuilder(View view) {
16476            mView = new WeakReference<View>(view);
16477        }
16478
16479        /**
16480         * Construct a shadow builder object with no associated View.  This
16481         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16482         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16483         * to supply the drag shadow's dimensions and appearance without
16484         * reference to any View object. If they are not overridden, then the result is an
16485         * invisible drag shadow.
16486         */
16487        public DragShadowBuilder() {
16488            mView = new WeakReference<View>(null);
16489        }
16490
16491        /**
16492         * Returns the View object that had been passed to the
16493         * {@link #View.DragShadowBuilder(View)}
16494         * constructor.  If that View parameter was {@code null} or if the
16495         * {@link #View.DragShadowBuilder()}
16496         * constructor was used to instantiate the builder object, this method will return
16497         * null.
16498         *
16499         * @return The View object associate with this builder object.
16500         */
16501        @SuppressWarnings({"JavadocReference"})
16502        final public View getView() {
16503            return mView.get();
16504        }
16505
16506        /**
16507         * Provides the metrics for the shadow image. These include the dimensions of
16508         * the shadow image, and the point within that shadow that should
16509         * be centered under the touch location while dragging.
16510         * <p>
16511         * The default implementation sets the dimensions of the shadow to be the
16512         * same as the dimensions of the View itself and centers the shadow under
16513         * the touch point.
16514         * </p>
16515         *
16516         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16517         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16518         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16519         * image.
16520         *
16521         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16522         * shadow image that should be underneath the touch point during the drag and drop
16523         * operation. Your application must set {@link android.graphics.Point#x} to the
16524         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16525         */
16526        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16527            final View view = mView.get();
16528            if (view != null) {
16529                shadowSize.set(view.getWidth(), view.getHeight());
16530                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16531            } else {
16532                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16533            }
16534        }
16535
16536        /**
16537         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16538         * based on the dimensions it received from the
16539         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16540         *
16541         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16542         */
16543        public void onDrawShadow(Canvas canvas) {
16544            final View view = mView.get();
16545            if (view != null) {
16546                view.draw(canvas);
16547            } else {
16548                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16549            }
16550        }
16551    }
16552
16553    /**
16554     * Starts a drag and drop operation. When your application calls this method, it passes a
16555     * {@link android.view.View.DragShadowBuilder} object to the system. The
16556     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16557     * to get metrics for the drag shadow, and then calls the object's
16558     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16559     * <p>
16560     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16561     *  drag events to all the View objects in your application that are currently visible. It does
16562     *  this either by calling the View object's drag listener (an implementation of
16563     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16564     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16565     *  Both are passed a {@link android.view.DragEvent} object that has a
16566     *  {@link android.view.DragEvent#getAction()} value of
16567     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16568     * </p>
16569     * <p>
16570     * Your application can invoke startDrag() on any attached View object. The View object does not
16571     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16572     * be related to the View the user selected for dragging.
16573     * </p>
16574     * @param data A {@link android.content.ClipData} object pointing to the data to be
16575     * transferred by the drag and drop operation.
16576     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16577     * drag shadow.
16578     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16579     * drop operation. This Object is put into every DragEvent object sent by the system during the
16580     * current drag.
16581     * <p>
16582     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16583     * to the target Views. For example, it can contain flags that differentiate between a
16584     * a copy operation and a move operation.
16585     * </p>
16586     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16587     * so the parameter should be set to 0.
16588     * @return {@code true} if the method completes successfully, or
16589     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16590     * do a drag, and so no drag operation is in progress.
16591     */
16592    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16593            Object myLocalState, int flags) {
16594        if (ViewDebug.DEBUG_DRAG) {
16595            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16596        }
16597        boolean okay = false;
16598
16599        Point shadowSize = new Point();
16600        Point shadowTouchPoint = new Point();
16601        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16602
16603        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16604                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16605            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16606        }
16607
16608        if (ViewDebug.DEBUG_DRAG) {
16609            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16610                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16611        }
16612        Surface surface = new Surface();
16613        try {
16614            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16615                    flags, shadowSize.x, shadowSize.y, surface);
16616            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16617                    + " surface=" + surface);
16618            if (token != null) {
16619                Canvas canvas = surface.lockCanvas(null);
16620                try {
16621                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16622                    shadowBuilder.onDrawShadow(canvas);
16623                } finally {
16624                    surface.unlockCanvasAndPost(canvas);
16625                }
16626
16627                final ViewRootImpl root = getViewRootImpl();
16628
16629                // Cache the local state object for delivery with DragEvents
16630                root.setLocalDragState(myLocalState);
16631
16632                // repurpose 'shadowSize' for the last touch point
16633                root.getLastTouchPoint(shadowSize);
16634
16635                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16636                        shadowSize.x, shadowSize.y,
16637                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16638                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16639
16640                // Off and running!  Release our local surface instance; the drag
16641                // shadow surface is now managed by the system process.
16642                surface.release();
16643            }
16644        } catch (Exception e) {
16645            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16646            surface.destroy();
16647        }
16648
16649        return okay;
16650    }
16651
16652    /**
16653     * Handles drag events sent by the system following a call to
16654     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16655     *<p>
16656     * When the system calls this method, it passes a
16657     * {@link android.view.DragEvent} object. A call to
16658     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16659     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16660     * operation.
16661     * @param event The {@link android.view.DragEvent} sent by the system.
16662     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16663     * in DragEvent, indicating the type of drag event represented by this object.
16664     * @return {@code true} if the method was successful, otherwise {@code false}.
16665     * <p>
16666     *  The method should return {@code true} in response to an action type of
16667     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16668     *  operation.
16669     * </p>
16670     * <p>
16671     *  The method should also return {@code true} in response to an action type of
16672     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16673     *  {@code false} if it didn't.
16674     * </p>
16675     */
16676    public boolean onDragEvent(DragEvent event) {
16677        return false;
16678    }
16679
16680    /**
16681     * Detects if this View is enabled and has a drag event listener.
16682     * If both are true, then it calls the drag event listener with the
16683     * {@link android.view.DragEvent} it received. If the drag event listener returns
16684     * {@code true}, then dispatchDragEvent() returns {@code true}.
16685     * <p>
16686     * For all other cases, the method calls the
16687     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16688     * method and returns its result.
16689     * </p>
16690     * <p>
16691     * This ensures that a drag event is always consumed, even if the View does not have a drag
16692     * event listener. However, if the View has a listener and the listener returns true, then
16693     * onDragEvent() is not called.
16694     * </p>
16695     */
16696    public boolean dispatchDragEvent(DragEvent event) {
16697        //noinspection SimplifiableIfStatement
16698        ListenerInfo li = mListenerInfo;
16699        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16700                && li.mOnDragListener.onDrag(this, event)) {
16701            return true;
16702        }
16703        return onDragEvent(event);
16704    }
16705
16706    boolean canAcceptDrag() {
16707        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16708    }
16709
16710    /**
16711     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16712     * it is ever exposed at all.
16713     * @hide
16714     */
16715    public void onCloseSystemDialogs(String reason) {
16716    }
16717
16718    /**
16719     * Given a Drawable whose bounds have been set to draw into this view,
16720     * update a Region being computed for
16721     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16722     * that any non-transparent parts of the Drawable are removed from the
16723     * given transparent region.
16724     *
16725     * @param dr The Drawable whose transparency is to be applied to the region.
16726     * @param region A Region holding the current transparency information,
16727     * where any parts of the region that are set are considered to be
16728     * transparent.  On return, this region will be modified to have the
16729     * transparency information reduced by the corresponding parts of the
16730     * Drawable that are not transparent.
16731     * {@hide}
16732     */
16733    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16734        if (DBG) {
16735            Log.i("View", "Getting transparent region for: " + this);
16736        }
16737        final Region r = dr.getTransparentRegion();
16738        final Rect db = dr.getBounds();
16739        final AttachInfo attachInfo = mAttachInfo;
16740        if (r != null && attachInfo != null) {
16741            final int w = getRight()-getLeft();
16742            final int h = getBottom()-getTop();
16743            if (db.left > 0) {
16744                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16745                r.op(0, 0, db.left, h, Region.Op.UNION);
16746            }
16747            if (db.right < w) {
16748                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16749                r.op(db.right, 0, w, h, Region.Op.UNION);
16750            }
16751            if (db.top > 0) {
16752                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16753                r.op(0, 0, w, db.top, Region.Op.UNION);
16754            }
16755            if (db.bottom < h) {
16756                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16757                r.op(0, db.bottom, w, h, Region.Op.UNION);
16758            }
16759            final int[] location = attachInfo.mTransparentLocation;
16760            getLocationInWindow(location);
16761            r.translate(location[0], location[1]);
16762            region.op(r, Region.Op.INTERSECT);
16763        } else {
16764            region.op(db, Region.Op.DIFFERENCE);
16765        }
16766    }
16767
16768    private void checkForLongClick(int delayOffset) {
16769        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16770            mHasPerformedLongPress = false;
16771
16772            if (mPendingCheckForLongPress == null) {
16773                mPendingCheckForLongPress = new CheckForLongPress();
16774            }
16775            mPendingCheckForLongPress.rememberWindowAttachCount();
16776            postDelayed(mPendingCheckForLongPress,
16777                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16778        }
16779    }
16780
16781    /**
16782     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16783     * LayoutInflater} class, which provides a full range of options for view inflation.
16784     *
16785     * @param context The Context object for your activity or application.
16786     * @param resource The resource ID to inflate
16787     * @param root A view group that will be the parent.  Used to properly inflate the
16788     * layout_* parameters.
16789     * @see LayoutInflater
16790     */
16791    public static View inflate(Context context, int resource, ViewGroup root) {
16792        LayoutInflater factory = LayoutInflater.from(context);
16793        return factory.inflate(resource, root);
16794    }
16795
16796    /**
16797     * Scroll the view with standard behavior for scrolling beyond the normal
16798     * content boundaries. Views that call this method should override
16799     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16800     * results of an over-scroll operation.
16801     *
16802     * Views can use this method to handle any touch or fling-based scrolling.
16803     *
16804     * @param deltaX Change in X in pixels
16805     * @param deltaY Change in Y in pixels
16806     * @param scrollX Current X scroll value in pixels before applying deltaX
16807     * @param scrollY Current Y scroll value in pixels before applying deltaY
16808     * @param scrollRangeX Maximum content scroll range along the X axis
16809     * @param scrollRangeY Maximum content scroll range along the Y axis
16810     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16811     *          along the X axis.
16812     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16813     *          along the Y axis.
16814     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16815     * @return true if scrolling was clamped to an over-scroll boundary along either
16816     *          axis, false otherwise.
16817     */
16818    @SuppressWarnings({"UnusedParameters"})
16819    protected boolean overScrollBy(int deltaX, int deltaY,
16820            int scrollX, int scrollY,
16821            int scrollRangeX, int scrollRangeY,
16822            int maxOverScrollX, int maxOverScrollY,
16823            boolean isTouchEvent) {
16824        final int overScrollMode = mOverScrollMode;
16825        final boolean canScrollHorizontal =
16826                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16827        final boolean canScrollVertical =
16828                computeVerticalScrollRange() > computeVerticalScrollExtent();
16829        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16830                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16831        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16832                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16833
16834        int newScrollX = scrollX + deltaX;
16835        if (!overScrollHorizontal) {
16836            maxOverScrollX = 0;
16837        }
16838
16839        int newScrollY = scrollY + deltaY;
16840        if (!overScrollVertical) {
16841            maxOverScrollY = 0;
16842        }
16843
16844        // Clamp values if at the limits and record
16845        final int left = -maxOverScrollX;
16846        final int right = maxOverScrollX + scrollRangeX;
16847        final int top = -maxOverScrollY;
16848        final int bottom = maxOverScrollY + scrollRangeY;
16849
16850        boolean clampedX = false;
16851        if (newScrollX > right) {
16852            newScrollX = right;
16853            clampedX = true;
16854        } else if (newScrollX < left) {
16855            newScrollX = left;
16856            clampedX = true;
16857        }
16858
16859        boolean clampedY = false;
16860        if (newScrollY > bottom) {
16861            newScrollY = bottom;
16862            clampedY = true;
16863        } else if (newScrollY < top) {
16864            newScrollY = top;
16865            clampedY = true;
16866        }
16867
16868        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16869
16870        return clampedX || clampedY;
16871    }
16872
16873    /**
16874     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16875     * respond to the results of an over-scroll operation.
16876     *
16877     * @param scrollX New X scroll value in pixels
16878     * @param scrollY New Y scroll value in pixels
16879     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16880     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16881     */
16882    protected void onOverScrolled(int scrollX, int scrollY,
16883            boolean clampedX, boolean clampedY) {
16884        // Intentionally empty.
16885    }
16886
16887    /**
16888     * Returns the over-scroll mode for this view. The result will be
16889     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16890     * (allow over-scrolling only if the view content is larger than the container),
16891     * or {@link #OVER_SCROLL_NEVER}.
16892     *
16893     * @return This view's over-scroll mode.
16894     */
16895    public int getOverScrollMode() {
16896        return mOverScrollMode;
16897    }
16898
16899    /**
16900     * Set the over-scroll mode for this view. Valid over-scroll modes are
16901     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16902     * (allow over-scrolling only if the view content is larger than the container),
16903     * or {@link #OVER_SCROLL_NEVER}.
16904     *
16905     * Setting the over-scroll mode of a view will have an effect only if the
16906     * view is capable of scrolling.
16907     *
16908     * @param overScrollMode The new over-scroll mode for this view.
16909     */
16910    public void setOverScrollMode(int overScrollMode) {
16911        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16912                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16913                overScrollMode != OVER_SCROLL_NEVER) {
16914            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16915        }
16916        mOverScrollMode = overScrollMode;
16917    }
16918
16919    /**
16920     * Gets a scale factor that determines the distance the view should scroll
16921     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16922     * @return The vertical scroll scale factor.
16923     * @hide
16924     */
16925    protected float getVerticalScrollFactor() {
16926        if (mVerticalScrollFactor == 0) {
16927            TypedValue outValue = new TypedValue();
16928            if (!mContext.getTheme().resolveAttribute(
16929                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16930                throw new IllegalStateException(
16931                        "Expected theme to define listPreferredItemHeight.");
16932            }
16933            mVerticalScrollFactor = outValue.getDimension(
16934                    mContext.getResources().getDisplayMetrics());
16935        }
16936        return mVerticalScrollFactor;
16937    }
16938
16939    /**
16940     * Gets a scale factor that determines the distance the view should scroll
16941     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16942     * @return The horizontal scroll scale factor.
16943     * @hide
16944     */
16945    protected float getHorizontalScrollFactor() {
16946        // TODO: Should use something else.
16947        return getVerticalScrollFactor();
16948    }
16949
16950    /**
16951     * Return the value specifying the text direction or policy that was set with
16952     * {@link #setTextDirection(int)}.
16953     *
16954     * @return the defined text direction. It can be one of:
16955     *
16956     * {@link #TEXT_DIRECTION_INHERIT},
16957     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16958     * {@link #TEXT_DIRECTION_ANY_RTL},
16959     * {@link #TEXT_DIRECTION_LTR},
16960     * {@link #TEXT_DIRECTION_RTL},
16961     * {@link #TEXT_DIRECTION_LOCALE}
16962     *
16963     * @attr ref android.R.styleable#View_textDirection
16964     *
16965     * @hide
16966     */
16967    @ViewDebug.ExportedProperty(category = "text", mapping = {
16968            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16969            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16970            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16971            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16972            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16973            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16974    })
16975    public int getRawTextDirection() {
16976        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16977    }
16978
16979    /**
16980     * Set the text direction.
16981     *
16982     * @param textDirection the direction to set. Should be one of:
16983     *
16984     * {@link #TEXT_DIRECTION_INHERIT},
16985     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16986     * {@link #TEXT_DIRECTION_ANY_RTL},
16987     * {@link #TEXT_DIRECTION_LTR},
16988     * {@link #TEXT_DIRECTION_RTL},
16989     * {@link #TEXT_DIRECTION_LOCALE}
16990     *
16991     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
16992     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
16993     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
16994     *
16995     * @attr ref android.R.styleable#View_textDirection
16996     */
16997    public void setTextDirection(int textDirection) {
16998        if (getRawTextDirection() != textDirection) {
16999            // Reset the current text direction and the resolved one
17000            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17001            resetResolvedTextDirection();
17002            // Set the new text direction
17003            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17004            // Do resolution
17005            resolveTextDirection();
17006            // Notify change
17007            onRtlPropertiesChanged(getLayoutDirection());
17008            // Refresh
17009            requestLayout();
17010            invalidate(true);
17011        }
17012    }
17013
17014    /**
17015     * Return the resolved text direction.
17016     *
17017     * @return the resolved text direction. Returns one of:
17018     *
17019     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17020     * {@link #TEXT_DIRECTION_ANY_RTL},
17021     * {@link #TEXT_DIRECTION_LTR},
17022     * {@link #TEXT_DIRECTION_RTL},
17023     * {@link #TEXT_DIRECTION_LOCALE}
17024     *
17025     * @attr ref android.R.styleable#View_textDirection
17026     */
17027    @ViewDebug.ExportedProperty(category = "text", mapping = {
17028            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17029            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17030            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17031            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17032            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17033            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17034    })
17035    public int getTextDirection() {
17036        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17037    }
17038
17039    /**
17040     * Resolve the text direction.
17041     *
17042     * @return true if resolution has been done, false otherwise.
17043     *
17044     * @hide
17045     */
17046    public boolean resolveTextDirection() {
17047        // Reset any previous text direction resolution
17048        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17049
17050        if (hasRtlSupport()) {
17051            // Set resolved text direction flag depending on text direction flag
17052            final int textDirection = getRawTextDirection();
17053            switch(textDirection) {
17054                case TEXT_DIRECTION_INHERIT:
17055                    if (!canResolveTextDirection()) {
17056                        // We cannot do the resolution if there is no parent, so use the default one
17057                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17058                        // Resolution will need to happen again later
17059                        return false;
17060                    }
17061
17062                    // Parent has not yet resolved, so we still return the default
17063                    if (!mParent.isTextDirectionResolved()) {
17064                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17065                        // Resolution will need to happen again later
17066                        return false;
17067                    }
17068
17069                    // Set current resolved direction to the same value as the parent's one
17070                    final int parentResolvedDirection = mParent.getTextDirection();
17071                    switch (parentResolvedDirection) {
17072                        case TEXT_DIRECTION_FIRST_STRONG:
17073                        case TEXT_DIRECTION_ANY_RTL:
17074                        case TEXT_DIRECTION_LTR:
17075                        case TEXT_DIRECTION_RTL:
17076                        case TEXT_DIRECTION_LOCALE:
17077                            mPrivateFlags2 |=
17078                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17079                            break;
17080                        default:
17081                            // Default resolved direction is "first strong" heuristic
17082                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17083                    }
17084                    break;
17085                case TEXT_DIRECTION_FIRST_STRONG:
17086                case TEXT_DIRECTION_ANY_RTL:
17087                case TEXT_DIRECTION_LTR:
17088                case TEXT_DIRECTION_RTL:
17089                case TEXT_DIRECTION_LOCALE:
17090                    // Resolved direction is the same as text direction
17091                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17092                    break;
17093                default:
17094                    // Default resolved direction is "first strong" heuristic
17095                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17096            }
17097        } else {
17098            // Default resolved direction is "first strong" heuristic
17099            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17100        }
17101
17102        // Set to resolved
17103        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17104        return true;
17105    }
17106
17107    /**
17108     * Check if text direction resolution can be done.
17109     *
17110     * @return true if text direction resolution can be done otherwise return false.
17111     *
17112     * @hide
17113     */
17114    public boolean canResolveTextDirection() {
17115        switch (getRawTextDirection()) {
17116            case TEXT_DIRECTION_INHERIT:
17117                return (mParent != null) && mParent.canResolveTextDirection();
17118            default:
17119                return true;
17120        }
17121    }
17122
17123    /**
17124     * Reset resolved text direction. Text direction will be resolved during a call to
17125     * {@link #onMeasure(int, int)}.
17126     *
17127     * @hide
17128     */
17129    public void resetResolvedTextDirection() {
17130        // Reset any previous text direction resolution
17131        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17132        // Set to default value
17133        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17134    }
17135
17136    /**
17137     * @return true if text direction is inherited.
17138     *
17139     * @hide
17140     */
17141    public boolean isTextDirectionInherited() {
17142        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17143    }
17144
17145    /**
17146     * @return true if text direction is resolved.
17147     *
17148     * @hide
17149     */
17150    public boolean isTextDirectionResolved() {
17151        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17152    }
17153
17154    /**
17155     * Return the value specifying the text alignment or policy that was set with
17156     * {@link #setTextAlignment(int)}.
17157     *
17158     * @return the defined text alignment. It can be one of:
17159     *
17160     * {@link #TEXT_ALIGNMENT_INHERIT},
17161     * {@link #TEXT_ALIGNMENT_GRAVITY},
17162     * {@link #TEXT_ALIGNMENT_CENTER},
17163     * {@link #TEXT_ALIGNMENT_TEXT_START},
17164     * {@link #TEXT_ALIGNMENT_TEXT_END},
17165     * {@link #TEXT_ALIGNMENT_VIEW_START},
17166     * {@link #TEXT_ALIGNMENT_VIEW_END}
17167     *
17168     * @attr ref android.R.styleable#View_textAlignment
17169     *
17170     * @hide
17171     */
17172    @ViewDebug.ExportedProperty(category = "text", mapping = {
17173            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17174            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17175            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17176            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17177            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17178            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17179            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17180    })
17181    public int getRawTextAlignment() {
17182        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17183    }
17184
17185    /**
17186     * Set the text alignment.
17187     *
17188     * @param textAlignment The text alignment to set. Should be one of
17189     *
17190     * {@link #TEXT_ALIGNMENT_INHERIT},
17191     * {@link #TEXT_ALIGNMENT_GRAVITY},
17192     * {@link #TEXT_ALIGNMENT_CENTER},
17193     * {@link #TEXT_ALIGNMENT_TEXT_START},
17194     * {@link #TEXT_ALIGNMENT_TEXT_END},
17195     * {@link #TEXT_ALIGNMENT_VIEW_START},
17196     * {@link #TEXT_ALIGNMENT_VIEW_END}
17197     *
17198     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17199     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17200     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17201     *
17202     * @attr ref android.R.styleable#View_textAlignment
17203     */
17204    public void setTextAlignment(int textAlignment) {
17205        if (textAlignment != getRawTextAlignment()) {
17206            // Reset the current and resolved text alignment
17207            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17208            resetResolvedTextAlignment();
17209            // Set the new text alignment
17210            mPrivateFlags2 |=
17211                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17212            // Do resolution
17213            resolveTextAlignment();
17214            // Notify change
17215            onRtlPropertiesChanged(getLayoutDirection());
17216            // Refresh
17217            requestLayout();
17218            invalidate(true);
17219        }
17220    }
17221
17222    /**
17223     * Return the resolved text alignment.
17224     *
17225     * @return the resolved text alignment. Returns one of:
17226     *
17227     * {@link #TEXT_ALIGNMENT_GRAVITY},
17228     * {@link #TEXT_ALIGNMENT_CENTER},
17229     * {@link #TEXT_ALIGNMENT_TEXT_START},
17230     * {@link #TEXT_ALIGNMENT_TEXT_END},
17231     * {@link #TEXT_ALIGNMENT_VIEW_START},
17232     * {@link #TEXT_ALIGNMENT_VIEW_END}
17233     *
17234     * @attr ref android.R.styleable#View_textAlignment
17235     */
17236    @ViewDebug.ExportedProperty(category = "text", mapping = {
17237            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17238            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17239            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17240            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17241            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17242            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17243            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17244    })
17245    public int getTextAlignment() {
17246        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17247                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17248    }
17249
17250    /**
17251     * Resolve the text alignment.
17252     *
17253     * @return true if resolution has been done, false otherwise.
17254     *
17255     * @hide
17256     */
17257    public boolean resolveTextAlignment() {
17258        // Reset any previous text alignment resolution
17259        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17260
17261        if (hasRtlSupport()) {
17262            // Set resolved text alignment flag depending on text alignment flag
17263            final int textAlignment = getRawTextAlignment();
17264            switch (textAlignment) {
17265                case TEXT_ALIGNMENT_INHERIT:
17266                    // Check if we can resolve the text alignment
17267                    if (!canResolveTextAlignment()) {
17268                        // We cannot do the resolution if there is no parent so use the default
17269                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17270                        // Resolution will need to happen again later
17271                        return false;
17272                    }
17273
17274                    // Parent has not yet resolved, so we still return the default
17275                    if (!mParent.isTextAlignmentResolved()) {
17276                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17277                        // Resolution will need to happen again later
17278                        return false;
17279                    }
17280
17281                    final int parentResolvedTextAlignment = mParent.getTextAlignment();
17282                    switch (parentResolvedTextAlignment) {
17283                        case TEXT_ALIGNMENT_GRAVITY:
17284                        case TEXT_ALIGNMENT_TEXT_START:
17285                        case TEXT_ALIGNMENT_TEXT_END:
17286                        case TEXT_ALIGNMENT_CENTER:
17287                        case TEXT_ALIGNMENT_VIEW_START:
17288                        case TEXT_ALIGNMENT_VIEW_END:
17289                            // Resolved text alignment is the same as the parent resolved
17290                            // text alignment
17291                            mPrivateFlags2 |=
17292                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17293                            break;
17294                        default:
17295                            // Use default resolved text alignment
17296                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17297                    }
17298                    break;
17299                case TEXT_ALIGNMENT_GRAVITY:
17300                case TEXT_ALIGNMENT_TEXT_START:
17301                case TEXT_ALIGNMENT_TEXT_END:
17302                case TEXT_ALIGNMENT_CENTER:
17303                case TEXT_ALIGNMENT_VIEW_START:
17304                case TEXT_ALIGNMENT_VIEW_END:
17305                    // Resolved text alignment is the same as text alignment
17306                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17307                    break;
17308                default:
17309                    // Use default resolved text alignment
17310                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17311            }
17312        } else {
17313            // Use default resolved text alignment
17314            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17315        }
17316
17317        // Set the resolved
17318        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17319        return true;
17320    }
17321
17322    /**
17323     * Check if text alignment resolution can be done.
17324     *
17325     * @return true if text alignment resolution can be done otherwise return false.
17326     *
17327     * @hide
17328     */
17329    public boolean canResolveTextAlignment() {
17330        switch (getRawTextAlignment()) {
17331            case TEXT_DIRECTION_INHERIT:
17332                return (mParent != null) && mParent.canResolveTextAlignment();
17333            default:
17334                return true;
17335        }
17336    }
17337
17338    /**
17339     * Reset resolved text alignment. Text alignment will be resolved during a call to
17340     * {@link #onMeasure(int, int)}.
17341     *
17342     * @hide
17343     */
17344    public void resetResolvedTextAlignment() {
17345        // Reset any previous text alignment resolution
17346        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17347        // Set to default
17348        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17349    }
17350
17351    /**
17352     * @return true if text alignment is inherited.
17353     *
17354     * @hide
17355     */
17356    public boolean isTextAlignmentInherited() {
17357        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17358    }
17359
17360    /**
17361     * @return true if text alignment is resolved.
17362     *
17363     * @hide
17364     */
17365    public boolean isTextAlignmentResolved() {
17366        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17367    }
17368
17369    /**
17370     * Generate a value suitable for use in {@link #setId(int)}.
17371     * This value will not collide with ID values generated at build time by aapt for R.id.
17372     *
17373     * @return a generated ID value
17374     */
17375    public static int generateViewId() {
17376        for (;;) {
17377            final int result = sNextGeneratedId.get();
17378            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17379            int newValue = result + 1;
17380            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17381            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17382                return result;
17383            }
17384        }
17385    }
17386
17387    //
17388    // Properties
17389    //
17390    /**
17391     * A Property wrapper around the <code>alpha</code> functionality handled by the
17392     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17393     */
17394    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17395        @Override
17396        public void setValue(View object, float value) {
17397            object.setAlpha(value);
17398        }
17399
17400        @Override
17401        public Float get(View object) {
17402            return object.getAlpha();
17403        }
17404    };
17405
17406    /**
17407     * A Property wrapper around the <code>translationX</code> functionality handled by the
17408     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17409     */
17410    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17411        @Override
17412        public void setValue(View object, float value) {
17413            object.setTranslationX(value);
17414        }
17415
17416                @Override
17417        public Float get(View object) {
17418            return object.getTranslationX();
17419        }
17420    };
17421
17422    /**
17423     * A Property wrapper around the <code>translationY</code> functionality handled by the
17424     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17425     */
17426    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17427        @Override
17428        public void setValue(View object, float value) {
17429            object.setTranslationY(value);
17430        }
17431
17432        @Override
17433        public Float get(View object) {
17434            return object.getTranslationY();
17435        }
17436    };
17437
17438    /**
17439     * A Property wrapper around the <code>x</code> functionality handled by the
17440     * {@link View#setX(float)} and {@link View#getX()} methods.
17441     */
17442    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17443        @Override
17444        public void setValue(View object, float value) {
17445            object.setX(value);
17446        }
17447
17448        @Override
17449        public Float get(View object) {
17450            return object.getX();
17451        }
17452    };
17453
17454    /**
17455     * A Property wrapper around the <code>y</code> functionality handled by the
17456     * {@link View#setY(float)} and {@link View#getY()} methods.
17457     */
17458    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17459        @Override
17460        public void setValue(View object, float value) {
17461            object.setY(value);
17462        }
17463
17464        @Override
17465        public Float get(View object) {
17466            return object.getY();
17467        }
17468    };
17469
17470    /**
17471     * A Property wrapper around the <code>rotation</code> functionality handled by the
17472     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17473     */
17474    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17475        @Override
17476        public void setValue(View object, float value) {
17477            object.setRotation(value);
17478        }
17479
17480        @Override
17481        public Float get(View object) {
17482            return object.getRotation();
17483        }
17484    };
17485
17486    /**
17487     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17488     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17489     */
17490    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17491        @Override
17492        public void setValue(View object, float value) {
17493            object.setRotationX(value);
17494        }
17495
17496        @Override
17497        public Float get(View object) {
17498            return object.getRotationX();
17499        }
17500    };
17501
17502    /**
17503     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17504     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17505     */
17506    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17507        @Override
17508        public void setValue(View object, float value) {
17509            object.setRotationY(value);
17510        }
17511
17512        @Override
17513        public Float get(View object) {
17514            return object.getRotationY();
17515        }
17516    };
17517
17518    /**
17519     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17520     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17521     */
17522    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17523        @Override
17524        public void setValue(View object, float value) {
17525            object.setScaleX(value);
17526        }
17527
17528        @Override
17529        public Float get(View object) {
17530            return object.getScaleX();
17531        }
17532    };
17533
17534    /**
17535     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17536     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17537     */
17538    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17539        @Override
17540        public void setValue(View object, float value) {
17541            object.setScaleY(value);
17542        }
17543
17544        @Override
17545        public Float get(View object) {
17546            return object.getScaleY();
17547        }
17548    };
17549
17550    /**
17551     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17552     * Each MeasureSpec represents a requirement for either the width or the height.
17553     * A MeasureSpec is comprised of a size and a mode. There are three possible
17554     * modes:
17555     * <dl>
17556     * <dt>UNSPECIFIED</dt>
17557     * <dd>
17558     * The parent has not imposed any constraint on the child. It can be whatever size
17559     * it wants.
17560     * </dd>
17561     *
17562     * <dt>EXACTLY</dt>
17563     * <dd>
17564     * The parent has determined an exact size for the child. The child is going to be
17565     * given those bounds regardless of how big it wants to be.
17566     * </dd>
17567     *
17568     * <dt>AT_MOST</dt>
17569     * <dd>
17570     * The child can be as large as it wants up to the specified size.
17571     * </dd>
17572     * </dl>
17573     *
17574     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17575     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17576     */
17577    public static class MeasureSpec {
17578        private static final int MODE_SHIFT = 30;
17579        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17580
17581        /**
17582         * Measure specification mode: The parent has not imposed any constraint
17583         * on the child. It can be whatever size it wants.
17584         */
17585        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17586
17587        /**
17588         * Measure specification mode: The parent has determined an exact size
17589         * for the child. The child is going to be given those bounds regardless
17590         * of how big it wants to be.
17591         */
17592        public static final int EXACTLY     = 1 << MODE_SHIFT;
17593
17594        /**
17595         * Measure specification mode: The child can be as large as it wants up
17596         * to the specified size.
17597         */
17598        public static final int AT_MOST     = 2 << MODE_SHIFT;
17599
17600        /**
17601         * Creates a measure specification based on the supplied size and mode.
17602         *
17603         * The mode must always be one of the following:
17604         * <ul>
17605         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17606         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17607         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17608         * </ul>
17609         *
17610         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17611         * implementation was such that the order of arguments did not matter
17612         * and overflow in either value could impact the resulting MeasureSpec.
17613         * {@link android.widget.RelativeLayout} was affected by this bug.
17614         * Apps targeting API levels greater than 17 will get the fixed, more strict
17615         * behavior.</p>
17616         *
17617         * @param size the size of the measure specification
17618         * @param mode the mode of the measure specification
17619         * @return the measure specification based on size and mode
17620         */
17621        public static int makeMeasureSpec(int size, int mode) {
17622            if (sUseBrokenMakeMeasureSpec) {
17623                return size + mode;
17624            } else {
17625                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17626            }
17627        }
17628
17629        /**
17630         * Extracts the mode from the supplied measure specification.
17631         *
17632         * @param measureSpec the measure specification to extract the mode from
17633         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17634         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17635         *         {@link android.view.View.MeasureSpec#EXACTLY}
17636         */
17637        public static int getMode(int measureSpec) {
17638            return (measureSpec & MODE_MASK);
17639        }
17640
17641        /**
17642         * Extracts the size from the supplied measure specification.
17643         *
17644         * @param measureSpec the measure specification to extract the size from
17645         * @return the size in pixels defined in the supplied measure specification
17646         */
17647        public static int getSize(int measureSpec) {
17648            return (measureSpec & ~MODE_MASK);
17649        }
17650
17651        static int adjust(int measureSpec, int delta) {
17652            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17653        }
17654
17655        /**
17656         * Returns a String representation of the specified measure
17657         * specification.
17658         *
17659         * @param measureSpec the measure specification to convert to a String
17660         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17661         */
17662        public static String toString(int measureSpec) {
17663            int mode = getMode(measureSpec);
17664            int size = getSize(measureSpec);
17665
17666            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17667
17668            if (mode == UNSPECIFIED)
17669                sb.append("UNSPECIFIED ");
17670            else if (mode == EXACTLY)
17671                sb.append("EXACTLY ");
17672            else if (mode == AT_MOST)
17673                sb.append("AT_MOST ");
17674            else
17675                sb.append(mode).append(" ");
17676
17677            sb.append(size);
17678            return sb.toString();
17679        }
17680    }
17681
17682    class CheckForLongPress implements Runnable {
17683
17684        private int mOriginalWindowAttachCount;
17685
17686        public void run() {
17687            if (isPressed() && (mParent != null)
17688                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17689                if (performLongClick()) {
17690                    mHasPerformedLongPress = true;
17691                }
17692            }
17693        }
17694
17695        public void rememberWindowAttachCount() {
17696            mOriginalWindowAttachCount = mWindowAttachCount;
17697        }
17698    }
17699
17700    private final class CheckForTap implements Runnable {
17701        public void run() {
17702            mPrivateFlags &= ~PFLAG_PREPRESSED;
17703            setPressed(true);
17704            checkForLongClick(ViewConfiguration.getTapTimeout());
17705        }
17706    }
17707
17708    private final class PerformClick implements Runnable {
17709        public void run() {
17710            performClick();
17711        }
17712    }
17713
17714    /** @hide */
17715    public void hackTurnOffWindowResizeAnim(boolean off) {
17716        mAttachInfo.mTurnOffWindowResizeAnim = off;
17717    }
17718
17719    /**
17720     * This method returns a ViewPropertyAnimator object, which can be used to animate
17721     * specific properties on this View.
17722     *
17723     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17724     */
17725    public ViewPropertyAnimator animate() {
17726        if (mAnimator == null) {
17727            mAnimator = new ViewPropertyAnimator(this);
17728        }
17729        return mAnimator;
17730    }
17731
17732    /**
17733     * Interface definition for a callback to be invoked when a hardware key event is
17734     * dispatched to this view. The callback will be invoked before the key event is
17735     * given to the view. This is only useful for hardware keyboards; a software input
17736     * method has no obligation to trigger this listener.
17737     */
17738    public interface OnKeyListener {
17739        /**
17740         * Called when a hardware key is dispatched to a view. This allows listeners to
17741         * get a chance to respond before the target view.
17742         * <p>Key presses in software keyboards will generally NOT trigger this method,
17743         * although some may elect to do so in some situations. Do not assume a
17744         * software input method has to be key-based; even if it is, it may use key presses
17745         * in a different way than you expect, so there is no way to reliably catch soft
17746         * input key presses.
17747         *
17748         * @param v The view the key has been dispatched to.
17749         * @param keyCode The code for the physical key that was pressed
17750         * @param event The KeyEvent object containing full information about
17751         *        the event.
17752         * @return True if the listener has consumed the event, false otherwise.
17753         */
17754        boolean onKey(View v, int keyCode, KeyEvent event);
17755    }
17756
17757    /**
17758     * Interface definition for a callback to be invoked when a touch event is
17759     * dispatched to this view. The callback will be invoked before the touch
17760     * event is given to the view.
17761     */
17762    public interface OnTouchListener {
17763        /**
17764         * Called when a touch event is dispatched to a view. This allows listeners to
17765         * get a chance to respond before the target view.
17766         *
17767         * @param v The view the touch event has been dispatched to.
17768         * @param event The MotionEvent object containing full information about
17769         *        the event.
17770         * @return True if the listener has consumed the event, false otherwise.
17771         */
17772        boolean onTouch(View v, MotionEvent event);
17773    }
17774
17775    /**
17776     * Interface definition for a callback to be invoked when a hover event is
17777     * dispatched to this view. The callback will be invoked before the hover
17778     * event is given to the view.
17779     */
17780    public interface OnHoverListener {
17781        /**
17782         * Called when a hover event is dispatched to a view. This allows listeners to
17783         * get a chance to respond before the target view.
17784         *
17785         * @param v The view the hover event has been dispatched to.
17786         * @param event The MotionEvent object containing full information about
17787         *        the event.
17788         * @return True if the listener has consumed the event, false otherwise.
17789         */
17790        boolean onHover(View v, MotionEvent event);
17791    }
17792
17793    /**
17794     * Interface definition for a callback to be invoked when a generic motion event is
17795     * dispatched to this view. The callback will be invoked before the generic motion
17796     * event is given to the view.
17797     */
17798    public interface OnGenericMotionListener {
17799        /**
17800         * Called when a generic motion event is dispatched to a view. This allows listeners to
17801         * get a chance to respond before the target view.
17802         *
17803         * @param v The view the generic motion event has been dispatched to.
17804         * @param event The MotionEvent object containing full information about
17805         *        the event.
17806         * @return True if the listener has consumed the event, false otherwise.
17807         */
17808        boolean onGenericMotion(View v, MotionEvent event);
17809    }
17810
17811    /**
17812     * Interface definition for a callback to be invoked when a view has been clicked and held.
17813     */
17814    public interface OnLongClickListener {
17815        /**
17816         * Called when a view has been clicked and held.
17817         *
17818         * @param v The view that was clicked and held.
17819         *
17820         * @return true if the callback consumed the long click, false otherwise.
17821         */
17822        boolean onLongClick(View v);
17823    }
17824
17825    /**
17826     * Interface definition for a callback to be invoked when a drag is being dispatched
17827     * to this view.  The callback will be invoked before the hosting view's own
17828     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17829     * onDrag(event) behavior, it should return 'false' from this callback.
17830     *
17831     * <div class="special reference">
17832     * <h3>Developer Guides</h3>
17833     * <p>For a guide to implementing drag and drop features, read the
17834     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17835     * </div>
17836     */
17837    public interface OnDragListener {
17838        /**
17839         * Called when a drag event is dispatched to a view. This allows listeners
17840         * to get a chance to override base View behavior.
17841         *
17842         * @param v The View that received the drag event.
17843         * @param event The {@link android.view.DragEvent} object for the drag event.
17844         * @return {@code true} if the drag event was handled successfully, or {@code false}
17845         * if the drag event was not handled. Note that {@code false} will trigger the View
17846         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17847         */
17848        boolean onDrag(View v, DragEvent event);
17849    }
17850
17851    /**
17852     * Interface definition for a callback to be invoked when the focus state of
17853     * a view changed.
17854     */
17855    public interface OnFocusChangeListener {
17856        /**
17857         * Called when the focus state of a view has changed.
17858         *
17859         * @param v The view whose state has changed.
17860         * @param hasFocus The new focus state of v.
17861         */
17862        void onFocusChange(View v, boolean hasFocus);
17863    }
17864
17865    /**
17866     * Interface definition for a callback to be invoked when a view is clicked.
17867     */
17868    public interface OnClickListener {
17869        /**
17870         * Called when a view has been clicked.
17871         *
17872         * @param v The view that was clicked.
17873         */
17874        void onClick(View v);
17875    }
17876
17877    /**
17878     * Interface definition for a callback to be invoked when the context menu
17879     * for this view is being built.
17880     */
17881    public interface OnCreateContextMenuListener {
17882        /**
17883         * Called when the context menu for this view is being built. It is not
17884         * safe to hold onto the menu after this method returns.
17885         *
17886         * @param menu The context menu that is being built
17887         * @param v The view for which the context menu is being built
17888         * @param menuInfo Extra information about the item for which the
17889         *            context menu should be shown. This information will vary
17890         *            depending on the class of v.
17891         */
17892        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17893    }
17894
17895    /**
17896     * Interface definition for a callback to be invoked when the status bar changes
17897     * visibility.  This reports <strong>global</strong> changes to the system UI
17898     * state, not what the application is requesting.
17899     *
17900     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17901     */
17902    public interface OnSystemUiVisibilityChangeListener {
17903        /**
17904         * Called when the status bar changes visibility because of a call to
17905         * {@link View#setSystemUiVisibility(int)}.
17906         *
17907         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17908         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17909         * This tells you the <strong>global</strong> state of these UI visibility
17910         * flags, not what your app is currently applying.
17911         */
17912        public void onSystemUiVisibilityChange(int visibility);
17913    }
17914
17915    /**
17916     * Interface definition for a callback to be invoked when this view is attached
17917     * or detached from its window.
17918     */
17919    public interface OnAttachStateChangeListener {
17920        /**
17921         * Called when the view is attached to a window.
17922         * @param v The view that was attached
17923         */
17924        public void onViewAttachedToWindow(View v);
17925        /**
17926         * Called when the view is detached from a window.
17927         * @param v The view that was detached
17928         */
17929        public void onViewDetachedFromWindow(View v);
17930    }
17931
17932    private final class UnsetPressedState implements Runnable {
17933        public void run() {
17934            setPressed(false);
17935        }
17936    }
17937
17938    /**
17939     * Base class for derived classes that want to save and restore their own
17940     * state in {@link android.view.View#onSaveInstanceState()}.
17941     */
17942    public static class BaseSavedState extends AbsSavedState {
17943        /**
17944         * Constructor used when reading from a parcel. Reads the state of the superclass.
17945         *
17946         * @param source
17947         */
17948        public BaseSavedState(Parcel source) {
17949            super(source);
17950        }
17951
17952        /**
17953         * Constructor called by derived classes when creating their SavedState objects
17954         *
17955         * @param superState The state of the superclass of this view
17956         */
17957        public BaseSavedState(Parcelable superState) {
17958            super(superState);
17959        }
17960
17961        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17962                new Parcelable.Creator<BaseSavedState>() {
17963            public BaseSavedState createFromParcel(Parcel in) {
17964                return new BaseSavedState(in);
17965            }
17966
17967            public BaseSavedState[] newArray(int size) {
17968                return new BaseSavedState[size];
17969            }
17970        };
17971    }
17972
17973    /**
17974     * A set of information given to a view when it is attached to its parent
17975     * window.
17976     */
17977    static class AttachInfo {
17978        interface Callbacks {
17979            void playSoundEffect(int effectId);
17980            boolean performHapticFeedback(int effectId, boolean always);
17981        }
17982
17983        /**
17984         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17985         * to a Handler. This class contains the target (View) to invalidate and
17986         * the coordinates of the dirty rectangle.
17987         *
17988         * For performance purposes, this class also implements a pool of up to
17989         * POOL_LIMIT objects that get reused. This reduces memory allocations
17990         * whenever possible.
17991         */
17992        static class InvalidateInfo {
17993            private static final int POOL_LIMIT = 10;
17994
17995            private static final SynchronizedPool<InvalidateInfo> sPool =
17996                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
17997
17998            View target;
17999
18000            int left;
18001            int top;
18002            int right;
18003            int bottom;
18004
18005            public static InvalidateInfo obtain() {
18006                InvalidateInfo instance = sPool.acquire();
18007                return (instance != null) ? instance : new InvalidateInfo();
18008            }
18009
18010            public void recycle() {
18011                target = null;
18012                sPool.release(this);
18013            }
18014        }
18015
18016        final IWindowSession mSession;
18017
18018        final IWindow mWindow;
18019
18020        final IBinder mWindowToken;
18021
18022        final Display mDisplay;
18023
18024        final Callbacks mRootCallbacks;
18025
18026        HardwareCanvas mHardwareCanvas;
18027
18028        IWindowId mIWindowId;
18029        WindowId mWindowId;
18030
18031        /**
18032         * The top view of the hierarchy.
18033         */
18034        View mRootView;
18035
18036        IBinder mPanelParentWindowToken;
18037        Surface mSurface;
18038
18039        boolean mHardwareAccelerated;
18040        boolean mHardwareAccelerationRequested;
18041        HardwareRenderer mHardwareRenderer;
18042
18043        boolean mScreenOn;
18044
18045        /**
18046         * Scale factor used by the compatibility mode
18047         */
18048        float mApplicationScale;
18049
18050        /**
18051         * Indicates whether the application is in compatibility mode
18052         */
18053        boolean mScalingRequired;
18054
18055        /**
18056         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18057         */
18058        boolean mTurnOffWindowResizeAnim;
18059
18060        /**
18061         * Left position of this view's window
18062         */
18063        int mWindowLeft;
18064
18065        /**
18066         * Top position of this view's window
18067         */
18068        int mWindowTop;
18069
18070        /**
18071         * Indicates whether views need to use 32-bit drawing caches
18072         */
18073        boolean mUse32BitDrawingCache;
18074
18075        /**
18076         * For windows that are full-screen but using insets to layout inside
18077         * of the screen areas, these are the current insets to appear inside
18078         * the overscan area of the display.
18079         */
18080        final Rect mOverscanInsets = new Rect();
18081
18082        /**
18083         * For windows that are full-screen but using insets to layout inside
18084         * of the screen decorations, these are the current insets for the
18085         * content of the window.
18086         */
18087        final Rect mContentInsets = new Rect();
18088
18089        /**
18090         * For windows that are full-screen but using insets to layout inside
18091         * of the screen decorations, these are the current insets for the
18092         * actual visible parts of the window.
18093         */
18094        final Rect mVisibleInsets = new Rect();
18095
18096        /**
18097         * The internal insets given by this window.  This value is
18098         * supplied by the client (through
18099         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18100         * be given to the window manager when changed to be used in laying
18101         * out windows behind it.
18102         */
18103        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18104                = new ViewTreeObserver.InternalInsetsInfo();
18105
18106        /**
18107         * All views in the window's hierarchy that serve as scroll containers,
18108         * used to determine if the window can be resized or must be panned
18109         * to adjust for a soft input area.
18110         */
18111        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18112
18113        final KeyEvent.DispatcherState mKeyDispatchState
18114                = new KeyEvent.DispatcherState();
18115
18116        /**
18117         * Indicates whether the view's window currently has the focus.
18118         */
18119        boolean mHasWindowFocus;
18120
18121        /**
18122         * The current visibility of the window.
18123         */
18124        int mWindowVisibility;
18125
18126        /**
18127         * Indicates the time at which drawing started to occur.
18128         */
18129        long mDrawingTime;
18130
18131        /**
18132         * Indicates whether or not ignoring the DIRTY_MASK flags.
18133         */
18134        boolean mIgnoreDirtyState;
18135
18136        /**
18137         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18138         * to avoid clearing that flag prematurely.
18139         */
18140        boolean mSetIgnoreDirtyState = false;
18141
18142        /**
18143         * Indicates whether the view's window is currently in touch mode.
18144         */
18145        boolean mInTouchMode;
18146
18147        /**
18148         * Indicates that ViewAncestor should trigger a global layout change
18149         * the next time it performs a traversal
18150         */
18151        boolean mRecomputeGlobalAttributes;
18152
18153        /**
18154         * Always report new attributes at next traversal.
18155         */
18156        boolean mForceReportNewAttributes;
18157
18158        /**
18159         * Set during a traveral if any views want to keep the screen on.
18160         */
18161        boolean mKeepScreenOn;
18162
18163        /**
18164         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18165         */
18166        int mSystemUiVisibility;
18167
18168        /**
18169         * Hack to force certain system UI visibility flags to be cleared.
18170         */
18171        int mDisabledSystemUiVisibility;
18172
18173        /**
18174         * Last global system UI visibility reported by the window manager.
18175         */
18176        int mGlobalSystemUiVisibility;
18177
18178        /**
18179         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18180         * attached.
18181         */
18182        boolean mHasSystemUiListeners;
18183
18184        /**
18185         * Set if the window has requested to extend into the overscan region
18186         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18187         */
18188        boolean mOverscanRequested;
18189
18190        /**
18191         * Set if the visibility of any views has changed.
18192         */
18193        boolean mViewVisibilityChanged;
18194
18195        /**
18196         * Set to true if a view has been scrolled.
18197         */
18198        boolean mViewScrollChanged;
18199
18200        /**
18201         * Global to the view hierarchy used as a temporary for dealing with
18202         * x/y points in the transparent region computations.
18203         */
18204        final int[] mTransparentLocation = new int[2];
18205
18206        /**
18207         * Global to the view hierarchy used as a temporary for dealing with
18208         * x/y points in the ViewGroup.invalidateChild implementation.
18209         */
18210        final int[] mInvalidateChildLocation = new int[2];
18211
18212
18213        /**
18214         * Global to the view hierarchy used as a temporary for dealing with
18215         * x/y location when view is transformed.
18216         */
18217        final float[] mTmpTransformLocation = new float[2];
18218
18219        /**
18220         * The view tree observer used to dispatch global events like
18221         * layout, pre-draw, touch mode change, etc.
18222         */
18223        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18224
18225        /**
18226         * A Canvas used by the view hierarchy to perform bitmap caching.
18227         */
18228        Canvas mCanvas;
18229
18230        /**
18231         * The view root impl.
18232         */
18233        final ViewRootImpl mViewRootImpl;
18234
18235        /**
18236         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18237         * handler can be used to pump events in the UI events queue.
18238         */
18239        final Handler mHandler;
18240
18241        /**
18242         * Temporary for use in computing invalidate rectangles while
18243         * calling up the hierarchy.
18244         */
18245        final Rect mTmpInvalRect = new Rect();
18246
18247        /**
18248         * Temporary for use in computing hit areas with transformed views
18249         */
18250        final RectF mTmpTransformRect = new RectF();
18251
18252        /**
18253         * Temporary for use in transforming invalidation rect
18254         */
18255        final Matrix mTmpMatrix = new Matrix();
18256
18257        /**
18258         * Temporary for use in transforming invalidation rect
18259         */
18260        final Transformation mTmpTransformation = new Transformation();
18261
18262        /**
18263         * Temporary list for use in collecting focusable descendents of a view.
18264         */
18265        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18266
18267        /**
18268         * The id of the window for accessibility purposes.
18269         */
18270        int mAccessibilityWindowId = View.NO_ID;
18271
18272        /**
18273         * Flags related to accessibility processing.
18274         *
18275         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18276         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18277         */
18278        int mAccessibilityFetchFlags;
18279
18280        /**
18281         * The drawable for highlighting accessibility focus.
18282         */
18283        Drawable mAccessibilityFocusDrawable;
18284
18285        /**
18286         * Show where the margins, bounds and layout bounds are for each view.
18287         */
18288        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18289
18290        /**
18291         * Point used to compute visible regions.
18292         */
18293        final Point mPoint = new Point();
18294
18295        /**
18296         * Used to track which View originated a requestLayout() call, used when
18297         * requestLayout() is called during layout.
18298         */
18299        View mViewRequestingLayout;
18300
18301        /**
18302         * Creates a new set of attachment information with the specified
18303         * events handler and thread.
18304         *
18305         * @param handler the events handler the view must use
18306         */
18307        AttachInfo(IWindowSession session, IWindow window, Display display,
18308                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18309            mSession = session;
18310            mWindow = window;
18311            mWindowToken = window.asBinder();
18312            mDisplay = display;
18313            mViewRootImpl = viewRootImpl;
18314            mHandler = handler;
18315            mRootCallbacks = effectPlayer;
18316        }
18317    }
18318
18319    /**
18320     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18321     * is supported. This avoids keeping too many unused fields in most
18322     * instances of View.</p>
18323     */
18324    private static class ScrollabilityCache implements Runnable {
18325
18326        /**
18327         * Scrollbars are not visible
18328         */
18329        public static final int OFF = 0;
18330
18331        /**
18332         * Scrollbars are visible
18333         */
18334        public static final int ON = 1;
18335
18336        /**
18337         * Scrollbars are fading away
18338         */
18339        public static final int FADING = 2;
18340
18341        public boolean fadeScrollBars;
18342
18343        public int fadingEdgeLength;
18344        public int scrollBarDefaultDelayBeforeFade;
18345        public int scrollBarFadeDuration;
18346
18347        public int scrollBarSize;
18348        public ScrollBarDrawable scrollBar;
18349        public float[] interpolatorValues;
18350        public View host;
18351
18352        public final Paint paint;
18353        public final Matrix matrix;
18354        public Shader shader;
18355
18356        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18357
18358        private static final float[] OPAQUE = { 255 };
18359        private static final float[] TRANSPARENT = { 0.0f };
18360
18361        /**
18362         * When fading should start. This time moves into the future every time
18363         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18364         */
18365        public long fadeStartTime;
18366
18367
18368        /**
18369         * The current state of the scrollbars: ON, OFF, or FADING
18370         */
18371        public int state = OFF;
18372
18373        private int mLastColor;
18374
18375        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18376            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18377            scrollBarSize = configuration.getScaledScrollBarSize();
18378            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18379            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18380
18381            paint = new Paint();
18382            matrix = new Matrix();
18383            // use use a height of 1, and then wack the matrix each time we
18384            // actually use it.
18385            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18386            paint.setShader(shader);
18387            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18388
18389            this.host = host;
18390        }
18391
18392        public void setFadeColor(int color) {
18393            if (color != mLastColor) {
18394                mLastColor = color;
18395
18396                if (color != 0) {
18397                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18398                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18399                    paint.setShader(shader);
18400                    // Restore the default transfer mode (src_over)
18401                    paint.setXfermode(null);
18402                } else {
18403                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18404                    paint.setShader(shader);
18405                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18406                }
18407            }
18408        }
18409
18410        public void run() {
18411            long now = AnimationUtils.currentAnimationTimeMillis();
18412            if (now >= fadeStartTime) {
18413
18414                // the animation fades the scrollbars out by changing
18415                // the opacity (alpha) from fully opaque to fully
18416                // transparent
18417                int nextFrame = (int) now;
18418                int framesCount = 0;
18419
18420                Interpolator interpolator = scrollBarInterpolator;
18421
18422                // Start opaque
18423                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18424
18425                // End transparent
18426                nextFrame += scrollBarFadeDuration;
18427                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18428
18429                state = FADING;
18430
18431                // Kick off the fade animation
18432                host.invalidate(true);
18433            }
18434        }
18435    }
18436
18437    /**
18438     * Resuable callback for sending
18439     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18440     */
18441    private class SendViewScrolledAccessibilityEvent implements Runnable {
18442        public volatile boolean mIsPending;
18443
18444        public void run() {
18445            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18446            mIsPending = false;
18447        }
18448    }
18449
18450    /**
18451     * <p>
18452     * This class represents a delegate that can be registered in a {@link View}
18453     * to enhance accessibility support via composition rather via inheritance.
18454     * It is specifically targeted to widget developers that extend basic View
18455     * classes i.e. classes in package android.view, that would like their
18456     * applications to be backwards compatible.
18457     * </p>
18458     * <div class="special reference">
18459     * <h3>Developer Guides</h3>
18460     * <p>For more information about making applications accessible, read the
18461     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18462     * developer guide.</p>
18463     * </div>
18464     * <p>
18465     * A scenario in which a developer would like to use an accessibility delegate
18466     * is overriding a method introduced in a later API version then the minimal API
18467     * version supported by the application. For example, the method
18468     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18469     * in API version 4 when the accessibility APIs were first introduced. If a
18470     * developer would like his application to run on API version 4 devices (assuming
18471     * all other APIs used by the application are version 4 or lower) and take advantage
18472     * of this method, instead of overriding the method which would break the application's
18473     * backwards compatibility, he can override the corresponding method in this
18474     * delegate and register the delegate in the target View if the API version of
18475     * the system is high enough i.e. the API version is same or higher to the API
18476     * version that introduced
18477     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18478     * </p>
18479     * <p>
18480     * Here is an example implementation:
18481     * </p>
18482     * <code><pre><p>
18483     * if (Build.VERSION.SDK_INT >= 14) {
18484     *     // If the API version is equal of higher than the version in
18485     *     // which onInitializeAccessibilityNodeInfo was introduced we
18486     *     // register a delegate with a customized implementation.
18487     *     View view = findViewById(R.id.view_id);
18488     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18489     *         public void onInitializeAccessibilityNodeInfo(View host,
18490     *                 AccessibilityNodeInfo info) {
18491     *             // Let the default implementation populate the info.
18492     *             super.onInitializeAccessibilityNodeInfo(host, info);
18493     *             // Set some other information.
18494     *             info.setEnabled(host.isEnabled());
18495     *         }
18496     *     });
18497     * }
18498     * </code></pre></p>
18499     * <p>
18500     * This delegate contains methods that correspond to the accessibility methods
18501     * in View. If a delegate has been specified the implementation in View hands
18502     * off handling to the corresponding method in this delegate. The default
18503     * implementation the delegate methods behaves exactly as the corresponding
18504     * method in View for the case of no accessibility delegate been set. Hence,
18505     * to customize the behavior of a View method, clients can override only the
18506     * corresponding delegate method without altering the behavior of the rest
18507     * accessibility related methods of the host view.
18508     * </p>
18509     */
18510    public static class AccessibilityDelegate {
18511
18512        /**
18513         * Sends an accessibility event of the given type. If accessibility is not
18514         * enabled this method has no effect.
18515         * <p>
18516         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18517         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18518         * been set.
18519         * </p>
18520         *
18521         * @param host The View hosting the delegate.
18522         * @param eventType The type of the event to send.
18523         *
18524         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18525         */
18526        public void sendAccessibilityEvent(View host, int eventType) {
18527            host.sendAccessibilityEventInternal(eventType);
18528        }
18529
18530        /**
18531         * Performs the specified accessibility action on the view. For
18532         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18533         * <p>
18534         * The default implementation behaves as
18535         * {@link View#performAccessibilityAction(int, Bundle)
18536         *  View#performAccessibilityAction(int, Bundle)} for the case of
18537         *  no accessibility delegate been set.
18538         * </p>
18539         *
18540         * @param action The action to perform.
18541         * @return Whether the action was performed.
18542         *
18543         * @see View#performAccessibilityAction(int, Bundle)
18544         *      View#performAccessibilityAction(int, Bundle)
18545         */
18546        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18547            return host.performAccessibilityActionInternal(action, args);
18548        }
18549
18550        /**
18551         * Sends an accessibility event. This method behaves exactly as
18552         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18553         * empty {@link AccessibilityEvent} and does not perform a check whether
18554         * accessibility is enabled.
18555         * <p>
18556         * The default implementation behaves as
18557         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18558         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18559         * the case of no accessibility delegate been set.
18560         * </p>
18561         *
18562         * @param host The View hosting the delegate.
18563         * @param event The event to send.
18564         *
18565         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18566         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18567         */
18568        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18569            host.sendAccessibilityEventUncheckedInternal(event);
18570        }
18571
18572        /**
18573         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18574         * to its children for adding their text content to the event.
18575         * <p>
18576         * The default implementation behaves as
18577         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18578         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18579         * the case of no accessibility delegate been set.
18580         * </p>
18581         *
18582         * @param host The View hosting the delegate.
18583         * @param event The event.
18584         * @return True if the event population was completed.
18585         *
18586         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18587         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18588         */
18589        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18590            return host.dispatchPopulateAccessibilityEventInternal(event);
18591        }
18592
18593        /**
18594         * Gives a chance to the host View to populate the accessibility event with its
18595         * text content.
18596         * <p>
18597         * The default implementation behaves as
18598         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18599         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18600         * the case of no accessibility delegate been set.
18601         * </p>
18602         *
18603         * @param host The View hosting the delegate.
18604         * @param event The accessibility event which to populate.
18605         *
18606         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18607         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18608         */
18609        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18610            host.onPopulateAccessibilityEventInternal(event);
18611        }
18612
18613        /**
18614         * Initializes an {@link AccessibilityEvent} with information about the
18615         * the host View which is the event source.
18616         * <p>
18617         * The default implementation behaves as
18618         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18619         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18620         * the case of no accessibility delegate been set.
18621         * </p>
18622         *
18623         * @param host The View hosting the delegate.
18624         * @param event The event to initialize.
18625         *
18626         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18627         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18628         */
18629        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18630            host.onInitializeAccessibilityEventInternal(event);
18631        }
18632
18633        /**
18634         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18635         * <p>
18636         * The default implementation behaves as
18637         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18638         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18639         * the case of no accessibility delegate been set.
18640         * </p>
18641         *
18642         * @param host The View hosting the delegate.
18643         * @param info The instance to initialize.
18644         *
18645         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18646         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18647         */
18648        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18649            host.onInitializeAccessibilityNodeInfoInternal(info);
18650        }
18651
18652        /**
18653         * Called when a child of the host View has requested sending an
18654         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18655         * to augment the event.
18656         * <p>
18657         * The default implementation behaves as
18658         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18659         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18660         * the case of no accessibility delegate been set.
18661         * </p>
18662         *
18663         * @param host The View hosting the delegate.
18664         * @param child The child which requests sending the event.
18665         * @param event The event to be sent.
18666         * @return True if the event should be sent
18667         *
18668         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18669         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18670         */
18671        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18672                AccessibilityEvent event) {
18673            return host.onRequestSendAccessibilityEventInternal(child, event);
18674        }
18675
18676        /**
18677         * Gets the provider for managing a virtual view hierarchy rooted at this View
18678         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18679         * that explore the window content.
18680         * <p>
18681         * The default implementation behaves as
18682         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18683         * the case of no accessibility delegate been set.
18684         * </p>
18685         *
18686         * @return The provider.
18687         *
18688         * @see AccessibilityNodeProvider
18689         */
18690        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18691            return null;
18692        }
18693    }
18694
18695    private class MatchIdPredicate implements Predicate<View> {
18696        public int mId;
18697
18698        @Override
18699        public boolean apply(View view) {
18700            return (view.mID == mId);
18701        }
18702    }
18703
18704    private class MatchLabelForPredicate implements Predicate<View> {
18705        private int mLabeledId;
18706
18707        @Override
18708        public boolean apply(View view) {
18709            return (view.mLabelForId == mLabeledId);
18710        }
18711    }
18712
18713    /**
18714     * Dump all private flags in readable format, useful for documentation and
18715     * sanity checking.
18716     */
18717    private static void dumpFlags() {
18718        final HashMap<String, String> found = Maps.newHashMap();
18719        try {
18720            for (Field field : View.class.getDeclaredFields()) {
18721                final int modifiers = field.getModifiers();
18722                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18723                    if (field.getType().equals(int.class)) {
18724                        final int value = field.getInt(null);
18725                        dumpFlag(found, field.getName(), value);
18726                    } else if (field.getType().equals(int[].class)) {
18727                        final int[] values = (int[]) field.get(null);
18728                        for (int i = 0; i < values.length; i++) {
18729                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18730                        }
18731                    }
18732                }
18733            }
18734        } catch (IllegalAccessException e) {
18735            throw new RuntimeException(e);
18736        }
18737
18738        final ArrayList<String> keys = Lists.newArrayList();
18739        keys.addAll(found.keySet());
18740        Collections.sort(keys);
18741        for (String key : keys) {
18742            Log.d(VIEW_LOG_TAG, found.get(key));
18743        }
18744    }
18745
18746    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18747        // Sort flags by prefix, then by bits, always keeping unique keys
18748        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18749        final int prefix = name.indexOf('_');
18750        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18751        final String output = bits + " " + name;
18752        found.put(key, output);
18753    }
18754}
18755