View.java revision 2f87014ea2f177e715032b07004d05e2549a63a8
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.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.text.TextUtils;
51import android.util.AttributeSet;
52import android.util.FloatProperty;
53import android.util.LocaleUtil;
54import android.util.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.Property;
60import android.util.SparseArray;
61import android.util.TypedValue;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.accessibility.AccessibilityEvent;
64import android.view.accessibility.AccessibilityEventSource;
65import android.view.accessibility.AccessibilityManager;
66import android.view.accessibility.AccessibilityNodeInfo;
67import android.view.accessibility.AccessibilityNodeProvider;
68import android.view.animation.Animation;
69import android.view.animation.AnimationUtils;
70import android.view.animation.Transformation;
71import android.view.inputmethod.EditorInfo;
72import android.view.inputmethod.InputConnection;
73import android.view.inputmethod.InputMethodManager;
74import android.widget.ScrollBarDrawable;
75
76import static android.os.Build.VERSION_CODES.*;
77import static java.lang.Math.max;
78
79import com.android.internal.R;
80import com.android.internal.util.Predicate;
81import com.android.internal.view.menu.MenuBuilder;
82
83import java.lang.ref.WeakReference;
84import java.lang.reflect.InvocationTargetException;
85import java.lang.reflect.Method;
86import java.util.ArrayList;
87import java.util.Arrays;
88import java.util.Locale;
89import java.util.concurrent.CopyOnWriteArrayList;
90
91/**
92 * <p>
93 * This class represents the basic building block for user interface components. A View
94 * occupies a rectangular area on the screen and is responsible for drawing and
95 * event handling. View is the base class for <em>widgets</em>, which are
96 * used to create interactive UI components (buttons, text fields, etc.). The
97 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
98 * are invisible containers that hold other Views (or other ViewGroups) and define
99 * their layout properties.
100 * </p>
101 *
102 * <div class="special reference">
103 * <h3>Developer Guides</h3>
104 * <p>For information about using this class to develop your application's user interface,
105 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
106 * </div>
107 *
108 * <a name="Using"></a>
109 * <h3>Using Views</h3>
110 * <p>
111 * All of the views in a window are arranged in a single tree. You can add views
112 * either from code or by specifying a tree of views in one or more XML layout
113 * files. There are many specialized subclasses of views that act as controls or
114 * are capable of displaying text, images, or other content.
115 * </p>
116 * <p>
117 * Once you have created a tree of views, there are typically a few types of
118 * common operations you may wish to perform:
119 * <ul>
120 * <li><strong>Set properties:</strong> for example setting the text of a
121 * {@link android.widget.TextView}. The available properties and the methods
122 * that set them will vary among the different subclasses of views. Note that
123 * properties that are known at build time can be set in the XML layout
124 * files.</li>
125 * <li><strong>Set focus:</strong> The framework will handled moving focus in
126 * response to user input. To force focus to a specific view, call
127 * {@link #requestFocus}.</li>
128 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
129 * that will be notified when something interesting happens to the view. For
130 * example, all views will let you set a listener to be notified when the view
131 * gains or loses focus. You can register such a listener using
132 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
133 * Other view subclasses offer more specialized listeners. For example, a Button
134 * exposes a listener to notify clients when the button is clicked.</li>
135 * <li><strong>Set visibility:</strong> You can hide or show views using
136 * {@link #setVisibility(int)}.</li>
137 * </ul>
138 * </p>
139 * <p><em>
140 * Note: The Android framework is responsible for measuring, laying out and
141 * drawing views. You should not call methods that perform these actions on
142 * views yourself unless you are actually implementing a
143 * {@link android.view.ViewGroup}.
144 * </em></p>
145 *
146 * <a name="Lifecycle"></a>
147 * <h3>Implementing a Custom View</h3>
148 *
149 * <p>
150 * To implement a custom view, you will usually begin by providing overrides for
151 * some of the standard methods that the framework calls on all views. You do
152 * not need to override all of these methods. In fact, you can start by just
153 * overriding {@link #onDraw(android.graphics.Canvas)}.
154 * <table border="2" width="85%" align="center" cellpadding="5">
155 *     <thead>
156 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
157 *     </thead>
158 *
159 *     <tbody>
160 *     <tr>
161 *         <td rowspan="2">Creation</td>
162 *         <td>Constructors</td>
163 *         <td>There is a form of the constructor that are called when the view
164 *         is created from code and a form that is called when the view is
165 *         inflated from a layout file. The second form should parse and apply
166 *         any attributes defined in the layout file.
167 *         </td>
168 *     </tr>
169 *     <tr>
170 *         <td><code>{@link #onFinishInflate()}</code></td>
171 *         <td>Called after a view and all of its children has been inflated
172 *         from XML.</td>
173 *     </tr>
174 *
175 *     <tr>
176 *         <td rowspan="3">Layout</td>
177 *         <td><code>{@link #onMeasure(int, int)}</code></td>
178 *         <td>Called to determine the size requirements for this view and all
179 *         of its children.
180 *         </td>
181 *     </tr>
182 *     <tr>
183 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
184 *         <td>Called when this view should assign a size and position to all
185 *         of its children.
186 *         </td>
187 *     </tr>
188 *     <tr>
189 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
190 *         <td>Called when the size of this view has changed.
191 *         </td>
192 *     </tr>
193 *
194 *     <tr>
195 *         <td>Drawing</td>
196 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
197 *         <td>Called when the view should render its content.
198 *         </td>
199 *     </tr>
200 *
201 *     <tr>
202 *         <td rowspan="4">Event processing</td>
203 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
204 *         <td>Called when a new key event occurs.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
209 *         <td>Called when a key up event occurs.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
214 *         <td>Called when a trackball motion event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
219 *         <td>Called when a touch screen motion event occurs.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="2">Focus</td>
225 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
226 *         <td>Called when the view gains or loses focus.
227 *         </td>
228 *     </tr>
229 *
230 *     <tr>
231 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
232 *         <td>Called when the window containing the view gains or loses focus.
233 *         </td>
234 *     </tr>
235 *
236 *     <tr>
237 *         <td rowspan="3">Attaching</td>
238 *         <td><code>{@link #onAttachedToWindow()}</code></td>
239 *         <td>Called when the view is attached to a window.
240 *         </td>
241 *     </tr>
242 *
243 *     <tr>
244 *         <td><code>{@link #onDetachedFromWindow}</code></td>
245 *         <td>Called when the view is detached from its window.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
251 *         <td>Called when the visibility of the window containing the view
252 *         has changed.
253 *         </td>
254 *     </tr>
255 *     </tbody>
256 *
257 * </table>
258 * </p>
259 *
260 * <a name="IDs"></a>
261 * <h3>IDs</h3>
262 * Views may have an integer id associated with them. These ids are typically
263 * assigned in the layout XML files, and are used to find specific views within
264 * the view tree. A common pattern is to:
265 * <ul>
266 * <li>Define a Button in the layout file and assign it a unique ID.
267 * <pre>
268 * &lt;Button
269 *     android:id="@+id/my_button"
270 *     android:layout_width="wrap_content"
271 *     android:layout_height="wrap_content"
272 *     android:text="@string/my_button_text"/&gt;
273 * </pre></li>
274 * <li>From the onCreate method of an Activity, find the Button
275 * <pre class="prettyprint">
276 *      Button myButton = (Button) findViewById(R.id.my_button);
277 * </pre></li>
278 * </ul>
279 * <p>
280 * View IDs need not be unique throughout the tree, but it is good practice to
281 * ensure that they are at least unique within the part of the tree you are
282 * searching.
283 * </p>
284 *
285 * <a name="Position"></a>
286 * <h3>Position</h3>
287 * <p>
288 * The geometry of a view is that of a rectangle. A view has a location,
289 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
290 * two dimensions, expressed as a width and a height. The unit for location
291 * and dimensions is the pixel.
292 * </p>
293 *
294 * <p>
295 * It is possible to retrieve the location of a view by invoking the methods
296 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
297 * coordinate of the rectangle representing the view. The latter returns the
298 * top, or Y, coordinate of the rectangle representing the view. These methods
299 * both return the location of the view relative to its parent. For instance,
300 * when getLeft() returns 20, that means the view is located 20 pixels to the
301 * right of the left edge of its direct parent.
302 * </p>
303 *
304 * <p>
305 * In addition, several convenience methods are offered to avoid unnecessary
306 * computations, namely {@link #getRight()} and {@link #getBottom()}.
307 * These methods return the coordinates of the right and bottom edges of the
308 * rectangle representing the view. For instance, calling {@link #getRight()}
309 * is similar to the following computation: <code>getLeft() + getWidth()</code>
310 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
311 * </p>
312 *
313 * <a name="SizePaddingMargins"></a>
314 * <h3>Size, padding and margins</h3>
315 * <p>
316 * The size of a view is expressed with a width and a height. A view actually
317 * possess two pairs of width and height values.
318 * </p>
319 *
320 * <p>
321 * The first pair is known as <em>measured width</em> and
322 * <em>measured height</em>. These dimensions define how big a view wants to be
323 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
324 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
325 * and {@link #getMeasuredHeight()}.
326 * </p>
327 *
328 * <p>
329 * The second pair is simply known as <em>width</em> and <em>height</em>, or
330 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
331 * dimensions define the actual size of the view on screen, at drawing time and
332 * after layout. These values may, but do not have to, be different from the
333 * measured width and height. The width and height can be obtained by calling
334 * {@link #getWidth()} and {@link #getHeight()}.
335 * </p>
336 *
337 * <p>
338 * To measure its dimensions, a view takes into account its padding. The padding
339 * is expressed in pixels for the left, top, right and bottom parts of the view.
340 * Padding can be used to offset the content of the view by a specific amount of
341 * pixels. For instance, a left padding of 2 will push the view's content by
342 * 2 pixels to the right of the left edge. Padding can be set using the
343 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
344 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
345 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
346 * {@link #getPaddingEnd()}.
347 * </p>
348 *
349 * <p>
350 * Even though a view can define a padding, it does not provide any support for
351 * margins. However, view groups provide such a support. Refer to
352 * {@link android.view.ViewGroup} and
353 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
354 * </p>
355 *
356 * <a name="Layout"></a>
357 * <h3>Layout</h3>
358 * <p>
359 * Layout is a two pass process: a measure pass and a layout pass. The measuring
360 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
361 * of the view tree. Each view pushes dimension specifications down the tree
362 * during the recursion. At the end of the measure pass, every view has stored
363 * its measurements. The second pass happens in
364 * {@link #layout(int,int,int,int)} and is also top-down. During
365 * this pass each parent is responsible for positioning all of its children
366 * using the sizes computed in the measure pass.
367 * </p>
368 *
369 * <p>
370 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
371 * {@link #getMeasuredHeight()} values must be set, along with those for all of
372 * that view's descendants. A view's measured width and measured height values
373 * must respect the constraints imposed by the view's parents. This guarantees
374 * that at the end of the measure pass, all parents accept all of their
375 * children's measurements. A parent view may call measure() more than once on
376 * its children. For example, the parent may measure each child once with
377 * unspecified dimensions to find out how big they want to be, then call
378 * measure() on them again with actual numbers if the sum of all the children's
379 * unconstrained sizes is too big or too small.
380 * </p>
381 *
382 * <p>
383 * The measure pass uses two classes to communicate dimensions. The
384 * {@link MeasureSpec} class is used by views to tell their parents how they
385 * want to be measured and positioned. The base LayoutParams class just
386 * describes how big the view wants to be for both width and height. For each
387 * dimension, it can specify one of:
388 * <ul>
389 * <li> an exact number
390 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
391 * (minus padding)
392 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
393 * enclose its content (plus padding).
394 * </ul>
395 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
396 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
397 * an X and Y value.
398 * </p>
399 *
400 * <p>
401 * MeasureSpecs are used to push requirements down the tree from parent to
402 * child. A MeasureSpec can be in one of three modes:
403 * <ul>
404 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
405 * of a child view. For example, a LinearLayout may call measure() on its child
406 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
407 * tall the child view wants to be given a width of 240 pixels.
408 * <li>EXACTLY: This is used by the parent to impose an exact size on the
409 * child. The child must use this size, and guarantee that all of its
410 * descendants will fit within this size.
411 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
412 * child. The child must gurantee that it and all of its descendants will fit
413 * within this size.
414 * </ul>
415 * </p>
416 *
417 * <p>
418 * To intiate a layout, call {@link #requestLayout}. This method is typically
419 * called by a view on itself when it believes that is can no longer fit within
420 * its current bounds.
421 * </p>
422 *
423 * <a name="Drawing"></a>
424 * <h3>Drawing</h3>
425 * <p>
426 * Drawing is handled by walking the tree and rendering each view that
427 * intersects the invalid region. Because the tree is traversed in-order,
428 * this means that parents will draw before (i.e., behind) their children, with
429 * siblings drawn in the order they appear in the tree.
430 * If you set a background drawable for a View, then the View will draw it for you
431 * before calling back to its <code>onDraw()</code> method.
432 * </p>
433 *
434 * <p>
435 * Note that the framework will not draw views that are not in the invalid region.
436 * </p>
437 *
438 * <p>
439 * To force a view to draw, call {@link #invalidate()}.
440 * </p>
441 *
442 * <a name="EventHandlingThreading"></a>
443 * <h3>Event Handling and Threading</h3>
444 * <p>
445 * The basic cycle of a view is as follows:
446 * <ol>
447 * <li>An event comes in and is dispatched to the appropriate view. The view
448 * handles the event and notifies any listeners.</li>
449 * <li>If in the course of processing the event, the view's bounds may need
450 * to be changed, the view will call {@link #requestLayout()}.</li>
451 * <li>Similarly, if in the course of processing the event the view's appearance
452 * may need to be changed, the view will call {@link #invalidate()}.</li>
453 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
454 * the framework will take care of measuring, laying out, and drawing the tree
455 * as appropriate.</li>
456 * </ol>
457 * </p>
458 *
459 * <p><em>Note: The entire view tree is single threaded. You must always be on
460 * the UI thread when calling any method on any view.</em>
461 * If you are doing work on other threads and want to update the state of a view
462 * from that thread, you should use a {@link Handler}.
463 * </p>
464 *
465 * <a name="FocusHandling"></a>
466 * <h3>Focus Handling</h3>
467 * <p>
468 * The framework will handle routine focus movement in response to user input.
469 * This includes changing the focus as views are removed or hidden, or as new
470 * views become available. Views indicate their willingness to take focus
471 * through the {@link #isFocusable} method. To change whether a view can take
472 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
473 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
474 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
475 * </p>
476 * <p>
477 * Focus movement is based on an algorithm which finds the nearest neighbor in a
478 * given direction. In rare cases, the default algorithm may not match the
479 * intended behavior of the developer. In these situations, you can provide
480 * explicit overrides by using these XML attributes in the layout file:
481 * <pre>
482 * nextFocusDown
483 * nextFocusLeft
484 * nextFocusRight
485 * nextFocusUp
486 * </pre>
487 * </p>
488 *
489 *
490 * <p>
491 * To get a particular view to take focus, call {@link #requestFocus()}.
492 * </p>
493 *
494 * <a name="TouchMode"></a>
495 * <h3>Touch Mode</h3>
496 * <p>
497 * When a user is navigating a user interface via directional keys such as a D-pad, it is
498 * necessary to give focus to actionable items such as buttons so the user can see
499 * what will take input.  If the device has touch capabilities, however, and the user
500 * begins interacting with the interface by touching it, it is no longer necessary to
501 * always highlight, or give focus to, a particular view.  This motivates a mode
502 * for interaction named 'touch mode'.
503 * </p>
504 * <p>
505 * For a touch capable device, once the user touches the screen, the device
506 * will enter touch mode.  From this point onward, only views for which
507 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
508 * Other views that are touchable, like buttons, will not take focus when touched; they will
509 * only fire the on click listeners.
510 * </p>
511 * <p>
512 * Any time a user hits a directional key, such as a D-pad direction, the view device will
513 * exit touch mode, and find a view to take focus, so that the user may resume interacting
514 * with the user interface without touching the screen again.
515 * </p>
516 * <p>
517 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
518 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
519 * </p>
520 *
521 * <a name="Scrolling"></a>
522 * <h3>Scrolling</h3>
523 * <p>
524 * The framework provides basic support for views that wish to internally
525 * scroll their content. This includes keeping track of the X and Y scroll
526 * offset as well as mechanisms for drawing scrollbars. See
527 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
528 * {@link #awakenScrollBars()} for more details.
529 * </p>
530 *
531 * <a name="Tags"></a>
532 * <h3>Tags</h3>
533 * <p>
534 * Unlike IDs, tags are not used to identify views. Tags are essentially an
535 * extra piece of information that can be associated with a view. They are most
536 * often used as a convenience to store data related to views in the views
537 * themselves rather than by putting them in a separate structure.
538 * </p>
539 *
540 * <a name="Animation"></a>
541 * <h3>Animation</h3>
542 * <p>
543 * You can attach an {@link Animation} object to a view using
544 * {@link #setAnimation(Animation)} or
545 * {@link #startAnimation(Animation)}. The animation can alter the scale,
546 * rotation, translation and alpha of a view over time. If the animation is
547 * attached to a view that has children, the animation will affect the entire
548 * subtree rooted by that node. When an animation is started, the framework will
549 * take care of redrawing the appropriate views until the animation completes.
550 * </p>
551 * <p>
552 * Starting with Android 3.0, the preferred way of animating views is to use the
553 * {@link android.animation} package APIs.
554 * </p>
555 *
556 * <a name="Security"></a>
557 * <h3>Security</h3>
558 * <p>
559 * Sometimes it is essential that an application be able to verify that an action
560 * is being performed with the full knowledge and consent of the user, such as
561 * granting a permission request, making a purchase or clicking on an advertisement.
562 * Unfortunately, a malicious application could try to spoof the user into
563 * performing these actions, unaware, by concealing the intended purpose of the view.
564 * As a remedy, the framework offers a touch filtering mechanism that can be used to
565 * improve the security of views that provide access to sensitive functionality.
566 * </p><p>
567 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
568 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
569 * will discard touches that are received whenever the view's window is obscured by
570 * another visible window.  As a result, the view will not receive touches whenever a
571 * toast, dialog or other window appears above the view's window.
572 * </p><p>
573 * For more fine-grained control over security, consider overriding the
574 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
575 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
576 * </p>
577 *
578 * @attr ref android.R.styleable#View_alpha
579 * @attr ref android.R.styleable#View_background
580 * @attr ref android.R.styleable#View_clickable
581 * @attr ref android.R.styleable#View_contentDescription
582 * @attr ref android.R.styleable#View_drawingCacheQuality
583 * @attr ref android.R.styleable#View_duplicateParentState
584 * @attr ref android.R.styleable#View_id
585 * @attr ref android.R.styleable#View_requiresFadingEdge
586 * @attr ref android.R.styleable#View_fadeScrollbars
587 * @attr ref android.R.styleable#View_fadingEdgeLength
588 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
589 * @attr ref android.R.styleable#View_fitsSystemWindows
590 * @attr ref android.R.styleable#View_isScrollContainer
591 * @attr ref android.R.styleable#View_focusable
592 * @attr ref android.R.styleable#View_focusableInTouchMode
593 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
594 * @attr ref android.R.styleable#View_keepScreenOn
595 * @attr ref android.R.styleable#View_layerType
596 * @attr ref android.R.styleable#View_longClickable
597 * @attr ref android.R.styleable#View_minHeight
598 * @attr ref android.R.styleable#View_minWidth
599 * @attr ref android.R.styleable#View_nextFocusDown
600 * @attr ref android.R.styleable#View_nextFocusLeft
601 * @attr ref android.R.styleable#View_nextFocusRight
602 * @attr ref android.R.styleable#View_nextFocusUp
603 * @attr ref android.R.styleable#View_onClick
604 * @attr ref android.R.styleable#View_padding
605 * @attr ref android.R.styleable#View_paddingBottom
606 * @attr ref android.R.styleable#View_paddingLeft
607 * @attr ref android.R.styleable#View_paddingRight
608 * @attr ref android.R.styleable#View_paddingTop
609 * @attr ref android.R.styleable#View_paddingStart
610 * @attr ref android.R.styleable#View_paddingEnd
611 * @attr ref android.R.styleable#View_saveEnabled
612 * @attr ref android.R.styleable#View_rotation
613 * @attr ref android.R.styleable#View_rotationX
614 * @attr ref android.R.styleable#View_rotationY
615 * @attr ref android.R.styleable#View_scaleX
616 * @attr ref android.R.styleable#View_scaleY
617 * @attr ref android.R.styleable#View_scrollX
618 * @attr ref android.R.styleable#View_scrollY
619 * @attr ref android.R.styleable#View_scrollbarSize
620 * @attr ref android.R.styleable#View_scrollbarStyle
621 * @attr ref android.R.styleable#View_scrollbars
622 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
623 * @attr ref android.R.styleable#View_scrollbarFadeDuration
624 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
625 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
626 * @attr ref android.R.styleable#View_scrollbarThumbVertical
627 * @attr ref android.R.styleable#View_scrollbarTrackVertical
628 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
629 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
630 * @attr ref android.R.styleable#View_soundEffectsEnabled
631 * @attr ref android.R.styleable#View_tag
632 * @attr ref android.R.styleable#View_textAlignment
633 * @attr ref android.R.styleable#View_transformPivotX
634 * @attr ref android.R.styleable#View_transformPivotY
635 * @attr ref android.R.styleable#View_translationX
636 * @attr ref android.R.styleable#View_translationY
637 * @attr ref android.R.styleable#View_visibility
638 *
639 * @see android.view.ViewGroup
640 */
641public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
642        AccessibilityEventSource {
643    private static final boolean DBG = false;
644
645    /**
646     * The logging tag used by this class with android.util.Log.
647     */
648    protected static final String VIEW_LOG_TAG = "View";
649
650    /**
651     * When set to true, apps will draw debugging information about their layouts.
652     *
653     * @hide
654     */
655    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
656
657    /**
658     * Used to mark a View that has no ID.
659     */
660    public static final int NO_ID = -1;
661
662    /**
663     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
664     * calling setFlags.
665     */
666    private static final int NOT_FOCUSABLE = 0x00000000;
667
668    /**
669     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
670     * setFlags.
671     */
672    private static final int FOCUSABLE = 0x00000001;
673
674    /**
675     * Mask for use with setFlags indicating bits used for focus.
676     */
677    private static final int FOCUSABLE_MASK = 0x00000001;
678
679    /**
680     * This view will adjust its padding to fit sytem windows (e.g. status bar)
681     */
682    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
683
684    /**
685     * This view is visible.
686     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
687     * android:visibility}.
688     */
689    public static final int VISIBLE = 0x00000000;
690
691    /**
692     * This view is invisible, but it still takes up space for layout purposes.
693     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
694     * android:visibility}.
695     */
696    public static final int INVISIBLE = 0x00000004;
697
698    /**
699     * This view is invisible, and it doesn't take any space for layout
700     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
701     * android:visibility}.
702     */
703    public static final int GONE = 0x00000008;
704
705    /**
706     * Mask for use with setFlags indicating bits used for visibility.
707     * {@hide}
708     */
709    static final int VISIBILITY_MASK = 0x0000000C;
710
711    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
712
713    /**
714     * This view is enabled. Interpretation varies by subclass.
715     * Use with ENABLED_MASK when calling setFlags.
716     * {@hide}
717     */
718    static final int ENABLED = 0x00000000;
719
720    /**
721     * This view is disabled. Interpretation varies by subclass.
722     * Use with ENABLED_MASK when calling setFlags.
723     * {@hide}
724     */
725    static final int DISABLED = 0x00000020;
726
727   /**
728    * Mask for use with setFlags indicating bits used for indicating whether
729    * this view is enabled
730    * {@hide}
731    */
732    static final int ENABLED_MASK = 0x00000020;
733
734    /**
735     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
736     * called and further optimizations will be performed. It is okay to have
737     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
738     * {@hide}
739     */
740    static final int WILL_NOT_DRAW = 0x00000080;
741
742    /**
743     * Mask for use with setFlags indicating bits used for indicating whether
744     * this view is will draw
745     * {@hide}
746     */
747    static final int DRAW_MASK = 0x00000080;
748
749    /**
750     * <p>This view doesn't show scrollbars.</p>
751     * {@hide}
752     */
753    static final int SCROLLBARS_NONE = 0x00000000;
754
755    /**
756     * <p>This view shows horizontal scrollbars.</p>
757     * {@hide}
758     */
759    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
760
761    /**
762     * <p>This view shows vertical scrollbars.</p>
763     * {@hide}
764     */
765    static final int SCROLLBARS_VERTICAL = 0x00000200;
766
767    /**
768     * <p>Mask for use with setFlags indicating bits used for indicating which
769     * scrollbars are enabled.</p>
770     * {@hide}
771     */
772    static final int SCROLLBARS_MASK = 0x00000300;
773
774    /**
775     * Indicates that the view should filter touches when its window is obscured.
776     * Refer to the class comments for more information about this security feature.
777     * {@hide}
778     */
779    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
780
781    /**
782     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
783     * that they are optional and should be skipped if the window has
784     * requested system UI flags that ignore those insets for layout.
785     */
786    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
787
788    /**
789     * <p>This view doesn't show fading edges.</p>
790     * {@hide}
791     */
792    static final int FADING_EDGE_NONE = 0x00000000;
793
794    /**
795     * <p>This view shows horizontal fading edges.</p>
796     * {@hide}
797     */
798    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
799
800    /**
801     * <p>This view shows vertical fading edges.</p>
802     * {@hide}
803     */
804    static final int FADING_EDGE_VERTICAL = 0x00002000;
805
806    /**
807     * <p>Mask for use with setFlags indicating bits used for indicating which
808     * fading edges are enabled.</p>
809     * {@hide}
810     */
811    static final int FADING_EDGE_MASK = 0x00003000;
812
813    /**
814     * <p>Indicates this view can be clicked. When clickable, a View reacts
815     * to clicks by notifying the OnClickListener.<p>
816     * {@hide}
817     */
818    static final int CLICKABLE = 0x00004000;
819
820    /**
821     * <p>Indicates this view is caching its drawing into a bitmap.</p>
822     * {@hide}
823     */
824    static final int DRAWING_CACHE_ENABLED = 0x00008000;
825
826    /**
827     * <p>Indicates that no icicle should be saved for this view.<p>
828     * {@hide}
829     */
830    static final int SAVE_DISABLED = 0x000010000;
831
832    /**
833     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
834     * property.</p>
835     * {@hide}
836     */
837    static final int SAVE_DISABLED_MASK = 0x000010000;
838
839    /**
840     * <p>Indicates that no drawing cache should ever be created for this view.<p>
841     * {@hide}
842     */
843    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
844
845    /**
846     * <p>Indicates this view can take / keep focus when int touch mode.</p>
847     * {@hide}
848     */
849    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
850
851    /**
852     * <p>Enables low quality mode for the drawing cache.</p>
853     */
854    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
855
856    /**
857     * <p>Enables high quality mode for the drawing cache.</p>
858     */
859    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
860
861    /**
862     * <p>Enables automatic quality mode for the drawing cache.</p>
863     */
864    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
865
866    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
867            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
868    };
869
870    /**
871     * <p>Mask for use with setFlags indicating bits used for the cache
872     * quality property.</p>
873     * {@hide}
874     */
875    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
876
877    /**
878     * <p>
879     * Indicates this view can be long clicked. When long clickable, a View
880     * reacts to long clicks by notifying the OnLongClickListener or showing a
881     * context menu.
882     * </p>
883     * {@hide}
884     */
885    static final int LONG_CLICKABLE = 0x00200000;
886
887    /**
888     * <p>Indicates that this view gets its drawable states from its direct parent
889     * and ignores its original internal states.</p>
890     *
891     * @hide
892     */
893    static final int DUPLICATE_PARENT_STATE = 0x00400000;
894
895    /**
896     * The scrollbar style to display the scrollbars inside the content area,
897     * without increasing the padding. The scrollbars will be overlaid with
898     * translucency on the view's content.
899     */
900    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
901
902    /**
903     * The scrollbar style to display the scrollbars inside the padded area,
904     * increasing the padding of the view. The scrollbars will not overlap the
905     * content area of the view.
906     */
907    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
908
909    /**
910     * The scrollbar style to display the scrollbars at the edge of the view,
911     * without increasing the padding. The scrollbars will be overlaid with
912     * translucency.
913     */
914    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
915
916    /**
917     * The scrollbar style to display the scrollbars at the edge of the view,
918     * increasing the padding of the view. The scrollbars will only overlap the
919     * background, if any.
920     */
921    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
922
923    /**
924     * Mask to check if the scrollbar style is overlay or inset.
925     * {@hide}
926     */
927    static final int SCROLLBARS_INSET_MASK = 0x01000000;
928
929    /**
930     * Mask to check if the scrollbar style is inside or outside.
931     * {@hide}
932     */
933    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
934
935    /**
936     * Mask for scrollbar style.
937     * {@hide}
938     */
939    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
940
941    /**
942     * View flag indicating that the screen should remain on while the
943     * window containing this view is visible to the user.  This effectively
944     * takes care of automatically setting the WindowManager's
945     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
946     */
947    public static final int KEEP_SCREEN_ON = 0x04000000;
948
949    /**
950     * View flag indicating whether this view should have sound effects enabled
951     * for events such as clicking and touching.
952     */
953    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
954
955    /**
956     * View flag indicating whether this view should have haptic feedback
957     * enabled for events such as long presses.
958     */
959    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
960
961    /**
962     * <p>Indicates that the view hierarchy should stop saving state when
963     * it reaches this view.  If state saving is initiated immediately at
964     * the view, it will be allowed.
965     * {@hide}
966     */
967    static final int PARENT_SAVE_DISABLED = 0x20000000;
968
969    /**
970     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
971     * {@hide}
972     */
973    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
974
975    /**
976     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
977     * should add all focusable Views regardless if they are focusable in touch mode.
978     */
979    public static final int FOCUSABLES_ALL = 0x00000000;
980
981    /**
982     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
983     * should add only Views focusable in touch mode.
984     */
985    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
986
987    /**
988     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
989     * should add only accessibility focusable Views.
990     *
991     * @hide
992     */
993    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
994
995    /**
996     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
997     * item.
998     */
999    public static final int FOCUS_BACKWARD = 0x00000001;
1000
1001    /**
1002     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1003     * item.
1004     */
1005    public static final int FOCUS_FORWARD = 0x00000002;
1006
1007    /**
1008     * Use with {@link #focusSearch(int)}. Move focus to the left.
1009     */
1010    public static final int FOCUS_LEFT = 0x00000011;
1011
1012    /**
1013     * Use with {@link #focusSearch(int)}. Move focus up.
1014     */
1015    public static final int FOCUS_UP = 0x00000021;
1016
1017    /**
1018     * Use with {@link #focusSearch(int)}. Move focus to the right.
1019     */
1020    public static final int FOCUS_RIGHT = 0x00000042;
1021
1022    /**
1023     * Use with {@link #focusSearch(int)}. Move focus down.
1024     */
1025    public static final int FOCUS_DOWN = 0x00000082;
1026
1027    // Accessibility focus directions.
1028
1029    /**
1030     * The accessibility focus which is the current user position when
1031     * interacting with the accessibility framework.
1032     */
1033    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1037     */
1038    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1042     */
1043    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1044
1045    /**
1046     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1047     */
1048    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1049
1050    /**
1051     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1052     */
1053    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1054
1055    /**
1056     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1057     */
1058    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1059
1060    /**
1061     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1062     */
1063    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1064
1065    /**
1066     * Bits of {@link #getMeasuredWidthAndState()} and
1067     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1068     */
1069    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1070
1071    /**
1072     * Bits of {@link #getMeasuredWidthAndState()} and
1073     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1074     */
1075    public static final int MEASURED_STATE_MASK = 0xff000000;
1076
1077    /**
1078     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1079     * for functions that combine both width and height into a single int,
1080     * such as {@link #getMeasuredState()} and the childState argument of
1081     * {@link #resolveSizeAndState(int, int, int)}.
1082     */
1083    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1084
1085    /**
1086     * Bit of {@link #getMeasuredWidthAndState()} and
1087     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1088     * is smaller that the space the view would like to have.
1089     */
1090    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1091
1092    /**
1093     * Base View state sets
1094     */
1095    // Singles
1096    /**
1097     * Indicates the view has no states set. States are used with
1098     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1099     * view depending on its state.
1100     *
1101     * @see android.graphics.drawable.Drawable
1102     * @see #getDrawableState()
1103     */
1104    protected static final int[] EMPTY_STATE_SET;
1105    /**
1106     * Indicates the view is enabled. States are used with
1107     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1108     * view depending on its state.
1109     *
1110     * @see android.graphics.drawable.Drawable
1111     * @see #getDrawableState()
1112     */
1113    protected static final int[] ENABLED_STATE_SET;
1114    /**
1115     * Indicates the view is focused. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     */
1122    protected static final int[] FOCUSED_STATE_SET;
1123    /**
1124     * Indicates the view is selected. States are used with
1125     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1126     * view depending on its state.
1127     *
1128     * @see android.graphics.drawable.Drawable
1129     * @see #getDrawableState()
1130     */
1131    protected static final int[] SELECTED_STATE_SET;
1132    /**
1133     * Indicates the view is pressed. States are used with
1134     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1135     * view depending on its state.
1136     *
1137     * @see android.graphics.drawable.Drawable
1138     * @see #getDrawableState()
1139     * @hide
1140     */
1141    protected static final int[] PRESSED_STATE_SET;
1142    /**
1143     * Indicates the view's window has focus. States are used with
1144     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1145     * view depending on its state.
1146     *
1147     * @see android.graphics.drawable.Drawable
1148     * @see #getDrawableState()
1149     */
1150    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1151    // Doubles
1152    /**
1153     * Indicates the view is enabled and has the focus.
1154     *
1155     * @see #ENABLED_STATE_SET
1156     * @see #FOCUSED_STATE_SET
1157     */
1158    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1159    /**
1160     * Indicates the view is enabled and selected.
1161     *
1162     * @see #ENABLED_STATE_SET
1163     * @see #SELECTED_STATE_SET
1164     */
1165    protected static final int[] ENABLED_SELECTED_STATE_SET;
1166    /**
1167     * Indicates the view is enabled and that its window has focus.
1168     *
1169     * @see #ENABLED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1173    /**
1174     * Indicates the view is focused and selected.
1175     *
1176     * @see #FOCUSED_STATE_SET
1177     * @see #SELECTED_STATE_SET
1178     */
1179    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1180    /**
1181     * Indicates the view has the focus and that its window has the focus.
1182     *
1183     * @see #FOCUSED_STATE_SET
1184     * @see #WINDOW_FOCUSED_STATE_SET
1185     */
1186    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1187    /**
1188     * Indicates the view is selected and that its window has the focus.
1189     *
1190     * @see #SELECTED_STATE_SET
1191     * @see #WINDOW_FOCUSED_STATE_SET
1192     */
1193    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1194    // Triples
1195    /**
1196     * Indicates the view is enabled, focused and selected.
1197     *
1198     * @see #ENABLED_STATE_SET
1199     * @see #FOCUSED_STATE_SET
1200     * @see #SELECTED_STATE_SET
1201     */
1202    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1203    /**
1204     * Indicates the view is enabled, focused and its window has the focus.
1205     *
1206     * @see #ENABLED_STATE_SET
1207     * @see #FOCUSED_STATE_SET
1208     * @see #WINDOW_FOCUSED_STATE_SET
1209     */
1210    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1211    /**
1212     * Indicates the view is enabled, selected and its window has the focus.
1213     *
1214     * @see #ENABLED_STATE_SET
1215     * @see #SELECTED_STATE_SET
1216     * @see #WINDOW_FOCUSED_STATE_SET
1217     */
1218    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1219    /**
1220     * Indicates the view is focused, selected and its window has the focus.
1221     *
1222     * @see #FOCUSED_STATE_SET
1223     * @see #SELECTED_STATE_SET
1224     * @see #WINDOW_FOCUSED_STATE_SET
1225     */
1226    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1227    /**
1228     * Indicates the view is enabled, focused, selected and its window
1229     * has the focus.
1230     *
1231     * @see #ENABLED_STATE_SET
1232     * @see #FOCUSED_STATE_SET
1233     * @see #SELECTED_STATE_SET
1234     * @see #WINDOW_FOCUSED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1237    /**
1238     * Indicates the view is pressed and its window has the focus.
1239     *
1240     * @see #PRESSED_STATE_SET
1241     * @see #WINDOW_FOCUSED_STATE_SET
1242     */
1243    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1244    /**
1245     * Indicates the view is pressed and selected.
1246     *
1247     * @see #PRESSED_STATE_SET
1248     * @see #SELECTED_STATE_SET
1249     */
1250    protected static final int[] PRESSED_SELECTED_STATE_SET;
1251    /**
1252     * Indicates the view is pressed, selected and its window has the focus.
1253     *
1254     * @see #PRESSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed and focused.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #FOCUSED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed, focused and its window has the focus.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #WINDOW_FOCUSED_STATE_SET
1272     */
1273    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1274    /**
1275     * Indicates the view is pressed, focused and selected.
1276     *
1277     * @see #PRESSED_STATE_SET
1278     * @see #SELECTED_STATE_SET
1279     * @see #FOCUSED_STATE_SET
1280     */
1281    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1282    /**
1283     * Indicates the view is pressed, focused, selected and its window has the focus.
1284     *
1285     * @see #PRESSED_STATE_SET
1286     * @see #FOCUSED_STATE_SET
1287     * @see #SELECTED_STATE_SET
1288     * @see #WINDOW_FOCUSED_STATE_SET
1289     */
1290    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1291    /**
1292     * Indicates the view is pressed and enabled.
1293     *
1294     * @see #PRESSED_STATE_SET
1295     * @see #ENABLED_STATE_SET
1296     */
1297    protected static final int[] PRESSED_ENABLED_STATE_SET;
1298    /**
1299     * Indicates the view is pressed, enabled and its window has the focus.
1300     *
1301     * @see #PRESSED_STATE_SET
1302     * @see #ENABLED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed, enabled and selected.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #ENABLED_STATE_SET
1311     * @see #SELECTED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, enabled, selected and its window has the
1316     * focus.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #ENABLED_STATE_SET
1320     * @see #SELECTED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled and focused.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, focused and its window has the
1334     * focus.
1335     *
1336     * @see #PRESSED_STATE_SET
1337     * @see #ENABLED_STATE_SET
1338     * @see #FOCUSED_STATE_SET
1339     * @see #WINDOW_FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1342    /**
1343     * Indicates the view is pressed, enabled, focused and selected.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #ENABLED_STATE_SET
1347     * @see #SELECTED_STATE_SET
1348     * @see #FOCUSED_STATE_SET
1349     */
1350    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1351    /**
1352     * Indicates the view is pressed, enabled, focused, selected and its window
1353     * has the focus.
1354     *
1355     * @see #PRESSED_STATE_SET
1356     * @see #ENABLED_STATE_SET
1357     * @see #SELECTED_STATE_SET
1358     * @see #FOCUSED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1362
1363    /**
1364     * The order here is very important to {@link #getDrawableState()}
1365     */
1366    private static final int[][] VIEW_STATE_SETS;
1367
1368    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1369    static final int VIEW_STATE_SELECTED = 1 << 1;
1370    static final int VIEW_STATE_FOCUSED = 1 << 2;
1371    static final int VIEW_STATE_ENABLED = 1 << 3;
1372    static final int VIEW_STATE_PRESSED = 1 << 4;
1373    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1374    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1375    static final int VIEW_STATE_HOVERED = 1 << 7;
1376    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1377    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1378
1379    static final int[] VIEW_STATE_IDS = new int[] {
1380        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1381        R.attr.state_selected,          VIEW_STATE_SELECTED,
1382        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1383        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1384        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1385        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1386        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1387        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1388        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1389        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1390    };
1391
1392    static {
1393        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1394            throw new IllegalStateException(
1395                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1396        }
1397        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1398        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1399            int viewState = R.styleable.ViewDrawableStates[i];
1400            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1401                if (VIEW_STATE_IDS[j] == viewState) {
1402                    orderedIds[i * 2] = viewState;
1403                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1404                }
1405            }
1406        }
1407        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1408        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1409        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1410            int numBits = Integer.bitCount(i);
1411            int[] set = new int[numBits];
1412            int pos = 0;
1413            for (int j = 0; j < orderedIds.length; j += 2) {
1414                if ((i & orderedIds[j+1]) != 0) {
1415                    set[pos++] = orderedIds[j];
1416                }
1417            }
1418            VIEW_STATE_SETS[i] = set;
1419        }
1420
1421        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1422        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1423        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1424        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1426        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1427        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1429        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1431        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1433                | VIEW_STATE_FOCUSED];
1434        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1435        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1436                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1437        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1439        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1441                | VIEW_STATE_ENABLED];
1442        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1444        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1446                | VIEW_STATE_ENABLED];
1447        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1449                | VIEW_STATE_ENABLED];
1450        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1452                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1453
1454        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1455        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1457        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1459        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1461                | VIEW_STATE_PRESSED];
1462        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1464        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1469                | VIEW_STATE_PRESSED];
1470        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1472                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1475        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1477                | VIEW_STATE_PRESSED];
1478        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1479                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1480                | VIEW_STATE_PRESSED];
1481        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1483                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1484        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1485                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1486                | VIEW_STATE_PRESSED];
1487        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1488                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1489                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1490        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1492                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1493        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1495                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1496                | VIEW_STATE_PRESSED];
1497    }
1498
1499    /**
1500     * Accessibility event types that are dispatched for text population.
1501     */
1502    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1503            AccessibilityEvent.TYPE_VIEW_CLICKED
1504            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1505            | AccessibilityEvent.TYPE_VIEW_SELECTED
1506            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1507            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1508            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1509            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1510            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1511            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1512            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
1513
1514    /**
1515     * Temporary Rect currently for use in setBackground().  This will probably
1516     * be extended in the future to hold our own class with more than just
1517     * a Rect. :)
1518     */
1519    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1520
1521    /**
1522     * Map used to store views' tags.
1523     */
1524    private SparseArray<Object> mKeyedTags;
1525
1526    /**
1527     * The next available accessiiblity id.
1528     */
1529    private static int sNextAccessibilityViewId;
1530
1531    /**
1532     * The animation currently associated with this view.
1533     * @hide
1534     */
1535    protected Animation mCurrentAnimation = null;
1536
1537    /**
1538     * Width as measured during measure pass.
1539     * {@hide}
1540     */
1541    @ViewDebug.ExportedProperty(category = "measurement")
1542    int mMeasuredWidth;
1543
1544    /**
1545     * Height as measured during measure pass.
1546     * {@hide}
1547     */
1548    @ViewDebug.ExportedProperty(category = "measurement")
1549    int mMeasuredHeight;
1550
1551    /**
1552     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1553     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1554     * its display list. This flag, used only when hw accelerated, allows us to clear the
1555     * flag while retaining this information until it's needed (at getDisplayList() time and
1556     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1557     *
1558     * {@hide}
1559     */
1560    boolean mRecreateDisplayList = false;
1561
1562    /**
1563     * The view's identifier.
1564     * {@hide}
1565     *
1566     * @see #setId(int)
1567     * @see #getId()
1568     */
1569    @ViewDebug.ExportedProperty(resolveId = true)
1570    int mID = NO_ID;
1571
1572    /**
1573     * The stable ID of this view for accessibility purposes.
1574     */
1575    int mAccessibilityViewId = NO_ID;
1576
1577    /**
1578     * The view's tag.
1579     * {@hide}
1580     *
1581     * @see #setTag(Object)
1582     * @see #getTag()
1583     */
1584    protected Object mTag;
1585
1586    // for mPrivateFlags:
1587    /** {@hide} */
1588    static final int WANTS_FOCUS                    = 0x00000001;
1589    /** {@hide} */
1590    static final int FOCUSED                        = 0x00000002;
1591    /** {@hide} */
1592    static final int SELECTED                       = 0x00000004;
1593    /** {@hide} */
1594    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1595    /** {@hide} */
1596    static final int HAS_BOUNDS                     = 0x00000010;
1597    /** {@hide} */
1598    static final int DRAWN                          = 0x00000020;
1599    /**
1600     * When this flag is set, this view is running an animation on behalf of its
1601     * children and should therefore not cancel invalidate requests, even if they
1602     * lie outside of this view's bounds.
1603     *
1604     * {@hide}
1605     */
1606    static final int DRAW_ANIMATION                 = 0x00000040;
1607    /** {@hide} */
1608    static final int SKIP_DRAW                      = 0x00000080;
1609    /** {@hide} */
1610    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1611    /** {@hide} */
1612    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1613    /** {@hide} */
1614    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1615    /** {@hide} */
1616    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1617    /** {@hide} */
1618    static final int FORCE_LAYOUT                   = 0x00001000;
1619    /** {@hide} */
1620    static final int LAYOUT_REQUIRED                = 0x00002000;
1621
1622    private static final int PRESSED                = 0x00004000;
1623
1624    /** {@hide} */
1625    static final int DRAWING_CACHE_VALID            = 0x00008000;
1626    /**
1627     * Flag used to indicate that this view should be drawn once more (and only once
1628     * more) after its animation has completed.
1629     * {@hide}
1630     */
1631    static final int ANIMATION_STARTED              = 0x00010000;
1632
1633    private static final int SAVE_STATE_CALLED      = 0x00020000;
1634
1635    /**
1636     * Indicates that the View returned true when onSetAlpha() was called and that
1637     * the alpha must be restored.
1638     * {@hide}
1639     */
1640    static final int ALPHA_SET                      = 0x00040000;
1641
1642    /**
1643     * Set by {@link #setScrollContainer(boolean)}.
1644     */
1645    static final int SCROLL_CONTAINER               = 0x00080000;
1646
1647    /**
1648     * Set by {@link #setScrollContainer(boolean)}.
1649     */
1650    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1651
1652    /**
1653     * View flag indicating whether this view was invalidated (fully or partially.)
1654     *
1655     * @hide
1656     */
1657    static final int DIRTY                          = 0x00200000;
1658
1659    /**
1660     * View flag indicating whether this view was invalidated by an opaque
1661     * invalidate request.
1662     *
1663     * @hide
1664     */
1665    static final int DIRTY_OPAQUE                   = 0x00400000;
1666
1667    /**
1668     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1669     *
1670     * @hide
1671     */
1672    static final int DIRTY_MASK                     = 0x00600000;
1673
1674    /**
1675     * Indicates whether the background is opaque.
1676     *
1677     * @hide
1678     */
1679    static final int OPAQUE_BACKGROUND              = 0x00800000;
1680
1681    /**
1682     * Indicates whether the scrollbars are opaque.
1683     *
1684     * @hide
1685     */
1686    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1687
1688    /**
1689     * Indicates whether the view is opaque.
1690     *
1691     * @hide
1692     */
1693    static final int OPAQUE_MASK                    = 0x01800000;
1694
1695    /**
1696     * Indicates a prepressed state;
1697     * the short time between ACTION_DOWN and recognizing
1698     * a 'real' press. Prepressed is used to recognize quick taps
1699     * even when they are shorter than ViewConfiguration.getTapTimeout().
1700     *
1701     * @hide
1702     */
1703    private static final int PREPRESSED             = 0x02000000;
1704
1705    /**
1706     * Indicates whether the view is temporarily detached.
1707     *
1708     * @hide
1709     */
1710    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1711
1712    /**
1713     * Indicates that we should awaken scroll bars once attached
1714     *
1715     * @hide
1716     */
1717    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1718
1719    /**
1720     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1721     * @hide
1722     */
1723    private static final int HOVERED              = 0x10000000;
1724
1725    /**
1726     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1727     * for transform operations
1728     *
1729     * @hide
1730     */
1731    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1732
1733    /** {@hide} */
1734    static final int ACTIVATED                    = 0x40000000;
1735
1736    /**
1737     * Indicates that this view was specifically invalidated, not just dirtied because some
1738     * child view was invalidated. The flag is used to determine when we need to recreate
1739     * a view's display list (as opposed to just returning a reference to its existing
1740     * display list).
1741     *
1742     * @hide
1743     */
1744    static final int INVALIDATED                  = 0x80000000;
1745
1746    /* Masks for mPrivateFlags2 */
1747
1748    /**
1749     * Indicates that this view has reported that it can accept the current drag's content.
1750     * Cleared when the drag operation concludes.
1751     * @hide
1752     */
1753    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1754
1755    /**
1756     * Indicates that this view is currently directly under the drag location in a
1757     * drag-and-drop operation involving content that it can accept.  Cleared when
1758     * the drag exits the view, or when the drag operation concludes.
1759     * @hide
1760     */
1761    static final int DRAG_HOVERED                 = 0x00000002;
1762
1763    /**
1764     * Horizontal layout direction of this view is from Left to Right.
1765     * Use with {@link #setLayoutDirection}.
1766     */
1767    public static final int LAYOUT_DIRECTION_LTR = 0;
1768
1769    /**
1770     * Horizontal layout direction of this view is from Right to Left.
1771     * Use with {@link #setLayoutDirection}.
1772     */
1773    public static final int LAYOUT_DIRECTION_RTL = 1;
1774
1775    /**
1776     * Horizontal layout direction of this view is inherited from its parent.
1777     * Use with {@link #setLayoutDirection}.
1778     */
1779    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1780
1781    /**
1782     * Horizontal layout direction of this view is from deduced from the default language
1783     * script for the locale. Use with {@link #setLayoutDirection}.
1784     */
1785    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1786
1787    /**
1788     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1789     * @hide
1790     */
1791    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1792
1793    /**
1794     * Mask for use with private flags indicating bits used for horizontal layout direction.
1795     * @hide
1796     */
1797    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1798
1799    /**
1800     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1801     * right-to-left direction.
1802     * @hide
1803     */
1804    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1805
1806    /**
1807     * Indicates whether the view horizontal layout direction has been resolved.
1808     * @hide
1809     */
1810    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1811
1812    /**
1813     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1814     * @hide
1815     */
1816    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1817
1818    /*
1819     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1820     * flag value.
1821     * @hide
1822     */
1823    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1824            LAYOUT_DIRECTION_LTR,
1825            LAYOUT_DIRECTION_RTL,
1826            LAYOUT_DIRECTION_INHERIT,
1827            LAYOUT_DIRECTION_LOCALE
1828    };
1829
1830    /**
1831     * Default horizontal layout direction.
1832     * @hide
1833     */
1834    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1835
1836    /**
1837     * Indicates that the view is tracking some sort of transient state
1838     * that the app should not need to be aware of, but that the framework
1839     * should take special care to preserve.
1840     *
1841     * @hide
1842     */
1843    static final int HAS_TRANSIENT_STATE = 0x00000100;
1844
1845
1846    /**
1847     * Text direction is inherited thru {@link ViewGroup}
1848     */
1849    public static final int TEXT_DIRECTION_INHERIT = 0;
1850
1851    /**
1852     * Text direction is using "first strong algorithm". The first strong directional character
1853     * determines the paragraph direction. If there is no strong directional character, the
1854     * paragraph direction is the view's resolved layout direction.
1855     */
1856    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1857
1858    /**
1859     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1860     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1861     * If there are neither, the paragraph direction is the view's resolved layout direction.
1862     */
1863    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1864
1865    /**
1866     * Text direction is forced to LTR.
1867     */
1868    public static final int TEXT_DIRECTION_LTR = 3;
1869
1870    /**
1871     * Text direction is forced to RTL.
1872     */
1873    public static final int TEXT_DIRECTION_RTL = 4;
1874
1875    /**
1876     * Text direction is coming from the system Locale.
1877     */
1878    public static final int TEXT_DIRECTION_LOCALE = 5;
1879
1880    /**
1881     * Default text direction is inherited
1882     */
1883    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1884
1885    /**
1886     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1887     * @hide
1888     */
1889    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1890
1891    /**
1892     * Mask for use with private flags indicating bits used for text direction.
1893     * @hide
1894     */
1895    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1896
1897    /**
1898     * Array of text direction flags for mapping attribute "textDirection" to correct
1899     * flag value.
1900     * @hide
1901     */
1902    private static final int[] TEXT_DIRECTION_FLAGS = {
1903            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1904            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1905            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1906            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1907            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1908            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1909    };
1910
1911    /**
1912     * Indicates whether the view text direction has been resolved.
1913     * @hide
1914     */
1915    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1916
1917    /**
1918     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1919     * @hide
1920     */
1921    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1922
1923    /**
1924     * Mask for use with private flags indicating bits used for resolved text direction.
1925     * @hide
1926     */
1927    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1928
1929    /**
1930     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1931     * @hide
1932     */
1933    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1934            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1935
1936    /*
1937     * Default text alignment. The text alignment of this View is inherited from its parent.
1938     * Use with {@link #setTextAlignment(int)}
1939     */
1940    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1941
1942    /**
1943     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1944     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1945     *
1946     * Use with {@link #setTextAlignment(int)}
1947     */
1948    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1949
1950    /**
1951     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1952     *
1953     * Use with {@link #setTextAlignment(int)}
1954     */
1955    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1956
1957    /**
1958     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1959     *
1960     * Use with {@link #setTextAlignment(int)}
1961     */
1962    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1963
1964    /**
1965     * Center the paragraph, e.g. ALIGN_CENTER.
1966     *
1967     * Use with {@link #setTextAlignment(int)}
1968     */
1969    public static final int TEXT_ALIGNMENT_CENTER = 4;
1970
1971    /**
1972     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1973     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1974     *
1975     * Use with {@link #setTextAlignment(int)}
1976     */
1977    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1978
1979    /**
1980     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1981     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1982     *
1983     * Use with {@link #setTextAlignment(int)}
1984     */
1985    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1986
1987    /**
1988     * Default text alignment is inherited
1989     */
1990    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
1991
1992    /**
1993      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1994      * @hide
1995      */
1996    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
1997
1998    /**
1999      * Mask for use with private flags indicating bits used for text alignment.
2000      * @hide
2001      */
2002    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2003
2004    /**
2005     * Array of text direction flags for mapping attribute "textAlignment" to correct
2006     * flag value.
2007     * @hide
2008     */
2009    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2010            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2011            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2012            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2013            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2014            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2015            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2016            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2017    };
2018
2019    /**
2020     * Indicates whether the view text alignment has been resolved.
2021     * @hide
2022     */
2023    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2024
2025    /**
2026     * Bit shift to get the resolved text alignment.
2027     * @hide
2028     */
2029    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2030
2031    /**
2032     * Mask for use with private flags indicating bits used for text alignment.
2033     * @hide
2034     */
2035    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2036
2037    /**
2038     * Indicates whether if the view text alignment has been resolved to gravity
2039     */
2040    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2041            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2042
2043    // Accessiblity constants for mPrivateFlags2
2044
2045    /**
2046     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2047     */
2048    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2049
2050    /**
2051     * Automatically determine whether a view is important for accessibility.
2052     */
2053    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2054
2055    /**
2056     * The view is important for accessibility.
2057     */
2058    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2059
2060    /**
2061     * The view is not important for accessibility.
2062     */
2063    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2064
2065    /**
2066     * The default whether the view is important for accessiblity.
2067     */
2068    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2069
2070    /**
2071     * Mask for obtainig the bits which specify how to determine
2072     * whether a view is important for accessibility.
2073     */
2074    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2075        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2076        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2077
2078    /**
2079     * Flag indicating whether a view has accessibility focus.
2080     */
2081    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2082
2083    /**
2084     * Flag indicating whether a view state for accessibility has changed.
2085     */
2086    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2087
2088    /* End of masks for mPrivateFlags2 */
2089
2090    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2091
2092    /**
2093     * Always allow a user to over-scroll this view, provided it is a
2094     * view that can scroll.
2095     *
2096     * @see #getOverScrollMode()
2097     * @see #setOverScrollMode(int)
2098     */
2099    public static final int OVER_SCROLL_ALWAYS = 0;
2100
2101    /**
2102     * Allow a user to over-scroll this view only if the content is large
2103     * enough to meaningfully scroll, provided it is a view that can scroll.
2104     *
2105     * @see #getOverScrollMode()
2106     * @see #setOverScrollMode(int)
2107     */
2108    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2109
2110    /**
2111     * Never allow a user to over-scroll this view.
2112     *
2113     * @see #getOverScrollMode()
2114     * @see #setOverScrollMode(int)
2115     */
2116    public static final int OVER_SCROLL_NEVER = 2;
2117
2118    /**
2119     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2120     * requested the system UI (status bar) to be visible (the default).
2121     *
2122     * @see #setSystemUiVisibility(int)
2123     */
2124    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2125
2126    /**
2127     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2128     * system UI to enter an unobtrusive "low profile" mode.
2129     *
2130     * <p>This is for use in games, book readers, video players, or any other
2131     * "immersive" application where the usual system chrome is deemed too distracting.
2132     *
2133     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2134     *
2135     * @see #setSystemUiVisibility(int)
2136     */
2137    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2138
2139    /**
2140     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2141     * system navigation be temporarily hidden.
2142     *
2143     * <p>This is an even less obtrusive state than that called for by
2144     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2145     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2146     * those to disappear. This is useful (in conjunction with the
2147     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2148     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2149     * window flags) for displaying content using every last pixel on the display.
2150     *
2151     * <p>There is a limitation: because navigation controls are so important, the least user
2152     * interaction will cause them to reappear immediately.  When this happens, both
2153     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2154     * so that both elements reappear at the same time.
2155     *
2156     * @see #setSystemUiVisibility(int)
2157     */
2158    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2159
2160    /**
2161     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2162     * into the normal fullscreen mode so that its content can take over the screen
2163     * while still allowing the user to interact with the application.
2164     *
2165     * <p>This has the same visual effect as
2166     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2167     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2168     * meaning that non-critical screen decorations (such as the status bar) will be
2169     * hidden while the user is in the View's window, focusing the experience on
2170     * that content.  Unlike the window flag, if you are using ActionBar in
2171     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2172     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2173     * hide the action bar.
2174     *
2175     * <p>This approach to going fullscreen is best used over the window flag when
2176     * it is a transient state -- that is, the application does this at certain
2177     * points in its user interaction where it wants to allow the user to focus
2178     * on content, but not as a continuous state.  For situations where the application
2179     * would like to simply stay full screen the entire time (such as a game that
2180     * wants to take over the screen), the
2181     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2182     * is usually a better approach.  The state set here will be removed by the system
2183     * in various situations (such as the user moving to another application) like
2184     * the other system UI states.
2185     *
2186     * <p>When using this flag, the application should provide some easy facility
2187     * for the user to go out of it.  A common example would be in an e-book
2188     * reader, where tapping on the screen brings back whatever screen and UI
2189     * decorations that had been hidden while the user was immersed in reading
2190     * the book.
2191     *
2192     * @see #setSystemUiVisibility(int)
2193     */
2194    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2195
2196    /**
2197     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2198     * flags, we would like a stable view of the content insets given to
2199     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2200     * will always represent the worst case that the application can expect
2201     * as a continue state.  In practice this means with any of system bar,
2202     * nav bar, and status bar shown, but not the space that would be needed
2203     * for an input method.
2204     *
2205     * <p>If you are using ActionBar in
2206     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2207     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2208     * insets it adds to those given to the application.
2209     */
2210    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2211
2212    /**
2213     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2214     * to be layed out as if it has requested
2215     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2216     * allows it to avoid artifacts when switching in and out of that mode, at
2217     * the expense that some of its user interface may be covered by screen
2218     * decorations when they are shown.  You can perform layout of your inner
2219     * UI elements to account for the navagation system UI through the
2220     * {@link #fitSystemWindows(Rect)} method.
2221     */
2222    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2223
2224    /**
2225     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2226     * to be layed out as if it has requested
2227     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2228     * allows it to avoid artifacts when switching in and out of that mode, at
2229     * the expense that some of its user interface may be covered by screen
2230     * decorations when they are shown.  You can perform layout of your inner
2231     * UI elements to account for non-fullscreen system UI through the
2232     * {@link #fitSystemWindows(Rect)} method.
2233     */
2234    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2235
2236    /**
2237     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2238     */
2239    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2240
2241    /**
2242     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2243     */
2244    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2245
2246    /**
2247     * @hide
2248     *
2249     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2250     * out of the public fields to keep the undefined bits out of the developer's way.
2251     *
2252     * Flag to make the status bar not expandable.  Unless you also
2253     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2254     */
2255    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2256
2257    /**
2258     * @hide
2259     *
2260     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2261     * out of the public fields to keep the undefined bits out of the developer's way.
2262     *
2263     * Flag to hide notification icons and scrolling ticker text.
2264     */
2265    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2266
2267    /**
2268     * @hide
2269     *
2270     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2271     * out of the public fields to keep the undefined bits out of the developer's way.
2272     *
2273     * Flag to disable incoming notification alerts.  This will not block
2274     * icons, but it will block sound, vibrating and other visual or aural notifications.
2275     */
2276    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2277
2278    /**
2279     * @hide
2280     *
2281     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2282     * out of the public fields to keep the undefined bits out of the developer's way.
2283     *
2284     * Flag to hide only the scrolling ticker.  Note that
2285     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2286     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2287     */
2288    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2289
2290    /**
2291     * @hide
2292     *
2293     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2294     * out of the public fields to keep the undefined bits out of the developer's way.
2295     *
2296     * Flag to hide the center system info area.
2297     */
2298    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2299
2300    /**
2301     * @hide
2302     *
2303     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2304     * out of the public fields to keep the undefined bits out of the developer's way.
2305     *
2306     * Flag to hide only the home button.  Don't use this
2307     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2308     */
2309    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2310
2311    /**
2312     * @hide
2313     *
2314     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2315     * out of the public fields to keep the undefined bits out of the developer's way.
2316     *
2317     * Flag to hide only the back button. Don't use this
2318     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2319     */
2320    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2321
2322    /**
2323     * @hide
2324     *
2325     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2326     * out of the public fields to keep the undefined bits out of the developer's way.
2327     *
2328     * Flag to hide only the clock.  You might use this if your activity has
2329     * its own clock making the status bar's clock redundant.
2330     */
2331    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2332
2333    /**
2334     * @hide
2335     *
2336     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2337     * out of the public fields to keep the undefined bits out of the developer's way.
2338     *
2339     * Flag to hide only the recent apps button. Don't use this
2340     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2341     */
2342    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2343
2344    /**
2345     * @hide
2346     */
2347    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2348
2349    /**
2350     * These are the system UI flags that can be cleared by events outside
2351     * of an application.  Currently this is just the ability to tap on the
2352     * screen while hiding the navigation bar to have it return.
2353     * @hide
2354     */
2355    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2356            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2357            | SYSTEM_UI_FLAG_FULLSCREEN;
2358
2359    /**
2360     * Flags that can impact the layout in relation to system UI.
2361     */
2362    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2363            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2364            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2365
2366    /**
2367     * Find views that render the specified text.
2368     *
2369     * @see #findViewsWithText(ArrayList, CharSequence, int)
2370     */
2371    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2372
2373    /**
2374     * Find find views that contain the specified content description.
2375     *
2376     * @see #findViewsWithText(ArrayList, CharSequence, int)
2377     */
2378    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2379
2380    /**
2381     * Find views that contain {@link AccessibilityNodeProvider}. Such
2382     * a View is a root of virtual view hierarchy and may contain the searched
2383     * text. If this flag is set Views with providers are automatically
2384     * added and it is a responsibility of the client to call the APIs of
2385     * the provider to determine whether the virtual tree rooted at this View
2386     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2387     * represeting the virtual views with this text.
2388     *
2389     * @see #findViewsWithText(ArrayList, CharSequence, int)
2390     *
2391     * @hide
2392     */
2393    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2394
2395    /**
2396     * Indicates that the screen has changed state and is now off.
2397     *
2398     * @see #onScreenStateChanged(int)
2399     */
2400    public static final int SCREEN_STATE_OFF = 0x0;
2401
2402    /**
2403     * Indicates that the screen has changed state and is now on.
2404     *
2405     * @see #onScreenStateChanged(int)
2406     */
2407    public static final int SCREEN_STATE_ON = 0x1;
2408
2409    /**
2410     * Controls the over-scroll mode for this view.
2411     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2412     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2413     * and {@link #OVER_SCROLL_NEVER}.
2414     */
2415    private int mOverScrollMode;
2416
2417    /**
2418     * The parent this view is attached to.
2419     * {@hide}
2420     *
2421     * @see #getParent()
2422     */
2423    protected ViewParent mParent;
2424
2425    /**
2426     * {@hide}
2427     */
2428    AttachInfo mAttachInfo;
2429
2430    /**
2431     * {@hide}
2432     */
2433    @ViewDebug.ExportedProperty(flagMapping = {
2434        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2435                name = "FORCE_LAYOUT"),
2436        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2437                name = "LAYOUT_REQUIRED"),
2438        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2439            name = "DRAWING_CACHE_INVALID", outputIf = false),
2440        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2441        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2442        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2443        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2444    })
2445    int mPrivateFlags;
2446    int mPrivateFlags2;
2447
2448    /**
2449     * This view's request for the visibility of the status bar.
2450     * @hide
2451     */
2452    @ViewDebug.ExportedProperty(flagMapping = {
2453        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2454                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2455                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2456        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2457                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2458                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2459        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2460                                equals = SYSTEM_UI_FLAG_VISIBLE,
2461                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2462    })
2463    int mSystemUiVisibility;
2464
2465    /**
2466     * Reference count for transient state.
2467     * @see #setHasTransientState(boolean)
2468     */
2469    int mTransientStateCount = 0;
2470
2471    /**
2472     * Count of how many windows this view has been attached to.
2473     */
2474    int mWindowAttachCount;
2475
2476    /**
2477     * The layout parameters associated with this view and used by the parent
2478     * {@link android.view.ViewGroup} to determine how this view should be
2479     * laid out.
2480     * {@hide}
2481     */
2482    protected ViewGroup.LayoutParams mLayoutParams;
2483
2484    /**
2485     * The view flags hold various views states.
2486     * {@hide}
2487     */
2488    @ViewDebug.ExportedProperty
2489    int mViewFlags;
2490
2491    static class TransformationInfo {
2492        /**
2493         * The transform matrix for the View. This transform is calculated internally
2494         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2495         * is used by default. Do *not* use this variable directly; instead call
2496         * getMatrix(), which will automatically recalculate the matrix if necessary
2497         * to get the correct matrix based on the latest rotation and scale properties.
2498         */
2499        private final Matrix mMatrix = new Matrix();
2500
2501        /**
2502         * The transform matrix for the View. This transform is calculated internally
2503         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2504         * is used by default. Do *not* use this variable directly; instead call
2505         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2506         * to get the correct matrix based on the latest rotation and scale properties.
2507         */
2508        private Matrix mInverseMatrix;
2509
2510        /**
2511         * An internal variable that tracks whether we need to recalculate the
2512         * transform matrix, based on whether the rotation or scaleX/Y properties
2513         * have changed since the matrix was last calculated.
2514         */
2515        boolean mMatrixDirty = false;
2516
2517        /**
2518         * An internal variable that tracks whether we need to recalculate the
2519         * transform matrix, based on whether the rotation or scaleX/Y properties
2520         * have changed since the matrix was last calculated.
2521         */
2522        private boolean mInverseMatrixDirty = true;
2523
2524        /**
2525         * A variable that tracks whether we need to recalculate the
2526         * transform matrix, based on whether the rotation or scaleX/Y properties
2527         * have changed since the matrix was last calculated. This variable
2528         * is only valid after a call to updateMatrix() or to a function that
2529         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2530         */
2531        private boolean mMatrixIsIdentity = true;
2532
2533        /**
2534         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2535         */
2536        private Camera mCamera = null;
2537
2538        /**
2539         * This matrix is used when computing the matrix for 3D rotations.
2540         */
2541        private Matrix matrix3D = null;
2542
2543        /**
2544         * These prev values are used to recalculate a centered pivot point when necessary. The
2545         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2546         * set), so thes values are only used then as well.
2547         */
2548        private int mPrevWidth = -1;
2549        private int mPrevHeight = -1;
2550
2551        /**
2552         * The degrees rotation around the vertical axis through the pivot point.
2553         */
2554        @ViewDebug.ExportedProperty
2555        float mRotationY = 0f;
2556
2557        /**
2558         * The degrees rotation around the horizontal axis through the pivot point.
2559         */
2560        @ViewDebug.ExportedProperty
2561        float mRotationX = 0f;
2562
2563        /**
2564         * The degrees rotation around the pivot point.
2565         */
2566        @ViewDebug.ExportedProperty
2567        float mRotation = 0f;
2568
2569        /**
2570         * The amount of translation of the object away from its left property (post-layout).
2571         */
2572        @ViewDebug.ExportedProperty
2573        float mTranslationX = 0f;
2574
2575        /**
2576         * The amount of translation of the object away from its top property (post-layout).
2577         */
2578        @ViewDebug.ExportedProperty
2579        float mTranslationY = 0f;
2580
2581        /**
2582         * The amount of scale in the x direction around the pivot point. A
2583         * value of 1 means no scaling is applied.
2584         */
2585        @ViewDebug.ExportedProperty
2586        float mScaleX = 1f;
2587
2588        /**
2589         * The amount of scale in the y direction around the pivot point. A
2590         * value of 1 means no scaling is applied.
2591         */
2592        @ViewDebug.ExportedProperty
2593        float mScaleY = 1f;
2594
2595        /**
2596         * The x location of the point around which the view is rotated and scaled.
2597         */
2598        @ViewDebug.ExportedProperty
2599        float mPivotX = 0f;
2600
2601        /**
2602         * The y location of the point around which the view is rotated and scaled.
2603         */
2604        @ViewDebug.ExportedProperty
2605        float mPivotY = 0f;
2606
2607        /**
2608         * The opacity of the View. This is a value from 0 to 1, where 0 means
2609         * completely transparent and 1 means completely opaque.
2610         */
2611        @ViewDebug.ExportedProperty
2612        float mAlpha = 1f;
2613    }
2614
2615    TransformationInfo mTransformationInfo;
2616
2617    private boolean mLastIsOpaque;
2618
2619    /**
2620     * Convenience value to check for float values that are close enough to zero to be considered
2621     * zero.
2622     */
2623    private static final float NONZERO_EPSILON = .001f;
2624
2625    /**
2626     * The distance in pixels from the left edge of this view's parent
2627     * to the left edge of this view.
2628     * {@hide}
2629     */
2630    @ViewDebug.ExportedProperty(category = "layout")
2631    protected int mLeft;
2632    /**
2633     * The distance in pixels from the left edge of this view's parent
2634     * to the right edge of this view.
2635     * {@hide}
2636     */
2637    @ViewDebug.ExportedProperty(category = "layout")
2638    protected int mRight;
2639    /**
2640     * The distance in pixels from the top edge of this view's parent
2641     * to the top edge of this view.
2642     * {@hide}
2643     */
2644    @ViewDebug.ExportedProperty(category = "layout")
2645    protected int mTop;
2646    /**
2647     * The distance in pixels from the top edge of this view's parent
2648     * to the bottom edge of this view.
2649     * {@hide}
2650     */
2651    @ViewDebug.ExportedProperty(category = "layout")
2652    protected int mBottom;
2653
2654    /**
2655     * The offset, in pixels, by which the content of this view is scrolled
2656     * horizontally.
2657     * {@hide}
2658     */
2659    @ViewDebug.ExportedProperty(category = "scrolling")
2660    protected int mScrollX;
2661    /**
2662     * The offset, in pixels, by which the content of this view is scrolled
2663     * vertically.
2664     * {@hide}
2665     */
2666    @ViewDebug.ExportedProperty(category = "scrolling")
2667    protected int mScrollY;
2668
2669    /**
2670     * The left padding in pixels, that is the distance in pixels between the
2671     * left edge of this view and the left edge of its content.
2672     * {@hide}
2673     */
2674    @ViewDebug.ExportedProperty(category = "padding")
2675    protected int mPaddingLeft;
2676    /**
2677     * The right padding in pixels, that is the distance in pixels between the
2678     * right edge of this view and the right edge of its content.
2679     * {@hide}
2680     */
2681    @ViewDebug.ExportedProperty(category = "padding")
2682    protected int mPaddingRight;
2683    /**
2684     * The top padding in pixels, that is the distance in pixels between the
2685     * top edge of this view and the top edge of its content.
2686     * {@hide}
2687     */
2688    @ViewDebug.ExportedProperty(category = "padding")
2689    protected int mPaddingTop;
2690    /**
2691     * The bottom padding in pixels, that is the distance in pixels between the
2692     * bottom edge of this view and the bottom edge of its content.
2693     * {@hide}
2694     */
2695    @ViewDebug.ExportedProperty(category = "padding")
2696    protected int mPaddingBottom;
2697
2698    /**
2699     * The layout insets in pixels, that is the distance in pixels between the
2700     * visible edges of this view its bounds.
2701     */
2702    private Insets mLayoutInsets;
2703
2704    /**
2705     * Briefly describes the view and is primarily used for accessibility support.
2706     */
2707    private CharSequence mContentDescription;
2708
2709    /**
2710     * Cache the paddingRight set by the user to append to the scrollbar's size.
2711     *
2712     * @hide
2713     */
2714    @ViewDebug.ExportedProperty(category = "padding")
2715    protected int mUserPaddingRight;
2716
2717    /**
2718     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2719     *
2720     * @hide
2721     */
2722    @ViewDebug.ExportedProperty(category = "padding")
2723    protected int mUserPaddingBottom;
2724
2725    /**
2726     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2727     *
2728     * @hide
2729     */
2730    @ViewDebug.ExportedProperty(category = "padding")
2731    protected int mUserPaddingLeft;
2732
2733    /**
2734     * Cache if the user padding is relative.
2735     *
2736     */
2737    @ViewDebug.ExportedProperty(category = "padding")
2738    boolean mUserPaddingRelative;
2739
2740    /**
2741     * Cache the paddingStart set by the user to append to the scrollbar's size.
2742     *
2743     */
2744    @ViewDebug.ExportedProperty(category = "padding")
2745    int mUserPaddingStart;
2746
2747    /**
2748     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2749     *
2750     */
2751    @ViewDebug.ExportedProperty(category = "padding")
2752    int mUserPaddingEnd;
2753
2754    /**
2755     * @hide
2756     */
2757    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2758    /**
2759     * @hide
2760     */
2761    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2762
2763    private Drawable mBackground;
2764
2765    private int mBackgroundResource;
2766    private boolean mBackgroundSizeChanged;
2767
2768    static class ListenerInfo {
2769        /**
2770         * Listener used to dispatch focus change events.
2771         * This field should be made private, so it is hidden from the SDK.
2772         * {@hide}
2773         */
2774        protected OnFocusChangeListener mOnFocusChangeListener;
2775
2776        /**
2777         * Listeners for layout change events.
2778         */
2779        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2780
2781        /**
2782         * Listeners for attach events.
2783         */
2784        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2785
2786        /**
2787         * Listener used to dispatch click events.
2788         * This field should be made private, so it is hidden from the SDK.
2789         * {@hide}
2790         */
2791        public OnClickListener mOnClickListener;
2792
2793        /**
2794         * Listener used to dispatch long click events.
2795         * This field should be made private, so it is hidden from the SDK.
2796         * {@hide}
2797         */
2798        protected OnLongClickListener mOnLongClickListener;
2799
2800        /**
2801         * Listener used to build the context menu.
2802         * This field should be made private, so it is hidden from the SDK.
2803         * {@hide}
2804         */
2805        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2806
2807        private OnKeyListener mOnKeyListener;
2808
2809        private OnTouchListener mOnTouchListener;
2810
2811        private OnHoverListener mOnHoverListener;
2812
2813        private OnGenericMotionListener mOnGenericMotionListener;
2814
2815        private OnDragListener mOnDragListener;
2816
2817        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2818    }
2819
2820    ListenerInfo mListenerInfo;
2821
2822    /**
2823     * The application environment this view lives in.
2824     * This field should be made private, so it is hidden from the SDK.
2825     * {@hide}
2826     */
2827    protected Context mContext;
2828
2829    private final Resources mResources;
2830
2831    private ScrollabilityCache mScrollCache;
2832
2833    private int[] mDrawableState = null;
2834
2835    /**
2836     * Set to true when drawing cache is enabled and cannot be created.
2837     *
2838     * @hide
2839     */
2840    public boolean mCachingFailed;
2841
2842    private Bitmap mDrawingCache;
2843    private Bitmap mUnscaledDrawingCache;
2844    private HardwareLayer mHardwareLayer;
2845    DisplayList mDisplayList;
2846
2847    /**
2848     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2849     * the user may specify which view to go to next.
2850     */
2851    private int mNextFocusLeftId = View.NO_ID;
2852
2853    /**
2854     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2855     * the user may specify which view to go to next.
2856     */
2857    private int mNextFocusRightId = View.NO_ID;
2858
2859    /**
2860     * When this view has focus and the next focus is {@link #FOCUS_UP},
2861     * the user may specify which view to go to next.
2862     */
2863    private int mNextFocusUpId = View.NO_ID;
2864
2865    /**
2866     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2867     * the user may specify which view to go to next.
2868     */
2869    private int mNextFocusDownId = View.NO_ID;
2870
2871    /**
2872     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2873     * the user may specify which view to go to next.
2874     */
2875    int mNextFocusForwardId = View.NO_ID;
2876
2877    private CheckForLongPress mPendingCheckForLongPress;
2878    private CheckForTap mPendingCheckForTap = null;
2879    private PerformClick mPerformClick;
2880    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2881
2882    private UnsetPressedState mUnsetPressedState;
2883
2884    /**
2885     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2886     * up event while a long press is invoked as soon as the long press duration is reached, so
2887     * a long press could be performed before the tap is checked, in which case the tap's action
2888     * should not be invoked.
2889     */
2890    private boolean mHasPerformedLongPress;
2891
2892    /**
2893     * The minimum height of the view. We'll try our best to have the height
2894     * of this view to at least this amount.
2895     */
2896    @ViewDebug.ExportedProperty(category = "measurement")
2897    private int mMinHeight;
2898
2899    /**
2900     * The minimum width of the view. We'll try our best to have the width
2901     * of this view to at least this amount.
2902     */
2903    @ViewDebug.ExportedProperty(category = "measurement")
2904    private int mMinWidth;
2905
2906    /**
2907     * The delegate to handle touch events that are physically in this view
2908     * but should be handled by another view.
2909     */
2910    private TouchDelegate mTouchDelegate = null;
2911
2912    /**
2913     * Solid color to use as a background when creating the drawing cache. Enables
2914     * the cache to use 16 bit bitmaps instead of 32 bit.
2915     */
2916    private int mDrawingCacheBackgroundColor = 0;
2917
2918    /**
2919     * Special tree observer used when mAttachInfo is null.
2920     */
2921    private ViewTreeObserver mFloatingTreeObserver;
2922
2923    /**
2924     * Cache the touch slop from the context that created the view.
2925     */
2926    private int mTouchSlop;
2927
2928    /**
2929     * Object that handles automatic animation of view properties.
2930     */
2931    private ViewPropertyAnimator mAnimator = null;
2932
2933    /**
2934     * Flag indicating that a drag can cross window boundaries.  When
2935     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2936     * with this flag set, all visible applications will be able to participate
2937     * in the drag operation and receive the dragged content.
2938     *
2939     * @hide
2940     */
2941    public static final int DRAG_FLAG_GLOBAL = 1;
2942
2943    /**
2944     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2945     */
2946    private float mVerticalScrollFactor;
2947
2948    /**
2949     * Position of the vertical scroll bar.
2950     */
2951    private int mVerticalScrollbarPosition;
2952
2953    /**
2954     * Position the scroll bar at the default position as determined by the system.
2955     */
2956    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2957
2958    /**
2959     * Position the scroll bar along the left edge.
2960     */
2961    public static final int SCROLLBAR_POSITION_LEFT = 1;
2962
2963    /**
2964     * Position the scroll bar along the right edge.
2965     */
2966    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2967
2968    /**
2969     * Indicates that the view does not have a layer.
2970     *
2971     * @see #getLayerType()
2972     * @see #setLayerType(int, android.graphics.Paint)
2973     * @see #LAYER_TYPE_SOFTWARE
2974     * @see #LAYER_TYPE_HARDWARE
2975     */
2976    public static final int LAYER_TYPE_NONE = 0;
2977
2978    /**
2979     * <p>Indicates that the view has a software layer. A software layer is backed
2980     * by a bitmap and causes the view to be rendered using Android's software
2981     * rendering pipeline, even if hardware acceleration is enabled.</p>
2982     *
2983     * <p>Software layers have various usages:</p>
2984     * <p>When the application is not using hardware acceleration, a software layer
2985     * is useful to apply a specific color filter and/or blending mode and/or
2986     * translucency to a view and all its children.</p>
2987     * <p>When the application is using hardware acceleration, a software layer
2988     * is useful to render drawing primitives not supported by the hardware
2989     * accelerated pipeline. It can also be used to cache a complex view tree
2990     * into a texture and reduce the complexity of drawing operations. For instance,
2991     * when animating a complex view tree with a translation, a software layer can
2992     * be used to render the view tree only once.</p>
2993     * <p>Software layers should be avoided when the affected view tree updates
2994     * often. Every update will require to re-render the software layer, which can
2995     * potentially be slow (particularly when hardware acceleration is turned on
2996     * since the layer will have to be uploaded into a hardware texture after every
2997     * update.)</p>
2998     *
2999     * @see #getLayerType()
3000     * @see #setLayerType(int, android.graphics.Paint)
3001     * @see #LAYER_TYPE_NONE
3002     * @see #LAYER_TYPE_HARDWARE
3003     */
3004    public static final int LAYER_TYPE_SOFTWARE = 1;
3005
3006    /**
3007     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3008     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3009     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3010     * rendering pipeline, but only if hardware acceleration is turned on for the
3011     * view hierarchy. When hardware acceleration is turned off, hardware layers
3012     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3013     *
3014     * <p>A hardware layer is useful to apply a specific color filter and/or
3015     * blending mode and/or translucency to a view and all its children.</p>
3016     * <p>A hardware layer can be used to cache a complex view tree into a
3017     * texture and reduce the complexity of drawing operations. For instance,
3018     * when animating a complex view tree with a translation, a hardware layer can
3019     * be used to render the view tree only once.</p>
3020     * <p>A hardware layer can also be used to increase the rendering quality when
3021     * rotation transformations are applied on a view. It can also be used to
3022     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3023     *
3024     * @see #getLayerType()
3025     * @see #setLayerType(int, android.graphics.Paint)
3026     * @see #LAYER_TYPE_NONE
3027     * @see #LAYER_TYPE_SOFTWARE
3028     */
3029    public static final int LAYER_TYPE_HARDWARE = 2;
3030
3031    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3032            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3033            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3034            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3035    })
3036    int mLayerType = LAYER_TYPE_NONE;
3037    Paint mLayerPaint;
3038    Rect mLocalDirtyRect;
3039
3040    /**
3041     * Set to true when the view is sending hover accessibility events because it
3042     * is the innermost hovered view.
3043     */
3044    private boolean mSendingHoverAccessibilityEvents;
3045
3046    /**
3047     * Simple constructor to use when creating a view from code.
3048     *
3049     * @param context The Context the view is running in, through which it can
3050     *        access the current theme, resources, etc.
3051     */
3052    public View(Context context) {
3053        mContext = context;
3054        mResources = context != null ? context.getResources() : null;
3055        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3056        // Set layout and text direction defaults
3057        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3058                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3059                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3060                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3061        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3062        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3063        mUserPaddingStart = -1;
3064        mUserPaddingEnd = -1;
3065        mUserPaddingRelative = false;
3066    }
3067
3068    /**
3069     * Delegate for injecting accessiblity functionality.
3070     */
3071    AccessibilityDelegate mAccessibilityDelegate;
3072
3073    /**
3074     * Consistency verifier for debugging purposes.
3075     * @hide
3076     */
3077    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3078            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3079                    new InputEventConsistencyVerifier(this, 0) : null;
3080
3081    /**
3082     * Constructor that is called when inflating a view from XML. This is called
3083     * when a view is being constructed from an XML file, supplying attributes
3084     * that were specified in the XML file. This version uses a default style of
3085     * 0, so the only attribute values applied are those in the Context's Theme
3086     * and the given AttributeSet.
3087     *
3088     * <p>
3089     * The method onFinishInflate() will be called after all children have been
3090     * added.
3091     *
3092     * @param context The Context the view is running in, through which it can
3093     *        access the current theme, resources, etc.
3094     * @param attrs The attributes of the XML tag that is inflating the view.
3095     * @see #View(Context, AttributeSet, int)
3096     */
3097    public View(Context context, AttributeSet attrs) {
3098        this(context, attrs, 0);
3099    }
3100
3101    /**
3102     * Perform inflation from XML and apply a class-specific base style. This
3103     * constructor of View allows subclasses to use their own base style when
3104     * they are inflating. For example, a Button class's constructor would call
3105     * this version of the super class constructor and supply
3106     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3107     * the theme's button style to modify all of the base view attributes (in
3108     * particular its background) as well as the Button class's attributes.
3109     *
3110     * @param context The Context the view is running in, through which it can
3111     *        access the current theme, resources, etc.
3112     * @param attrs The attributes of the XML tag that is inflating the view.
3113     * @param defStyle The default style to apply to this view. If 0, no style
3114     *        will be applied (beyond what is included in the theme). This may
3115     *        either be an attribute resource, whose value will be retrieved
3116     *        from the current theme, or an explicit style resource.
3117     * @see #View(Context, AttributeSet)
3118     */
3119    public View(Context context, AttributeSet attrs, int defStyle) {
3120        this(context);
3121
3122        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3123                defStyle, 0);
3124
3125        Drawable background = null;
3126
3127        int leftPadding = -1;
3128        int topPadding = -1;
3129        int rightPadding = -1;
3130        int bottomPadding = -1;
3131        int startPadding = -1;
3132        int endPadding = -1;
3133
3134        int padding = -1;
3135
3136        int viewFlagValues = 0;
3137        int viewFlagMasks = 0;
3138
3139        boolean setScrollContainer = false;
3140
3141        int x = 0;
3142        int y = 0;
3143
3144        float tx = 0;
3145        float ty = 0;
3146        float rotation = 0;
3147        float rotationX = 0;
3148        float rotationY = 0;
3149        float sx = 1f;
3150        float sy = 1f;
3151        boolean transformSet = false;
3152
3153        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3154
3155        int overScrollMode = mOverScrollMode;
3156        final int N = a.getIndexCount();
3157        for (int i = 0; i < N; i++) {
3158            int attr = a.getIndex(i);
3159            switch (attr) {
3160                case com.android.internal.R.styleable.View_background:
3161                    background = a.getDrawable(attr);
3162                    break;
3163                case com.android.internal.R.styleable.View_padding:
3164                    padding = a.getDimensionPixelSize(attr, -1);
3165                    break;
3166                 case com.android.internal.R.styleable.View_paddingLeft:
3167                    leftPadding = a.getDimensionPixelSize(attr, -1);
3168                    break;
3169                case com.android.internal.R.styleable.View_paddingTop:
3170                    topPadding = a.getDimensionPixelSize(attr, -1);
3171                    break;
3172                case com.android.internal.R.styleable.View_paddingRight:
3173                    rightPadding = a.getDimensionPixelSize(attr, -1);
3174                    break;
3175                case com.android.internal.R.styleable.View_paddingBottom:
3176                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3177                    break;
3178                case com.android.internal.R.styleable.View_paddingStart:
3179                    startPadding = a.getDimensionPixelSize(attr, -1);
3180                    break;
3181                case com.android.internal.R.styleable.View_paddingEnd:
3182                    endPadding = a.getDimensionPixelSize(attr, -1);
3183                    break;
3184                case com.android.internal.R.styleable.View_scrollX:
3185                    x = a.getDimensionPixelOffset(attr, 0);
3186                    break;
3187                case com.android.internal.R.styleable.View_scrollY:
3188                    y = a.getDimensionPixelOffset(attr, 0);
3189                    break;
3190                case com.android.internal.R.styleable.View_alpha:
3191                    setAlpha(a.getFloat(attr, 1f));
3192                    break;
3193                case com.android.internal.R.styleable.View_transformPivotX:
3194                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3195                    break;
3196                case com.android.internal.R.styleable.View_transformPivotY:
3197                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3198                    break;
3199                case com.android.internal.R.styleable.View_translationX:
3200                    tx = a.getDimensionPixelOffset(attr, 0);
3201                    transformSet = true;
3202                    break;
3203                case com.android.internal.R.styleable.View_translationY:
3204                    ty = a.getDimensionPixelOffset(attr, 0);
3205                    transformSet = true;
3206                    break;
3207                case com.android.internal.R.styleable.View_rotation:
3208                    rotation = a.getFloat(attr, 0);
3209                    transformSet = true;
3210                    break;
3211                case com.android.internal.R.styleable.View_rotationX:
3212                    rotationX = a.getFloat(attr, 0);
3213                    transformSet = true;
3214                    break;
3215                case com.android.internal.R.styleable.View_rotationY:
3216                    rotationY = a.getFloat(attr, 0);
3217                    transformSet = true;
3218                    break;
3219                case com.android.internal.R.styleable.View_scaleX:
3220                    sx = a.getFloat(attr, 1f);
3221                    transformSet = true;
3222                    break;
3223                case com.android.internal.R.styleable.View_scaleY:
3224                    sy = a.getFloat(attr, 1f);
3225                    transformSet = true;
3226                    break;
3227                case com.android.internal.R.styleable.View_id:
3228                    mID = a.getResourceId(attr, NO_ID);
3229                    break;
3230                case com.android.internal.R.styleable.View_tag:
3231                    mTag = a.getText(attr);
3232                    break;
3233                case com.android.internal.R.styleable.View_fitsSystemWindows:
3234                    if (a.getBoolean(attr, false)) {
3235                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3236                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3237                    }
3238                    break;
3239                case com.android.internal.R.styleable.View_focusable:
3240                    if (a.getBoolean(attr, false)) {
3241                        viewFlagValues |= FOCUSABLE;
3242                        viewFlagMasks |= FOCUSABLE_MASK;
3243                    }
3244                    break;
3245                case com.android.internal.R.styleable.View_focusableInTouchMode:
3246                    if (a.getBoolean(attr, false)) {
3247                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3248                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3249                    }
3250                    break;
3251                case com.android.internal.R.styleable.View_clickable:
3252                    if (a.getBoolean(attr, false)) {
3253                        viewFlagValues |= CLICKABLE;
3254                        viewFlagMasks |= CLICKABLE;
3255                    }
3256                    break;
3257                case com.android.internal.R.styleable.View_longClickable:
3258                    if (a.getBoolean(attr, false)) {
3259                        viewFlagValues |= LONG_CLICKABLE;
3260                        viewFlagMasks |= LONG_CLICKABLE;
3261                    }
3262                    break;
3263                case com.android.internal.R.styleable.View_saveEnabled:
3264                    if (!a.getBoolean(attr, true)) {
3265                        viewFlagValues |= SAVE_DISABLED;
3266                        viewFlagMasks |= SAVE_DISABLED_MASK;
3267                    }
3268                    break;
3269                case com.android.internal.R.styleable.View_duplicateParentState:
3270                    if (a.getBoolean(attr, false)) {
3271                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3272                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3273                    }
3274                    break;
3275                case com.android.internal.R.styleable.View_visibility:
3276                    final int visibility = a.getInt(attr, 0);
3277                    if (visibility != 0) {
3278                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3279                        viewFlagMasks |= VISIBILITY_MASK;
3280                    }
3281                    break;
3282                case com.android.internal.R.styleable.View_layoutDirection:
3283                    // Clear any layout direction flags (included resolved bits) already set
3284                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3285                    // Set the layout direction flags depending on the value of the attribute
3286                    final int layoutDirection = a.getInt(attr, -1);
3287                    final int value = (layoutDirection != -1) ?
3288                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3289                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3290                    break;
3291                case com.android.internal.R.styleable.View_drawingCacheQuality:
3292                    final int cacheQuality = a.getInt(attr, 0);
3293                    if (cacheQuality != 0) {
3294                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3295                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3296                    }
3297                    break;
3298                case com.android.internal.R.styleable.View_contentDescription:
3299                    mContentDescription = a.getString(attr);
3300                    break;
3301                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3302                    if (!a.getBoolean(attr, true)) {
3303                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3304                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3305                    }
3306                    break;
3307                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3308                    if (!a.getBoolean(attr, true)) {
3309                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3310                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3311                    }
3312                    break;
3313                case R.styleable.View_scrollbars:
3314                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3315                    if (scrollbars != SCROLLBARS_NONE) {
3316                        viewFlagValues |= scrollbars;
3317                        viewFlagMasks |= SCROLLBARS_MASK;
3318                        initializeScrollbars(a);
3319                    }
3320                    break;
3321                //noinspection deprecation
3322                case R.styleable.View_fadingEdge:
3323                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3324                        // Ignore the attribute starting with ICS
3325                        break;
3326                    }
3327                    // With builds < ICS, fall through and apply fading edges
3328                case R.styleable.View_requiresFadingEdge:
3329                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3330                    if (fadingEdge != FADING_EDGE_NONE) {
3331                        viewFlagValues |= fadingEdge;
3332                        viewFlagMasks |= FADING_EDGE_MASK;
3333                        initializeFadingEdge(a);
3334                    }
3335                    break;
3336                case R.styleable.View_scrollbarStyle:
3337                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3338                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3339                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3340                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3341                    }
3342                    break;
3343                case R.styleable.View_isScrollContainer:
3344                    setScrollContainer = true;
3345                    if (a.getBoolean(attr, false)) {
3346                        setScrollContainer(true);
3347                    }
3348                    break;
3349                case com.android.internal.R.styleable.View_keepScreenOn:
3350                    if (a.getBoolean(attr, false)) {
3351                        viewFlagValues |= KEEP_SCREEN_ON;
3352                        viewFlagMasks |= KEEP_SCREEN_ON;
3353                    }
3354                    break;
3355                case R.styleable.View_filterTouchesWhenObscured:
3356                    if (a.getBoolean(attr, false)) {
3357                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3358                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3359                    }
3360                    break;
3361                case R.styleable.View_nextFocusLeft:
3362                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3363                    break;
3364                case R.styleable.View_nextFocusRight:
3365                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3366                    break;
3367                case R.styleable.View_nextFocusUp:
3368                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3369                    break;
3370                case R.styleable.View_nextFocusDown:
3371                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3372                    break;
3373                case R.styleable.View_nextFocusForward:
3374                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3375                    break;
3376                case R.styleable.View_minWidth:
3377                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3378                    break;
3379                case R.styleable.View_minHeight:
3380                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3381                    break;
3382                case R.styleable.View_onClick:
3383                    if (context.isRestricted()) {
3384                        throw new IllegalStateException("The android:onClick attribute cannot "
3385                                + "be used within a restricted context");
3386                    }
3387
3388                    final String handlerName = a.getString(attr);
3389                    if (handlerName != null) {
3390                        setOnClickListener(new OnClickListener() {
3391                            private Method mHandler;
3392
3393                            public void onClick(View v) {
3394                                if (mHandler == null) {
3395                                    try {
3396                                        mHandler = getContext().getClass().getMethod(handlerName,
3397                                                View.class);
3398                                    } catch (NoSuchMethodException e) {
3399                                        int id = getId();
3400                                        String idText = id == NO_ID ? "" : " with id '"
3401                                                + getContext().getResources().getResourceEntryName(
3402                                                    id) + "'";
3403                                        throw new IllegalStateException("Could not find a method " +
3404                                                handlerName + "(View) in the activity "
3405                                                + getContext().getClass() + " for onClick handler"
3406                                                + " on view " + View.this.getClass() + idText, e);
3407                                    }
3408                                }
3409
3410                                try {
3411                                    mHandler.invoke(getContext(), View.this);
3412                                } catch (IllegalAccessException e) {
3413                                    throw new IllegalStateException("Could not execute non "
3414                                            + "public method of the activity", e);
3415                                } catch (InvocationTargetException e) {
3416                                    throw new IllegalStateException("Could not execute "
3417                                            + "method of the activity", e);
3418                                }
3419                            }
3420                        });
3421                    }
3422                    break;
3423                case R.styleable.View_overScrollMode:
3424                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3425                    break;
3426                case R.styleable.View_verticalScrollbarPosition:
3427                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3428                    break;
3429                case R.styleable.View_layerType:
3430                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3431                    break;
3432                case R.styleable.View_textDirection:
3433                    // Clear any text direction flag already set
3434                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3435                    // Set the text direction flags depending on the value of the attribute
3436                    final int textDirection = a.getInt(attr, -1);
3437                    if (textDirection != -1) {
3438                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3439                    }
3440                    break;
3441                case R.styleable.View_textAlignment:
3442                    // Clear any text alignment flag already set
3443                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3444                    // Set the text alignment flag depending on the value of the attribute
3445                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3446                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3447                    break;
3448                case R.styleable.View_importantForAccessibility:
3449                    setImportantForAccessibility(a.getInt(attr,
3450                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3451            }
3452        }
3453
3454        a.recycle();
3455
3456        setOverScrollMode(overScrollMode);
3457
3458        if (background != null) {
3459            setBackground(background);
3460        }
3461
3462        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3463        // layout direction). Those cached values will be used later during padding resolution.
3464        mUserPaddingStart = startPadding;
3465        mUserPaddingEnd = endPadding;
3466
3467        updateUserPaddingRelative();
3468
3469        if (padding >= 0) {
3470            leftPadding = padding;
3471            topPadding = padding;
3472            rightPadding = padding;
3473            bottomPadding = padding;
3474        }
3475
3476        // If the user specified the padding (either with android:padding or
3477        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3478        // use the default padding or the padding from the background drawable
3479        // (stored at this point in mPadding*)
3480        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3481                topPadding >= 0 ? topPadding : mPaddingTop,
3482                rightPadding >= 0 ? rightPadding : mPaddingRight,
3483                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3484
3485        if (viewFlagMasks != 0) {
3486            setFlags(viewFlagValues, viewFlagMasks);
3487        }
3488
3489        // Needs to be called after mViewFlags is set
3490        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3491            recomputePadding();
3492        }
3493
3494        if (x != 0 || y != 0) {
3495            scrollTo(x, y);
3496        }
3497
3498        if (transformSet) {
3499            setTranslationX(tx);
3500            setTranslationY(ty);
3501            setRotation(rotation);
3502            setRotationX(rotationX);
3503            setRotationY(rotationY);
3504            setScaleX(sx);
3505            setScaleY(sy);
3506        }
3507
3508        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3509            setScrollContainer(true);
3510        }
3511
3512        computeOpaqueFlags();
3513    }
3514
3515    private void updateUserPaddingRelative() {
3516        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3517    }
3518
3519    /**
3520     * Non-public constructor for use in testing
3521     */
3522    View() {
3523        mResources = null;
3524    }
3525
3526    /**
3527     * <p>
3528     * Initializes the fading edges from a given set of styled attributes. This
3529     * method should be called by subclasses that need fading edges and when an
3530     * instance of these subclasses is created programmatically rather than
3531     * being inflated from XML. This method is automatically called when the XML
3532     * is inflated.
3533     * </p>
3534     *
3535     * @param a the styled attributes set to initialize the fading edges from
3536     */
3537    protected void initializeFadingEdge(TypedArray a) {
3538        initScrollCache();
3539
3540        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3541                R.styleable.View_fadingEdgeLength,
3542                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3543    }
3544
3545    /**
3546     * Returns the size of the vertical faded edges used to indicate that more
3547     * content in this view is visible.
3548     *
3549     * @return The size in pixels of the vertical faded edge or 0 if vertical
3550     *         faded edges are not enabled for this view.
3551     * @attr ref android.R.styleable#View_fadingEdgeLength
3552     */
3553    public int getVerticalFadingEdgeLength() {
3554        if (isVerticalFadingEdgeEnabled()) {
3555            ScrollabilityCache cache = mScrollCache;
3556            if (cache != null) {
3557                return cache.fadingEdgeLength;
3558            }
3559        }
3560        return 0;
3561    }
3562
3563    /**
3564     * Set the size of the faded edge used to indicate that more content in this
3565     * view is available.  Will not change whether the fading edge is enabled; use
3566     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3567     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3568     * for the vertical or horizontal fading edges.
3569     *
3570     * @param length The size in pixels of the faded edge used to indicate that more
3571     *        content in this view is visible.
3572     */
3573    public void setFadingEdgeLength(int length) {
3574        initScrollCache();
3575        mScrollCache.fadingEdgeLength = length;
3576    }
3577
3578    /**
3579     * Returns the size of the horizontal faded edges used to indicate that more
3580     * content in this view is visible.
3581     *
3582     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3583     *         faded edges are not enabled for this view.
3584     * @attr ref android.R.styleable#View_fadingEdgeLength
3585     */
3586    public int getHorizontalFadingEdgeLength() {
3587        if (isHorizontalFadingEdgeEnabled()) {
3588            ScrollabilityCache cache = mScrollCache;
3589            if (cache != null) {
3590                return cache.fadingEdgeLength;
3591            }
3592        }
3593        return 0;
3594    }
3595
3596    /**
3597     * Returns the width of the vertical scrollbar.
3598     *
3599     * @return The width in pixels of the vertical scrollbar or 0 if there
3600     *         is no vertical scrollbar.
3601     */
3602    public int getVerticalScrollbarWidth() {
3603        ScrollabilityCache cache = mScrollCache;
3604        if (cache != null) {
3605            ScrollBarDrawable scrollBar = cache.scrollBar;
3606            if (scrollBar != null) {
3607                int size = scrollBar.getSize(true);
3608                if (size <= 0) {
3609                    size = cache.scrollBarSize;
3610                }
3611                return size;
3612            }
3613            return 0;
3614        }
3615        return 0;
3616    }
3617
3618    /**
3619     * Returns the height of the horizontal scrollbar.
3620     *
3621     * @return The height in pixels of the horizontal scrollbar or 0 if
3622     *         there is no horizontal scrollbar.
3623     */
3624    protected int getHorizontalScrollbarHeight() {
3625        ScrollabilityCache cache = mScrollCache;
3626        if (cache != null) {
3627            ScrollBarDrawable scrollBar = cache.scrollBar;
3628            if (scrollBar != null) {
3629                int size = scrollBar.getSize(false);
3630                if (size <= 0) {
3631                    size = cache.scrollBarSize;
3632                }
3633                return size;
3634            }
3635            return 0;
3636        }
3637        return 0;
3638    }
3639
3640    /**
3641     * <p>
3642     * Initializes the scrollbars from a given set of styled attributes. This
3643     * method should be called by subclasses that need scrollbars and when an
3644     * instance of these subclasses is created programmatically rather than
3645     * being inflated from XML. This method is automatically called when the XML
3646     * is inflated.
3647     * </p>
3648     *
3649     * @param a the styled attributes set to initialize the scrollbars from
3650     */
3651    protected void initializeScrollbars(TypedArray a) {
3652        initScrollCache();
3653
3654        final ScrollabilityCache scrollabilityCache = mScrollCache;
3655
3656        if (scrollabilityCache.scrollBar == null) {
3657            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3658        }
3659
3660        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3661
3662        if (!fadeScrollbars) {
3663            scrollabilityCache.state = ScrollabilityCache.ON;
3664        }
3665        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3666
3667
3668        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3669                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3670                        .getScrollBarFadeDuration());
3671        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3672                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3673                ViewConfiguration.getScrollDefaultDelay());
3674
3675
3676        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3677                com.android.internal.R.styleable.View_scrollbarSize,
3678                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3679
3680        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3681        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3682
3683        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3684        if (thumb != null) {
3685            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3686        }
3687
3688        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3689                false);
3690        if (alwaysDraw) {
3691            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3692        }
3693
3694        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3695        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3696
3697        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3698        if (thumb != null) {
3699            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3700        }
3701
3702        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3703                false);
3704        if (alwaysDraw) {
3705            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3706        }
3707
3708        // Re-apply user/background padding so that scrollbar(s) get added
3709        resolvePadding();
3710    }
3711
3712    /**
3713     * <p>
3714     * Initalizes the scrollability cache if necessary.
3715     * </p>
3716     */
3717    private void initScrollCache() {
3718        if (mScrollCache == null) {
3719            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3720        }
3721    }
3722
3723    private ScrollabilityCache getScrollCache() {
3724        initScrollCache();
3725        return mScrollCache;
3726    }
3727
3728    /**
3729     * Set the position of the vertical scroll bar. Should be one of
3730     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3731     * {@link #SCROLLBAR_POSITION_RIGHT}.
3732     *
3733     * @param position Where the vertical scroll bar should be positioned.
3734     */
3735    public void setVerticalScrollbarPosition(int position) {
3736        if (mVerticalScrollbarPosition != position) {
3737            mVerticalScrollbarPosition = position;
3738            computeOpaqueFlags();
3739            resolvePadding();
3740        }
3741    }
3742
3743    /**
3744     * @return The position where the vertical scroll bar will show, if applicable.
3745     * @see #setVerticalScrollbarPosition(int)
3746     */
3747    public int getVerticalScrollbarPosition() {
3748        return mVerticalScrollbarPosition;
3749    }
3750
3751    ListenerInfo getListenerInfo() {
3752        if (mListenerInfo != null) {
3753            return mListenerInfo;
3754        }
3755        mListenerInfo = new ListenerInfo();
3756        return mListenerInfo;
3757    }
3758
3759    /**
3760     * Register a callback to be invoked when focus of this view changed.
3761     *
3762     * @param l The callback that will run.
3763     */
3764    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3765        getListenerInfo().mOnFocusChangeListener = l;
3766    }
3767
3768    /**
3769     * Add a listener that will be called when the bounds of the view change due to
3770     * layout processing.
3771     *
3772     * @param listener The listener that will be called when layout bounds change.
3773     */
3774    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3775        ListenerInfo li = getListenerInfo();
3776        if (li.mOnLayoutChangeListeners == null) {
3777            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3778        }
3779        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3780            li.mOnLayoutChangeListeners.add(listener);
3781        }
3782    }
3783
3784    /**
3785     * Remove a listener for layout changes.
3786     *
3787     * @param listener The listener for layout bounds change.
3788     */
3789    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3790        ListenerInfo li = mListenerInfo;
3791        if (li == null || li.mOnLayoutChangeListeners == null) {
3792            return;
3793        }
3794        li.mOnLayoutChangeListeners.remove(listener);
3795    }
3796
3797    /**
3798     * Add a listener for attach state changes.
3799     *
3800     * This listener will be called whenever this view is attached or detached
3801     * from a window. Remove the listener using
3802     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3803     *
3804     * @param listener Listener to attach
3805     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3806     */
3807    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3808        ListenerInfo li = getListenerInfo();
3809        if (li.mOnAttachStateChangeListeners == null) {
3810            li.mOnAttachStateChangeListeners
3811                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3812        }
3813        li.mOnAttachStateChangeListeners.add(listener);
3814    }
3815
3816    /**
3817     * Remove a listener for attach state changes. The listener will receive no further
3818     * notification of window attach/detach events.
3819     *
3820     * @param listener Listener to remove
3821     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3822     */
3823    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3824        ListenerInfo li = mListenerInfo;
3825        if (li == null || li.mOnAttachStateChangeListeners == null) {
3826            return;
3827        }
3828        li.mOnAttachStateChangeListeners.remove(listener);
3829    }
3830
3831    /**
3832     * Returns the focus-change callback registered for this view.
3833     *
3834     * @return The callback, or null if one is not registered.
3835     */
3836    public OnFocusChangeListener getOnFocusChangeListener() {
3837        ListenerInfo li = mListenerInfo;
3838        return li != null ? li.mOnFocusChangeListener : null;
3839    }
3840
3841    /**
3842     * Register a callback to be invoked when this view is clicked. If this view is not
3843     * clickable, it becomes clickable.
3844     *
3845     * @param l The callback that will run
3846     *
3847     * @see #setClickable(boolean)
3848     */
3849    public void setOnClickListener(OnClickListener l) {
3850        if (!isClickable()) {
3851            setClickable(true);
3852        }
3853        getListenerInfo().mOnClickListener = l;
3854    }
3855
3856    /**
3857     * Return whether this view has an attached OnClickListener.  Returns
3858     * true if there is a listener, false if there is none.
3859     */
3860    public boolean hasOnClickListeners() {
3861        ListenerInfo li = mListenerInfo;
3862        return (li != null && li.mOnClickListener != null);
3863    }
3864
3865    /**
3866     * Register a callback to be invoked when this view is clicked and held. If this view is not
3867     * long clickable, it becomes long clickable.
3868     *
3869     * @param l The callback that will run
3870     *
3871     * @see #setLongClickable(boolean)
3872     */
3873    public void setOnLongClickListener(OnLongClickListener l) {
3874        if (!isLongClickable()) {
3875            setLongClickable(true);
3876        }
3877        getListenerInfo().mOnLongClickListener = l;
3878    }
3879
3880    /**
3881     * Register a callback to be invoked when the context menu for this view is
3882     * being built. If this view is not long clickable, it becomes long clickable.
3883     *
3884     * @param l The callback that will run
3885     *
3886     */
3887    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3888        if (!isLongClickable()) {
3889            setLongClickable(true);
3890        }
3891        getListenerInfo().mOnCreateContextMenuListener = l;
3892    }
3893
3894    /**
3895     * Call this view's OnClickListener, if it is defined.  Performs all normal
3896     * actions associated with clicking: reporting accessibility event, playing
3897     * a sound, etc.
3898     *
3899     * @return True there was an assigned OnClickListener that was called, false
3900     *         otherwise is returned.
3901     */
3902    public boolean performClick() {
3903        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3904
3905        ListenerInfo li = mListenerInfo;
3906        if (li != null && li.mOnClickListener != null) {
3907            playSoundEffect(SoundEffectConstants.CLICK);
3908            li.mOnClickListener.onClick(this);
3909            return true;
3910        }
3911
3912        return false;
3913    }
3914
3915    /**
3916     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3917     * this only calls the listener, and does not do any associated clicking
3918     * actions like reporting an accessibility event.
3919     *
3920     * @return True there was an assigned OnClickListener that was called, false
3921     *         otherwise is returned.
3922     */
3923    public boolean callOnClick() {
3924        ListenerInfo li = mListenerInfo;
3925        if (li != null && li.mOnClickListener != null) {
3926            li.mOnClickListener.onClick(this);
3927            return true;
3928        }
3929        return false;
3930    }
3931
3932    /**
3933     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3934     * OnLongClickListener did not consume the event.
3935     *
3936     * @return True if one of the above receivers consumed the event, false otherwise.
3937     */
3938    public boolean performLongClick() {
3939        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3940
3941        boolean handled = false;
3942        ListenerInfo li = mListenerInfo;
3943        if (li != null && li.mOnLongClickListener != null) {
3944            handled = li.mOnLongClickListener.onLongClick(View.this);
3945        }
3946        if (!handled) {
3947            handled = showContextMenu();
3948        }
3949        if (handled) {
3950            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3951        }
3952        return handled;
3953    }
3954
3955    /**
3956     * Performs button-related actions during a touch down event.
3957     *
3958     * @param event The event.
3959     * @return True if the down was consumed.
3960     *
3961     * @hide
3962     */
3963    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3964        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3965            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3966                return true;
3967            }
3968        }
3969        return false;
3970    }
3971
3972    /**
3973     * Bring up the context menu for this view.
3974     *
3975     * @return Whether a context menu was displayed.
3976     */
3977    public boolean showContextMenu() {
3978        return getParent().showContextMenuForChild(this);
3979    }
3980
3981    /**
3982     * Bring up the context menu for this view, referring to the item under the specified point.
3983     *
3984     * @param x The referenced x coordinate.
3985     * @param y The referenced y coordinate.
3986     * @param metaState The keyboard modifiers that were pressed.
3987     * @return Whether a context menu was displayed.
3988     *
3989     * @hide
3990     */
3991    public boolean showContextMenu(float x, float y, int metaState) {
3992        return showContextMenu();
3993    }
3994
3995    /**
3996     * Start an action mode.
3997     *
3998     * @param callback Callback that will control the lifecycle of the action mode
3999     * @return The new action mode if it is started, null otherwise
4000     *
4001     * @see ActionMode
4002     */
4003    public ActionMode startActionMode(ActionMode.Callback callback) {
4004        ViewParent parent = getParent();
4005        if (parent == null) return null;
4006        return parent.startActionModeForChild(this, callback);
4007    }
4008
4009    /**
4010     * Register a callback to be invoked when a key is pressed in this view.
4011     * @param l the key listener to attach to this view
4012     */
4013    public void setOnKeyListener(OnKeyListener l) {
4014        getListenerInfo().mOnKeyListener = l;
4015    }
4016
4017    /**
4018     * Register a callback to be invoked when a touch event is sent to this view.
4019     * @param l the touch listener to attach to this view
4020     */
4021    public void setOnTouchListener(OnTouchListener l) {
4022        getListenerInfo().mOnTouchListener = l;
4023    }
4024
4025    /**
4026     * Register a callback to be invoked when a generic motion event is sent to this view.
4027     * @param l the generic motion listener to attach to this view
4028     */
4029    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4030        getListenerInfo().mOnGenericMotionListener = l;
4031    }
4032
4033    /**
4034     * Register a callback to be invoked when a hover event is sent to this view.
4035     * @param l the hover listener to attach to this view
4036     */
4037    public void setOnHoverListener(OnHoverListener l) {
4038        getListenerInfo().mOnHoverListener = l;
4039    }
4040
4041    /**
4042     * Register a drag event listener callback object for this View. The parameter is
4043     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4044     * View, the system calls the
4045     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4046     * @param l An implementation of {@link android.view.View.OnDragListener}.
4047     */
4048    public void setOnDragListener(OnDragListener l) {
4049        getListenerInfo().mOnDragListener = l;
4050    }
4051
4052    /**
4053     * Give this view focus. This will cause
4054     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4055     *
4056     * Note: this does not check whether this {@link View} should get focus, it just
4057     * gives it focus no matter what.  It should only be called internally by framework
4058     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4059     *
4060     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4061     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4062     *        focus moved when requestFocus() is called. It may not always
4063     *        apply, in which case use the default View.FOCUS_DOWN.
4064     * @param previouslyFocusedRect The rectangle of the view that had focus
4065     *        prior in this View's coordinate system.
4066     */
4067    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4068        if (DBG) {
4069            System.out.println(this + " requestFocus()");
4070        }
4071
4072        if ((mPrivateFlags & FOCUSED) == 0) {
4073            mPrivateFlags |= FOCUSED;
4074
4075            if (mParent != null) {
4076                mParent.requestChildFocus(this, this);
4077            }
4078
4079            onFocusChanged(true, direction, previouslyFocusedRect);
4080            refreshDrawableState();
4081
4082            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4083                notifyAccessibilityStateChanged();
4084            }
4085        }
4086    }
4087
4088    /**
4089     * Request that a rectangle of this view be visible on the screen,
4090     * scrolling if necessary just enough.
4091     *
4092     * <p>A View should call this if it maintains some notion of which part
4093     * of its content is interesting.  For example, a text editing view
4094     * should call this when its cursor moves.
4095     *
4096     * @param rectangle The rectangle.
4097     * @return Whether any parent scrolled.
4098     */
4099    public boolean requestRectangleOnScreen(Rect rectangle) {
4100        return requestRectangleOnScreen(rectangle, false);
4101    }
4102
4103    /**
4104     * Request that a rectangle of this view be visible on the screen,
4105     * scrolling if necessary just enough.
4106     *
4107     * <p>A View should call this if it maintains some notion of which part
4108     * of its content is interesting.  For example, a text editing view
4109     * should call this when its cursor moves.
4110     *
4111     * <p>When <code>immediate</code> is set to true, scrolling will not be
4112     * animated.
4113     *
4114     * @param rectangle The rectangle.
4115     * @param immediate True to forbid animated scrolling, false otherwise
4116     * @return Whether any parent scrolled.
4117     */
4118    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4119        View child = this;
4120        ViewParent parent = mParent;
4121        boolean scrolled = false;
4122        while (parent != null) {
4123            scrolled |= parent.requestChildRectangleOnScreen(child,
4124                    rectangle, immediate);
4125
4126            // offset rect so next call has the rectangle in the
4127            // coordinate system of its direct child.
4128            rectangle.offset(child.getLeft(), child.getTop());
4129            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4130
4131            if (!(parent instanceof View)) {
4132                break;
4133            }
4134
4135            child = (View) parent;
4136            parent = child.getParent();
4137        }
4138        return scrolled;
4139    }
4140
4141    /**
4142     * Called when this view wants to give up focus. If focus is cleared
4143     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4144     * <p>
4145     * <strong>Note:</strong> When a View clears focus the framework is trying
4146     * to give focus to the first focusable View from the top. Hence, if this
4147     * View is the first from the top that can take focus, then all callbacks
4148     * related to clearing focus will be invoked after wich the framework will
4149     * give focus to this view.
4150     * </p>
4151     */
4152    public void clearFocus() {
4153        if (DBG) {
4154            System.out.println(this + " clearFocus()");
4155        }
4156
4157        if ((mPrivateFlags & FOCUSED) != 0) {
4158            mPrivateFlags &= ~FOCUSED;
4159
4160            if (mParent != null) {
4161                mParent.clearChildFocus(this);
4162            }
4163
4164            onFocusChanged(false, 0, null);
4165
4166            refreshDrawableState();
4167
4168            ensureInputFocusOnFirstFocusable();
4169
4170            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4171                notifyAccessibilityStateChanged();
4172            }
4173        }
4174    }
4175
4176    void ensureInputFocusOnFirstFocusable() {
4177        View root = getRootView();
4178        if (root != null) {
4179            root.requestFocus();
4180        }
4181    }
4182
4183    /**
4184     * Called internally by the view system when a new view is getting focus.
4185     * This is what clears the old focus.
4186     */
4187    void unFocus() {
4188        if (DBG) {
4189            System.out.println(this + " unFocus()");
4190        }
4191
4192        if ((mPrivateFlags & FOCUSED) != 0) {
4193            mPrivateFlags &= ~FOCUSED;
4194
4195            onFocusChanged(false, 0, null);
4196            refreshDrawableState();
4197
4198            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4199                notifyAccessibilityStateChanged();
4200            }
4201        }
4202    }
4203
4204    /**
4205     * Returns true if this view has focus iteself, or is the ancestor of the
4206     * view that has focus.
4207     *
4208     * @return True if this view has or contains focus, false otherwise.
4209     */
4210    @ViewDebug.ExportedProperty(category = "focus")
4211    public boolean hasFocus() {
4212        return (mPrivateFlags & FOCUSED) != 0;
4213    }
4214
4215    /**
4216     * Returns true if this view is focusable or if it contains a reachable View
4217     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4218     * is a View whose parents do not block descendants focus.
4219     *
4220     * Only {@link #VISIBLE} views are considered focusable.
4221     *
4222     * @return True if the view is focusable or if the view contains a focusable
4223     *         View, false otherwise.
4224     *
4225     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4226     */
4227    public boolean hasFocusable() {
4228        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4229    }
4230
4231    /**
4232     * Called by the view system when the focus state of this view changes.
4233     * When the focus change event is caused by directional navigation, direction
4234     * and previouslyFocusedRect provide insight into where the focus is coming from.
4235     * When overriding, be sure to call up through to the super class so that
4236     * the standard focus handling will occur.
4237     *
4238     * @param gainFocus True if the View has focus; false otherwise.
4239     * @param direction The direction focus has moved when requestFocus()
4240     *                  is called to give this view focus. Values are
4241     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4242     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4243     *                  It may not always apply, in which case use the default.
4244     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4245     *        system, of the previously focused view.  If applicable, this will be
4246     *        passed in as finer grained information about where the focus is coming
4247     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4248     */
4249    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4250        if (gainFocus) {
4251            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4252                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4253                requestAccessibilityFocus();
4254            }
4255        }
4256
4257        InputMethodManager imm = InputMethodManager.peekInstance();
4258        if (!gainFocus) {
4259            if (isPressed()) {
4260                setPressed(false);
4261            }
4262            if (imm != null && mAttachInfo != null
4263                    && mAttachInfo.mHasWindowFocus) {
4264                imm.focusOut(this);
4265            }
4266            onFocusLost();
4267        } else if (imm != null && mAttachInfo != null
4268                && mAttachInfo.mHasWindowFocus) {
4269            imm.focusIn(this);
4270        }
4271
4272        invalidate(true);
4273        ListenerInfo li = mListenerInfo;
4274        if (li != null && li.mOnFocusChangeListener != null) {
4275            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4276        }
4277
4278        if (mAttachInfo != null) {
4279            mAttachInfo.mKeyDispatchState.reset(this);
4280        }
4281    }
4282
4283    /**
4284     * Sends an accessibility event of the given type. If accessiiblity is
4285     * not enabled this method has no effect. The default implementation calls
4286     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4287     * to populate information about the event source (this View), then calls
4288     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4289     * populate the text content of the event source including its descendants,
4290     * and last calls
4291     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4292     * on its parent to resuest sending of the event to interested parties.
4293     * <p>
4294     * If an {@link AccessibilityDelegate} has been specified via calling
4295     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4296     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4297     * responsible for handling this call.
4298     * </p>
4299     *
4300     * @param eventType The type of the event to send, as defined by several types from
4301     * {@link android.view.accessibility.AccessibilityEvent}, such as
4302     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4303     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4304     *
4305     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4306     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4307     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4308     * @see AccessibilityDelegate
4309     */
4310    public void sendAccessibilityEvent(int eventType) {
4311        if (mAccessibilityDelegate != null) {
4312            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4313        } else {
4314            sendAccessibilityEventInternal(eventType);
4315        }
4316    }
4317
4318    /**
4319     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4320     * {@link AccessibilityEvent} to make an announcement which is related to some
4321     * sort of a context change for which none of the events representing UI transitions
4322     * is a good fit. For example, announcing a new page in a book. If accessibility
4323     * is not enabled this method does nothing.
4324     *
4325     * @param text The announcement text.
4326     */
4327    public void announceForAccessibility(CharSequence text) {
4328        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4329            AccessibilityEvent event = AccessibilityEvent.obtain(
4330                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4331            event.getText().add(text);
4332            sendAccessibilityEventUnchecked(event);
4333        }
4334    }
4335
4336    /**
4337     * @see #sendAccessibilityEvent(int)
4338     *
4339     * Note: Called from the default {@link AccessibilityDelegate}.
4340     */
4341    void sendAccessibilityEventInternal(int eventType) {
4342        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4343            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4344        }
4345    }
4346
4347    /**
4348     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4349     * takes as an argument an empty {@link AccessibilityEvent} and does not
4350     * perform a check whether accessibility is enabled.
4351     * <p>
4352     * If an {@link AccessibilityDelegate} has been specified via calling
4353     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4354     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4355     * is responsible for handling this call.
4356     * </p>
4357     *
4358     * @param event The event to send.
4359     *
4360     * @see #sendAccessibilityEvent(int)
4361     */
4362    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4363        if (mAccessibilityDelegate != null) {
4364            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4365        } else {
4366            sendAccessibilityEventUncheckedInternal(event);
4367        }
4368    }
4369
4370    /**
4371     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4372     *
4373     * Note: Called from the default {@link AccessibilityDelegate}.
4374     */
4375    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4376        if (!isShown()) {
4377            return;
4378        }
4379        onInitializeAccessibilityEvent(event);
4380        // Only a subset of accessibility events populates text content.
4381        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4382            dispatchPopulateAccessibilityEvent(event);
4383        }
4384        // Intercept accessibility focus events fired by virtual nodes to keep
4385        // track of accessibility focus position in such nodes.
4386        final int eventType = event.getEventType();
4387        switch (eventType) {
4388            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4389                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4390                        event.getSourceNodeId());
4391                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4392                    ViewRootImpl viewRootImpl = getViewRootImpl();
4393                    if (viewRootImpl != null) {
4394                        viewRootImpl.setAccessibilityFocusedHost(this);
4395                    }
4396                }
4397            } break;
4398            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4399                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4400                        event.getSourceNodeId());
4401                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4402                    ViewRootImpl viewRootImpl = getViewRootImpl();
4403                    if (viewRootImpl != null) {
4404                        viewRootImpl.setAccessibilityFocusedHost(null);
4405                    }
4406                }
4407            } break;
4408        }
4409        // In the beginning we called #isShown(), so we know that getParent() is not null.
4410        getParent().requestSendAccessibilityEvent(this, event);
4411    }
4412
4413    /**
4414     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4415     * to its children for adding their text content to the event. Note that the
4416     * event text is populated in a separate dispatch path since we add to the
4417     * event not only the text of the source but also the text of all its descendants.
4418     * A typical implementation will call
4419     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4420     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4421     * on each child. Override this method if custom population of the event text
4422     * content is required.
4423     * <p>
4424     * If an {@link AccessibilityDelegate} has been specified via calling
4425     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4426     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4427     * is responsible for handling this call.
4428     * </p>
4429     * <p>
4430     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4431     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4432     * </p>
4433     *
4434     * @param event The event.
4435     *
4436     * @return True if the event population was completed.
4437     */
4438    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4439        if (mAccessibilityDelegate != null) {
4440            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4441        } else {
4442            return dispatchPopulateAccessibilityEventInternal(event);
4443        }
4444    }
4445
4446    /**
4447     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4448     *
4449     * Note: Called from the default {@link AccessibilityDelegate}.
4450     */
4451    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4452        onPopulateAccessibilityEvent(event);
4453        return false;
4454    }
4455
4456    /**
4457     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4458     * giving a chance to this View to populate the accessibility event with its
4459     * text content. While this method is free to modify event
4460     * attributes other than text content, doing so should normally be performed in
4461     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4462     * <p>
4463     * Example: Adding formatted date string to an accessibility event in addition
4464     *          to the text added by the super implementation:
4465     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4466     *     super.onPopulateAccessibilityEvent(event);
4467     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4468     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4469     *         mCurrentDate.getTimeInMillis(), flags);
4470     *     event.getText().add(selectedDateUtterance);
4471     * }</pre>
4472     * <p>
4473     * If an {@link AccessibilityDelegate} has been specified via calling
4474     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4475     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4476     * is responsible for handling this call.
4477     * </p>
4478     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4479     * information to the event, in case the default implementation has basic information to add.
4480     * </p>
4481     *
4482     * @param event The accessibility event which to populate.
4483     *
4484     * @see #sendAccessibilityEvent(int)
4485     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4486     */
4487    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4488        if (mAccessibilityDelegate != null) {
4489            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4490        } else {
4491            onPopulateAccessibilityEventInternal(event);
4492        }
4493    }
4494
4495    /**
4496     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4497     *
4498     * Note: Called from the default {@link AccessibilityDelegate}.
4499     */
4500    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4501
4502    }
4503
4504    /**
4505     * Initializes an {@link AccessibilityEvent} with information about
4506     * this View which is the event source. In other words, the source of
4507     * an accessibility event is the view whose state change triggered firing
4508     * the event.
4509     * <p>
4510     * Example: Setting the password property of an event in addition
4511     *          to properties set by the super implementation:
4512     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4513     *     super.onInitializeAccessibilityEvent(event);
4514     *     event.setPassword(true);
4515     * }</pre>
4516     * <p>
4517     * If an {@link AccessibilityDelegate} has been specified via calling
4518     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4519     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4520     * is responsible for handling this call.
4521     * </p>
4522     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4523     * information to the event, in case the default implementation has basic information to add.
4524     * </p>
4525     * @param event The event to initialize.
4526     *
4527     * @see #sendAccessibilityEvent(int)
4528     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4529     */
4530    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4531        if (mAccessibilityDelegate != null) {
4532            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4533        } else {
4534            onInitializeAccessibilityEventInternal(event);
4535        }
4536    }
4537
4538    /**
4539     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4540     *
4541     * Note: Called from the default {@link AccessibilityDelegate}.
4542     */
4543    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4544        event.setSource(this);
4545        event.setClassName(View.class.getName());
4546        event.setPackageName(getContext().getPackageName());
4547        event.setEnabled(isEnabled());
4548        event.setContentDescription(mContentDescription);
4549
4550        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4551            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4552            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4553                    FOCUSABLES_ALL);
4554            event.setItemCount(focusablesTempList.size());
4555            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4556            focusablesTempList.clear();
4557        }
4558    }
4559
4560    /**
4561     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4562     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4563     * This method is responsible for obtaining an accessibility node info from a
4564     * pool of reusable instances and calling
4565     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4566     * initialize the former.
4567     * <p>
4568     * Note: The client is responsible for recycling the obtained instance by calling
4569     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4570     * </p>
4571     *
4572     * @return A populated {@link AccessibilityNodeInfo}.
4573     *
4574     * @see AccessibilityNodeInfo
4575     */
4576    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4577        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4578        if (provider != null) {
4579            return provider.createAccessibilityNodeInfo(View.NO_ID);
4580        } else {
4581            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4582            onInitializeAccessibilityNodeInfo(info);
4583            return info;
4584        }
4585    }
4586
4587    /**
4588     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4589     * The base implementation sets:
4590     * <ul>
4591     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4592     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4593     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4594     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4595     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4596     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4597     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4598     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4599     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4600     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4601     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4602     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4603     * </ul>
4604     * <p>
4605     * Subclasses should override this method, call the super implementation,
4606     * and set additional attributes.
4607     * </p>
4608     * <p>
4609     * If an {@link AccessibilityDelegate} has been specified via calling
4610     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4611     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4612     * is responsible for handling this call.
4613     * </p>
4614     *
4615     * @param info The instance to initialize.
4616     */
4617    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4618        if (mAccessibilityDelegate != null) {
4619            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4620        } else {
4621            onInitializeAccessibilityNodeInfoInternal(info);
4622        }
4623    }
4624
4625    /**
4626     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4627     *
4628     * Note: Called from the default {@link AccessibilityDelegate}.
4629     */
4630    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4631        Rect bounds = mAttachInfo.mTmpInvalRect;
4632        getDrawingRect(bounds);
4633        info.setBoundsInParent(bounds);
4634
4635        getGlobalVisibleRect(bounds);
4636        bounds.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4637        info.setBoundsInScreen(bounds);
4638
4639        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4640            ViewParent parent = getParentForAccessibility();
4641            if (parent instanceof View) {
4642                info.setParent((View) parent);
4643            }
4644        }
4645
4646        info.setPackageName(mContext.getPackageName());
4647        info.setClassName(View.class.getName());
4648        info.setContentDescription(getContentDescription());
4649
4650        info.setEnabled(isEnabled());
4651        info.setClickable(isClickable());
4652        info.setFocusable(isFocusable());
4653        info.setFocused(isFocused());
4654        info.setAccessibilityFocused(isAccessibilityFocused());
4655        info.setSelected(isSelected());
4656        info.setLongClickable(isLongClickable());
4657
4658        // TODO: These make sense only if we are in an AdapterView but all
4659        // views can be selected. Maybe from accessiiblity perspective
4660        // we should report as selectable view in an AdapterView.
4661        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4662        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4663
4664        if (isFocusable()) {
4665            if (isFocused()) {
4666                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4667            } else {
4668                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4669            }
4670        }
4671
4672        info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4673        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4674
4675        if (isClickable()) {
4676            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4677        }
4678
4679        if (isLongClickable()) {
4680            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4681        }
4682
4683        if (getContentDescription() != null) {
4684            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_GRANULARITY);
4685            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_GRANULARITY);
4686            info.setGranularities(AccessibilityNodeInfo.GRANULARITY_CHARACTER
4687                    | AccessibilityNodeInfo.GRANULARITY_WORD);
4688        }
4689    }
4690
4691    /**
4692     * Computes whether this view is visible on the screen.
4693     *
4694     * @return Whether the view is visible on the screen.
4695     */
4696    boolean isDisplayedOnScreen() {
4697        // The first two checks are made also made by isShown() which
4698        // however traverses the tree up to the parent to catch that.
4699        // Therefore, we do some fail fast check to minimize the up
4700        // tree traversal.
4701        return (mAttachInfo != null
4702                && mAttachInfo.mWindowVisibility == View.VISIBLE
4703                && getAlpha() > 0
4704                && isShown()
4705                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4706    }
4707
4708    /**
4709     * Sets a delegate for implementing accessibility support via compositon as
4710     * opposed to inheritance. The delegate's primary use is for implementing
4711     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4712     *
4713     * @param delegate The delegate instance.
4714     *
4715     * @see AccessibilityDelegate
4716     */
4717    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4718        mAccessibilityDelegate = delegate;
4719    }
4720
4721    /**
4722     * Gets the provider for managing a virtual view hierarchy rooted at this View
4723     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4724     * that explore the window content.
4725     * <p>
4726     * If this method returns an instance, this instance is responsible for managing
4727     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4728     * View including the one representing the View itself. Similarly the returned
4729     * instance is responsible for performing accessibility actions on any virtual
4730     * view or the root view itself.
4731     * </p>
4732     * <p>
4733     * If an {@link AccessibilityDelegate} has been specified via calling
4734     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4735     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4736     * is responsible for handling this call.
4737     * </p>
4738     *
4739     * @return The provider.
4740     *
4741     * @see AccessibilityNodeProvider
4742     */
4743    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4744        if (mAccessibilityDelegate != null) {
4745            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4746        } else {
4747            return null;
4748        }
4749    }
4750
4751    /**
4752     * Gets the unique identifier of this view on the screen for accessibility purposes.
4753     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4754     *
4755     * @return The view accessibility id.
4756     *
4757     * @hide
4758     */
4759    public int getAccessibilityViewId() {
4760        if (mAccessibilityViewId == NO_ID) {
4761            mAccessibilityViewId = sNextAccessibilityViewId++;
4762        }
4763        return mAccessibilityViewId;
4764    }
4765
4766    /**
4767     * Gets the unique identifier of the window in which this View reseides.
4768     *
4769     * @return The window accessibility id.
4770     *
4771     * @hide
4772     */
4773    public int getAccessibilityWindowId() {
4774        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4775    }
4776
4777    /**
4778     * Gets the {@link View} description. It briefly describes the view and is
4779     * primarily used for accessibility support. Set this property to enable
4780     * better accessibility support for your application. This is especially
4781     * true for views that do not have textual representation (For example,
4782     * ImageButton).
4783     *
4784     * @return The content description.
4785     *
4786     * @attr ref android.R.styleable#View_contentDescription
4787     */
4788    @ViewDebug.ExportedProperty(category = "accessibility")
4789    public CharSequence getContentDescription() {
4790        return mContentDescription;
4791    }
4792
4793    /**
4794     * Sets the {@link View} description. It briefly describes the view and is
4795     * primarily used for accessibility support. Set this property to enable
4796     * better accessibility support for your application. This is especially
4797     * true for views that do not have textual representation (For example,
4798     * ImageButton).
4799     *
4800     * @param contentDescription The content description.
4801     *
4802     * @attr ref android.R.styleable#View_contentDescription
4803     */
4804    @RemotableViewMethod
4805    public void setContentDescription(CharSequence contentDescription) {
4806        mContentDescription = contentDescription;
4807    }
4808
4809    /**
4810     * Invoked whenever this view loses focus, either by losing window focus or by losing
4811     * focus within its window. This method can be used to clear any state tied to the
4812     * focus. For instance, if a button is held pressed with the trackball and the window
4813     * loses focus, this method can be used to cancel the press.
4814     *
4815     * Subclasses of View overriding this method should always call super.onFocusLost().
4816     *
4817     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4818     * @see #onWindowFocusChanged(boolean)
4819     *
4820     * @hide pending API council approval
4821     */
4822    protected void onFocusLost() {
4823        resetPressedState();
4824    }
4825
4826    private void resetPressedState() {
4827        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4828            return;
4829        }
4830
4831        if (isPressed()) {
4832            setPressed(false);
4833
4834            if (!mHasPerformedLongPress) {
4835                removeLongPressCallback();
4836            }
4837        }
4838    }
4839
4840    /**
4841     * Returns true if this view has focus
4842     *
4843     * @return True if this view has focus, false otherwise.
4844     */
4845    @ViewDebug.ExportedProperty(category = "focus")
4846    public boolean isFocused() {
4847        return (mPrivateFlags & FOCUSED) != 0;
4848    }
4849
4850    /**
4851     * Find the view in the hierarchy rooted at this view that currently has
4852     * focus.
4853     *
4854     * @return The view that currently has focus, or null if no focused view can
4855     *         be found.
4856     */
4857    public View findFocus() {
4858        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4859    }
4860
4861    /**
4862     * Indicates whether this view is one of the set of scrollable containers in
4863     * its window.
4864     *
4865     * @return whether this view is one of the set of scrollable containers in
4866     * its window
4867     *
4868     * @attr ref android.R.styleable#View_isScrollContainer
4869     */
4870    public boolean isScrollContainer() {
4871        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4872    }
4873
4874    /**
4875     * Change whether this view is one of the set of scrollable containers in
4876     * its window.  This will be used to determine whether the window can
4877     * resize or must pan when a soft input area is open -- scrollable
4878     * containers allow the window to use resize mode since the container
4879     * will appropriately shrink.
4880     *
4881     * @attr ref android.R.styleable#View_isScrollContainer
4882     */
4883    public void setScrollContainer(boolean isScrollContainer) {
4884        if (isScrollContainer) {
4885            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4886                mAttachInfo.mScrollContainers.add(this);
4887                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4888            }
4889            mPrivateFlags |= SCROLL_CONTAINER;
4890        } else {
4891            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4892                mAttachInfo.mScrollContainers.remove(this);
4893            }
4894            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4895        }
4896    }
4897
4898    /**
4899     * Returns the quality of the drawing cache.
4900     *
4901     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4902     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4903     *
4904     * @see #setDrawingCacheQuality(int)
4905     * @see #setDrawingCacheEnabled(boolean)
4906     * @see #isDrawingCacheEnabled()
4907     *
4908     * @attr ref android.R.styleable#View_drawingCacheQuality
4909     */
4910    public int getDrawingCacheQuality() {
4911        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4912    }
4913
4914    /**
4915     * Set the drawing cache quality of this view. This value is used only when the
4916     * drawing cache is enabled
4917     *
4918     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4919     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4920     *
4921     * @see #getDrawingCacheQuality()
4922     * @see #setDrawingCacheEnabled(boolean)
4923     * @see #isDrawingCacheEnabled()
4924     *
4925     * @attr ref android.R.styleable#View_drawingCacheQuality
4926     */
4927    public void setDrawingCacheQuality(int quality) {
4928        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4929    }
4930
4931    /**
4932     * Returns whether the screen should remain on, corresponding to the current
4933     * value of {@link #KEEP_SCREEN_ON}.
4934     *
4935     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4936     *
4937     * @see #setKeepScreenOn(boolean)
4938     *
4939     * @attr ref android.R.styleable#View_keepScreenOn
4940     */
4941    public boolean getKeepScreenOn() {
4942        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4943    }
4944
4945    /**
4946     * Controls whether the screen should remain on, modifying the
4947     * value of {@link #KEEP_SCREEN_ON}.
4948     *
4949     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4950     *
4951     * @see #getKeepScreenOn()
4952     *
4953     * @attr ref android.R.styleable#View_keepScreenOn
4954     */
4955    public void setKeepScreenOn(boolean keepScreenOn) {
4956        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4957    }
4958
4959    /**
4960     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4961     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4962     *
4963     * @attr ref android.R.styleable#View_nextFocusLeft
4964     */
4965    public int getNextFocusLeftId() {
4966        return mNextFocusLeftId;
4967    }
4968
4969    /**
4970     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4971     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4972     * decide automatically.
4973     *
4974     * @attr ref android.R.styleable#View_nextFocusLeft
4975     */
4976    public void setNextFocusLeftId(int nextFocusLeftId) {
4977        mNextFocusLeftId = nextFocusLeftId;
4978    }
4979
4980    /**
4981     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4982     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4983     *
4984     * @attr ref android.R.styleable#View_nextFocusRight
4985     */
4986    public int getNextFocusRightId() {
4987        return mNextFocusRightId;
4988    }
4989
4990    /**
4991     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4992     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4993     * decide automatically.
4994     *
4995     * @attr ref android.R.styleable#View_nextFocusRight
4996     */
4997    public void setNextFocusRightId(int nextFocusRightId) {
4998        mNextFocusRightId = nextFocusRightId;
4999    }
5000
5001    /**
5002     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5003     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5004     *
5005     * @attr ref android.R.styleable#View_nextFocusUp
5006     */
5007    public int getNextFocusUpId() {
5008        return mNextFocusUpId;
5009    }
5010
5011    /**
5012     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5013     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5014     * decide automatically.
5015     *
5016     * @attr ref android.R.styleable#View_nextFocusUp
5017     */
5018    public void setNextFocusUpId(int nextFocusUpId) {
5019        mNextFocusUpId = nextFocusUpId;
5020    }
5021
5022    /**
5023     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5024     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5025     *
5026     * @attr ref android.R.styleable#View_nextFocusDown
5027     */
5028    public int getNextFocusDownId() {
5029        return mNextFocusDownId;
5030    }
5031
5032    /**
5033     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5034     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5035     * decide automatically.
5036     *
5037     * @attr ref android.R.styleable#View_nextFocusDown
5038     */
5039    public void setNextFocusDownId(int nextFocusDownId) {
5040        mNextFocusDownId = nextFocusDownId;
5041    }
5042
5043    /**
5044     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5045     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5046     *
5047     * @attr ref android.R.styleable#View_nextFocusForward
5048     */
5049    public int getNextFocusForwardId() {
5050        return mNextFocusForwardId;
5051    }
5052
5053    /**
5054     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5055     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5056     * decide automatically.
5057     *
5058     * @attr ref android.R.styleable#View_nextFocusForward
5059     */
5060    public void setNextFocusForwardId(int nextFocusForwardId) {
5061        mNextFocusForwardId = nextFocusForwardId;
5062    }
5063
5064    /**
5065     * Returns the visibility of this view and all of its ancestors
5066     *
5067     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5068     */
5069    public boolean isShown() {
5070        View current = this;
5071        //noinspection ConstantConditions
5072        do {
5073            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5074                return false;
5075            }
5076            ViewParent parent = current.mParent;
5077            if (parent == null) {
5078                return false; // We are not attached to the view root
5079            }
5080            if (!(parent instanceof View)) {
5081                return true;
5082            }
5083            current = (View) parent;
5084        } while (current != null);
5085
5086        return false;
5087    }
5088
5089    /**
5090     * Called by the view hierarchy when the content insets for a window have
5091     * changed, to allow it to adjust its content to fit within those windows.
5092     * The content insets tell you the space that the status bar, input method,
5093     * and other system windows infringe on the application's window.
5094     *
5095     * <p>You do not normally need to deal with this function, since the default
5096     * window decoration given to applications takes care of applying it to the
5097     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5098     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5099     * and your content can be placed under those system elements.  You can then
5100     * use this method within your view hierarchy if you have parts of your UI
5101     * which you would like to ensure are not being covered.
5102     *
5103     * <p>The default implementation of this method simply applies the content
5104     * inset's to the view's padding.  This can be enabled through
5105     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5106     * the method and handle the insets however you would like.  Note that the
5107     * insets provided by the framework are always relative to the far edges
5108     * of the window, not accounting for the location of the called view within
5109     * that window.  (In fact when this method is called you do not yet know
5110     * where the layout will place the view, as it is done before layout happens.)
5111     *
5112     * <p>Note: unlike many View methods, there is no dispatch phase to this
5113     * call.  If you are overriding it in a ViewGroup and want to allow the
5114     * call to continue to your children, you must be sure to call the super
5115     * implementation.
5116     *
5117     * @param insets Current content insets of the window.  Prior to
5118     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5119     * the insets or else you and Android will be unhappy.
5120     *
5121     * @return Return true if this view applied the insets and it should not
5122     * continue propagating further down the hierarchy, false otherwise.
5123     */
5124    protected boolean fitSystemWindows(Rect insets) {
5125        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5126            mUserPaddingStart = -1;
5127            mUserPaddingEnd = -1;
5128            mUserPaddingRelative = false;
5129            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5130                    || mAttachInfo == null
5131                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5132                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5133                return true;
5134            } else {
5135                internalSetPadding(0, 0, 0, 0);
5136                return false;
5137            }
5138        }
5139        return false;
5140    }
5141
5142    /**
5143     * Set whether or not this view should account for system screen decorations
5144     * such as the status bar and inset its content. This allows this view to be
5145     * positioned in absolute screen coordinates and remain visible to the user.
5146     *
5147     * <p>This should only be used by top-level window decor views.
5148     *
5149     * @param fitSystemWindows true to inset content for system screen decorations, false for
5150     *                         default behavior.
5151     *
5152     * @attr ref android.R.styleable#View_fitsSystemWindows
5153     */
5154    public void setFitsSystemWindows(boolean fitSystemWindows) {
5155        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5156    }
5157
5158    /**
5159     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5160     * will account for system screen decorations such as the status bar and inset its
5161     * content. This allows the view to be positioned in absolute screen coordinates
5162     * and remain visible to the user.
5163     *
5164     * @return true if this view will adjust its content bounds for system screen decorations.
5165     *
5166     * @attr ref android.R.styleable#View_fitsSystemWindows
5167     */
5168    public boolean fitsSystemWindows() {
5169        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5170    }
5171
5172    /**
5173     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5174     */
5175    public void requestFitSystemWindows() {
5176        if (mParent != null) {
5177            mParent.requestFitSystemWindows();
5178        }
5179    }
5180
5181    /**
5182     * For use by PhoneWindow to make its own system window fitting optional.
5183     * @hide
5184     */
5185    public void makeOptionalFitsSystemWindows() {
5186        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5187    }
5188
5189    /**
5190     * Returns the visibility status for this view.
5191     *
5192     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5193     * @attr ref android.R.styleable#View_visibility
5194     */
5195    @ViewDebug.ExportedProperty(mapping = {
5196        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5197        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5198        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5199    })
5200    public int getVisibility() {
5201        return mViewFlags & VISIBILITY_MASK;
5202    }
5203
5204    /**
5205     * Set the enabled state of this view.
5206     *
5207     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5208     * @attr ref android.R.styleable#View_visibility
5209     */
5210    @RemotableViewMethod
5211    public void setVisibility(int visibility) {
5212        setFlags(visibility, VISIBILITY_MASK);
5213        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5214    }
5215
5216    /**
5217     * Returns the enabled status for this view. The interpretation of the
5218     * enabled state varies by subclass.
5219     *
5220     * @return True if this view is enabled, false otherwise.
5221     */
5222    @ViewDebug.ExportedProperty
5223    public boolean isEnabled() {
5224        return (mViewFlags & ENABLED_MASK) == ENABLED;
5225    }
5226
5227    /**
5228     * Set the enabled state of this view. The interpretation of the enabled
5229     * state varies by subclass.
5230     *
5231     * @param enabled True if this view is enabled, false otherwise.
5232     */
5233    @RemotableViewMethod
5234    public void setEnabled(boolean enabled) {
5235        if (enabled == isEnabled()) return;
5236
5237        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5238
5239        /*
5240         * The View most likely has to change its appearance, so refresh
5241         * the drawable state.
5242         */
5243        refreshDrawableState();
5244
5245        // Invalidate too, since the default behavior for views is to be
5246        // be drawn at 50% alpha rather than to change the drawable.
5247        invalidate(true);
5248    }
5249
5250    /**
5251     * Set whether this view can receive the focus.
5252     *
5253     * Setting this to false will also ensure that this view is not focusable
5254     * in touch mode.
5255     *
5256     * @param focusable If true, this view can receive the focus.
5257     *
5258     * @see #setFocusableInTouchMode(boolean)
5259     * @attr ref android.R.styleable#View_focusable
5260     */
5261    public void setFocusable(boolean focusable) {
5262        if (!focusable) {
5263            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5264        }
5265        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5266    }
5267
5268    /**
5269     * Set whether this view can receive focus while in touch mode.
5270     *
5271     * Setting this to true will also ensure that this view is focusable.
5272     *
5273     * @param focusableInTouchMode If true, this view can receive the focus while
5274     *   in touch mode.
5275     *
5276     * @see #setFocusable(boolean)
5277     * @attr ref android.R.styleable#View_focusableInTouchMode
5278     */
5279    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5280        // Focusable in touch mode should always be set before the focusable flag
5281        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5282        // which, in touch mode, will not successfully request focus on this view
5283        // because the focusable in touch mode flag is not set
5284        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5285        if (focusableInTouchMode) {
5286            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5287        }
5288    }
5289
5290    /**
5291     * Set whether this view should have sound effects enabled for events such as
5292     * clicking and touching.
5293     *
5294     * <p>You may wish to disable sound effects for a view if you already play sounds,
5295     * for instance, a dial key that plays dtmf tones.
5296     *
5297     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5298     * @see #isSoundEffectsEnabled()
5299     * @see #playSoundEffect(int)
5300     * @attr ref android.R.styleable#View_soundEffectsEnabled
5301     */
5302    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5303        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5304    }
5305
5306    /**
5307     * @return whether this view should have sound effects enabled for events such as
5308     *     clicking and touching.
5309     *
5310     * @see #setSoundEffectsEnabled(boolean)
5311     * @see #playSoundEffect(int)
5312     * @attr ref android.R.styleable#View_soundEffectsEnabled
5313     */
5314    @ViewDebug.ExportedProperty
5315    public boolean isSoundEffectsEnabled() {
5316        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5317    }
5318
5319    /**
5320     * Set whether this view should have haptic feedback for events such as
5321     * long presses.
5322     *
5323     * <p>You may wish to disable haptic feedback if your view already controls
5324     * its own haptic feedback.
5325     *
5326     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5327     * @see #isHapticFeedbackEnabled()
5328     * @see #performHapticFeedback(int)
5329     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5330     */
5331    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5332        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5333    }
5334
5335    /**
5336     * @return whether this view should have haptic feedback enabled for events
5337     * long presses.
5338     *
5339     * @see #setHapticFeedbackEnabled(boolean)
5340     * @see #performHapticFeedback(int)
5341     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5342     */
5343    @ViewDebug.ExportedProperty
5344    public boolean isHapticFeedbackEnabled() {
5345        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5346    }
5347
5348    /**
5349     * Returns the layout direction for this view.
5350     *
5351     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5352     *   {@link #LAYOUT_DIRECTION_RTL},
5353     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5354     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5355     * @attr ref android.R.styleable#View_layoutDirection
5356     */
5357    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5358        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5359        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5360        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5361        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5362    })
5363    public int getLayoutDirection() {
5364        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5365    }
5366
5367    /**
5368     * Set the layout direction for this view. This will propagate a reset of layout direction
5369     * resolution to the view's children and resolve layout direction for this view.
5370     *
5371     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5372     *   {@link #LAYOUT_DIRECTION_RTL},
5373     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5374     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5375     *
5376     * @attr ref android.R.styleable#View_layoutDirection
5377     */
5378    @RemotableViewMethod
5379    public void setLayoutDirection(int layoutDirection) {
5380        if (getLayoutDirection() != layoutDirection) {
5381            // Reset the current layout direction and the resolved one
5382            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5383            resetResolvedLayoutDirection();
5384            // Set the new layout direction (filtered) and ask for a layout pass
5385            mPrivateFlags2 |=
5386                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5387            requestLayout();
5388        }
5389    }
5390
5391    /**
5392     * Returns the resolved layout direction for this view.
5393     *
5394     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5395     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5396     */
5397    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5398        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5399        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5400    })
5401    public int getResolvedLayoutDirection() {
5402        // The layout diretion will be resolved only if needed
5403        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5404            resolveLayoutDirection();
5405        }
5406        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5407                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5408    }
5409
5410    /**
5411     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5412     * layout attribute and/or the inherited value from the parent
5413     *
5414     * @return true if the layout is right-to-left.
5415     */
5416    @ViewDebug.ExportedProperty(category = "layout")
5417    public boolean isLayoutRtl() {
5418        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5419    }
5420
5421    /**
5422     * Indicates whether the view is currently tracking transient state that the
5423     * app should not need to concern itself with saving and restoring, but that
5424     * the framework should take special note to preserve when possible.
5425     *
5426     * @return true if the view has transient state
5427     */
5428    @ViewDebug.ExportedProperty(category = "layout")
5429    public boolean hasTransientState() {
5430        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5431    }
5432
5433    /**
5434     * Set whether this view is currently tracking transient state that the
5435     * framework should attempt to preserve when possible. This flag is reference counted,
5436     * so every call to setHasTransientState(true) should be paired with a later call
5437     * to setHasTransientState(false).
5438     *
5439     * @param hasTransientState true if this view has transient state
5440     */
5441    public void setHasTransientState(boolean hasTransientState) {
5442        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5443                mTransientStateCount - 1;
5444        if (mTransientStateCount < 0) {
5445            mTransientStateCount = 0;
5446            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5447                    "unmatched pair of setHasTransientState calls");
5448        }
5449        if ((hasTransientState && mTransientStateCount == 1) ||
5450                (hasTransientState && mTransientStateCount == 0)) {
5451            // update flag if we've just incremented up from 0 or decremented down to 0
5452            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5453                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5454            if (mParent != null) {
5455                try {
5456                    mParent.childHasTransientStateChanged(this, hasTransientState);
5457                } catch (AbstractMethodError e) {
5458                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5459                            " does not fully implement ViewParent", e);
5460                }
5461            }
5462        }
5463    }
5464
5465    /**
5466     * If this view doesn't do any drawing on its own, set this flag to
5467     * allow further optimizations. By default, this flag is not set on
5468     * View, but could be set on some View subclasses such as ViewGroup.
5469     *
5470     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5471     * you should clear this flag.
5472     *
5473     * @param willNotDraw whether or not this View draw on its own
5474     */
5475    public void setWillNotDraw(boolean willNotDraw) {
5476        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5477    }
5478
5479    /**
5480     * Returns whether or not this View draws on its own.
5481     *
5482     * @return true if this view has nothing to draw, false otherwise
5483     */
5484    @ViewDebug.ExportedProperty(category = "drawing")
5485    public boolean willNotDraw() {
5486        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5487    }
5488
5489    /**
5490     * When a View's drawing cache is enabled, drawing is redirected to an
5491     * offscreen bitmap. Some views, like an ImageView, must be able to
5492     * bypass this mechanism if they already draw a single bitmap, to avoid
5493     * unnecessary usage of the memory.
5494     *
5495     * @param willNotCacheDrawing true if this view does not cache its
5496     *        drawing, false otherwise
5497     */
5498    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5499        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5500    }
5501
5502    /**
5503     * Returns whether or not this View can cache its drawing or not.
5504     *
5505     * @return true if this view does not cache its drawing, false otherwise
5506     */
5507    @ViewDebug.ExportedProperty(category = "drawing")
5508    public boolean willNotCacheDrawing() {
5509        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5510    }
5511
5512    /**
5513     * Indicates whether this view reacts to click events or not.
5514     *
5515     * @return true if the view is clickable, false otherwise
5516     *
5517     * @see #setClickable(boolean)
5518     * @attr ref android.R.styleable#View_clickable
5519     */
5520    @ViewDebug.ExportedProperty
5521    public boolean isClickable() {
5522        return (mViewFlags & CLICKABLE) == CLICKABLE;
5523    }
5524
5525    /**
5526     * Enables or disables click events for this view. When a view
5527     * is clickable it will change its state to "pressed" on every click.
5528     * Subclasses should set the view clickable to visually react to
5529     * user's clicks.
5530     *
5531     * @param clickable true to make the view clickable, false otherwise
5532     *
5533     * @see #isClickable()
5534     * @attr ref android.R.styleable#View_clickable
5535     */
5536    public void setClickable(boolean clickable) {
5537        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5538    }
5539
5540    /**
5541     * Indicates whether this view reacts to long click events or not.
5542     *
5543     * @return true if the view is long clickable, false otherwise
5544     *
5545     * @see #setLongClickable(boolean)
5546     * @attr ref android.R.styleable#View_longClickable
5547     */
5548    public boolean isLongClickable() {
5549        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5550    }
5551
5552    /**
5553     * Enables or disables long click events for this view. When a view is long
5554     * clickable it reacts to the user holding down the button for a longer
5555     * duration than a tap. This event can either launch the listener or a
5556     * context menu.
5557     *
5558     * @param longClickable true to make the view long clickable, false otherwise
5559     * @see #isLongClickable()
5560     * @attr ref android.R.styleable#View_longClickable
5561     */
5562    public void setLongClickable(boolean longClickable) {
5563        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5564    }
5565
5566    /**
5567     * Sets the pressed state for this view.
5568     *
5569     * @see #isClickable()
5570     * @see #setClickable(boolean)
5571     *
5572     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5573     *        the View's internal state from a previously set "pressed" state.
5574     */
5575    public void setPressed(boolean pressed) {
5576        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5577
5578        if (pressed) {
5579            mPrivateFlags |= PRESSED;
5580        } else {
5581            mPrivateFlags &= ~PRESSED;
5582        }
5583
5584        if (needsRefresh) {
5585            refreshDrawableState();
5586        }
5587        dispatchSetPressed(pressed);
5588    }
5589
5590    /**
5591     * Dispatch setPressed to all of this View's children.
5592     *
5593     * @see #setPressed(boolean)
5594     *
5595     * @param pressed The new pressed state
5596     */
5597    protected void dispatchSetPressed(boolean pressed) {
5598    }
5599
5600    /**
5601     * Indicates whether the view is currently in pressed state. Unless
5602     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5603     * the pressed state.
5604     *
5605     * @see #setPressed(boolean)
5606     * @see #isClickable()
5607     * @see #setClickable(boolean)
5608     *
5609     * @return true if the view is currently pressed, false otherwise
5610     */
5611    public boolean isPressed() {
5612        return (mPrivateFlags & PRESSED) == PRESSED;
5613    }
5614
5615    /**
5616     * Indicates whether this view will save its state (that is,
5617     * whether its {@link #onSaveInstanceState} method will be called).
5618     *
5619     * @return Returns true if the view state saving is enabled, else false.
5620     *
5621     * @see #setSaveEnabled(boolean)
5622     * @attr ref android.R.styleable#View_saveEnabled
5623     */
5624    public boolean isSaveEnabled() {
5625        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5626    }
5627
5628    /**
5629     * Controls whether the saving of this view's state is
5630     * enabled (that is, whether its {@link #onSaveInstanceState} method
5631     * will be called).  Note that even if freezing is enabled, the
5632     * view still must have an id assigned to it (via {@link #setId(int)})
5633     * for its state to be saved.  This flag can only disable the
5634     * saving of this view; any child views may still have their state saved.
5635     *
5636     * @param enabled Set to false to <em>disable</em> state saving, or true
5637     * (the default) to allow it.
5638     *
5639     * @see #isSaveEnabled()
5640     * @see #setId(int)
5641     * @see #onSaveInstanceState()
5642     * @attr ref android.R.styleable#View_saveEnabled
5643     */
5644    public void setSaveEnabled(boolean enabled) {
5645        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5646    }
5647
5648    /**
5649     * Gets whether the framework should discard touches when the view's
5650     * window is obscured by another visible window.
5651     * Refer to the {@link View} security documentation for more details.
5652     *
5653     * @return True if touch filtering is enabled.
5654     *
5655     * @see #setFilterTouchesWhenObscured(boolean)
5656     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5657     */
5658    @ViewDebug.ExportedProperty
5659    public boolean getFilterTouchesWhenObscured() {
5660        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5661    }
5662
5663    /**
5664     * Sets whether the framework should discard touches when the view's
5665     * window is obscured by another visible window.
5666     * Refer to the {@link View} security documentation for more details.
5667     *
5668     * @param enabled True if touch filtering should be enabled.
5669     *
5670     * @see #getFilterTouchesWhenObscured
5671     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5672     */
5673    public void setFilterTouchesWhenObscured(boolean enabled) {
5674        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5675                FILTER_TOUCHES_WHEN_OBSCURED);
5676    }
5677
5678    /**
5679     * Indicates whether the entire hierarchy under this view will save its
5680     * state when a state saving traversal occurs from its parent.  The default
5681     * is true; if false, these views will not be saved unless
5682     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5683     *
5684     * @return Returns true if the view state saving from parent is enabled, else false.
5685     *
5686     * @see #setSaveFromParentEnabled(boolean)
5687     */
5688    public boolean isSaveFromParentEnabled() {
5689        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5690    }
5691
5692    /**
5693     * Controls whether the entire hierarchy under this view will save its
5694     * state when a state saving traversal occurs from its parent.  The default
5695     * is true; if false, these views will not be saved unless
5696     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5697     *
5698     * @param enabled Set to false to <em>disable</em> state saving, or true
5699     * (the default) to allow it.
5700     *
5701     * @see #isSaveFromParentEnabled()
5702     * @see #setId(int)
5703     * @see #onSaveInstanceState()
5704     */
5705    public void setSaveFromParentEnabled(boolean enabled) {
5706        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5707    }
5708
5709
5710    /**
5711     * Returns whether this View is able to take focus.
5712     *
5713     * @return True if this view can take focus, or false otherwise.
5714     * @attr ref android.R.styleable#View_focusable
5715     */
5716    @ViewDebug.ExportedProperty(category = "focus")
5717    public final boolean isFocusable() {
5718        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5719    }
5720
5721    /**
5722     * When a view is focusable, it may not want to take focus when in touch mode.
5723     * For example, a button would like focus when the user is navigating via a D-pad
5724     * so that the user can click on it, but once the user starts touching the screen,
5725     * the button shouldn't take focus
5726     * @return Whether the view is focusable in touch mode.
5727     * @attr ref android.R.styleable#View_focusableInTouchMode
5728     */
5729    @ViewDebug.ExportedProperty
5730    public final boolean isFocusableInTouchMode() {
5731        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5732    }
5733
5734    /**
5735     * Find the nearest view in the specified direction that can take focus.
5736     * This does not actually give focus to that view.
5737     *
5738     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5739     *
5740     * @return The nearest focusable in the specified direction, or null if none
5741     *         can be found.
5742     */
5743    public View focusSearch(int direction) {
5744        if (mParent != null) {
5745            return mParent.focusSearch(this, direction);
5746        } else {
5747            return null;
5748        }
5749    }
5750
5751    /**
5752     * This method is the last chance for the focused view and its ancestors to
5753     * respond to an arrow key. This is called when the focused view did not
5754     * consume the key internally, nor could the view system find a new view in
5755     * the requested direction to give focus to.
5756     *
5757     * @param focused The currently focused view.
5758     * @param direction The direction focus wants to move. One of FOCUS_UP,
5759     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5760     * @return True if the this view consumed this unhandled move.
5761     */
5762    public boolean dispatchUnhandledMove(View focused, int direction) {
5763        return false;
5764    }
5765
5766    /**
5767     * If a user manually specified the next view id for a particular direction,
5768     * use the root to look up the view.
5769     * @param root The root view of the hierarchy containing this view.
5770     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5771     * or FOCUS_BACKWARD.
5772     * @return The user specified next view, or null if there is none.
5773     */
5774    View findUserSetNextFocus(View root, int direction) {
5775        switch (direction) {
5776            case FOCUS_LEFT:
5777                if (mNextFocusLeftId == View.NO_ID) return null;
5778                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5779            case FOCUS_RIGHT:
5780                if (mNextFocusRightId == View.NO_ID) return null;
5781                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5782            case FOCUS_UP:
5783                if (mNextFocusUpId == View.NO_ID) return null;
5784                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5785            case FOCUS_DOWN:
5786                if (mNextFocusDownId == View.NO_ID) return null;
5787                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5788            case FOCUS_FORWARD:
5789                if (mNextFocusForwardId == View.NO_ID) return null;
5790                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5791            case FOCUS_BACKWARD: {
5792                if (mID == View.NO_ID) return null;
5793                final int id = mID;
5794                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5795                    @Override
5796                    public boolean apply(View t) {
5797                        return t.mNextFocusForwardId == id;
5798                    }
5799                });
5800            }
5801        }
5802        return null;
5803    }
5804
5805    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5806        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5807            @Override
5808            public boolean apply(View t) {
5809                return t.mID == childViewId;
5810            }
5811        });
5812
5813        if (result == null) {
5814            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5815                    + "by user for id " + childViewId);
5816        }
5817        return result;
5818    }
5819
5820    /**
5821     * Find and return all focusable views that are descendants of this view,
5822     * possibly including this view if it is focusable itself.
5823     *
5824     * @param direction The direction of the focus
5825     * @return A list of focusable views
5826     */
5827    public ArrayList<View> getFocusables(int direction) {
5828        ArrayList<View> result = new ArrayList<View>(24);
5829        addFocusables(result, direction);
5830        return result;
5831    }
5832
5833    /**
5834     * Add any focusable views that are descendants of this view (possibly
5835     * including this view if it is focusable itself) to views.  If we are in touch mode,
5836     * only add views that are also focusable in touch mode.
5837     *
5838     * @param views Focusable views found so far
5839     * @param direction The direction of the focus
5840     */
5841    public void addFocusables(ArrayList<View> views, int direction) {
5842        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5843    }
5844
5845    /**
5846     * Adds any focusable views that are descendants of this view (possibly
5847     * including this view if it is focusable itself) to views. This method
5848     * adds all focusable views regardless if we are in touch mode or
5849     * only views focusable in touch mode if we are in touch mode or
5850     * only views that can take accessibility focus if accessibility is enabeld
5851     * depending on the focusable mode paramater.
5852     *
5853     * @param views Focusable views found so far or null if all we are interested is
5854     *        the number of focusables.
5855     * @param direction The direction of the focus.
5856     * @param focusableMode The type of focusables to be added.
5857     *
5858     * @see #FOCUSABLES_ALL
5859     * @see #FOCUSABLES_TOUCH_MODE
5860     */
5861    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5862        if (views == null) {
5863            return;
5864        }
5865        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5866            if (AccessibilityManager.getInstance(mContext).isEnabled()
5867                    && includeForAccessibility()) {
5868                views.add(this);
5869                return;
5870            }
5871        }
5872        if (!isFocusable()) {
5873            return;
5874        }
5875        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5876                && isInTouchMode() && !isFocusableInTouchMode()) {
5877            return;
5878        }
5879        views.add(this);
5880    }
5881
5882    /**
5883     * Finds the Views that contain given text. The containment is case insensitive.
5884     * The search is performed by either the text that the View renders or the content
5885     * description that describes the view for accessibility purposes and the view does
5886     * not render or both. Clients can specify how the search is to be performed via
5887     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5888     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5889     *
5890     * @param outViews The output list of matching Views.
5891     * @param searched The text to match against.
5892     *
5893     * @see #FIND_VIEWS_WITH_TEXT
5894     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5895     * @see #setContentDescription(CharSequence)
5896     */
5897    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5898        if (getAccessibilityNodeProvider() != null) {
5899            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5900                outViews.add(this);
5901            }
5902        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5903                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5904            String searchedLowerCase = searched.toString().toLowerCase();
5905            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5906            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5907                outViews.add(this);
5908            }
5909        }
5910    }
5911
5912    /**
5913     * Find and return all touchable views that are descendants of this view,
5914     * possibly including this view if it is touchable itself.
5915     *
5916     * @return A list of touchable views
5917     */
5918    public ArrayList<View> getTouchables() {
5919        ArrayList<View> result = new ArrayList<View>();
5920        addTouchables(result);
5921        return result;
5922    }
5923
5924    /**
5925     * Add any touchable views that are descendants of this view (possibly
5926     * including this view if it is touchable itself) to views.
5927     *
5928     * @param views Touchable views found so far
5929     */
5930    public void addTouchables(ArrayList<View> views) {
5931        final int viewFlags = mViewFlags;
5932
5933        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5934                && (viewFlags & ENABLED_MASK) == ENABLED) {
5935            views.add(this);
5936        }
5937    }
5938
5939    /**
5940     * Returns whether this View is accessibility focused.
5941     *
5942     * @return True if this View is accessibility focused.
5943     */
5944    boolean isAccessibilityFocused() {
5945        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
5946    }
5947
5948    /**
5949     * Call this to try to give accessibility focus to this view.
5950     *
5951     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
5952     * returns false or the view is no visible or the view already has accessibility
5953     * focus.
5954     *
5955     * See also {@link #focusSearch(int)}, which is what you call to say that you
5956     * have focus, and you want your parent to look for the next one.
5957     *
5958     * @return Whether this view actually took accessibility focus.
5959     *
5960     * @hide
5961     */
5962    public boolean requestAccessibilityFocus() {
5963        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
5964        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
5965            return false;
5966        }
5967        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5968            return false;
5969        }
5970        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
5971            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
5972            ViewRootImpl viewRootImpl = getViewRootImpl();
5973            if (viewRootImpl != null) {
5974                viewRootImpl.setAccessibilityFocusedHost(this);
5975            }
5976            invalidate();
5977            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
5978            notifyAccessibilityStateChanged();
5979            // Try to give input focus to this view - not a descendant.
5980            requestFocusNoSearch(View.FOCUS_DOWN, null);
5981            return true;
5982        }
5983        return false;
5984    }
5985
5986    /**
5987     * Call this to try to clear accessibility focus of this view.
5988     *
5989     * See also {@link #focusSearch(int)}, which is what you call to say that you
5990     * have focus, and you want your parent to look for the next one.
5991     *
5992     * @hide
5993     */
5994    public void clearAccessibilityFocus() {
5995        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
5996            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
5997            ViewRootImpl viewRootImpl = getViewRootImpl();
5998            if (viewRootImpl != null) {
5999                viewRootImpl.setAccessibilityFocusedHost(null);
6000            }
6001            invalidate();
6002            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6003            notifyAccessibilityStateChanged();
6004            // Try to move accessibility focus to the input focus.
6005            View rootView = getRootView();
6006            if (rootView != null) {
6007                View inputFocus = rootView.findFocus();
6008                if (inputFocus != null) {
6009                    inputFocus.requestAccessibilityFocus();
6010                }
6011            }
6012        }
6013    }
6014
6015    /**
6016     * Find the best view to take accessibility focus from a hover.
6017     * This function finds the deepest actionable view and if that
6018     * fails ask the parent to take accessibility focus from hover.
6019     *
6020     * @param x The X hovered location in this view coorditantes.
6021     * @param y The Y hovered location in this view coorditantes.
6022     * @return Whether the request was handled.
6023     *
6024     * @hide
6025     */
6026    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6027        if (onRequestAccessibilityFocusFromHover(x, y)) {
6028            return true;
6029        }
6030        ViewParent parent = mParent;
6031        if (parent instanceof View) {
6032            View parentView = (View) parent;
6033
6034            float[] position = mAttachInfo.mTmpTransformLocation;
6035            position[0] = x;
6036            position[1] = y;
6037
6038            // Compensate for the transformation of the current matrix.
6039            if (!hasIdentityMatrix()) {
6040                getMatrix().mapPoints(position);
6041            }
6042
6043            // Compensate for the parent scroll and the offset
6044            // of this view stop from the parent top.
6045            position[0] += mLeft - parentView.mScrollX;
6046            position[1] += mTop - parentView.mScrollY;
6047
6048            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6049        }
6050        return false;
6051    }
6052
6053    /**
6054     * Requests to give this View focus from hover.
6055     *
6056     * @param x The X hovered location in this view coorditantes.
6057     * @param y The Y hovered location in this view coorditantes.
6058     * @return Whether the request was handled.
6059     *
6060     * @hide
6061     */
6062    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6063        if (includeForAccessibility()
6064                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6065            return requestAccessibilityFocus();
6066        }
6067        return false;
6068    }
6069
6070    /**
6071     * Clears accessibility focus without calling any callback methods
6072     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6073     * is used for clearing accessibility focus when giving this focus to
6074     * another view.
6075     */
6076    void clearAccessibilityFocusNoCallbacks() {
6077        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6078            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6079            invalidate();
6080        }
6081    }
6082
6083    /**
6084     * Call this to try to give focus to a specific view or to one of its
6085     * descendants.
6086     *
6087     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6088     * false), or if it is focusable and it is not focusable in touch mode
6089     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6090     *
6091     * See also {@link #focusSearch(int)}, which is what you call to say that you
6092     * have focus, and you want your parent to look for the next one.
6093     *
6094     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6095     * {@link #FOCUS_DOWN} and <code>null</code>.
6096     *
6097     * @return Whether this view or one of its descendants actually took focus.
6098     */
6099    public final boolean requestFocus() {
6100        return requestFocus(View.FOCUS_DOWN);
6101    }
6102
6103    /**
6104     * Call this to try to give focus to a specific view or to one of its
6105     * descendants and give it a hint about what direction focus is heading.
6106     *
6107     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6108     * false), or if it is focusable and it is not focusable in touch mode
6109     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6110     *
6111     * See also {@link #focusSearch(int)}, which is what you call to say that you
6112     * have focus, and you want your parent to look for the next one.
6113     *
6114     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6115     * <code>null</code> set for the previously focused rectangle.
6116     *
6117     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6118     * @return Whether this view or one of its descendants actually took focus.
6119     */
6120    public final boolean requestFocus(int direction) {
6121        return requestFocus(direction, null);
6122    }
6123
6124    /**
6125     * Call this to try to give focus to a specific view or to one of its descendants
6126     * and give it hints about the direction and a specific rectangle that the focus
6127     * is coming from.  The rectangle can help give larger views a finer grained hint
6128     * about where focus is coming from, and therefore, where to show selection, or
6129     * forward focus change internally.
6130     *
6131     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6132     * false), or if it is focusable and it is not focusable in touch mode
6133     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6134     *
6135     * A View will not take focus if it is not visible.
6136     *
6137     * A View will not take focus if one of its parents has
6138     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6139     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6140     *
6141     * See also {@link #focusSearch(int)}, which is what you call to say that you
6142     * have focus, and you want your parent to look for the next one.
6143     *
6144     * You may wish to override this method if your custom {@link View} has an internal
6145     * {@link View} that it wishes to forward the request to.
6146     *
6147     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6148     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6149     *        to give a finer grained hint about where focus is coming from.  May be null
6150     *        if there is no hint.
6151     * @return Whether this view or one of its descendants actually took focus.
6152     */
6153    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6154        return requestFocusNoSearch(direction, previouslyFocusedRect);
6155    }
6156
6157    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6158        // need to be focusable
6159        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6160                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6161            return false;
6162        }
6163
6164        // need to be focusable in touch mode if in touch mode
6165        if (isInTouchMode() &&
6166            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6167               return false;
6168        }
6169
6170        // need to not have any parents blocking us
6171        if (hasAncestorThatBlocksDescendantFocus()) {
6172            return false;
6173        }
6174
6175        handleFocusGainInternal(direction, previouslyFocusedRect);
6176        return true;
6177    }
6178
6179    /**
6180     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6181     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6182     * touch mode to request focus when they are touched.
6183     *
6184     * @return Whether this view or one of its descendants actually took focus.
6185     *
6186     * @see #isInTouchMode()
6187     *
6188     */
6189    public final boolean requestFocusFromTouch() {
6190        // Leave touch mode if we need to
6191        if (isInTouchMode()) {
6192            ViewRootImpl viewRoot = getViewRootImpl();
6193            if (viewRoot != null) {
6194                viewRoot.ensureTouchMode(false);
6195            }
6196        }
6197        return requestFocus(View.FOCUS_DOWN);
6198    }
6199
6200    /**
6201     * @return Whether any ancestor of this view blocks descendant focus.
6202     */
6203    private boolean hasAncestorThatBlocksDescendantFocus() {
6204        ViewParent ancestor = mParent;
6205        while (ancestor instanceof ViewGroup) {
6206            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6207            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6208                return true;
6209            } else {
6210                ancestor = vgAncestor.getParent();
6211            }
6212        }
6213        return false;
6214    }
6215
6216    /**
6217     * Gets the mode for determining whether this View is important for accessibility
6218     * which is if it fires accessibility events and if it is reported to
6219     * accessibility services that query the screen.
6220     *
6221     * @return The mode for determining whether a View is important for accessibility.
6222     *
6223     * @attr ref android.R.styleable#View_importantForAccessibility
6224     *
6225     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6226     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6227     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6228     */
6229    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6230            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6231                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6232            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6233                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6234            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6235                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6236        })
6237    public int getImportantForAccessibility() {
6238        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6239                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6240    }
6241
6242    /**
6243     * Sets how to determine whether this view is important for accessibility
6244     * which is if it fires accessibility events and if it is reported to
6245     * accessibility services that query the screen.
6246     *
6247     * @param mode How to determine whether this view is important for accessibility.
6248     *
6249     * @attr ref android.R.styleable#View_importantForAccessibility
6250     *
6251     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6252     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6253     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6254     */
6255    public void setImportantForAccessibility(int mode) {
6256        if (mode != getImportantForAccessibility()) {
6257            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6258            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6259                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6260            notifyAccessibilityStateChanged();
6261        }
6262    }
6263
6264    /**
6265     * Gets whether this view should be exposed for accessibility.
6266     *
6267     * @return Whether the view is exposed for accessibility.
6268     *
6269     * @hide
6270     */
6271    public boolean isImportantForAccessibility() {
6272        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6273                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6274        switch (mode) {
6275            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6276                return true;
6277            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6278                return false;
6279            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6280                return isActionableForAccessibility() || hasListenersForAccessibility();
6281            default:
6282                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6283                        + mode);
6284        }
6285    }
6286
6287    /**
6288     * Gets the parent for accessibility purposes. Note that the parent for
6289     * accessibility is not necessary the immediate parent. It is the first
6290     * predecessor that is important for accessibility.
6291     *
6292     * @return The parent for accessibility purposes.
6293     */
6294    public ViewParent getParentForAccessibility() {
6295        if (mParent instanceof View) {
6296            View parentView = (View) mParent;
6297            if (parentView.includeForAccessibility()) {
6298                return mParent;
6299            } else {
6300                return mParent.getParentForAccessibility();
6301            }
6302        }
6303        return null;
6304    }
6305
6306    /**
6307     * Adds the children of a given View for accessibility. Since some Views are
6308     * not important for accessibility the children for accessibility are not
6309     * necessarily direct children of the riew, rather they are the first level of
6310     * descendants important for accessibility.
6311     *
6312     * @param children The list of children for accessibility.
6313     */
6314    public void addChildrenForAccessibility(ArrayList<View> children) {
6315        if (includeForAccessibility()) {
6316            children.add(this);
6317        }
6318    }
6319
6320    /**
6321     * Whether to regard this view for accessibility. A view is regarded for
6322     * accessibility if it is important for accessibility or the querying
6323     * accessibility service has explicitly requested that view not
6324     * important for accessibility are regarded.
6325     *
6326     * @return Whether to regard the view for accessibility.
6327     */
6328    boolean includeForAccessibility() {
6329        if (mAttachInfo != null) {
6330            if (!mAttachInfo.mIncludeNotImportantViews) {
6331                return isImportantForAccessibility() && isDisplayedOnScreen();
6332            } else {
6333                return isDisplayedOnScreen();
6334            }
6335        }
6336        return false;
6337    }
6338
6339    /**
6340     * Returns whether the View is considered actionable from
6341     * accessibility perspective. Such view are important for
6342     * accessiiblity.
6343     *
6344     * @return True if the view is actionable for accessibility.
6345     */
6346    private boolean isActionableForAccessibility() {
6347        return (isClickable() || isLongClickable() || isFocusable());
6348    }
6349
6350    /**
6351     * Returns whether the View has registered callbacks wich makes it
6352     * important for accessiiblity.
6353     *
6354     * @return True if the view is actionable for accessibility.
6355     */
6356    private boolean hasListenersForAccessibility() {
6357        ListenerInfo info = getListenerInfo();
6358        return mTouchDelegate != null || info.mOnKeyListener != null
6359                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6360                || info.mOnHoverListener != null || info.mOnDragListener != null;
6361    }
6362
6363    /**
6364     * Notifies accessibility services that some view's important for
6365     * accessibility state has changed. Note that such notifications
6366     * are made at most once every
6367     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6368     * to avoid unnecessary load to the system. Also once a view has
6369     * made a notifucation this method is a NOP until the notification has
6370     * been sent to clients.
6371     *
6372     * @hide
6373     *
6374     * TODO: Makse sure this method is called for any view state change
6375     *       that is interesting for accessilility purposes.
6376     */
6377    public void notifyAccessibilityStateChanged() {
6378        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6379            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6380            if (mParent != null) {
6381                mParent.childAccessibilityStateChanged(this);
6382            }
6383        }
6384    }
6385
6386    /**
6387     * Reset the state indicating the this view has requested clients
6388     * interested in its accessiblity state to be notified.
6389     *
6390     * @hide
6391     */
6392    public void resetAccessibilityStateChanged() {
6393        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6394    }
6395
6396    /**
6397     * Performs the specified accessibility action on the view. For
6398     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6399     *
6400     * @param action The action to perform.
6401     * @return Whether the action was performed.
6402     */
6403    public boolean performAccessibilityAction(int action, Bundle args) {
6404        switch (action) {
6405            case AccessibilityNodeInfo.ACTION_CLICK: {
6406                if (isClickable()) {
6407                    performClick();
6408                }
6409            } break;
6410            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6411                if (isLongClickable()) {
6412                    performLongClick();
6413                }
6414            } break;
6415            case AccessibilityNodeInfo.ACTION_FOCUS: {
6416                if (!hasFocus()) {
6417                    // Get out of touch mode since accessibility
6418                    // wants to move focus around.
6419                    getViewRootImpl().ensureTouchMode(false);
6420                    return requestFocus();
6421                }
6422            } break;
6423            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6424                if (hasFocus()) {
6425                    clearFocus();
6426                    return !isFocused();
6427                }
6428            } break;
6429            case AccessibilityNodeInfo.ACTION_SELECT: {
6430                if (!isSelected()) {
6431                    setSelected(true);
6432                    return isSelected();
6433                }
6434            } break;
6435            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6436                if (isSelected()) {
6437                    setSelected(false);
6438                    return !isSelected();
6439                }
6440            } break;
6441            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6442                if (!isAccessibilityFocused()) {
6443                    return requestAccessibilityFocus();
6444                }
6445            } break;
6446            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6447                if (isAccessibilityFocused()) {
6448                    clearAccessibilityFocus();
6449                    return true;
6450                }
6451            } break;
6452        }
6453        return false;
6454    }
6455
6456    /**
6457     * @hide
6458     */
6459    public void dispatchStartTemporaryDetach() {
6460        onStartTemporaryDetach();
6461    }
6462
6463    /**
6464     * This is called when a container is going to temporarily detach a child, with
6465     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6466     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6467     * {@link #onDetachedFromWindow()} when the container is done.
6468     */
6469    public void onStartTemporaryDetach() {
6470        removeUnsetPressCallback();
6471        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6472    }
6473
6474    /**
6475     * @hide
6476     */
6477    public void dispatchFinishTemporaryDetach() {
6478        onFinishTemporaryDetach();
6479    }
6480
6481    /**
6482     * Called after {@link #onStartTemporaryDetach} when the container is done
6483     * changing the view.
6484     */
6485    public void onFinishTemporaryDetach() {
6486    }
6487
6488    /**
6489     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6490     * for this view's window.  Returns null if the view is not currently attached
6491     * to the window.  Normally you will not need to use this directly, but
6492     * just use the standard high-level event callbacks like
6493     * {@link #onKeyDown(int, KeyEvent)}.
6494     */
6495    public KeyEvent.DispatcherState getKeyDispatcherState() {
6496        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6497    }
6498
6499    /**
6500     * Dispatch a key event before it is processed by any input method
6501     * associated with the view hierarchy.  This can be used to intercept
6502     * key events in special situations before the IME consumes them; a
6503     * typical example would be handling the BACK key to update the application's
6504     * UI instead of allowing the IME to see it and close itself.
6505     *
6506     * @param event The key event to be dispatched.
6507     * @return True if the event was handled, false otherwise.
6508     */
6509    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6510        return onKeyPreIme(event.getKeyCode(), event);
6511    }
6512
6513    /**
6514     * Dispatch a key event to the next view on the focus path. This path runs
6515     * from the top of the view tree down to the currently focused view. If this
6516     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6517     * the next node down the focus path. This method also fires any key
6518     * listeners.
6519     *
6520     * @param event The key event to be dispatched.
6521     * @return True if the event was handled, false otherwise.
6522     */
6523    public boolean dispatchKeyEvent(KeyEvent event) {
6524        if (mInputEventConsistencyVerifier != null) {
6525            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6526        }
6527
6528        // Give any attached key listener a first crack at the event.
6529        //noinspection SimplifiableIfStatement
6530        ListenerInfo li = mListenerInfo;
6531        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6532                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6533            return true;
6534        }
6535
6536        if (event.dispatch(this, mAttachInfo != null
6537                ? mAttachInfo.mKeyDispatchState : null, this)) {
6538            return true;
6539        }
6540
6541        if (mInputEventConsistencyVerifier != null) {
6542            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6543        }
6544        return false;
6545    }
6546
6547    /**
6548     * Dispatches a key shortcut event.
6549     *
6550     * @param event The key event to be dispatched.
6551     * @return True if the event was handled by the view, false otherwise.
6552     */
6553    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6554        return onKeyShortcut(event.getKeyCode(), event);
6555    }
6556
6557    /**
6558     * Pass the touch screen motion event down to the target view, or this
6559     * view if it is the target.
6560     *
6561     * @param event The motion event to be dispatched.
6562     * @return True if the event was handled by the view, false otherwise.
6563     */
6564    public boolean dispatchTouchEvent(MotionEvent event) {
6565        if (mInputEventConsistencyVerifier != null) {
6566            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6567        }
6568
6569        if (onFilterTouchEventForSecurity(event)) {
6570            //noinspection SimplifiableIfStatement
6571            ListenerInfo li = mListenerInfo;
6572            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6573                    && li.mOnTouchListener.onTouch(this, event)) {
6574                return true;
6575            }
6576
6577            if (onTouchEvent(event)) {
6578                return true;
6579            }
6580        }
6581
6582        if (mInputEventConsistencyVerifier != null) {
6583            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6584        }
6585        return false;
6586    }
6587
6588    /**
6589     * Filter the touch event to apply security policies.
6590     *
6591     * @param event The motion event to be filtered.
6592     * @return True if the event should be dispatched, false if the event should be dropped.
6593     *
6594     * @see #getFilterTouchesWhenObscured
6595     */
6596    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6597        //noinspection RedundantIfStatement
6598        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6599                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6600            // Window is obscured, drop this touch.
6601            return false;
6602        }
6603        return true;
6604    }
6605
6606    /**
6607     * Pass a trackball motion event down to the focused view.
6608     *
6609     * @param event The motion event to be dispatched.
6610     * @return True if the event was handled by the view, false otherwise.
6611     */
6612    public boolean dispatchTrackballEvent(MotionEvent event) {
6613        if (mInputEventConsistencyVerifier != null) {
6614            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6615        }
6616
6617        return onTrackballEvent(event);
6618    }
6619
6620    /**
6621     * Dispatch a generic motion event.
6622     * <p>
6623     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6624     * are delivered to the view under the pointer.  All other generic motion events are
6625     * delivered to the focused view.  Hover events are handled specially and are delivered
6626     * to {@link #onHoverEvent(MotionEvent)}.
6627     * </p>
6628     *
6629     * @param event The motion event to be dispatched.
6630     * @return True if the event was handled by the view, false otherwise.
6631     */
6632    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6633        if (mInputEventConsistencyVerifier != null) {
6634            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6635        }
6636
6637        final int source = event.getSource();
6638        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6639            final int action = event.getAction();
6640            if (action == MotionEvent.ACTION_HOVER_ENTER
6641                    || action == MotionEvent.ACTION_HOVER_MOVE
6642                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6643                if (dispatchHoverEvent(event)) {
6644                    return true;
6645                }
6646            } else if (dispatchGenericPointerEvent(event)) {
6647                return true;
6648            }
6649        } else if (dispatchGenericFocusedEvent(event)) {
6650            return true;
6651        }
6652
6653        if (dispatchGenericMotionEventInternal(event)) {
6654            return true;
6655        }
6656
6657        if (mInputEventConsistencyVerifier != null) {
6658            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6659        }
6660        return false;
6661    }
6662
6663    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6664        //noinspection SimplifiableIfStatement
6665        ListenerInfo li = mListenerInfo;
6666        if (li != null && li.mOnGenericMotionListener != null
6667                && (mViewFlags & ENABLED_MASK) == ENABLED
6668                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6669            return true;
6670        }
6671
6672        if (onGenericMotionEvent(event)) {
6673            return true;
6674        }
6675
6676        if (mInputEventConsistencyVerifier != null) {
6677            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6678        }
6679        return false;
6680    }
6681
6682    /**
6683     * Dispatch a hover event.
6684     * <p>
6685     * Do not call this method directly.
6686     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6687     * </p>
6688     *
6689     * @param event The motion event to be dispatched.
6690     * @return True if the event was handled by the view, false otherwise.
6691     */
6692    protected boolean dispatchHoverEvent(MotionEvent event) {
6693        //noinspection SimplifiableIfStatement
6694        ListenerInfo li = mListenerInfo;
6695        if (li != null && li.mOnHoverListener != null
6696                && (mViewFlags & ENABLED_MASK) == ENABLED
6697                && li.mOnHoverListener.onHover(this, event)) {
6698            return true;
6699        }
6700
6701        return onHoverEvent(event);
6702    }
6703
6704    /**
6705     * Returns true if the view has a child to which it has recently sent
6706     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6707     * it does not have a hovered child, then it must be the innermost hovered view.
6708     * @hide
6709     */
6710    protected boolean hasHoveredChild() {
6711        return false;
6712    }
6713
6714    /**
6715     * Dispatch a generic motion event to the view under the first pointer.
6716     * <p>
6717     * Do not call this method directly.
6718     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6719     * </p>
6720     *
6721     * @param event The motion event to be dispatched.
6722     * @return True if the event was handled by the view, false otherwise.
6723     */
6724    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6725        return false;
6726    }
6727
6728    /**
6729     * Dispatch a generic motion event to the currently focused view.
6730     * <p>
6731     * Do not call this method directly.
6732     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6733     * </p>
6734     *
6735     * @param event The motion event to be dispatched.
6736     * @return True if the event was handled by the view, false otherwise.
6737     */
6738    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6739        return false;
6740    }
6741
6742    /**
6743     * Dispatch a pointer event.
6744     * <p>
6745     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6746     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6747     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6748     * and should not be expected to handle other pointing device features.
6749     * </p>
6750     *
6751     * @param event The motion event to be dispatched.
6752     * @return True if the event was handled by the view, false otherwise.
6753     * @hide
6754     */
6755    public final boolean dispatchPointerEvent(MotionEvent event) {
6756        if (event.isTouchEvent()) {
6757            return dispatchTouchEvent(event);
6758        } else {
6759            return dispatchGenericMotionEvent(event);
6760        }
6761    }
6762
6763    /**
6764     * Called when the window containing this view gains or loses window focus.
6765     * ViewGroups should override to route to their children.
6766     *
6767     * @param hasFocus True if the window containing this view now has focus,
6768     *        false otherwise.
6769     */
6770    public void dispatchWindowFocusChanged(boolean hasFocus) {
6771        onWindowFocusChanged(hasFocus);
6772    }
6773
6774    /**
6775     * Called when the window containing this view gains or loses focus.  Note
6776     * that this is separate from view focus: to receive key events, both
6777     * your view and its window must have focus.  If a window is displayed
6778     * on top of yours that takes input focus, then your own window will lose
6779     * focus but the view focus will remain unchanged.
6780     *
6781     * @param hasWindowFocus True if the window containing this view now has
6782     *        focus, false otherwise.
6783     */
6784    public void onWindowFocusChanged(boolean hasWindowFocus) {
6785        InputMethodManager imm = InputMethodManager.peekInstance();
6786        if (!hasWindowFocus) {
6787            if (isPressed()) {
6788                setPressed(false);
6789            }
6790            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6791                imm.focusOut(this);
6792            }
6793            removeLongPressCallback();
6794            removeTapCallback();
6795            onFocusLost();
6796        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6797            imm.focusIn(this);
6798        }
6799        refreshDrawableState();
6800    }
6801
6802    /**
6803     * Returns true if this view is in a window that currently has window focus.
6804     * Note that this is not the same as the view itself having focus.
6805     *
6806     * @return True if this view is in a window that currently has window focus.
6807     */
6808    public boolean hasWindowFocus() {
6809        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6810    }
6811
6812    /**
6813     * Dispatch a view visibility change down the view hierarchy.
6814     * ViewGroups should override to route to their children.
6815     * @param changedView The view whose visibility changed. Could be 'this' or
6816     * an ancestor view.
6817     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6818     * {@link #INVISIBLE} or {@link #GONE}.
6819     */
6820    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6821        onVisibilityChanged(changedView, visibility);
6822    }
6823
6824    /**
6825     * Called when the visibility of the view or an ancestor of the view is changed.
6826     * @param changedView The view whose visibility changed. Could be 'this' or
6827     * an ancestor view.
6828     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6829     * {@link #INVISIBLE} or {@link #GONE}.
6830     */
6831    protected void onVisibilityChanged(View changedView, int visibility) {
6832        if (visibility == VISIBLE) {
6833            if (mAttachInfo != null) {
6834                initialAwakenScrollBars();
6835            } else {
6836                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6837            }
6838        }
6839    }
6840
6841    /**
6842     * Dispatch a hint about whether this view is displayed. For instance, when
6843     * a View moves out of the screen, it might receives a display hint indicating
6844     * the view is not displayed. Applications should not <em>rely</em> on this hint
6845     * as there is no guarantee that they will receive one.
6846     *
6847     * @param hint A hint about whether or not this view is displayed:
6848     * {@link #VISIBLE} or {@link #INVISIBLE}.
6849     */
6850    public void dispatchDisplayHint(int hint) {
6851        onDisplayHint(hint);
6852    }
6853
6854    /**
6855     * Gives this view a hint about whether is displayed or not. For instance, when
6856     * a View moves out of the screen, it might receives a display hint indicating
6857     * the view is not displayed. Applications should not <em>rely</em> on this hint
6858     * as there is no guarantee that they will receive one.
6859     *
6860     * @param hint A hint about whether or not this view is displayed:
6861     * {@link #VISIBLE} or {@link #INVISIBLE}.
6862     */
6863    protected void onDisplayHint(int hint) {
6864    }
6865
6866    /**
6867     * Dispatch a window visibility change down the view hierarchy.
6868     * ViewGroups should override to route to their children.
6869     *
6870     * @param visibility The new visibility of the window.
6871     *
6872     * @see #onWindowVisibilityChanged(int)
6873     */
6874    public void dispatchWindowVisibilityChanged(int visibility) {
6875        onWindowVisibilityChanged(visibility);
6876    }
6877
6878    /**
6879     * Called when the window containing has change its visibility
6880     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6881     * that this tells you whether or not your window is being made visible
6882     * to the window manager; this does <em>not</em> tell you whether or not
6883     * your window is obscured by other windows on the screen, even if it
6884     * is itself visible.
6885     *
6886     * @param visibility The new visibility of the window.
6887     */
6888    protected void onWindowVisibilityChanged(int visibility) {
6889        if (visibility == VISIBLE) {
6890            initialAwakenScrollBars();
6891        }
6892    }
6893
6894    /**
6895     * Returns the current visibility of the window this view is attached to
6896     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6897     *
6898     * @return Returns the current visibility of the view's window.
6899     */
6900    public int getWindowVisibility() {
6901        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6902    }
6903
6904    /**
6905     * Retrieve the overall visible display size in which the window this view is
6906     * attached to has been positioned in.  This takes into account screen
6907     * decorations above the window, for both cases where the window itself
6908     * is being position inside of them or the window is being placed under
6909     * then and covered insets are used for the window to position its content
6910     * inside.  In effect, this tells you the available area where content can
6911     * be placed and remain visible to users.
6912     *
6913     * <p>This function requires an IPC back to the window manager to retrieve
6914     * the requested information, so should not be used in performance critical
6915     * code like drawing.
6916     *
6917     * @param outRect Filled in with the visible display frame.  If the view
6918     * is not attached to a window, this is simply the raw display size.
6919     */
6920    public void getWindowVisibleDisplayFrame(Rect outRect) {
6921        if (mAttachInfo != null) {
6922            try {
6923                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6924            } catch (RemoteException e) {
6925                return;
6926            }
6927            // XXX This is really broken, and probably all needs to be done
6928            // in the window manager, and we need to know more about whether
6929            // we want the area behind or in front of the IME.
6930            final Rect insets = mAttachInfo.mVisibleInsets;
6931            outRect.left += insets.left;
6932            outRect.top += insets.top;
6933            outRect.right -= insets.right;
6934            outRect.bottom -= insets.bottom;
6935            return;
6936        }
6937        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6938        d.getRectSize(outRect);
6939    }
6940
6941    /**
6942     * Dispatch a notification about a resource configuration change down
6943     * the view hierarchy.
6944     * ViewGroups should override to route to their children.
6945     *
6946     * @param newConfig The new resource configuration.
6947     *
6948     * @see #onConfigurationChanged(android.content.res.Configuration)
6949     */
6950    public void dispatchConfigurationChanged(Configuration newConfig) {
6951        onConfigurationChanged(newConfig);
6952    }
6953
6954    /**
6955     * Called when the current configuration of the resources being used
6956     * by the application have changed.  You can use this to decide when
6957     * to reload resources that can changed based on orientation and other
6958     * configuration characterstics.  You only need to use this if you are
6959     * not relying on the normal {@link android.app.Activity} mechanism of
6960     * recreating the activity instance upon a configuration change.
6961     *
6962     * @param newConfig The new resource configuration.
6963     */
6964    protected void onConfigurationChanged(Configuration newConfig) {
6965    }
6966
6967    /**
6968     * Private function to aggregate all per-view attributes in to the view
6969     * root.
6970     */
6971    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6972        performCollectViewAttributes(attachInfo, visibility);
6973    }
6974
6975    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6976        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
6977            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6978                attachInfo.mKeepScreenOn = true;
6979            }
6980            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6981            ListenerInfo li = mListenerInfo;
6982            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6983                attachInfo.mHasSystemUiListeners = true;
6984            }
6985        }
6986    }
6987
6988    void needGlobalAttributesUpdate(boolean force) {
6989        final AttachInfo ai = mAttachInfo;
6990        if (ai != null) {
6991            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6992                    || ai.mHasSystemUiListeners) {
6993                ai.mRecomputeGlobalAttributes = true;
6994            }
6995        }
6996    }
6997
6998    /**
6999     * Returns whether the device is currently in touch mode.  Touch mode is entered
7000     * once the user begins interacting with the device by touch, and affects various
7001     * things like whether focus is always visible to the user.
7002     *
7003     * @return Whether the device is in touch mode.
7004     */
7005    @ViewDebug.ExportedProperty
7006    public boolean isInTouchMode() {
7007        if (mAttachInfo != null) {
7008            return mAttachInfo.mInTouchMode;
7009        } else {
7010            return ViewRootImpl.isInTouchMode();
7011        }
7012    }
7013
7014    /**
7015     * Returns the context the view is running in, through which it can
7016     * access the current theme, resources, etc.
7017     *
7018     * @return The view's Context.
7019     */
7020    @ViewDebug.CapturedViewProperty
7021    public final Context getContext() {
7022        return mContext;
7023    }
7024
7025    /**
7026     * Handle a key event before it is processed by any input method
7027     * associated with the view hierarchy.  This can be used to intercept
7028     * key events in special situations before the IME consumes them; a
7029     * typical example would be handling the BACK key to update the application's
7030     * UI instead of allowing the IME to see it and close itself.
7031     *
7032     * @param keyCode The value in event.getKeyCode().
7033     * @param event Description of the key event.
7034     * @return If you handled the event, return true. If you want to allow the
7035     *         event to be handled by the next receiver, return false.
7036     */
7037    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7038        return false;
7039    }
7040
7041    /**
7042     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7043     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7044     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7045     * is released, if the view is enabled and clickable.
7046     *
7047     * @param keyCode A key code that represents the button pressed, from
7048     *                {@link android.view.KeyEvent}.
7049     * @param event   The KeyEvent object that defines the button action.
7050     */
7051    public boolean onKeyDown(int keyCode, KeyEvent event) {
7052        boolean result = false;
7053
7054        switch (keyCode) {
7055            case KeyEvent.KEYCODE_DPAD_CENTER:
7056            case KeyEvent.KEYCODE_ENTER: {
7057                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7058                    return true;
7059                }
7060                // Long clickable items don't necessarily have to be clickable
7061                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7062                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7063                        (event.getRepeatCount() == 0)) {
7064                    setPressed(true);
7065                    checkForLongClick(0);
7066                    return true;
7067                }
7068                break;
7069            }
7070        }
7071        return result;
7072    }
7073
7074    /**
7075     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7076     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7077     * the event).
7078     */
7079    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7080        return false;
7081    }
7082
7083    /**
7084     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7085     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7086     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7087     * {@link KeyEvent#KEYCODE_ENTER} is released.
7088     *
7089     * @param keyCode A key code that represents the button pressed, from
7090     *                {@link android.view.KeyEvent}.
7091     * @param event   The KeyEvent object that defines the button action.
7092     */
7093    public boolean onKeyUp(int keyCode, KeyEvent event) {
7094        boolean result = false;
7095
7096        switch (keyCode) {
7097            case KeyEvent.KEYCODE_DPAD_CENTER:
7098            case KeyEvent.KEYCODE_ENTER: {
7099                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7100                    return true;
7101                }
7102                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7103                    setPressed(false);
7104
7105                    if (!mHasPerformedLongPress) {
7106                        // This is a tap, so remove the longpress check
7107                        removeLongPressCallback();
7108
7109                        result = performClick();
7110                    }
7111                }
7112                break;
7113            }
7114        }
7115        return result;
7116    }
7117
7118    /**
7119     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7120     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7121     * the event).
7122     *
7123     * @param keyCode     A key code that represents the button pressed, from
7124     *                    {@link android.view.KeyEvent}.
7125     * @param repeatCount The number of times the action was made.
7126     * @param event       The KeyEvent object that defines the button action.
7127     */
7128    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7129        return false;
7130    }
7131
7132    /**
7133     * Called on the focused view when a key shortcut event is not handled.
7134     * Override this method to implement local key shortcuts for the View.
7135     * Key shortcuts can also be implemented by setting the
7136     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7137     *
7138     * @param keyCode The value in event.getKeyCode().
7139     * @param event Description of the key event.
7140     * @return If you handled the event, return true. If you want to allow the
7141     *         event to be handled by the next receiver, return false.
7142     */
7143    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7144        return false;
7145    }
7146
7147    /**
7148     * Check whether the called view is a text editor, in which case it
7149     * would make sense to automatically display a soft input window for
7150     * it.  Subclasses should override this if they implement
7151     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7152     * a call on that method would return a non-null InputConnection, and
7153     * they are really a first-class editor that the user would normally
7154     * start typing on when the go into a window containing your view.
7155     *
7156     * <p>The default implementation always returns false.  This does
7157     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7158     * will not be called or the user can not otherwise perform edits on your
7159     * view; it is just a hint to the system that this is not the primary
7160     * purpose of this view.
7161     *
7162     * @return Returns true if this view is a text editor, else false.
7163     */
7164    public boolean onCheckIsTextEditor() {
7165        return false;
7166    }
7167
7168    /**
7169     * Create a new InputConnection for an InputMethod to interact
7170     * with the view.  The default implementation returns null, since it doesn't
7171     * support input methods.  You can override this to implement such support.
7172     * This is only needed for views that take focus and text input.
7173     *
7174     * <p>When implementing this, you probably also want to implement
7175     * {@link #onCheckIsTextEditor()} to indicate you will return a
7176     * non-null InputConnection.
7177     *
7178     * @param outAttrs Fill in with attribute information about the connection.
7179     */
7180    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7181        return null;
7182    }
7183
7184    /**
7185     * Called by the {@link android.view.inputmethod.InputMethodManager}
7186     * when a view who is not the current
7187     * input connection target is trying to make a call on the manager.  The
7188     * default implementation returns false; you can override this to return
7189     * true for certain views if you are performing InputConnection proxying
7190     * to them.
7191     * @param view The View that is making the InputMethodManager call.
7192     * @return Return true to allow the call, false to reject.
7193     */
7194    public boolean checkInputConnectionProxy(View view) {
7195        return false;
7196    }
7197
7198    /**
7199     * Show the context menu for this view. It is not safe to hold on to the
7200     * menu after returning from this method.
7201     *
7202     * You should normally not overload this method. Overload
7203     * {@link #onCreateContextMenu(ContextMenu)} or define an
7204     * {@link OnCreateContextMenuListener} to add items to the context menu.
7205     *
7206     * @param menu The context menu to populate
7207     */
7208    public void createContextMenu(ContextMenu menu) {
7209        ContextMenuInfo menuInfo = getContextMenuInfo();
7210
7211        // Sets the current menu info so all items added to menu will have
7212        // my extra info set.
7213        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7214
7215        onCreateContextMenu(menu);
7216        ListenerInfo li = mListenerInfo;
7217        if (li != null && li.mOnCreateContextMenuListener != null) {
7218            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7219        }
7220
7221        // Clear the extra information so subsequent items that aren't mine don't
7222        // have my extra info.
7223        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7224
7225        if (mParent != null) {
7226            mParent.createContextMenu(menu);
7227        }
7228    }
7229
7230    /**
7231     * Views should implement this if they have extra information to associate
7232     * with the context menu. The return result is supplied as a parameter to
7233     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7234     * callback.
7235     *
7236     * @return Extra information about the item for which the context menu
7237     *         should be shown. This information will vary across different
7238     *         subclasses of View.
7239     */
7240    protected ContextMenuInfo getContextMenuInfo() {
7241        return null;
7242    }
7243
7244    /**
7245     * Views should implement this if the view itself is going to add items to
7246     * the context menu.
7247     *
7248     * @param menu the context menu to populate
7249     */
7250    protected void onCreateContextMenu(ContextMenu menu) {
7251    }
7252
7253    /**
7254     * Implement this method to handle trackball motion events.  The
7255     * <em>relative</em> movement of the trackball since the last event
7256     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7257     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7258     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7259     * they will often be fractional values, representing the more fine-grained
7260     * movement information available from a trackball).
7261     *
7262     * @param event The motion event.
7263     * @return True if the event was handled, false otherwise.
7264     */
7265    public boolean onTrackballEvent(MotionEvent event) {
7266        return false;
7267    }
7268
7269    /**
7270     * Implement this method to handle generic motion events.
7271     * <p>
7272     * Generic motion events describe joystick movements, mouse hovers, track pad
7273     * touches, scroll wheel movements and other input events.  The
7274     * {@link MotionEvent#getSource() source} of the motion event specifies
7275     * the class of input that was received.  Implementations of this method
7276     * must examine the bits in the source before processing the event.
7277     * The following code example shows how this is done.
7278     * </p><p>
7279     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7280     * are delivered to the view under the pointer.  All other generic motion events are
7281     * delivered to the focused view.
7282     * </p>
7283     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7284     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7285     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7286     *             // process the joystick movement...
7287     *             return true;
7288     *         }
7289     *     }
7290     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7291     *         switch (event.getAction()) {
7292     *             case MotionEvent.ACTION_HOVER_MOVE:
7293     *                 // process the mouse hover movement...
7294     *                 return true;
7295     *             case MotionEvent.ACTION_SCROLL:
7296     *                 // process the scroll wheel movement...
7297     *                 return true;
7298     *         }
7299     *     }
7300     *     return super.onGenericMotionEvent(event);
7301     * }</pre>
7302     *
7303     * @param event The generic motion event being processed.
7304     * @return True if the event was handled, false otherwise.
7305     */
7306    public boolean onGenericMotionEvent(MotionEvent event) {
7307        return false;
7308    }
7309
7310    /**
7311     * Implement this method to handle hover events.
7312     * <p>
7313     * This method is called whenever a pointer is hovering into, over, or out of the
7314     * bounds of a view and the view is not currently being touched.
7315     * Hover events are represented as pointer events with action
7316     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7317     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7318     * </p>
7319     * <ul>
7320     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7321     * when the pointer enters the bounds of the view.</li>
7322     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7323     * when the pointer has already entered the bounds of the view and has moved.</li>
7324     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7325     * when the pointer has exited the bounds of the view or when the pointer is
7326     * about to go down due to a button click, tap, or similar user action that
7327     * causes the view to be touched.</li>
7328     * </ul>
7329     * <p>
7330     * The view should implement this method to return true to indicate that it is
7331     * handling the hover event, such as by changing its drawable state.
7332     * </p><p>
7333     * The default implementation calls {@link #setHovered} to update the hovered state
7334     * of the view when a hover enter or hover exit event is received, if the view
7335     * is enabled and is clickable.  The default implementation also sends hover
7336     * accessibility events.
7337     * </p>
7338     *
7339     * @param event The motion event that describes the hover.
7340     * @return True if the view handled the hover event.
7341     *
7342     * @see #isHovered
7343     * @see #setHovered
7344     * @see #onHoverChanged
7345     */
7346    public boolean onHoverEvent(MotionEvent event) {
7347        // The root view may receive hover (or touch) events that are outside the bounds of
7348        // the window.  This code ensures that we only send accessibility events for
7349        // hovers that are actually within the bounds of the root view.
7350        final int action = event.getActionMasked();
7351        if (!mSendingHoverAccessibilityEvents) {
7352            if ((action == MotionEvent.ACTION_HOVER_ENTER
7353                    || action == MotionEvent.ACTION_HOVER_MOVE)
7354                    && !hasHoveredChild()
7355                    && pointInView(event.getX(), event.getY())) {
7356                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7357                mSendingHoverAccessibilityEvents = true;
7358                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7359            }
7360        } else {
7361            if (action == MotionEvent.ACTION_HOVER_EXIT
7362                    || (action == MotionEvent.ACTION_MOVE
7363                            && !pointInView(event.getX(), event.getY()))) {
7364                mSendingHoverAccessibilityEvents = false;
7365                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7366                // If the window does not have input focus we take away accessibility
7367                // focus as soon as the user stop hovering over the view.
7368                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7369                    getViewRootImpl().setAccessibilityFocusedHost(null);
7370                }
7371            }
7372        }
7373
7374        if (isHoverable()) {
7375            switch (action) {
7376                case MotionEvent.ACTION_HOVER_ENTER:
7377                    setHovered(true);
7378                    break;
7379                case MotionEvent.ACTION_HOVER_EXIT:
7380                    setHovered(false);
7381                    break;
7382            }
7383
7384            // Dispatch the event to onGenericMotionEvent before returning true.
7385            // This is to provide compatibility with existing applications that
7386            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7387            // break because of the new default handling for hoverable views
7388            // in onHoverEvent.
7389            // Note that onGenericMotionEvent will be called by default when
7390            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7391            dispatchGenericMotionEventInternal(event);
7392            return true;
7393        }
7394
7395        return false;
7396    }
7397
7398    /**
7399     * Returns true if the view should handle {@link #onHoverEvent}
7400     * by calling {@link #setHovered} to change its hovered state.
7401     *
7402     * @return True if the view is hoverable.
7403     */
7404    private boolean isHoverable() {
7405        final int viewFlags = mViewFlags;
7406        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7407            return false;
7408        }
7409
7410        return (viewFlags & CLICKABLE) == CLICKABLE
7411                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7412    }
7413
7414    /**
7415     * Returns true if the view is currently hovered.
7416     *
7417     * @return True if the view is currently hovered.
7418     *
7419     * @see #setHovered
7420     * @see #onHoverChanged
7421     */
7422    @ViewDebug.ExportedProperty
7423    public boolean isHovered() {
7424        return (mPrivateFlags & HOVERED) != 0;
7425    }
7426
7427    /**
7428     * Sets whether the view is currently hovered.
7429     * <p>
7430     * Calling this method also changes the drawable state of the view.  This
7431     * enables the view to react to hover by using different drawable resources
7432     * to change its appearance.
7433     * </p><p>
7434     * The {@link #onHoverChanged} method is called when the hovered state changes.
7435     * </p>
7436     *
7437     * @param hovered True if the view is hovered.
7438     *
7439     * @see #isHovered
7440     * @see #onHoverChanged
7441     */
7442    public void setHovered(boolean hovered) {
7443        if (hovered) {
7444            if ((mPrivateFlags & HOVERED) == 0) {
7445                mPrivateFlags |= HOVERED;
7446                refreshDrawableState();
7447                onHoverChanged(true);
7448            }
7449        } else {
7450            if ((mPrivateFlags & HOVERED) != 0) {
7451                mPrivateFlags &= ~HOVERED;
7452                refreshDrawableState();
7453                onHoverChanged(false);
7454            }
7455        }
7456    }
7457
7458    /**
7459     * Implement this method to handle hover state changes.
7460     * <p>
7461     * This method is called whenever the hover state changes as a result of a
7462     * call to {@link #setHovered}.
7463     * </p>
7464     *
7465     * @param hovered The current hover state, as returned by {@link #isHovered}.
7466     *
7467     * @see #isHovered
7468     * @see #setHovered
7469     */
7470    public void onHoverChanged(boolean hovered) {
7471    }
7472
7473    /**
7474     * Implement this method to handle touch screen motion events.
7475     *
7476     * @param event The motion event.
7477     * @return True if the event was handled, false otherwise.
7478     */
7479    public boolean onTouchEvent(MotionEvent event) {
7480        final int viewFlags = mViewFlags;
7481
7482        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7483            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7484                setPressed(false);
7485            }
7486            // A disabled view that is clickable still consumes the touch
7487            // events, it just doesn't respond to them.
7488            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7489                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7490        }
7491
7492        if (mTouchDelegate != null) {
7493            if (mTouchDelegate.onTouchEvent(event)) {
7494                return true;
7495            }
7496        }
7497
7498        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7499                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7500            switch (event.getAction()) {
7501                case MotionEvent.ACTION_UP:
7502                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7503                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7504                        // take focus if we don't have it already and we should in
7505                        // touch mode.
7506                        boolean focusTaken = false;
7507                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7508                            focusTaken = requestFocus();
7509                        }
7510
7511                        if (prepressed) {
7512                            // The button is being released before we actually
7513                            // showed it as pressed.  Make it show the pressed
7514                            // state now (before scheduling the click) to ensure
7515                            // the user sees it.
7516                            setPressed(true);
7517                       }
7518
7519                        if (!mHasPerformedLongPress) {
7520                            // This is a tap, so remove the longpress check
7521                            removeLongPressCallback();
7522
7523                            // Only perform take click actions if we were in the pressed state
7524                            if (!focusTaken) {
7525                                // Use a Runnable and post this rather than calling
7526                                // performClick directly. This lets other visual state
7527                                // of the view update before click actions start.
7528                                if (mPerformClick == null) {
7529                                    mPerformClick = new PerformClick();
7530                                }
7531                                if (!post(mPerformClick)) {
7532                                    performClick();
7533                                }
7534                            }
7535                        }
7536
7537                        if (mUnsetPressedState == null) {
7538                            mUnsetPressedState = new UnsetPressedState();
7539                        }
7540
7541                        if (prepressed) {
7542                            postDelayed(mUnsetPressedState,
7543                                    ViewConfiguration.getPressedStateDuration());
7544                        } else if (!post(mUnsetPressedState)) {
7545                            // If the post failed, unpress right now
7546                            mUnsetPressedState.run();
7547                        }
7548                        removeTapCallback();
7549                    }
7550                    break;
7551
7552                case MotionEvent.ACTION_DOWN:
7553                    mHasPerformedLongPress = false;
7554
7555                    if (performButtonActionOnTouchDown(event)) {
7556                        break;
7557                    }
7558
7559                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7560                    boolean isInScrollingContainer = isInScrollingContainer();
7561
7562                    // For views inside a scrolling container, delay the pressed feedback for
7563                    // a short period in case this is a scroll.
7564                    if (isInScrollingContainer) {
7565                        mPrivateFlags |= PREPRESSED;
7566                        if (mPendingCheckForTap == null) {
7567                            mPendingCheckForTap = new CheckForTap();
7568                        }
7569                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7570                    } else {
7571                        // Not inside a scrolling container, so show the feedback right away
7572                        setPressed(true);
7573                        checkForLongClick(0);
7574                    }
7575                    break;
7576
7577                case MotionEvent.ACTION_CANCEL:
7578                    setPressed(false);
7579                    removeTapCallback();
7580                    break;
7581
7582                case MotionEvent.ACTION_MOVE:
7583                    final int x = (int) event.getX();
7584                    final int y = (int) event.getY();
7585
7586                    // Be lenient about moving outside of buttons
7587                    if (!pointInView(x, y, mTouchSlop)) {
7588                        // Outside button
7589                        removeTapCallback();
7590                        if ((mPrivateFlags & PRESSED) != 0) {
7591                            // Remove any future long press/tap checks
7592                            removeLongPressCallback();
7593
7594                            setPressed(false);
7595                        }
7596                    }
7597                    break;
7598            }
7599            return true;
7600        }
7601
7602        return false;
7603    }
7604
7605    /**
7606     * @hide
7607     */
7608    public boolean isInScrollingContainer() {
7609        ViewParent p = getParent();
7610        while (p != null && p instanceof ViewGroup) {
7611            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7612                return true;
7613            }
7614            p = p.getParent();
7615        }
7616        return false;
7617    }
7618
7619    /**
7620     * Remove the longpress detection timer.
7621     */
7622    private void removeLongPressCallback() {
7623        if (mPendingCheckForLongPress != null) {
7624          removeCallbacks(mPendingCheckForLongPress);
7625        }
7626    }
7627
7628    /**
7629     * Remove the pending click action
7630     */
7631    private void removePerformClickCallback() {
7632        if (mPerformClick != null) {
7633            removeCallbacks(mPerformClick);
7634        }
7635    }
7636
7637    /**
7638     * Remove the prepress detection timer.
7639     */
7640    private void removeUnsetPressCallback() {
7641        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7642            setPressed(false);
7643            removeCallbacks(mUnsetPressedState);
7644        }
7645    }
7646
7647    /**
7648     * Remove the tap detection timer.
7649     */
7650    private void removeTapCallback() {
7651        if (mPendingCheckForTap != null) {
7652            mPrivateFlags &= ~PREPRESSED;
7653            removeCallbacks(mPendingCheckForTap);
7654        }
7655    }
7656
7657    /**
7658     * Cancels a pending long press.  Your subclass can use this if you
7659     * want the context menu to come up if the user presses and holds
7660     * at the same place, but you don't want it to come up if they press
7661     * and then move around enough to cause scrolling.
7662     */
7663    public void cancelLongPress() {
7664        removeLongPressCallback();
7665
7666        /*
7667         * The prepressed state handled by the tap callback is a display
7668         * construct, but the tap callback will post a long press callback
7669         * less its own timeout. Remove it here.
7670         */
7671        removeTapCallback();
7672    }
7673
7674    /**
7675     * Remove the pending callback for sending a
7676     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7677     */
7678    private void removeSendViewScrolledAccessibilityEventCallback() {
7679        if (mSendViewScrolledAccessibilityEvent != null) {
7680            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7681        }
7682    }
7683
7684    /**
7685     * Sets the TouchDelegate for this View.
7686     */
7687    public void setTouchDelegate(TouchDelegate delegate) {
7688        mTouchDelegate = delegate;
7689    }
7690
7691    /**
7692     * Gets the TouchDelegate for this View.
7693     */
7694    public TouchDelegate getTouchDelegate() {
7695        return mTouchDelegate;
7696    }
7697
7698    /**
7699     * Set flags controlling behavior of this view.
7700     *
7701     * @param flags Constant indicating the value which should be set
7702     * @param mask Constant indicating the bit range that should be changed
7703     */
7704    void setFlags(int flags, int mask) {
7705        int old = mViewFlags;
7706        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7707
7708        int changed = mViewFlags ^ old;
7709        if (changed == 0) {
7710            return;
7711        }
7712        int privateFlags = mPrivateFlags;
7713
7714        /* Check if the FOCUSABLE bit has changed */
7715        if (((changed & FOCUSABLE_MASK) != 0) &&
7716                ((privateFlags & HAS_BOUNDS) !=0)) {
7717            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7718                    && ((privateFlags & FOCUSED) != 0)) {
7719                /* Give up focus if we are no longer focusable */
7720                clearFocus();
7721            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7722                    && ((privateFlags & FOCUSED) == 0)) {
7723                /*
7724                 * Tell the view system that we are now available to take focus
7725                 * if no one else already has it.
7726                 */
7727                if (mParent != null) mParent.focusableViewAvailable(this);
7728            }
7729            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7730                notifyAccessibilityStateChanged();
7731            }
7732        }
7733
7734        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7735            if ((changed & VISIBILITY_MASK) != 0) {
7736                /*
7737                 * If this view is becoming visible, invalidate it in case it changed while
7738                 * it was not visible. Marking it drawn ensures that the invalidation will
7739                 * go through.
7740                 */
7741                mPrivateFlags |= DRAWN;
7742                invalidate(true);
7743
7744                needGlobalAttributesUpdate(true);
7745
7746                // a view becoming visible is worth notifying the parent
7747                // about in case nothing has focus.  even if this specific view
7748                // isn't focusable, it may contain something that is, so let
7749                // the root view try to give this focus if nothing else does.
7750                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7751                    mParent.focusableViewAvailable(this);
7752                }
7753            }
7754        }
7755
7756        /* Check if the GONE bit has changed */
7757        if ((changed & GONE) != 0) {
7758            needGlobalAttributesUpdate(false);
7759            requestLayout();
7760
7761            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7762                if (hasFocus()) clearFocus();
7763                clearAccessibilityFocus();
7764                destroyDrawingCache();
7765                if (mParent instanceof View) {
7766                    // GONE views noop invalidation, so invalidate the parent
7767                    ((View) mParent).invalidate(true);
7768                }
7769                // Mark the view drawn to ensure that it gets invalidated properly the next
7770                // time it is visible and gets invalidated
7771                mPrivateFlags |= DRAWN;
7772            }
7773            if (mAttachInfo != null) {
7774                mAttachInfo.mViewVisibilityChanged = true;
7775            }
7776        }
7777
7778        /* Check if the VISIBLE bit has changed */
7779        if ((changed & INVISIBLE) != 0) {
7780            needGlobalAttributesUpdate(false);
7781            /*
7782             * If this view is becoming invisible, set the DRAWN flag so that
7783             * the next invalidate() will not be skipped.
7784             */
7785            mPrivateFlags |= DRAWN;
7786
7787            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7788                // root view becoming invisible shouldn't clear focus and accessibility focus
7789                if (getRootView() != this) {
7790                    clearFocus();
7791                    clearAccessibilityFocus();
7792                }
7793            }
7794            if (mAttachInfo != null) {
7795                mAttachInfo.mViewVisibilityChanged = true;
7796            }
7797        }
7798
7799        if ((changed & VISIBILITY_MASK) != 0) {
7800            if (mParent instanceof ViewGroup) {
7801                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7802                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7803                ((View) mParent).invalidate(true);
7804            } else if (mParent != null) {
7805                mParent.invalidateChild(this, null);
7806            }
7807            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7808        }
7809
7810        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7811            destroyDrawingCache();
7812        }
7813
7814        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7815            destroyDrawingCache();
7816            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7817            invalidateParentCaches();
7818        }
7819
7820        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7821            destroyDrawingCache();
7822            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7823        }
7824
7825        if ((changed & DRAW_MASK) != 0) {
7826            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7827                if (mBackground != null) {
7828                    mPrivateFlags &= ~SKIP_DRAW;
7829                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7830                } else {
7831                    mPrivateFlags |= SKIP_DRAW;
7832                }
7833            } else {
7834                mPrivateFlags &= ~SKIP_DRAW;
7835            }
7836            requestLayout();
7837            invalidate(true);
7838        }
7839
7840        if ((changed & KEEP_SCREEN_ON) != 0) {
7841            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7842                mParent.recomputeViewAttributes(this);
7843            }
7844        }
7845
7846        if (AccessibilityManager.getInstance(mContext).isEnabled()
7847                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
7848                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
7849            notifyAccessibilityStateChanged();
7850        }
7851    }
7852
7853    /**
7854     * Change the view's z order in the tree, so it's on top of other sibling
7855     * views
7856     */
7857    public void bringToFront() {
7858        if (mParent != null) {
7859            mParent.bringChildToFront(this);
7860        }
7861    }
7862
7863    /**
7864     * This is called in response to an internal scroll in this view (i.e., the
7865     * view scrolled its own contents). This is typically as a result of
7866     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7867     * called.
7868     *
7869     * @param l Current horizontal scroll origin.
7870     * @param t Current vertical scroll origin.
7871     * @param oldl Previous horizontal scroll origin.
7872     * @param oldt Previous vertical scroll origin.
7873     */
7874    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7875        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7876            postSendViewScrolledAccessibilityEventCallback();
7877        }
7878
7879        mBackgroundSizeChanged = true;
7880
7881        final AttachInfo ai = mAttachInfo;
7882        if (ai != null) {
7883            ai.mViewScrollChanged = true;
7884        }
7885    }
7886
7887    /**
7888     * Interface definition for a callback to be invoked when the layout bounds of a view
7889     * changes due to layout processing.
7890     */
7891    public interface OnLayoutChangeListener {
7892        /**
7893         * Called when the focus state of a view has changed.
7894         *
7895         * @param v The view whose state has changed.
7896         * @param left The new value of the view's left property.
7897         * @param top The new value of the view's top property.
7898         * @param right The new value of the view's right property.
7899         * @param bottom The new value of the view's bottom property.
7900         * @param oldLeft The previous value of the view's left property.
7901         * @param oldTop The previous value of the view's top property.
7902         * @param oldRight The previous value of the view's right property.
7903         * @param oldBottom The previous value of the view's bottom property.
7904         */
7905        void onLayoutChange(View v, int left, int top, int right, int bottom,
7906            int oldLeft, int oldTop, int oldRight, int oldBottom);
7907    }
7908
7909    /**
7910     * This is called during layout when the size of this view has changed. If
7911     * you were just added to the view hierarchy, you're called with the old
7912     * values of 0.
7913     *
7914     * @param w Current width of this view.
7915     * @param h Current height of this view.
7916     * @param oldw Old width of this view.
7917     * @param oldh Old height of this view.
7918     */
7919    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7920    }
7921
7922    /**
7923     * Called by draw to draw the child views. This may be overridden
7924     * by derived classes to gain control just before its children are drawn
7925     * (but after its own view has been drawn).
7926     * @param canvas the canvas on which to draw the view
7927     */
7928    protected void dispatchDraw(Canvas canvas) {
7929
7930    }
7931
7932    /**
7933     * Gets the parent of this view. Note that the parent is a
7934     * ViewParent and not necessarily a View.
7935     *
7936     * @return Parent of this view.
7937     */
7938    public final ViewParent getParent() {
7939        return mParent;
7940    }
7941
7942    /**
7943     * Set the horizontal scrolled position of your view. This will cause a call to
7944     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7945     * invalidated.
7946     * @param value the x position to scroll to
7947     */
7948    public void setScrollX(int value) {
7949        scrollTo(value, mScrollY);
7950    }
7951
7952    /**
7953     * Set the vertical scrolled position of your view. This will cause a call to
7954     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7955     * invalidated.
7956     * @param value the y position to scroll to
7957     */
7958    public void setScrollY(int value) {
7959        scrollTo(mScrollX, value);
7960    }
7961
7962    /**
7963     * Return the scrolled left position of this view. This is the left edge of
7964     * the displayed part of your view. You do not need to draw any pixels
7965     * farther left, since those are outside of the frame of your view on
7966     * screen.
7967     *
7968     * @return The left edge of the displayed part of your view, in pixels.
7969     */
7970    public final int getScrollX() {
7971        return mScrollX;
7972    }
7973
7974    /**
7975     * Return the scrolled top position of this view. This is the top edge of
7976     * the displayed part of your view. You do not need to draw any pixels above
7977     * it, since those are outside of the frame of your view on screen.
7978     *
7979     * @return The top edge of the displayed part of your view, in pixels.
7980     */
7981    public final int getScrollY() {
7982        return mScrollY;
7983    }
7984
7985    /**
7986     * Return the width of the your view.
7987     *
7988     * @return The width of your view, in pixels.
7989     */
7990    @ViewDebug.ExportedProperty(category = "layout")
7991    public final int getWidth() {
7992        return mRight - mLeft;
7993    }
7994
7995    /**
7996     * Return the height of your view.
7997     *
7998     * @return The height of your view, in pixels.
7999     */
8000    @ViewDebug.ExportedProperty(category = "layout")
8001    public final int getHeight() {
8002        return mBottom - mTop;
8003    }
8004
8005    /**
8006     * Return the visible drawing bounds of your view. Fills in the output
8007     * rectangle with the values from getScrollX(), getScrollY(),
8008     * getWidth(), and getHeight().
8009     *
8010     * @param outRect The (scrolled) drawing bounds of the view.
8011     */
8012    public void getDrawingRect(Rect outRect) {
8013        outRect.left = mScrollX;
8014        outRect.top = mScrollY;
8015        outRect.right = mScrollX + (mRight - mLeft);
8016        outRect.bottom = mScrollY + (mBottom - mTop);
8017    }
8018
8019    /**
8020     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8021     * raw width component (that is the result is masked by
8022     * {@link #MEASURED_SIZE_MASK}).
8023     *
8024     * @return The raw measured width of this view.
8025     */
8026    public final int getMeasuredWidth() {
8027        return mMeasuredWidth & MEASURED_SIZE_MASK;
8028    }
8029
8030    /**
8031     * Return the full width measurement information for this view as computed
8032     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8033     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8034     * This should be used during measurement and layout calculations only. Use
8035     * {@link #getWidth()} to see how wide a view is after layout.
8036     *
8037     * @return The measured width of this view as a bit mask.
8038     */
8039    public final int getMeasuredWidthAndState() {
8040        return mMeasuredWidth;
8041    }
8042
8043    /**
8044     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8045     * raw width component (that is the result is masked by
8046     * {@link #MEASURED_SIZE_MASK}).
8047     *
8048     * @return The raw measured height of this view.
8049     */
8050    public final int getMeasuredHeight() {
8051        return mMeasuredHeight & MEASURED_SIZE_MASK;
8052    }
8053
8054    /**
8055     * Return the full height measurement information for this view as computed
8056     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8057     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8058     * This should be used during measurement and layout calculations only. Use
8059     * {@link #getHeight()} to see how wide a view is after layout.
8060     *
8061     * @return The measured width of this view as a bit mask.
8062     */
8063    public final int getMeasuredHeightAndState() {
8064        return mMeasuredHeight;
8065    }
8066
8067    /**
8068     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8069     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8070     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8071     * and the height component is at the shifted bits
8072     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8073     */
8074    public final int getMeasuredState() {
8075        return (mMeasuredWidth&MEASURED_STATE_MASK)
8076                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8077                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8078    }
8079
8080    /**
8081     * The transform matrix of this view, which is calculated based on the current
8082     * roation, scale, and pivot properties.
8083     *
8084     * @see #getRotation()
8085     * @see #getScaleX()
8086     * @see #getScaleY()
8087     * @see #getPivotX()
8088     * @see #getPivotY()
8089     * @return The current transform matrix for the view
8090     */
8091    public Matrix getMatrix() {
8092        if (mTransformationInfo != null) {
8093            updateMatrix();
8094            return mTransformationInfo.mMatrix;
8095        }
8096        return Matrix.IDENTITY_MATRIX;
8097    }
8098
8099    /**
8100     * Utility function to determine if the value is far enough away from zero to be
8101     * considered non-zero.
8102     * @param value A floating point value to check for zero-ness
8103     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8104     */
8105    private static boolean nonzero(float value) {
8106        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8107    }
8108
8109    /**
8110     * Returns true if the transform matrix is the identity matrix.
8111     * Recomputes the matrix if necessary.
8112     *
8113     * @return True if the transform matrix is the identity matrix, false otherwise.
8114     */
8115    final boolean hasIdentityMatrix() {
8116        if (mTransformationInfo != null) {
8117            updateMatrix();
8118            return mTransformationInfo.mMatrixIsIdentity;
8119        }
8120        return true;
8121    }
8122
8123    void ensureTransformationInfo() {
8124        if (mTransformationInfo == null) {
8125            mTransformationInfo = new TransformationInfo();
8126        }
8127    }
8128
8129    /**
8130     * Recomputes the transform matrix if necessary.
8131     */
8132    private void updateMatrix() {
8133        final TransformationInfo info = mTransformationInfo;
8134        if (info == null) {
8135            return;
8136        }
8137        if (info.mMatrixDirty) {
8138            // transform-related properties have changed since the last time someone
8139            // asked for the matrix; recalculate it with the current values
8140
8141            // Figure out if we need to update the pivot point
8142            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8143                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8144                    info.mPrevWidth = mRight - mLeft;
8145                    info.mPrevHeight = mBottom - mTop;
8146                    info.mPivotX = info.mPrevWidth / 2f;
8147                    info.mPivotY = info.mPrevHeight / 2f;
8148                }
8149            }
8150            info.mMatrix.reset();
8151            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8152                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8153                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8154                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8155            } else {
8156                if (info.mCamera == null) {
8157                    info.mCamera = new Camera();
8158                    info.matrix3D = new Matrix();
8159                }
8160                info.mCamera.save();
8161                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8162                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8163                info.mCamera.getMatrix(info.matrix3D);
8164                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8165                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8166                        info.mPivotY + info.mTranslationY);
8167                info.mMatrix.postConcat(info.matrix3D);
8168                info.mCamera.restore();
8169            }
8170            info.mMatrixDirty = false;
8171            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8172            info.mInverseMatrixDirty = true;
8173        }
8174    }
8175
8176    /**
8177     * Utility method to retrieve the inverse of the current mMatrix property.
8178     * We cache the matrix to avoid recalculating it when transform properties
8179     * have not changed.
8180     *
8181     * @return The inverse of the current matrix of this view.
8182     */
8183    final Matrix getInverseMatrix() {
8184        final TransformationInfo info = mTransformationInfo;
8185        if (info != null) {
8186            updateMatrix();
8187            if (info.mInverseMatrixDirty) {
8188                if (info.mInverseMatrix == null) {
8189                    info.mInverseMatrix = new Matrix();
8190                }
8191                info.mMatrix.invert(info.mInverseMatrix);
8192                info.mInverseMatrixDirty = false;
8193            }
8194            return info.mInverseMatrix;
8195        }
8196        return Matrix.IDENTITY_MATRIX;
8197    }
8198
8199    /**
8200     * Gets the distance along the Z axis from the camera to this view.
8201     *
8202     * @see #setCameraDistance(float)
8203     *
8204     * @return The distance along the Z axis.
8205     */
8206    public float getCameraDistance() {
8207        ensureTransformationInfo();
8208        final float dpi = mResources.getDisplayMetrics().densityDpi;
8209        final TransformationInfo info = mTransformationInfo;
8210        if (info.mCamera == null) {
8211            info.mCamera = new Camera();
8212            info.matrix3D = new Matrix();
8213        }
8214        return -(info.mCamera.getLocationZ() * dpi);
8215    }
8216
8217    /**
8218     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8219     * views are drawn) from the camera to this view. The camera's distance
8220     * affects 3D transformations, for instance rotations around the X and Y
8221     * axis. If the rotationX or rotationY properties are changed and this view is
8222     * large (more than half the size of the screen), it is recommended to always
8223     * use a camera distance that's greater than the height (X axis rotation) or
8224     * the width (Y axis rotation) of this view.</p>
8225     *
8226     * <p>The distance of the camera from the view plane can have an affect on the
8227     * perspective distortion of the view when it is rotated around the x or y axis.
8228     * For example, a large distance will result in a large viewing angle, and there
8229     * will not be much perspective distortion of the view as it rotates. A short
8230     * distance may cause much more perspective distortion upon rotation, and can
8231     * also result in some drawing artifacts if the rotated view ends up partially
8232     * behind the camera (which is why the recommendation is to use a distance at
8233     * least as far as the size of the view, if the view is to be rotated.)</p>
8234     *
8235     * <p>The distance is expressed in "depth pixels." The default distance depends
8236     * on the screen density. For instance, on a medium density display, the
8237     * default distance is 1280. On a high density display, the default distance
8238     * is 1920.</p>
8239     *
8240     * <p>If you want to specify a distance that leads to visually consistent
8241     * results across various densities, use the following formula:</p>
8242     * <pre>
8243     * float scale = context.getResources().getDisplayMetrics().density;
8244     * view.setCameraDistance(distance * scale);
8245     * </pre>
8246     *
8247     * <p>The density scale factor of a high density display is 1.5,
8248     * and 1920 = 1280 * 1.5.</p>
8249     *
8250     * @param distance The distance in "depth pixels", if negative the opposite
8251     *        value is used
8252     *
8253     * @see #setRotationX(float)
8254     * @see #setRotationY(float)
8255     */
8256    public void setCameraDistance(float distance) {
8257        invalidateViewProperty(true, false);
8258
8259        ensureTransformationInfo();
8260        final float dpi = mResources.getDisplayMetrics().densityDpi;
8261        final TransformationInfo info = mTransformationInfo;
8262        if (info.mCamera == null) {
8263            info.mCamera = new Camera();
8264            info.matrix3D = new Matrix();
8265        }
8266
8267        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8268        info.mMatrixDirty = true;
8269
8270        invalidateViewProperty(false, false);
8271        if (mDisplayList != null) {
8272            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8273        }
8274    }
8275
8276    /**
8277     * The degrees that the view is rotated around the pivot point.
8278     *
8279     * @see #setRotation(float)
8280     * @see #getPivotX()
8281     * @see #getPivotY()
8282     *
8283     * @return The degrees of rotation.
8284     */
8285    @ViewDebug.ExportedProperty(category = "drawing")
8286    public float getRotation() {
8287        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8288    }
8289
8290    /**
8291     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8292     * result in clockwise rotation.
8293     *
8294     * @param rotation The degrees of rotation.
8295     *
8296     * @see #getRotation()
8297     * @see #getPivotX()
8298     * @see #getPivotY()
8299     * @see #setRotationX(float)
8300     * @see #setRotationY(float)
8301     *
8302     * @attr ref android.R.styleable#View_rotation
8303     */
8304    public void setRotation(float rotation) {
8305        ensureTransformationInfo();
8306        final TransformationInfo info = mTransformationInfo;
8307        if (info.mRotation != rotation) {
8308            // Double-invalidation is necessary to capture view's old and new areas
8309            invalidateViewProperty(true, false);
8310            info.mRotation = rotation;
8311            info.mMatrixDirty = true;
8312            invalidateViewProperty(false, true);
8313            if (mDisplayList != null) {
8314                mDisplayList.setRotation(rotation);
8315            }
8316        }
8317    }
8318
8319    /**
8320     * The degrees that the view is rotated around the vertical axis through the pivot point.
8321     *
8322     * @see #getPivotX()
8323     * @see #getPivotY()
8324     * @see #setRotationY(float)
8325     *
8326     * @return The degrees of Y rotation.
8327     */
8328    @ViewDebug.ExportedProperty(category = "drawing")
8329    public float getRotationY() {
8330        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8331    }
8332
8333    /**
8334     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8335     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8336     * down the y axis.
8337     *
8338     * When rotating large views, it is recommended to adjust the camera distance
8339     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8340     *
8341     * @param rotationY The degrees of Y rotation.
8342     *
8343     * @see #getRotationY()
8344     * @see #getPivotX()
8345     * @see #getPivotY()
8346     * @see #setRotation(float)
8347     * @see #setRotationX(float)
8348     * @see #setCameraDistance(float)
8349     *
8350     * @attr ref android.R.styleable#View_rotationY
8351     */
8352    public void setRotationY(float rotationY) {
8353        ensureTransformationInfo();
8354        final TransformationInfo info = mTransformationInfo;
8355        if (info.mRotationY != rotationY) {
8356            invalidateViewProperty(true, false);
8357            info.mRotationY = rotationY;
8358            info.mMatrixDirty = true;
8359            invalidateViewProperty(false, true);
8360            if (mDisplayList != null) {
8361                mDisplayList.setRotationY(rotationY);
8362            }
8363        }
8364    }
8365
8366    /**
8367     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8368     *
8369     * @see #getPivotX()
8370     * @see #getPivotY()
8371     * @see #setRotationX(float)
8372     *
8373     * @return The degrees of X rotation.
8374     */
8375    @ViewDebug.ExportedProperty(category = "drawing")
8376    public float getRotationX() {
8377        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8378    }
8379
8380    /**
8381     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8382     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8383     * x axis.
8384     *
8385     * When rotating large views, it is recommended to adjust the camera distance
8386     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8387     *
8388     * @param rotationX The degrees of X rotation.
8389     *
8390     * @see #getRotationX()
8391     * @see #getPivotX()
8392     * @see #getPivotY()
8393     * @see #setRotation(float)
8394     * @see #setRotationY(float)
8395     * @see #setCameraDistance(float)
8396     *
8397     * @attr ref android.R.styleable#View_rotationX
8398     */
8399    public void setRotationX(float rotationX) {
8400        ensureTransformationInfo();
8401        final TransformationInfo info = mTransformationInfo;
8402        if (info.mRotationX != rotationX) {
8403            invalidateViewProperty(true, false);
8404            info.mRotationX = rotationX;
8405            info.mMatrixDirty = true;
8406            invalidateViewProperty(false, true);
8407            if (mDisplayList != null) {
8408                mDisplayList.setRotationX(rotationX);
8409            }
8410        }
8411    }
8412
8413    /**
8414     * The amount that the view is scaled in x around the pivot point, as a proportion of
8415     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8416     *
8417     * <p>By default, this is 1.0f.
8418     *
8419     * @see #getPivotX()
8420     * @see #getPivotY()
8421     * @return The scaling factor.
8422     */
8423    @ViewDebug.ExportedProperty(category = "drawing")
8424    public float getScaleX() {
8425        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8426    }
8427
8428    /**
8429     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8430     * the view's unscaled width. A value of 1 means that no scaling is applied.
8431     *
8432     * @param scaleX The scaling factor.
8433     * @see #getPivotX()
8434     * @see #getPivotY()
8435     *
8436     * @attr ref android.R.styleable#View_scaleX
8437     */
8438    public void setScaleX(float scaleX) {
8439        ensureTransformationInfo();
8440        final TransformationInfo info = mTransformationInfo;
8441        if (info.mScaleX != scaleX) {
8442            invalidateViewProperty(true, false);
8443            info.mScaleX = scaleX;
8444            info.mMatrixDirty = true;
8445            invalidateViewProperty(false, true);
8446            if (mDisplayList != null) {
8447                mDisplayList.setScaleX(scaleX);
8448            }
8449        }
8450    }
8451
8452    /**
8453     * The amount that the view is scaled in y around the pivot point, as a proportion of
8454     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8455     *
8456     * <p>By default, this is 1.0f.
8457     *
8458     * @see #getPivotX()
8459     * @see #getPivotY()
8460     * @return The scaling factor.
8461     */
8462    @ViewDebug.ExportedProperty(category = "drawing")
8463    public float getScaleY() {
8464        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8465    }
8466
8467    /**
8468     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8469     * the view's unscaled width. A value of 1 means that no scaling is applied.
8470     *
8471     * @param scaleY The scaling factor.
8472     * @see #getPivotX()
8473     * @see #getPivotY()
8474     *
8475     * @attr ref android.R.styleable#View_scaleY
8476     */
8477    public void setScaleY(float scaleY) {
8478        ensureTransformationInfo();
8479        final TransformationInfo info = mTransformationInfo;
8480        if (info.mScaleY != scaleY) {
8481            invalidateViewProperty(true, false);
8482            info.mScaleY = scaleY;
8483            info.mMatrixDirty = true;
8484            invalidateViewProperty(false, true);
8485            if (mDisplayList != null) {
8486                mDisplayList.setScaleY(scaleY);
8487            }
8488        }
8489    }
8490
8491    /**
8492     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8493     * and {@link #setScaleX(float) scaled}.
8494     *
8495     * @see #getRotation()
8496     * @see #getScaleX()
8497     * @see #getScaleY()
8498     * @see #getPivotY()
8499     * @return The x location of the pivot point.
8500     *
8501     * @attr ref android.R.styleable#View_transformPivotX
8502     */
8503    @ViewDebug.ExportedProperty(category = "drawing")
8504    public float getPivotX() {
8505        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8506    }
8507
8508    /**
8509     * Sets the x location of the point around which the view is
8510     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8511     * By default, the pivot point is centered on the object.
8512     * Setting this property disables this behavior and causes the view to use only the
8513     * explicitly set pivotX and pivotY values.
8514     *
8515     * @param pivotX The x location of the pivot point.
8516     * @see #getRotation()
8517     * @see #getScaleX()
8518     * @see #getScaleY()
8519     * @see #getPivotY()
8520     *
8521     * @attr ref android.R.styleable#View_transformPivotX
8522     */
8523    public void setPivotX(float pivotX) {
8524        ensureTransformationInfo();
8525        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8526        final TransformationInfo info = mTransformationInfo;
8527        if (info.mPivotX != pivotX) {
8528            invalidateViewProperty(true, false);
8529            info.mPivotX = pivotX;
8530            info.mMatrixDirty = true;
8531            invalidateViewProperty(false, true);
8532            if (mDisplayList != null) {
8533                mDisplayList.setPivotX(pivotX);
8534            }
8535        }
8536    }
8537
8538    /**
8539     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8540     * and {@link #setScaleY(float) scaled}.
8541     *
8542     * @see #getRotation()
8543     * @see #getScaleX()
8544     * @see #getScaleY()
8545     * @see #getPivotY()
8546     * @return The y location of the pivot point.
8547     *
8548     * @attr ref android.R.styleable#View_transformPivotY
8549     */
8550    @ViewDebug.ExportedProperty(category = "drawing")
8551    public float getPivotY() {
8552        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8553    }
8554
8555    /**
8556     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8557     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8558     * Setting this property disables this behavior and causes the view to use only the
8559     * explicitly set pivotX and pivotY values.
8560     *
8561     * @param pivotY The y location of the pivot point.
8562     * @see #getRotation()
8563     * @see #getScaleX()
8564     * @see #getScaleY()
8565     * @see #getPivotY()
8566     *
8567     * @attr ref android.R.styleable#View_transformPivotY
8568     */
8569    public void setPivotY(float pivotY) {
8570        ensureTransformationInfo();
8571        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8572        final TransformationInfo info = mTransformationInfo;
8573        if (info.mPivotY != pivotY) {
8574            invalidateViewProperty(true, false);
8575            info.mPivotY = pivotY;
8576            info.mMatrixDirty = true;
8577            invalidateViewProperty(false, true);
8578            if (mDisplayList != null) {
8579                mDisplayList.setPivotY(pivotY);
8580            }
8581        }
8582    }
8583
8584    /**
8585     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8586     * completely transparent and 1 means the view is completely opaque.
8587     *
8588     * <p>By default this is 1.0f.
8589     * @return The opacity of the view.
8590     */
8591    @ViewDebug.ExportedProperty(category = "drawing")
8592    public float getAlpha() {
8593        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8594    }
8595
8596    /**
8597     * Returns whether this View has content which overlaps. This function, intended to be
8598     * overridden by specific View types, is an optimization when alpha is set on a view. If
8599     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8600     * and then composited it into place, which can be expensive. If the view has no overlapping
8601     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8602     * An example of overlapping rendering is a TextView with a background image, such as a
8603     * Button. An example of non-overlapping rendering is a TextView with no background, or
8604     * an ImageView with only the foreground image. The default implementation returns true;
8605     * subclasses should override if they have cases which can be optimized.
8606     *
8607     * @return true if the content in this view might overlap, false otherwise.
8608     */
8609    public boolean hasOverlappingRendering() {
8610        return true;
8611    }
8612
8613    /**
8614     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8615     * completely transparent and 1 means the view is completely opaque.</p>
8616     *
8617     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8618     * responsible for applying the opacity itself. Otherwise, calling this method is
8619     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8620     * setting a hardware layer.</p>
8621     *
8622     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8623     * performance implications. It is generally best to use the alpha property sparingly and
8624     * transiently, as in the case of fading animations.</p>
8625     *
8626     * @param alpha The opacity of the view.
8627     *
8628     * @see #setLayerType(int, android.graphics.Paint)
8629     *
8630     * @attr ref android.R.styleable#View_alpha
8631     */
8632    public void setAlpha(float alpha) {
8633        ensureTransformationInfo();
8634        if (mTransformationInfo.mAlpha != alpha) {
8635            mTransformationInfo.mAlpha = alpha;
8636            if (onSetAlpha((int) (alpha * 255))) {
8637                mPrivateFlags |= ALPHA_SET;
8638                // subclass is handling alpha - don't optimize rendering cache invalidation
8639                invalidateParentCaches();
8640                invalidate(true);
8641            } else {
8642                mPrivateFlags &= ~ALPHA_SET;
8643                invalidateViewProperty(true, false);
8644                if (mDisplayList != null) {
8645                    mDisplayList.setAlpha(alpha);
8646                }
8647            }
8648        }
8649    }
8650
8651    /**
8652     * Faster version of setAlpha() which performs the same steps except there are
8653     * no calls to invalidate(). The caller of this function should perform proper invalidation
8654     * on the parent and this object. The return value indicates whether the subclass handles
8655     * alpha (the return value for onSetAlpha()).
8656     *
8657     * @param alpha The new value for the alpha property
8658     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8659     *         the new value for the alpha property is different from the old value
8660     */
8661    boolean setAlphaNoInvalidation(float alpha) {
8662        ensureTransformationInfo();
8663        if (mTransformationInfo.mAlpha != alpha) {
8664            mTransformationInfo.mAlpha = alpha;
8665            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8666            if (subclassHandlesAlpha) {
8667                mPrivateFlags |= ALPHA_SET;
8668                return true;
8669            } else {
8670                mPrivateFlags &= ~ALPHA_SET;
8671                if (mDisplayList != null) {
8672                    mDisplayList.setAlpha(alpha);
8673                }
8674            }
8675        }
8676        return false;
8677    }
8678
8679    /**
8680     * Top position of this view relative to its parent.
8681     *
8682     * @return The top of this view, in pixels.
8683     */
8684    @ViewDebug.CapturedViewProperty
8685    public final int getTop() {
8686        return mTop;
8687    }
8688
8689    /**
8690     * Sets the top position of this view relative to its parent. This method is meant to be called
8691     * by the layout system and should not generally be called otherwise, because the property
8692     * may be changed at any time by the layout.
8693     *
8694     * @param top The top of this view, in pixels.
8695     */
8696    public final void setTop(int top) {
8697        if (top != mTop) {
8698            updateMatrix();
8699            final boolean matrixIsIdentity = mTransformationInfo == null
8700                    || mTransformationInfo.mMatrixIsIdentity;
8701            if (matrixIsIdentity) {
8702                if (mAttachInfo != null) {
8703                    int minTop;
8704                    int yLoc;
8705                    if (top < mTop) {
8706                        minTop = top;
8707                        yLoc = top - mTop;
8708                    } else {
8709                        minTop = mTop;
8710                        yLoc = 0;
8711                    }
8712                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8713                }
8714            } else {
8715                // Double-invalidation is necessary to capture view's old and new areas
8716                invalidate(true);
8717            }
8718
8719            int width = mRight - mLeft;
8720            int oldHeight = mBottom - mTop;
8721
8722            mTop = top;
8723            if (mDisplayList != null) {
8724                mDisplayList.setTop(mTop);
8725            }
8726
8727            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8728
8729            if (!matrixIsIdentity) {
8730                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8731                    // A change in dimension means an auto-centered pivot point changes, too
8732                    mTransformationInfo.mMatrixDirty = true;
8733                }
8734                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8735                invalidate(true);
8736            }
8737            mBackgroundSizeChanged = true;
8738            invalidateParentIfNeeded();
8739        }
8740    }
8741
8742    /**
8743     * Bottom position of this view relative to its parent.
8744     *
8745     * @return The bottom of this view, in pixels.
8746     */
8747    @ViewDebug.CapturedViewProperty
8748    public final int getBottom() {
8749        return mBottom;
8750    }
8751
8752    /**
8753     * True if this view has changed since the last time being drawn.
8754     *
8755     * @return The dirty state of this view.
8756     */
8757    public boolean isDirty() {
8758        return (mPrivateFlags & DIRTY_MASK) != 0;
8759    }
8760
8761    /**
8762     * Sets the bottom position of this view relative to its parent. This method is meant to be
8763     * called by the layout system and should not generally be called otherwise, because the
8764     * property may be changed at any time by the layout.
8765     *
8766     * @param bottom The bottom of this view, in pixels.
8767     */
8768    public final void setBottom(int bottom) {
8769        if (bottom != mBottom) {
8770            updateMatrix();
8771            final boolean matrixIsIdentity = mTransformationInfo == null
8772                    || mTransformationInfo.mMatrixIsIdentity;
8773            if (matrixIsIdentity) {
8774                if (mAttachInfo != null) {
8775                    int maxBottom;
8776                    if (bottom < mBottom) {
8777                        maxBottom = mBottom;
8778                    } else {
8779                        maxBottom = bottom;
8780                    }
8781                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8782                }
8783            } else {
8784                // Double-invalidation is necessary to capture view's old and new areas
8785                invalidate(true);
8786            }
8787
8788            int width = mRight - mLeft;
8789            int oldHeight = mBottom - mTop;
8790
8791            mBottom = bottom;
8792            if (mDisplayList != null) {
8793                mDisplayList.setBottom(mBottom);
8794            }
8795
8796            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8797
8798            if (!matrixIsIdentity) {
8799                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8800                    // A change in dimension means an auto-centered pivot point changes, too
8801                    mTransformationInfo.mMatrixDirty = true;
8802                }
8803                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8804                invalidate(true);
8805            }
8806            mBackgroundSizeChanged = true;
8807            invalidateParentIfNeeded();
8808        }
8809    }
8810
8811    /**
8812     * Left position of this view relative to its parent.
8813     *
8814     * @return The left edge of this view, in pixels.
8815     */
8816    @ViewDebug.CapturedViewProperty
8817    public final int getLeft() {
8818        return mLeft;
8819    }
8820
8821    /**
8822     * Sets the left position of this view relative to its parent. This method is meant to be called
8823     * by the layout system and should not generally be called otherwise, because the property
8824     * may be changed at any time by the layout.
8825     *
8826     * @param left The bottom of this view, in pixels.
8827     */
8828    public final void setLeft(int left) {
8829        if (left != mLeft) {
8830            updateMatrix();
8831            final boolean matrixIsIdentity = mTransformationInfo == null
8832                    || mTransformationInfo.mMatrixIsIdentity;
8833            if (matrixIsIdentity) {
8834                if (mAttachInfo != null) {
8835                    int minLeft;
8836                    int xLoc;
8837                    if (left < mLeft) {
8838                        minLeft = left;
8839                        xLoc = left - mLeft;
8840                    } else {
8841                        minLeft = mLeft;
8842                        xLoc = 0;
8843                    }
8844                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8845                }
8846            } else {
8847                // Double-invalidation is necessary to capture view's old and new areas
8848                invalidate(true);
8849            }
8850
8851            int oldWidth = mRight - mLeft;
8852            int height = mBottom - mTop;
8853
8854            mLeft = left;
8855            if (mDisplayList != null) {
8856                mDisplayList.setLeft(left);
8857            }
8858
8859            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8860
8861            if (!matrixIsIdentity) {
8862                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8863                    // A change in dimension means an auto-centered pivot point changes, too
8864                    mTransformationInfo.mMatrixDirty = true;
8865                }
8866                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8867                invalidate(true);
8868            }
8869            mBackgroundSizeChanged = true;
8870            invalidateParentIfNeeded();
8871        }
8872    }
8873
8874    /**
8875     * Right position of this view relative to its parent.
8876     *
8877     * @return The right edge of this view, in pixels.
8878     */
8879    @ViewDebug.CapturedViewProperty
8880    public final int getRight() {
8881        return mRight;
8882    }
8883
8884    /**
8885     * Sets the right position of this view relative to its parent. This method is meant to be called
8886     * by the layout system and should not generally be called otherwise, because the property
8887     * may be changed at any time by the layout.
8888     *
8889     * @param right The bottom of this view, in pixels.
8890     */
8891    public final void setRight(int right) {
8892        if (right != mRight) {
8893            updateMatrix();
8894            final boolean matrixIsIdentity = mTransformationInfo == null
8895                    || mTransformationInfo.mMatrixIsIdentity;
8896            if (matrixIsIdentity) {
8897                if (mAttachInfo != null) {
8898                    int maxRight;
8899                    if (right < mRight) {
8900                        maxRight = mRight;
8901                    } else {
8902                        maxRight = right;
8903                    }
8904                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8905                }
8906            } else {
8907                // Double-invalidation is necessary to capture view's old and new areas
8908                invalidate(true);
8909            }
8910
8911            int oldWidth = mRight - mLeft;
8912            int height = mBottom - mTop;
8913
8914            mRight = right;
8915            if (mDisplayList != null) {
8916                mDisplayList.setRight(mRight);
8917            }
8918
8919            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8920
8921            if (!matrixIsIdentity) {
8922                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8923                    // A change in dimension means an auto-centered pivot point changes, too
8924                    mTransformationInfo.mMatrixDirty = true;
8925                }
8926                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8927                invalidate(true);
8928            }
8929            mBackgroundSizeChanged = true;
8930            invalidateParentIfNeeded();
8931        }
8932    }
8933
8934    /**
8935     * The visual x position of this view, in pixels. This is equivalent to the
8936     * {@link #setTranslationX(float) translationX} property plus the current
8937     * {@link #getLeft() left} property.
8938     *
8939     * @return The visual x position of this view, in pixels.
8940     */
8941    @ViewDebug.ExportedProperty(category = "drawing")
8942    public float getX() {
8943        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8944    }
8945
8946    /**
8947     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8948     * {@link #setTranslationX(float) translationX} property to be the difference between
8949     * the x value passed in and the current {@link #getLeft() left} property.
8950     *
8951     * @param x The visual x position of this view, in pixels.
8952     */
8953    public void setX(float x) {
8954        setTranslationX(x - mLeft);
8955    }
8956
8957    /**
8958     * The visual y position of this view, in pixels. This is equivalent to the
8959     * {@link #setTranslationY(float) translationY} property plus the current
8960     * {@link #getTop() top} property.
8961     *
8962     * @return The visual y position of this view, in pixels.
8963     */
8964    @ViewDebug.ExportedProperty(category = "drawing")
8965    public float getY() {
8966        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8967    }
8968
8969    /**
8970     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8971     * {@link #setTranslationY(float) translationY} property to be the difference between
8972     * the y value passed in and the current {@link #getTop() top} property.
8973     *
8974     * @param y The visual y position of this view, in pixels.
8975     */
8976    public void setY(float y) {
8977        setTranslationY(y - mTop);
8978    }
8979
8980
8981    /**
8982     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8983     * This position is post-layout, in addition to wherever the object's
8984     * layout placed it.
8985     *
8986     * @return The horizontal position of this view relative to its left position, in pixels.
8987     */
8988    @ViewDebug.ExportedProperty(category = "drawing")
8989    public float getTranslationX() {
8990        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8991    }
8992
8993    /**
8994     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8995     * This effectively positions the object post-layout, in addition to wherever the object's
8996     * layout placed it.
8997     *
8998     * @param translationX The horizontal position of this view relative to its left position,
8999     * in pixels.
9000     *
9001     * @attr ref android.R.styleable#View_translationX
9002     */
9003    public void setTranslationX(float translationX) {
9004        ensureTransformationInfo();
9005        final TransformationInfo info = mTransformationInfo;
9006        if (info.mTranslationX != translationX) {
9007            // Double-invalidation is necessary to capture view's old and new areas
9008            invalidateViewProperty(true, false);
9009            info.mTranslationX = translationX;
9010            info.mMatrixDirty = true;
9011            invalidateViewProperty(false, true);
9012            if (mDisplayList != null) {
9013                mDisplayList.setTranslationX(translationX);
9014            }
9015        }
9016    }
9017
9018    /**
9019     * The horizontal location of this view relative to its {@link #getTop() top} position.
9020     * This position is post-layout, in addition to wherever the object's
9021     * layout placed it.
9022     *
9023     * @return The vertical position of this view relative to its top position,
9024     * in pixels.
9025     */
9026    @ViewDebug.ExportedProperty(category = "drawing")
9027    public float getTranslationY() {
9028        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9029    }
9030
9031    /**
9032     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9033     * This effectively positions the object post-layout, in addition to wherever the object's
9034     * layout placed it.
9035     *
9036     * @param translationY The vertical position of this view relative to its top position,
9037     * in pixels.
9038     *
9039     * @attr ref android.R.styleable#View_translationY
9040     */
9041    public void setTranslationY(float translationY) {
9042        ensureTransformationInfo();
9043        final TransformationInfo info = mTransformationInfo;
9044        if (info.mTranslationY != translationY) {
9045            invalidateViewProperty(true, false);
9046            info.mTranslationY = translationY;
9047            info.mMatrixDirty = true;
9048            invalidateViewProperty(false, true);
9049            if (mDisplayList != null) {
9050                mDisplayList.setTranslationY(translationY);
9051            }
9052        }
9053    }
9054
9055    /**
9056     * Hit rectangle in parent's coordinates
9057     *
9058     * @param outRect The hit rectangle of the view.
9059     */
9060    public void getHitRect(Rect outRect) {
9061        updateMatrix();
9062        final TransformationInfo info = mTransformationInfo;
9063        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9064            outRect.set(mLeft, mTop, mRight, mBottom);
9065        } else {
9066            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9067            tmpRect.set(-info.mPivotX, -info.mPivotY,
9068                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9069            info.mMatrix.mapRect(tmpRect);
9070            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9071                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9072        }
9073    }
9074
9075    /**
9076     * Determines whether the given point, in local coordinates is inside the view.
9077     */
9078    /*package*/ final boolean pointInView(float localX, float localY) {
9079        return localX >= 0 && localX < (mRight - mLeft)
9080                && localY >= 0 && localY < (mBottom - mTop);
9081    }
9082
9083    /**
9084     * Utility method to determine whether the given point, in local coordinates,
9085     * is inside the view, where the area of the view is expanded by the slop factor.
9086     * This method is called while processing touch-move events to determine if the event
9087     * is still within the view.
9088     */
9089    private boolean pointInView(float localX, float localY, float slop) {
9090        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9091                localY < ((mBottom - mTop) + slop);
9092    }
9093
9094    /**
9095     * When a view has focus and the user navigates away from it, the next view is searched for
9096     * starting from the rectangle filled in by this method.
9097     *
9098     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9099     * of the view.  However, if your view maintains some idea of internal selection,
9100     * such as a cursor, or a selected row or column, you should override this method and
9101     * fill in a more specific rectangle.
9102     *
9103     * @param r The rectangle to fill in, in this view's coordinates.
9104     */
9105    public void getFocusedRect(Rect r) {
9106        getDrawingRect(r);
9107    }
9108
9109    /**
9110     * If some part of this view is not clipped by any of its parents, then
9111     * return that area in r in global (root) coordinates. To convert r to local
9112     * coordinates (without taking possible View rotations into account), offset
9113     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9114     * If the view is completely clipped or translated out, return false.
9115     *
9116     * @param r If true is returned, r holds the global coordinates of the
9117     *        visible portion of this view.
9118     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9119     *        between this view and its root. globalOffet may be null.
9120     * @return true if r is non-empty (i.e. part of the view is visible at the
9121     *         root level.
9122     */
9123    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9124        int width = mRight - mLeft;
9125        int height = mBottom - mTop;
9126        if (width > 0 && height > 0) {
9127            r.set(0, 0, width, height);
9128            if (globalOffset != null) {
9129                globalOffset.set(-mScrollX, -mScrollY);
9130            }
9131            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9132        }
9133        return false;
9134    }
9135
9136    public final boolean getGlobalVisibleRect(Rect r) {
9137        return getGlobalVisibleRect(r, null);
9138    }
9139
9140    public final boolean getLocalVisibleRect(Rect r) {
9141        Point offset = new Point();
9142        if (getGlobalVisibleRect(r, offset)) {
9143            r.offset(-offset.x, -offset.y); // make r local
9144            return true;
9145        }
9146        return false;
9147    }
9148
9149    /**
9150     * Offset this view's vertical location by the specified number of pixels.
9151     *
9152     * @param offset the number of pixels to offset the view by
9153     */
9154    public void offsetTopAndBottom(int offset) {
9155        if (offset != 0) {
9156            updateMatrix();
9157            final boolean matrixIsIdentity = mTransformationInfo == null
9158                    || mTransformationInfo.mMatrixIsIdentity;
9159            if (matrixIsIdentity) {
9160                if (mDisplayList != null) {
9161                    invalidateViewProperty(false, false);
9162                } else {
9163                    final ViewParent p = mParent;
9164                    if (p != null && mAttachInfo != null) {
9165                        final Rect r = mAttachInfo.mTmpInvalRect;
9166                        int minTop;
9167                        int maxBottom;
9168                        int yLoc;
9169                        if (offset < 0) {
9170                            minTop = mTop + offset;
9171                            maxBottom = mBottom;
9172                            yLoc = offset;
9173                        } else {
9174                            minTop = mTop;
9175                            maxBottom = mBottom + offset;
9176                            yLoc = 0;
9177                        }
9178                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9179                        p.invalidateChild(this, r);
9180                    }
9181                }
9182            } else {
9183                invalidateViewProperty(false, false);
9184            }
9185
9186            mTop += offset;
9187            mBottom += offset;
9188            if (mDisplayList != null) {
9189                mDisplayList.offsetTopBottom(offset);
9190                invalidateViewProperty(false, false);
9191            } else {
9192                if (!matrixIsIdentity) {
9193                    invalidateViewProperty(false, true);
9194                }
9195                invalidateParentIfNeeded();
9196            }
9197        }
9198    }
9199
9200    /**
9201     * Offset this view's horizontal location by the specified amount of pixels.
9202     *
9203     * @param offset the numer of pixels to offset the view by
9204     */
9205    public void offsetLeftAndRight(int offset) {
9206        if (offset != 0) {
9207            updateMatrix();
9208            final boolean matrixIsIdentity = mTransformationInfo == null
9209                    || mTransformationInfo.mMatrixIsIdentity;
9210            if (matrixIsIdentity) {
9211                if (mDisplayList != null) {
9212                    invalidateViewProperty(false, false);
9213                } else {
9214                    final ViewParent p = mParent;
9215                    if (p != null && mAttachInfo != null) {
9216                        final Rect r = mAttachInfo.mTmpInvalRect;
9217                        int minLeft;
9218                        int maxRight;
9219                        if (offset < 0) {
9220                            minLeft = mLeft + offset;
9221                            maxRight = mRight;
9222                        } else {
9223                            minLeft = mLeft;
9224                            maxRight = mRight + offset;
9225                        }
9226                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9227                        p.invalidateChild(this, r);
9228                    }
9229                }
9230            } else {
9231                invalidateViewProperty(false, false);
9232            }
9233
9234            mLeft += offset;
9235            mRight += offset;
9236            if (mDisplayList != null) {
9237                mDisplayList.offsetLeftRight(offset);
9238                invalidateViewProperty(false, false);
9239            } else {
9240                if (!matrixIsIdentity) {
9241                    invalidateViewProperty(false, true);
9242                }
9243                invalidateParentIfNeeded();
9244            }
9245        }
9246    }
9247
9248    /**
9249     * Get the LayoutParams associated with this view. All views should have
9250     * layout parameters. These supply parameters to the <i>parent</i> of this
9251     * view specifying how it should be arranged. There are many subclasses of
9252     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9253     * of ViewGroup that are responsible for arranging their children.
9254     *
9255     * This method may return null if this View is not attached to a parent
9256     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9257     * was not invoked successfully. When a View is attached to a parent
9258     * ViewGroup, this method must not return null.
9259     *
9260     * @return The LayoutParams associated with this view, or null if no
9261     *         parameters have been set yet
9262     */
9263    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9264    public ViewGroup.LayoutParams getLayoutParams() {
9265        return mLayoutParams;
9266    }
9267
9268    /**
9269     * Set the layout parameters associated with this view. These supply
9270     * parameters to the <i>parent</i> of this view specifying how it should be
9271     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9272     * correspond to the different subclasses of ViewGroup that are responsible
9273     * for arranging their children.
9274     *
9275     * @param params The layout parameters for this view, cannot be null
9276     */
9277    public void setLayoutParams(ViewGroup.LayoutParams params) {
9278        if (params == null) {
9279            throw new NullPointerException("Layout parameters cannot be null");
9280        }
9281        mLayoutParams = params;
9282        if (mParent instanceof ViewGroup) {
9283            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9284        }
9285        requestLayout();
9286    }
9287
9288    /**
9289     * Set the scrolled position of your view. This will cause a call to
9290     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9291     * invalidated.
9292     * @param x the x position to scroll to
9293     * @param y the y position to scroll to
9294     */
9295    public void scrollTo(int x, int y) {
9296        if (mScrollX != x || mScrollY != y) {
9297            int oldX = mScrollX;
9298            int oldY = mScrollY;
9299            mScrollX = x;
9300            mScrollY = y;
9301            invalidateParentCaches();
9302            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9303            if (!awakenScrollBars()) {
9304                postInvalidateOnAnimation();
9305            }
9306        }
9307    }
9308
9309    /**
9310     * Move the scrolled position of your view. This will cause a call to
9311     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9312     * invalidated.
9313     * @param x the amount of pixels to scroll by horizontally
9314     * @param y the amount of pixels to scroll by vertically
9315     */
9316    public void scrollBy(int x, int y) {
9317        scrollTo(mScrollX + x, mScrollY + y);
9318    }
9319
9320    /**
9321     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9322     * animation to fade the scrollbars out after a default delay. If a subclass
9323     * provides animated scrolling, the start delay should equal the duration
9324     * of the scrolling animation.</p>
9325     *
9326     * <p>The animation starts only if at least one of the scrollbars is
9327     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9328     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9329     * this method returns true, and false otherwise. If the animation is
9330     * started, this method calls {@link #invalidate()}; in that case the
9331     * caller should not call {@link #invalidate()}.</p>
9332     *
9333     * <p>This method should be invoked every time a subclass directly updates
9334     * the scroll parameters.</p>
9335     *
9336     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9337     * and {@link #scrollTo(int, int)}.</p>
9338     *
9339     * @return true if the animation is played, false otherwise
9340     *
9341     * @see #awakenScrollBars(int)
9342     * @see #scrollBy(int, int)
9343     * @see #scrollTo(int, int)
9344     * @see #isHorizontalScrollBarEnabled()
9345     * @see #isVerticalScrollBarEnabled()
9346     * @see #setHorizontalScrollBarEnabled(boolean)
9347     * @see #setVerticalScrollBarEnabled(boolean)
9348     */
9349    protected boolean awakenScrollBars() {
9350        return mScrollCache != null &&
9351                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9352    }
9353
9354    /**
9355     * Trigger the scrollbars to draw.
9356     * This method differs from awakenScrollBars() only in its default duration.
9357     * initialAwakenScrollBars() will show the scroll bars for longer than
9358     * usual to give the user more of a chance to notice them.
9359     *
9360     * @return true if the animation is played, false otherwise.
9361     */
9362    private boolean initialAwakenScrollBars() {
9363        return mScrollCache != null &&
9364                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9365    }
9366
9367    /**
9368     * <p>
9369     * Trigger the scrollbars to draw. When invoked this method starts an
9370     * animation to fade the scrollbars out after a fixed delay. If a subclass
9371     * provides animated scrolling, the start delay should equal the duration of
9372     * the scrolling animation.
9373     * </p>
9374     *
9375     * <p>
9376     * The animation starts only if at least one of the scrollbars is enabled,
9377     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9378     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9379     * this method returns true, and false otherwise. If the animation is
9380     * started, this method calls {@link #invalidate()}; in that case the caller
9381     * should not call {@link #invalidate()}.
9382     * </p>
9383     *
9384     * <p>
9385     * This method should be invoked everytime a subclass directly updates the
9386     * scroll parameters.
9387     * </p>
9388     *
9389     * @param startDelay the delay, in milliseconds, after which the animation
9390     *        should start; when the delay is 0, the animation starts
9391     *        immediately
9392     * @return true if the animation is played, false otherwise
9393     *
9394     * @see #scrollBy(int, int)
9395     * @see #scrollTo(int, int)
9396     * @see #isHorizontalScrollBarEnabled()
9397     * @see #isVerticalScrollBarEnabled()
9398     * @see #setHorizontalScrollBarEnabled(boolean)
9399     * @see #setVerticalScrollBarEnabled(boolean)
9400     */
9401    protected boolean awakenScrollBars(int startDelay) {
9402        return awakenScrollBars(startDelay, true);
9403    }
9404
9405    /**
9406     * <p>
9407     * Trigger the scrollbars to draw. When invoked this method starts an
9408     * animation to fade the scrollbars out after a fixed delay. If a subclass
9409     * provides animated scrolling, the start delay should equal the duration of
9410     * the scrolling animation.
9411     * </p>
9412     *
9413     * <p>
9414     * The animation starts only if at least one of the scrollbars is enabled,
9415     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9416     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9417     * this method returns true, and false otherwise. If the animation is
9418     * started, this method calls {@link #invalidate()} if the invalidate parameter
9419     * is set to true; in that case the caller
9420     * should not call {@link #invalidate()}.
9421     * </p>
9422     *
9423     * <p>
9424     * This method should be invoked everytime a subclass directly updates the
9425     * scroll parameters.
9426     * </p>
9427     *
9428     * @param startDelay the delay, in milliseconds, after which the animation
9429     *        should start; when the delay is 0, the animation starts
9430     *        immediately
9431     *
9432     * @param invalidate Wheter this method should call invalidate
9433     *
9434     * @return true if the animation is played, false otherwise
9435     *
9436     * @see #scrollBy(int, int)
9437     * @see #scrollTo(int, int)
9438     * @see #isHorizontalScrollBarEnabled()
9439     * @see #isVerticalScrollBarEnabled()
9440     * @see #setHorizontalScrollBarEnabled(boolean)
9441     * @see #setVerticalScrollBarEnabled(boolean)
9442     */
9443    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9444        final ScrollabilityCache scrollCache = mScrollCache;
9445
9446        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9447            return false;
9448        }
9449
9450        if (scrollCache.scrollBar == null) {
9451            scrollCache.scrollBar = new ScrollBarDrawable();
9452        }
9453
9454        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9455
9456            if (invalidate) {
9457                // Invalidate to show the scrollbars
9458                postInvalidateOnAnimation();
9459            }
9460
9461            if (scrollCache.state == ScrollabilityCache.OFF) {
9462                // FIXME: this is copied from WindowManagerService.
9463                // We should get this value from the system when it
9464                // is possible to do so.
9465                final int KEY_REPEAT_FIRST_DELAY = 750;
9466                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9467            }
9468
9469            // Tell mScrollCache when we should start fading. This may
9470            // extend the fade start time if one was already scheduled
9471            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9472            scrollCache.fadeStartTime = fadeStartTime;
9473            scrollCache.state = ScrollabilityCache.ON;
9474
9475            // Schedule our fader to run, unscheduling any old ones first
9476            if (mAttachInfo != null) {
9477                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9478                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9479            }
9480
9481            return true;
9482        }
9483
9484        return false;
9485    }
9486
9487    /**
9488     * Do not invalidate views which are not visible and which are not running an animation. They
9489     * will not get drawn and they should not set dirty flags as if they will be drawn
9490     */
9491    private boolean skipInvalidate() {
9492        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9493                (!(mParent instanceof ViewGroup) ||
9494                        !((ViewGroup) mParent).isViewTransitioning(this));
9495    }
9496    /**
9497     * Mark the area defined by dirty as needing to be drawn. If the view is
9498     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9499     * in the future. This must be called from a UI thread. To call from a non-UI
9500     * thread, call {@link #postInvalidate()}.
9501     *
9502     * WARNING: This method is destructive to dirty.
9503     * @param dirty the rectangle representing the bounds of the dirty region
9504     */
9505    public void invalidate(Rect dirty) {
9506        if (ViewDebug.TRACE_HIERARCHY) {
9507            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9508        }
9509
9510        if (skipInvalidate()) {
9511            return;
9512        }
9513        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9514                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9515                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9516            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9517            mPrivateFlags |= INVALIDATED;
9518            mPrivateFlags |= DIRTY;
9519            final ViewParent p = mParent;
9520            final AttachInfo ai = mAttachInfo;
9521            //noinspection PointlessBooleanExpression,ConstantConditions
9522            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9523                if (p != null && ai != null && ai.mHardwareAccelerated) {
9524                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9525                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9526                    p.invalidateChild(this, null);
9527                    return;
9528                }
9529            }
9530            if (p != null && ai != null) {
9531                final int scrollX = mScrollX;
9532                final int scrollY = mScrollY;
9533                final Rect r = ai.mTmpInvalRect;
9534                r.set(dirty.left - scrollX, dirty.top - scrollY,
9535                        dirty.right - scrollX, dirty.bottom - scrollY);
9536                mParent.invalidateChild(this, r);
9537            }
9538        }
9539    }
9540
9541    /**
9542     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9543     * The coordinates of the dirty rect are relative to the view.
9544     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9545     * will be called at some point in the future. This must be called from
9546     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9547     * @param l the left position of the dirty region
9548     * @param t the top position of the dirty region
9549     * @param r the right position of the dirty region
9550     * @param b the bottom position of the dirty region
9551     */
9552    public void invalidate(int l, int t, int r, int b) {
9553        if (ViewDebug.TRACE_HIERARCHY) {
9554            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9555        }
9556
9557        if (skipInvalidate()) {
9558            return;
9559        }
9560        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9561                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9562                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9563            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9564            mPrivateFlags |= INVALIDATED;
9565            mPrivateFlags |= DIRTY;
9566            final ViewParent p = mParent;
9567            final AttachInfo ai = mAttachInfo;
9568            //noinspection PointlessBooleanExpression,ConstantConditions
9569            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9570                if (p != null && ai != null && ai.mHardwareAccelerated) {
9571                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9572                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9573                    p.invalidateChild(this, null);
9574                    return;
9575                }
9576            }
9577            if (p != null && ai != null && l < r && t < b) {
9578                final int scrollX = mScrollX;
9579                final int scrollY = mScrollY;
9580                final Rect tmpr = ai.mTmpInvalRect;
9581                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9582                p.invalidateChild(this, tmpr);
9583            }
9584        }
9585    }
9586
9587    /**
9588     * Invalidate the whole view. If the view is visible,
9589     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9590     * the future. This must be called from a UI thread. To call from a non-UI thread,
9591     * call {@link #postInvalidate()}.
9592     */
9593    public void invalidate() {
9594        invalidate(true);
9595    }
9596
9597    /**
9598     * This is where the invalidate() work actually happens. A full invalidate()
9599     * causes the drawing cache to be invalidated, but this function can be called with
9600     * invalidateCache set to false to skip that invalidation step for cases that do not
9601     * need it (for example, a component that remains at the same dimensions with the same
9602     * content).
9603     *
9604     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9605     * well. This is usually true for a full invalidate, but may be set to false if the
9606     * View's contents or dimensions have not changed.
9607     */
9608    void invalidate(boolean invalidateCache) {
9609        if (ViewDebug.TRACE_HIERARCHY) {
9610            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9611        }
9612
9613        if (skipInvalidate()) {
9614            return;
9615        }
9616        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9617                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9618                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9619            mLastIsOpaque = isOpaque();
9620            mPrivateFlags &= ~DRAWN;
9621            mPrivateFlags |= DIRTY;
9622            if (invalidateCache) {
9623                mPrivateFlags |= INVALIDATED;
9624                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9625            }
9626            final AttachInfo ai = mAttachInfo;
9627            final ViewParent p = mParent;
9628            //noinspection PointlessBooleanExpression,ConstantConditions
9629            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9630                if (p != null && ai != null && ai.mHardwareAccelerated) {
9631                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9632                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9633                    p.invalidateChild(this, null);
9634                    return;
9635                }
9636            }
9637
9638            if (p != null && ai != null) {
9639                final Rect r = ai.mTmpInvalRect;
9640                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9641                // Don't call invalidate -- we don't want to internally scroll
9642                // our own bounds
9643                p.invalidateChild(this, r);
9644            }
9645        }
9646    }
9647
9648    /**
9649     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9650     * set any flags or handle all of the cases handled by the default invalidation methods.
9651     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9652     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9653     * walk up the hierarchy, transforming the dirty rect as necessary.
9654     *
9655     * The method also handles normal invalidation logic if display list properties are not
9656     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9657     * backup approach, to handle these cases used in the various property-setting methods.
9658     *
9659     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9660     * are not being used in this view
9661     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9662     * list properties are not being used in this view
9663     */
9664    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9665        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9666            if (invalidateParent) {
9667                invalidateParentCaches();
9668            }
9669            if (forceRedraw) {
9670                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9671            }
9672            invalidate(false);
9673        } else {
9674            final AttachInfo ai = mAttachInfo;
9675            final ViewParent p = mParent;
9676            if (p != null && ai != null) {
9677                final Rect r = ai.mTmpInvalRect;
9678                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9679                if (mParent instanceof ViewGroup) {
9680                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9681                } else {
9682                    mParent.invalidateChild(this, r);
9683                }
9684            }
9685        }
9686    }
9687
9688    /**
9689     * Utility method to transform a given Rect by the current matrix of this view.
9690     */
9691    void transformRect(final Rect rect) {
9692        if (!getMatrix().isIdentity()) {
9693            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9694            boundingRect.set(rect);
9695            getMatrix().mapRect(boundingRect);
9696            rect.set((int) (boundingRect.left - 0.5f),
9697                    (int) (boundingRect.top - 0.5f),
9698                    (int) (boundingRect.right + 0.5f),
9699                    (int) (boundingRect.bottom + 0.5f));
9700        }
9701    }
9702
9703    /**
9704     * Used to indicate that the parent of this view should clear its caches. This functionality
9705     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9706     * which is necessary when various parent-managed properties of the view change, such as
9707     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9708     * clears the parent caches and does not causes an invalidate event.
9709     *
9710     * @hide
9711     */
9712    protected void invalidateParentCaches() {
9713        if (mParent instanceof View) {
9714            ((View) mParent).mPrivateFlags |= INVALIDATED;
9715        }
9716    }
9717
9718    /**
9719     * Used to indicate that the parent of this view should be invalidated. This functionality
9720     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9721     * which is necessary when various parent-managed properties of the view change, such as
9722     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9723     * an invalidation event to the parent.
9724     *
9725     * @hide
9726     */
9727    protected void invalidateParentIfNeeded() {
9728        if (isHardwareAccelerated() && mParent instanceof View) {
9729            ((View) mParent).invalidate(true);
9730        }
9731    }
9732
9733    /**
9734     * Indicates whether this View is opaque. An opaque View guarantees that it will
9735     * draw all the pixels overlapping its bounds using a fully opaque color.
9736     *
9737     * Subclasses of View should override this method whenever possible to indicate
9738     * whether an instance is opaque. Opaque Views are treated in a special way by
9739     * the View hierarchy, possibly allowing it to perform optimizations during
9740     * invalidate/draw passes.
9741     *
9742     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9743     */
9744    @ViewDebug.ExportedProperty(category = "drawing")
9745    public boolean isOpaque() {
9746        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9747                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9748                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9749    }
9750
9751    /**
9752     * @hide
9753     */
9754    protected void computeOpaqueFlags() {
9755        // Opaque if:
9756        //   - Has a background
9757        //   - Background is opaque
9758        //   - Doesn't have scrollbars or scrollbars are inside overlay
9759
9760        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
9761            mPrivateFlags |= OPAQUE_BACKGROUND;
9762        } else {
9763            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9764        }
9765
9766        final int flags = mViewFlags;
9767        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9768                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9769            mPrivateFlags |= OPAQUE_SCROLLBARS;
9770        } else {
9771            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9772        }
9773    }
9774
9775    /**
9776     * @hide
9777     */
9778    protected boolean hasOpaqueScrollbars() {
9779        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9780    }
9781
9782    /**
9783     * @return A handler associated with the thread running the View. This
9784     * handler can be used to pump events in the UI events queue.
9785     */
9786    public Handler getHandler() {
9787        if (mAttachInfo != null) {
9788            return mAttachInfo.mHandler;
9789        }
9790        return null;
9791    }
9792
9793    /**
9794     * Gets the view root associated with the View.
9795     * @return The view root, or null if none.
9796     * @hide
9797     */
9798    public ViewRootImpl getViewRootImpl() {
9799        if (mAttachInfo != null) {
9800            return mAttachInfo.mViewRootImpl;
9801        }
9802        return null;
9803    }
9804
9805    /**
9806     * <p>Causes the Runnable to be added to the message queue.
9807     * The runnable will be run on the user interface thread.</p>
9808     *
9809     * <p>This method can be invoked from outside of the UI thread
9810     * only when this View is attached to a window.</p>
9811     *
9812     * @param action The Runnable that will be executed.
9813     *
9814     * @return Returns true if the Runnable was successfully placed in to the
9815     *         message queue.  Returns false on failure, usually because the
9816     *         looper processing the message queue is exiting.
9817     *
9818     * @see #postDelayed
9819     * @see #removeCallbacks
9820     */
9821    public boolean post(Runnable action) {
9822        final AttachInfo attachInfo = mAttachInfo;
9823        if (attachInfo != null) {
9824            return attachInfo.mHandler.post(action);
9825        }
9826        // Assume that post will succeed later
9827        ViewRootImpl.getRunQueue().post(action);
9828        return true;
9829    }
9830
9831    /**
9832     * <p>Causes the Runnable to be added to the message queue, to be run
9833     * after the specified amount of time elapses.
9834     * The runnable will be run on the user interface thread.</p>
9835     *
9836     * <p>This method can be invoked from outside of the UI thread
9837     * only when this View is attached to a window.</p>
9838     *
9839     * @param action The Runnable that will be executed.
9840     * @param delayMillis The delay (in milliseconds) until the Runnable
9841     *        will be executed.
9842     *
9843     * @return true if the Runnable was successfully placed in to the
9844     *         message queue.  Returns false on failure, usually because the
9845     *         looper processing the message queue is exiting.  Note that a
9846     *         result of true does not mean the Runnable will be processed --
9847     *         if the looper is quit before the delivery time of the message
9848     *         occurs then the message will be dropped.
9849     *
9850     * @see #post
9851     * @see #removeCallbacks
9852     */
9853    public boolean postDelayed(Runnable action, long delayMillis) {
9854        final AttachInfo attachInfo = mAttachInfo;
9855        if (attachInfo != null) {
9856            return attachInfo.mHandler.postDelayed(action, delayMillis);
9857        }
9858        // Assume that post will succeed later
9859        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9860        return true;
9861    }
9862
9863    /**
9864     * <p>Causes the Runnable to execute on the next animation time step.
9865     * The runnable will be run on the user interface thread.</p>
9866     *
9867     * <p>This method can be invoked from outside of the UI thread
9868     * only when this View is attached to a window.</p>
9869     *
9870     * @param action The Runnable that will be executed.
9871     *
9872     * @see #postOnAnimationDelayed
9873     * @see #removeCallbacks
9874     */
9875    public void postOnAnimation(Runnable action) {
9876        final AttachInfo attachInfo = mAttachInfo;
9877        if (attachInfo != null) {
9878            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9879                    Choreographer.CALLBACK_ANIMATION, action, null);
9880        } else {
9881            // Assume that post will succeed later
9882            ViewRootImpl.getRunQueue().post(action);
9883        }
9884    }
9885
9886    /**
9887     * <p>Causes the Runnable to execute on the next animation time step,
9888     * after the specified amount of time elapses.
9889     * The runnable will be run on the user interface thread.</p>
9890     *
9891     * <p>This method can be invoked from outside of the UI thread
9892     * only when this View is attached to a window.</p>
9893     *
9894     * @param action The Runnable that will be executed.
9895     * @param delayMillis The delay (in milliseconds) until the Runnable
9896     *        will be executed.
9897     *
9898     * @see #postOnAnimation
9899     * @see #removeCallbacks
9900     */
9901    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9902        final AttachInfo attachInfo = mAttachInfo;
9903        if (attachInfo != null) {
9904            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9905                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9906        } else {
9907            // Assume that post will succeed later
9908            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9909        }
9910    }
9911
9912    /**
9913     * <p>Removes the specified Runnable from the message queue.</p>
9914     *
9915     * <p>This method can be invoked from outside of the UI thread
9916     * only when this View is attached to a window.</p>
9917     *
9918     * @param action The Runnable to remove from the message handling queue
9919     *
9920     * @return true if this view could ask the Handler to remove the Runnable,
9921     *         false otherwise. When the returned value is true, the Runnable
9922     *         may or may not have been actually removed from the message queue
9923     *         (for instance, if the Runnable was not in the queue already.)
9924     *
9925     * @see #post
9926     * @see #postDelayed
9927     * @see #postOnAnimation
9928     * @see #postOnAnimationDelayed
9929     */
9930    public boolean removeCallbacks(Runnable action) {
9931        if (action != null) {
9932            final AttachInfo attachInfo = mAttachInfo;
9933            if (attachInfo != null) {
9934                attachInfo.mHandler.removeCallbacks(action);
9935                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9936                        Choreographer.CALLBACK_ANIMATION, action, null);
9937            } else {
9938                // Assume that post will succeed later
9939                ViewRootImpl.getRunQueue().removeCallbacks(action);
9940            }
9941        }
9942        return true;
9943    }
9944
9945    /**
9946     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9947     * Use this to invalidate the View from a non-UI thread.</p>
9948     *
9949     * <p>This method can be invoked from outside of the UI thread
9950     * only when this View is attached to a window.</p>
9951     *
9952     * @see #invalidate()
9953     * @see #postInvalidateDelayed(long)
9954     */
9955    public void postInvalidate() {
9956        postInvalidateDelayed(0);
9957    }
9958
9959    /**
9960     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9961     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9962     *
9963     * <p>This method can be invoked from outside of the UI thread
9964     * only when this View is attached to a window.</p>
9965     *
9966     * @param left The left coordinate of the rectangle to invalidate.
9967     * @param top The top coordinate of the rectangle to invalidate.
9968     * @param right The right coordinate of the rectangle to invalidate.
9969     * @param bottom The bottom coordinate of the rectangle to invalidate.
9970     *
9971     * @see #invalidate(int, int, int, int)
9972     * @see #invalidate(Rect)
9973     * @see #postInvalidateDelayed(long, int, int, int, int)
9974     */
9975    public void postInvalidate(int left, int top, int right, int bottom) {
9976        postInvalidateDelayed(0, left, top, right, bottom);
9977    }
9978
9979    /**
9980     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9981     * loop. Waits for the specified amount of time.</p>
9982     *
9983     * <p>This method can be invoked from outside of the UI thread
9984     * only when this View is attached to a window.</p>
9985     *
9986     * @param delayMilliseconds the duration in milliseconds to delay the
9987     *         invalidation by
9988     *
9989     * @see #invalidate()
9990     * @see #postInvalidate()
9991     */
9992    public void postInvalidateDelayed(long delayMilliseconds) {
9993        // We try only with the AttachInfo because there's no point in invalidating
9994        // if we are not attached to our window
9995        final AttachInfo attachInfo = mAttachInfo;
9996        if (attachInfo != null) {
9997            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9998        }
9999    }
10000
10001    /**
10002     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10003     * through the event loop. Waits for the specified amount of time.</p>
10004     *
10005     * <p>This method can be invoked from outside of the UI thread
10006     * only when this View is attached to a window.</p>
10007     *
10008     * @param delayMilliseconds the duration in milliseconds to delay the
10009     *         invalidation by
10010     * @param left The left coordinate of the rectangle to invalidate.
10011     * @param top The top coordinate of the rectangle to invalidate.
10012     * @param right The right coordinate of the rectangle to invalidate.
10013     * @param bottom The bottom coordinate of the rectangle to invalidate.
10014     *
10015     * @see #invalidate(int, int, int, int)
10016     * @see #invalidate(Rect)
10017     * @see #postInvalidate(int, int, int, int)
10018     */
10019    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10020            int right, int bottom) {
10021
10022        // We try only with the AttachInfo because there's no point in invalidating
10023        // if we are not attached to our window
10024        final AttachInfo attachInfo = mAttachInfo;
10025        if (attachInfo != null) {
10026            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10027            info.target = this;
10028            info.left = left;
10029            info.top = top;
10030            info.right = right;
10031            info.bottom = bottom;
10032
10033            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10034        }
10035    }
10036
10037    /**
10038     * <p>Cause an invalidate to happen on the next animation time step, typically the
10039     * next display frame.</p>
10040     *
10041     * <p>This method can be invoked from outside of the UI thread
10042     * only when this View is attached to a window.</p>
10043     *
10044     * @see #invalidate()
10045     */
10046    public void postInvalidateOnAnimation() {
10047        // We try only with the AttachInfo because there's no point in invalidating
10048        // if we are not attached to our window
10049        final AttachInfo attachInfo = mAttachInfo;
10050        if (attachInfo != null) {
10051            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10052        }
10053    }
10054
10055    /**
10056     * <p>Cause an invalidate of the specified area to happen on the next animation
10057     * time step, typically the next display frame.</p>
10058     *
10059     * <p>This method can be invoked from outside of the UI thread
10060     * only when this View is attached to a window.</p>
10061     *
10062     * @param left The left coordinate of the rectangle to invalidate.
10063     * @param top The top coordinate of the rectangle to invalidate.
10064     * @param right The right coordinate of the rectangle to invalidate.
10065     * @param bottom The bottom coordinate of the rectangle to invalidate.
10066     *
10067     * @see #invalidate(int, int, int, int)
10068     * @see #invalidate(Rect)
10069     */
10070    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10071        // We try only with the AttachInfo because there's no point in invalidating
10072        // if we are not attached to our window
10073        final AttachInfo attachInfo = mAttachInfo;
10074        if (attachInfo != null) {
10075            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10076            info.target = this;
10077            info.left = left;
10078            info.top = top;
10079            info.right = right;
10080            info.bottom = bottom;
10081
10082            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10083        }
10084    }
10085
10086    /**
10087     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10088     * This event is sent at most once every
10089     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10090     */
10091    private void postSendViewScrolledAccessibilityEventCallback() {
10092        if (mSendViewScrolledAccessibilityEvent == null) {
10093            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10094        }
10095        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10096            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10097            postDelayed(mSendViewScrolledAccessibilityEvent,
10098                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10099        }
10100    }
10101
10102    /**
10103     * Called by a parent to request that a child update its values for mScrollX
10104     * and mScrollY if necessary. This will typically be done if the child is
10105     * animating a scroll using a {@link android.widget.Scroller Scroller}
10106     * object.
10107     */
10108    public void computeScroll() {
10109    }
10110
10111    /**
10112     * <p>Indicate whether the horizontal edges are faded when the view is
10113     * scrolled horizontally.</p>
10114     *
10115     * @return true if the horizontal edges should are faded on scroll, false
10116     *         otherwise
10117     *
10118     * @see #setHorizontalFadingEdgeEnabled(boolean)
10119     *
10120     * @attr ref android.R.styleable#View_requiresFadingEdge
10121     */
10122    public boolean isHorizontalFadingEdgeEnabled() {
10123        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10124    }
10125
10126    /**
10127     * <p>Define whether the horizontal edges should be faded when this view
10128     * is scrolled horizontally.</p>
10129     *
10130     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10131     *                                    be faded when the view is scrolled
10132     *                                    horizontally
10133     *
10134     * @see #isHorizontalFadingEdgeEnabled()
10135     *
10136     * @attr ref android.R.styleable#View_requiresFadingEdge
10137     */
10138    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10139        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10140            if (horizontalFadingEdgeEnabled) {
10141                initScrollCache();
10142            }
10143
10144            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10145        }
10146    }
10147
10148    /**
10149     * <p>Indicate whether the vertical edges are faded when the view is
10150     * scrolled horizontally.</p>
10151     *
10152     * @return true if the vertical edges should are faded on scroll, false
10153     *         otherwise
10154     *
10155     * @see #setVerticalFadingEdgeEnabled(boolean)
10156     *
10157     * @attr ref android.R.styleable#View_requiresFadingEdge
10158     */
10159    public boolean isVerticalFadingEdgeEnabled() {
10160        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10161    }
10162
10163    /**
10164     * <p>Define whether the vertical edges should be faded when this view
10165     * is scrolled vertically.</p>
10166     *
10167     * @param verticalFadingEdgeEnabled true if the vertical edges should
10168     *                                  be faded when the view is scrolled
10169     *                                  vertically
10170     *
10171     * @see #isVerticalFadingEdgeEnabled()
10172     *
10173     * @attr ref android.R.styleable#View_requiresFadingEdge
10174     */
10175    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10176        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10177            if (verticalFadingEdgeEnabled) {
10178                initScrollCache();
10179            }
10180
10181            mViewFlags ^= FADING_EDGE_VERTICAL;
10182        }
10183    }
10184
10185    /**
10186     * Returns the strength, or intensity, of the top faded edge. The strength is
10187     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10188     * returns 0.0 or 1.0 but no value in between.
10189     *
10190     * Subclasses should override this method to provide a smoother fade transition
10191     * when scrolling occurs.
10192     *
10193     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10194     */
10195    protected float getTopFadingEdgeStrength() {
10196        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10197    }
10198
10199    /**
10200     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10201     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10202     * returns 0.0 or 1.0 but no value in between.
10203     *
10204     * Subclasses should override this method to provide a smoother fade transition
10205     * when scrolling occurs.
10206     *
10207     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10208     */
10209    protected float getBottomFadingEdgeStrength() {
10210        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10211                computeVerticalScrollRange() ? 1.0f : 0.0f;
10212    }
10213
10214    /**
10215     * Returns the strength, or intensity, of the left faded edge. The strength is
10216     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10217     * returns 0.0 or 1.0 but no value in between.
10218     *
10219     * Subclasses should override this method to provide a smoother fade transition
10220     * when scrolling occurs.
10221     *
10222     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10223     */
10224    protected float getLeftFadingEdgeStrength() {
10225        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10226    }
10227
10228    /**
10229     * Returns the strength, or intensity, of the right faded edge. The strength is
10230     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10231     * returns 0.0 or 1.0 but no value in between.
10232     *
10233     * Subclasses should override this method to provide a smoother fade transition
10234     * when scrolling occurs.
10235     *
10236     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10237     */
10238    protected float getRightFadingEdgeStrength() {
10239        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10240                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10241    }
10242
10243    /**
10244     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10245     * scrollbar is not drawn by default.</p>
10246     *
10247     * @return true if the horizontal scrollbar should be painted, false
10248     *         otherwise
10249     *
10250     * @see #setHorizontalScrollBarEnabled(boolean)
10251     */
10252    public boolean isHorizontalScrollBarEnabled() {
10253        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10254    }
10255
10256    /**
10257     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10258     * scrollbar is not drawn by default.</p>
10259     *
10260     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10261     *                                   be painted
10262     *
10263     * @see #isHorizontalScrollBarEnabled()
10264     */
10265    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10266        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10267            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10268            computeOpaqueFlags();
10269            resolvePadding();
10270        }
10271    }
10272
10273    /**
10274     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10275     * scrollbar is not drawn by default.</p>
10276     *
10277     * @return true if the vertical scrollbar should be painted, false
10278     *         otherwise
10279     *
10280     * @see #setVerticalScrollBarEnabled(boolean)
10281     */
10282    public boolean isVerticalScrollBarEnabled() {
10283        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10284    }
10285
10286    /**
10287     * <p>Define whether the vertical scrollbar should be drawn or not. The
10288     * scrollbar is not drawn by default.</p>
10289     *
10290     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10291     *                                 be painted
10292     *
10293     * @see #isVerticalScrollBarEnabled()
10294     */
10295    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10296        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10297            mViewFlags ^= SCROLLBARS_VERTICAL;
10298            computeOpaqueFlags();
10299            resolvePadding();
10300        }
10301    }
10302
10303    /**
10304     * @hide
10305     */
10306    protected void recomputePadding() {
10307        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10308    }
10309
10310    /**
10311     * Define whether scrollbars will fade when the view is not scrolling.
10312     *
10313     * @param fadeScrollbars wheter to enable fading
10314     *
10315     * @attr ref android.R.styleable#View_fadeScrollbars
10316     */
10317    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10318        initScrollCache();
10319        final ScrollabilityCache scrollabilityCache = mScrollCache;
10320        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10321        if (fadeScrollbars) {
10322            scrollabilityCache.state = ScrollabilityCache.OFF;
10323        } else {
10324            scrollabilityCache.state = ScrollabilityCache.ON;
10325        }
10326    }
10327
10328    /**
10329     *
10330     * Returns true if scrollbars will fade when this view is not scrolling
10331     *
10332     * @return true if scrollbar fading is enabled
10333     *
10334     * @attr ref android.R.styleable#View_fadeScrollbars
10335     */
10336    public boolean isScrollbarFadingEnabled() {
10337        return mScrollCache != null && mScrollCache.fadeScrollBars;
10338    }
10339
10340    /**
10341     *
10342     * Returns the delay before scrollbars fade.
10343     *
10344     * @return the delay before scrollbars fade
10345     *
10346     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10347     */
10348    public int getScrollBarDefaultDelayBeforeFade() {
10349        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10350                mScrollCache.scrollBarDefaultDelayBeforeFade;
10351    }
10352
10353    /**
10354     * Define the delay before scrollbars fade.
10355     *
10356     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10357     *
10358     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10359     */
10360    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10361        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10362    }
10363
10364    /**
10365     *
10366     * Returns the scrollbar fade duration.
10367     *
10368     * @return the scrollbar fade duration
10369     *
10370     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10371     */
10372    public int getScrollBarFadeDuration() {
10373        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10374                mScrollCache.scrollBarFadeDuration;
10375    }
10376
10377    /**
10378     * Define the scrollbar fade duration.
10379     *
10380     * @param scrollBarFadeDuration - the scrollbar fade duration
10381     *
10382     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10383     */
10384    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10385        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10386    }
10387
10388    /**
10389     *
10390     * Returns the scrollbar size.
10391     *
10392     * @return the scrollbar size
10393     *
10394     * @attr ref android.R.styleable#View_scrollbarSize
10395     */
10396    public int getScrollBarSize() {
10397        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10398                mScrollCache.scrollBarSize;
10399    }
10400
10401    /**
10402     * Define the scrollbar size.
10403     *
10404     * @param scrollBarSize - the scrollbar size
10405     *
10406     * @attr ref android.R.styleable#View_scrollbarSize
10407     */
10408    public void setScrollBarSize(int scrollBarSize) {
10409        getScrollCache().scrollBarSize = scrollBarSize;
10410    }
10411
10412    /**
10413     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10414     * inset. When inset, they add to the padding of the view. And the scrollbars
10415     * can be drawn inside the padding area or on the edge of the view. For example,
10416     * if a view has a background drawable and you want to draw the scrollbars
10417     * inside the padding specified by the drawable, you can use
10418     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10419     * appear at the edge of the view, ignoring the padding, then you can use
10420     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10421     * @param style the style of the scrollbars. Should be one of
10422     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10423     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10424     * @see #SCROLLBARS_INSIDE_OVERLAY
10425     * @see #SCROLLBARS_INSIDE_INSET
10426     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10427     * @see #SCROLLBARS_OUTSIDE_INSET
10428     *
10429     * @attr ref android.R.styleable#View_scrollbarStyle
10430     */
10431    public void setScrollBarStyle(int style) {
10432        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10433            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10434            computeOpaqueFlags();
10435            resolvePadding();
10436        }
10437    }
10438
10439    /**
10440     * <p>Returns the current scrollbar style.</p>
10441     * @return the current scrollbar style
10442     * @see #SCROLLBARS_INSIDE_OVERLAY
10443     * @see #SCROLLBARS_INSIDE_INSET
10444     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10445     * @see #SCROLLBARS_OUTSIDE_INSET
10446     *
10447     * @attr ref android.R.styleable#View_scrollbarStyle
10448     */
10449    @ViewDebug.ExportedProperty(mapping = {
10450            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10451            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10452            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10453            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10454    })
10455    public int getScrollBarStyle() {
10456        return mViewFlags & SCROLLBARS_STYLE_MASK;
10457    }
10458
10459    /**
10460     * <p>Compute the horizontal range that the horizontal scrollbar
10461     * represents.</p>
10462     *
10463     * <p>The range is expressed in arbitrary units that must be the same as the
10464     * units used by {@link #computeHorizontalScrollExtent()} and
10465     * {@link #computeHorizontalScrollOffset()}.</p>
10466     *
10467     * <p>The default range is the drawing width of this view.</p>
10468     *
10469     * @return the total horizontal range represented by the horizontal
10470     *         scrollbar
10471     *
10472     * @see #computeHorizontalScrollExtent()
10473     * @see #computeHorizontalScrollOffset()
10474     * @see android.widget.ScrollBarDrawable
10475     */
10476    protected int computeHorizontalScrollRange() {
10477        return getWidth();
10478    }
10479
10480    /**
10481     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10482     * within the horizontal range. This value is used to compute the position
10483     * of the thumb within the scrollbar's track.</p>
10484     *
10485     * <p>The range is expressed in arbitrary units that must be the same as the
10486     * units used by {@link #computeHorizontalScrollRange()} and
10487     * {@link #computeHorizontalScrollExtent()}.</p>
10488     *
10489     * <p>The default offset is the scroll offset of this view.</p>
10490     *
10491     * @return the horizontal offset of the scrollbar's thumb
10492     *
10493     * @see #computeHorizontalScrollRange()
10494     * @see #computeHorizontalScrollExtent()
10495     * @see android.widget.ScrollBarDrawable
10496     */
10497    protected int computeHorizontalScrollOffset() {
10498        return mScrollX;
10499    }
10500
10501    /**
10502     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10503     * within the horizontal range. This value is used to compute the length
10504     * of the thumb within the scrollbar's track.</p>
10505     *
10506     * <p>The range is expressed in arbitrary units that must be the same as the
10507     * units used by {@link #computeHorizontalScrollRange()} and
10508     * {@link #computeHorizontalScrollOffset()}.</p>
10509     *
10510     * <p>The default extent is the drawing width of this view.</p>
10511     *
10512     * @return the horizontal extent of the scrollbar's thumb
10513     *
10514     * @see #computeHorizontalScrollRange()
10515     * @see #computeHorizontalScrollOffset()
10516     * @see android.widget.ScrollBarDrawable
10517     */
10518    protected int computeHorizontalScrollExtent() {
10519        return getWidth();
10520    }
10521
10522    /**
10523     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10524     *
10525     * <p>The range is expressed in arbitrary units that must be the same as the
10526     * units used by {@link #computeVerticalScrollExtent()} and
10527     * {@link #computeVerticalScrollOffset()}.</p>
10528     *
10529     * @return the total vertical range represented by the vertical scrollbar
10530     *
10531     * <p>The default range is the drawing height of this view.</p>
10532     *
10533     * @see #computeVerticalScrollExtent()
10534     * @see #computeVerticalScrollOffset()
10535     * @see android.widget.ScrollBarDrawable
10536     */
10537    protected int computeVerticalScrollRange() {
10538        return getHeight();
10539    }
10540
10541    /**
10542     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10543     * within the horizontal range. This value is used to compute the position
10544     * of the thumb within the scrollbar's track.</p>
10545     *
10546     * <p>The range is expressed in arbitrary units that must be the same as the
10547     * units used by {@link #computeVerticalScrollRange()} and
10548     * {@link #computeVerticalScrollExtent()}.</p>
10549     *
10550     * <p>The default offset is the scroll offset of this view.</p>
10551     *
10552     * @return the vertical offset of the scrollbar's thumb
10553     *
10554     * @see #computeVerticalScrollRange()
10555     * @see #computeVerticalScrollExtent()
10556     * @see android.widget.ScrollBarDrawable
10557     */
10558    protected int computeVerticalScrollOffset() {
10559        return mScrollY;
10560    }
10561
10562    /**
10563     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10564     * within the vertical range. This value is used to compute the length
10565     * of the thumb within the scrollbar's track.</p>
10566     *
10567     * <p>The range is expressed in arbitrary units that must be the same as the
10568     * units used by {@link #computeVerticalScrollRange()} and
10569     * {@link #computeVerticalScrollOffset()}.</p>
10570     *
10571     * <p>The default extent is the drawing height of this view.</p>
10572     *
10573     * @return the vertical extent of the scrollbar's thumb
10574     *
10575     * @see #computeVerticalScrollRange()
10576     * @see #computeVerticalScrollOffset()
10577     * @see android.widget.ScrollBarDrawable
10578     */
10579    protected int computeVerticalScrollExtent() {
10580        return getHeight();
10581    }
10582
10583    /**
10584     * Check if this view can be scrolled horizontally in a certain direction.
10585     *
10586     * @param direction Negative to check scrolling left, positive to check scrolling right.
10587     * @return true if this view can be scrolled in the specified direction, false otherwise.
10588     */
10589    public boolean canScrollHorizontally(int direction) {
10590        final int offset = computeHorizontalScrollOffset();
10591        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10592        if (range == 0) return false;
10593        if (direction < 0) {
10594            return offset > 0;
10595        } else {
10596            return offset < range - 1;
10597        }
10598    }
10599
10600    /**
10601     * Check if this view can be scrolled vertically in a certain direction.
10602     *
10603     * @param direction Negative to check scrolling up, positive to check scrolling down.
10604     * @return true if this view can be scrolled in the specified direction, false otherwise.
10605     */
10606    public boolean canScrollVertically(int direction) {
10607        final int offset = computeVerticalScrollOffset();
10608        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10609        if (range == 0) return false;
10610        if (direction < 0) {
10611            return offset > 0;
10612        } else {
10613            return offset < range - 1;
10614        }
10615    }
10616
10617    /**
10618     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10619     * scrollbars are painted only if they have been awakened first.</p>
10620     *
10621     * @param canvas the canvas on which to draw the scrollbars
10622     *
10623     * @see #awakenScrollBars(int)
10624     */
10625    protected final void onDrawScrollBars(Canvas canvas) {
10626        // scrollbars are drawn only when the animation is running
10627        final ScrollabilityCache cache = mScrollCache;
10628        if (cache != null) {
10629
10630            int state = cache.state;
10631
10632            if (state == ScrollabilityCache.OFF) {
10633                return;
10634            }
10635
10636            boolean invalidate = false;
10637
10638            if (state == ScrollabilityCache.FADING) {
10639                // We're fading -- get our fade interpolation
10640                if (cache.interpolatorValues == null) {
10641                    cache.interpolatorValues = new float[1];
10642                }
10643
10644                float[] values = cache.interpolatorValues;
10645
10646                // Stops the animation if we're done
10647                if (cache.scrollBarInterpolator.timeToValues(values) ==
10648                        Interpolator.Result.FREEZE_END) {
10649                    cache.state = ScrollabilityCache.OFF;
10650                } else {
10651                    cache.scrollBar.setAlpha(Math.round(values[0]));
10652                }
10653
10654                // This will make the scroll bars inval themselves after
10655                // drawing. We only want this when we're fading so that
10656                // we prevent excessive redraws
10657                invalidate = true;
10658            } else {
10659                // We're just on -- but we may have been fading before so
10660                // reset alpha
10661                cache.scrollBar.setAlpha(255);
10662            }
10663
10664
10665            final int viewFlags = mViewFlags;
10666
10667            final boolean drawHorizontalScrollBar =
10668                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10669            final boolean drawVerticalScrollBar =
10670                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10671                && !isVerticalScrollBarHidden();
10672
10673            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10674                final int width = mRight - mLeft;
10675                final int height = mBottom - mTop;
10676
10677                final ScrollBarDrawable scrollBar = cache.scrollBar;
10678
10679                final int scrollX = mScrollX;
10680                final int scrollY = mScrollY;
10681                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10682
10683                int left, top, right, bottom;
10684
10685                if (drawHorizontalScrollBar) {
10686                    int size = scrollBar.getSize(false);
10687                    if (size <= 0) {
10688                        size = cache.scrollBarSize;
10689                    }
10690
10691                    scrollBar.setParameters(computeHorizontalScrollRange(),
10692                                            computeHorizontalScrollOffset(),
10693                                            computeHorizontalScrollExtent(), false);
10694                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10695                            getVerticalScrollbarWidth() : 0;
10696                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10697                    left = scrollX + (mPaddingLeft & inside);
10698                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10699                    bottom = top + size;
10700                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10701                    if (invalidate) {
10702                        invalidate(left, top, right, bottom);
10703                    }
10704                }
10705
10706                if (drawVerticalScrollBar) {
10707                    int size = scrollBar.getSize(true);
10708                    if (size <= 0) {
10709                        size = cache.scrollBarSize;
10710                    }
10711
10712                    scrollBar.setParameters(computeVerticalScrollRange(),
10713                                            computeVerticalScrollOffset(),
10714                                            computeVerticalScrollExtent(), true);
10715                    switch (mVerticalScrollbarPosition) {
10716                        default:
10717                        case SCROLLBAR_POSITION_DEFAULT:
10718                        case SCROLLBAR_POSITION_RIGHT:
10719                            left = scrollX + width - size - (mUserPaddingRight & inside);
10720                            break;
10721                        case SCROLLBAR_POSITION_LEFT:
10722                            left = scrollX + (mUserPaddingLeft & inside);
10723                            break;
10724                    }
10725                    top = scrollY + (mPaddingTop & inside);
10726                    right = left + size;
10727                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10728                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10729                    if (invalidate) {
10730                        invalidate(left, top, right, bottom);
10731                    }
10732                }
10733            }
10734        }
10735    }
10736
10737    /**
10738     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10739     * FastScroller is visible.
10740     * @return whether to temporarily hide the vertical scrollbar
10741     * @hide
10742     */
10743    protected boolean isVerticalScrollBarHidden() {
10744        return false;
10745    }
10746
10747    /**
10748     * <p>Draw the horizontal scrollbar if
10749     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
10750     *
10751     * @param canvas the canvas on which to draw the scrollbar
10752     * @param scrollBar the scrollbar's drawable
10753     *
10754     * @see #isHorizontalScrollBarEnabled()
10755     * @see #computeHorizontalScrollRange()
10756     * @see #computeHorizontalScrollExtent()
10757     * @see #computeHorizontalScrollOffset()
10758     * @see android.widget.ScrollBarDrawable
10759     * @hide
10760     */
10761    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
10762            int l, int t, int r, int b) {
10763        scrollBar.setBounds(l, t, r, b);
10764        scrollBar.draw(canvas);
10765    }
10766
10767    /**
10768     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
10769     * returns true.</p>
10770     *
10771     * @param canvas the canvas on which to draw the scrollbar
10772     * @param scrollBar the scrollbar's drawable
10773     *
10774     * @see #isVerticalScrollBarEnabled()
10775     * @see #computeVerticalScrollRange()
10776     * @see #computeVerticalScrollExtent()
10777     * @see #computeVerticalScrollOffset()
10778     * @see android.widget.ScrollBarDrawable
10779     * @hide
10780     */
10781    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
10782            int l, int t, int r, int b) {
10783        scrollBar.setBounds(l, t, r, b);
10784        scrollBar.draw(canvas);
10785    }
10786
10787    /**
10788     * Implement this to do your drawing.
10789     *
10790     * @param canvas the canvas on which the background will be drawn
10791     */
10792    protected void onDraw(Canvas canvas) {
10793    }
10794
10795    /*
10796     * Caller is responsible for calling requestLayout if necessary.
10797     * (This allows addViewInLayout to not request a new layout.)
10798     */
10799    void assignParent(ViewParent parent) {
10800        if (mParent == null) {
10801            mParent = parent;
10802        } else if (parent == null) {
10803            mParent = null;
10804        } else {
10805            throw new RuntimeException("view " + this + " being added, but"
10806                    + " it already has a parent");
10807        }
10808    }
10809
10810    /**
10811     * This is called when the view is attached to a window.  At this point it
10812     * has a Surface and will start drawing.  Note that this function is
10813     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
10814     * however it may be called any time before the first onDraw -- including
10815     * before or after {@link #onMeasure(int, int)}.
10816     *
10817     * @see #onDetachedFromWindow()
10818     */
10819    protected void onAttachedToWindow() {
10820        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
10821            mParent.requestTransparentRegion(this);
10822        }
10823        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
10824            initialAwakenScrollBars();
10825            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
10826        }
10827        jumpDrawablesToCurrentState();
10828        // Order is important here: LayoutDirection MUST be resolved before Padding
10829        // and TextDirection
10830        resolveLayoutDirection();
10831        resolvePadding();
10832        resolveTextDirection();
10833        resolveTextAlignment();
10834        clearAccessibilityFocus();
10835        if (isFocused()) {
10836            InputMethodManager imm = InputMethodManager.peekInstance();
10837            imm.focusIn(this);
10838        }
10839    }
10840
10841    /**
10842     * @see #onScreenStateChanged(int)
10843     */
10844    void dispatchScreenStateChanged(int screenState) {
10845        onScreenStateChanged(screenState);
10846    }
10847
10848    /**
10849     * This method is called whenever the state of the screen this view is
10850     * attached to changes. A state change will usually occurs when the screen
10851     * turns on or off (whether it happens automatically or the user does it
10852     * manually.)
10853     *
10854     * @param screenState The new state of the screen. Can be either
10855     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10856     */
10857    public void onScreenStateChanged(int screenState) {
10858    }
10859
10860    /**
10861     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10862     */
10863    private boolean hasRtlSupport() {
10864        return mContext.getApplicationInfo().hasRtlSupport();
10865    }
10866
10867    /**
10868     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10869     * that the parent directionality can and will be resolved before its children.
10870     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10871     */
10872    public void resolveLayoutDirection() {
10873        // Clear any previous layout direction resolution
10874        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10875
10876        if (hasRtlSupport()) {
10877            // Set resolved depending on layout direction
10878            switch (getLayoutDirection()) {
10879                case LAYOUT_DIRECTION_INHERIT:
10880                    // If this is root view, no need to look at parent's layout dir.
10881                    if (canResolveLayoutDirection()) {
10882                        ViewGroup viewGroup = ((ViewGroup) mParent);
10883
10884                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10885                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10886                        }
10887                    } else {
10888                        // Nothing to do, LTR by default
10889                    }
10890                    break;
10891                case LAYOUT_DIRECTION_RTL:
10892                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10893                    break;
10894                case LAYOUT_DIRECTION_LOCALE:
10895                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10896                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10897                    }
10898                    break;
10899                default:
10900                    // Nothing to do, LTR by default
10901            }
10902        }
10903
10904        // Set to resolved
10905        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10906        onResolvedLayoutDirectionChanged();
10907        // Resolve padding
10908        resolvePadding();
10909    }
10910
10911    /**
10912     * Called when layout direction has been resolved.
10913     *
10914     * The default implementation does nothing.
10915     */
10916    public void onResolvedLayoutDirectionChanged() {
10917    }
10918
10919    /**
10920     * Resolve padding depending on layout direction.
10921     */
10922    public void resolvePadding() {
10923        // If the user specified the absolute padding (either with android:padding or
10924        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10925        // use the default padding or the padding from the background drawable
10926        // (stored at this point in mPadding*)
10927        int resolvedLayoutDirection = getResolvedLayoutDirection();
10928        switch (resolvedLayoutDirection) {
10929            case LAYOUT_DIRECTION_RTL:
10930                // Start user padding override Right user padding. Otherwise, if Right user
10931                // padding is not defined, use the default Right padding. If Right user padding
10932                // is defined, just use it.
10933                if (mUserPaddingStart >= 0) {
10934                    mUserPaddingRight = mUserPaddingStart;
10935                } else if (mUserPaddingRight < 0) {
10936                    mUserPaddingRight = mPaddingRight;
10937                }
10938                if (mUserPaddingEnd >= 0) {
10939                    mUserPaddingLeft = mUserPaddingEnd;
10940                } else if (mUserPaddingLeft < 0) {
10941                    mUserPaddingLeft = mPaddingLeft;
10942                }
10943                break;
10944            case LAYOUT_DIRECTION_LTR:
10945            default:
10946                // Start user padding override Left user padding. Otherwise, if Left user
10947                // padding is not defined, use the default left padding. If Left user padding
10948                // is defined, just use it.
10949                if (mUserPaddingStart >= 0) {
10950                    mUserPaddingLeft = mUserPaddingStart;
10951                } else if (mUserPaddingLeft < 0) {
10952                    mUserPaddingLeft = mPaddingLeft;
10953                }
10954                if (mUserPaddingEnd >= 0) {
10955                    mUserPaddingRight = mUserPaddingEnd;
10956                } else if (mUserPaddingRight < 0) {
10957                    mUserPaddingRight = mPaddingRight;
10958                }
10959        }
10960
10961        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
10962
10963        if(isPaddingRelative()) {
10964            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
10965        } else {
10966            recomputePadding();
10967        }
10968        onPaddingChanged(resolvedLayoutDirection);
10969    }
10970
10971    /**
10972     * Resolve padding depending on the layout direction. Subclasses that care about
10973     * padding resolution should override this method. The default implementation does
10974     * nothing.
10975     *
10976     * @param layoutDirection the direction of the layout
10977     *
10978     * @see {@link #LAYOUT_DIRECTION_LTR}
10979     * @see {@link #LAYOUT_DIRECTION_RTL}
10980     */
10981    public void onPaddingChanged(int layoutDirection) {
10982    }
10983
10984    /**
10985     * Check if layout direction resolution can be done.
10986     *
10987     * @return true if layout direction resolution can be done otherwise return false.
10988     */
10989    public boolean canResolveLayoutDirection() {
10990        switch (getLayoutDirection()) {
10991            case LAYOUT_DIRECTION_INHERIT:
10992                return (mParent != null) && (mParent instanceof ViewGroup);
10993            default:
10994                return true;
10995        }
10996    }
10997
10998    /**
10999     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11000     * when reset is done.
11001     */
11002    public void resetResolvedLayoutDirection() {
11003        // Reset the current resolved bits
11004        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11005        onResolvedLayoutDirectionReset();
11006        // Reset also the text direction
11007        resetResolvedTextDirection();
11008    }
11009
11010    /**
11011     * Called during reset of resolved layout direction.
11012     *
11013     * Subclasses need to override this method to clear cached information that depends on the
11014     * resolved layout direction, or to inform child views that inherit their layout direction.
11015     *
11016     * The default implementation does nothing.
11017     */
11018    public void onResolvedLayoutDirectionReset() {
11019    }
11020
11021    /**
11022     * Check if a Locale uses an RTL script.
11023     *
11024     * @param locale Locale to check
11025     * @return true if the Locale uses an RTL script.
11026     */
11027    protected static boolean isLayoutDirectionRtl(Locale locale) {
11028        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11029    }
11030
11031    /**
11032     * This is called when the view is detached from a window.  At this point it
11033     * no longer has a surface for drawing.
11034     *
11035     * @see #onAttachedToWindow()
11036     */
11037    protected void onDetachedFromWindow() {
11038        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11039
11040        removeUnsetPressCallback();
11041        removeLongPressCallback();
11042        removePerformClickCallback();
11043        removeSendViewScrolledAccessibilityEventCallback();
11044
11045        destroyDrawingCache();
11046
11047        destroyLayer(false);
11048
11049        if (mAttachInfo != null) {
11050            if (mDisplayList != null) {
11051                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
11052            }
11053            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11054        } else {
11055            if (mDisplayList != null) {
11056                // Should never happen
11057                mDisplayList.invalidate();
11058            }
11059        }
11060
11061        mCurrentAnimation = null;
11062
11063        resetResolvedLayoutDirection();
11064        resetResolvedTextAlignment();
11065        resetAccessibilityStateChanged();
11066        clearAccessibilityFocus();
11067    }
11068
11069    /**
11070     * @return The number of times this view has been attached to a window
11071     */
11072    protected int getWindowAttachCount() {
11073        return mWindowAttachCount;
11074    }
11075
11076    /**
11077     * Retrieve a unique token identifying the window this view is attached to.
11078     * @return Return the window's token for use in
11079     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11080     */
11081    public IBinder getWindowToken() {
11082        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11083    }
11084
11085    /**
11086     * Retrieve a unique token identifying the top-level "real" window of
11087     * the window that this view is attached to.  That is, this is like
11088     * {@link #getWindowToken}, except if the window this view in is a panel
11089     * window (attached to another containing window), then the token of
11090     * the containing window is returned instead.
11091     *
11092     * @return Returns the associated window token, either
11093     * {@link #getWindowToken()} or the containing window's token.
11094     */
11095    public IBinder getApplicationWindowToken() {
11096        AttachInfo ai = mAttachInfo;
11097        if (ai != null) {
11098            IBinder appWindowToken = ai.mPanelParentWindowToken;
11099            if (appWindowToken == null) {
11100                appWindowToken = ai.mWindowToken;
11101            }
11102            return appWindowToken;
11103        }
11104        return null;
11105    }
11106
11107    /**
11108     * Retrieve private session object this view hierarchy is using to
11109     * communicate with the window manager.
11110     * @return the session object to communicate with the window manager
11111     */
11112    /*package*/ IWindowSession getWindowSession() {
11113        return mAttachInfo != null ? mAttachInfo.mSession : null;
11114    }
11115
11116    /**
11117     * @param info the {@link android.view.View.AttachInfo} to associated with
11118     *        this view
11119     */
11120    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11121        //System.out.println("Attached! " + this);
11122        mAttachInfo = info;
11123        mWindowAttachCount++;
11124        // We will need to evaluate the drawable state at least once.
11125        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11126        if (mFloatingTreeObserver != null) {
11127            info.mTreeObserver.merge(mFloatingTreeObserver);
11128            mFloatingTreeObserver = null;
11129        }
11130        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11131            mAttachInfo.mScrollContainers.add(this);
11132            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11133        }
11134        performCollectViewAttributes(mAttachInfo, visibility);
11135        onAttachedToWindow();
11136
11137        ListenerInfo li = mListenerInfo;
11138        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11139                li != null ? li.mOnAttachStateChangeListeners : null;
11140        if (listeners != null && listeners.size() > 0) {
11141            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11142            // perform the dispatching. The iterator is a safe guard against listeners that
11143            // could mutate the list by calling the various add/remove methods. This prevents
11144            // the array from being modified while we iterate it.
11145            for (OnAttachStateChangeListener listener : listeners) {
11146                listener.onViewAttachedToWindow(this);
11147            }
11148        }
11149
11150        int vis = info.mWindowVisibility;
11151        if (vis != GONE) {
11152            onWindowVisibilityChanged(vis);
11153        }
11154        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11155            // If nobody has evaluated the drawable state yet, then do it now.
11156            refreshDrawableState();
11157        }
11158    }
11159
11160    void dispatchDetachedFromWindow() {
11161        AttachInfo info = mAttachInfo;
11162        if (info != null) {
11163            int vis = info.mWindowVisibility;
11164            if (vis != GONE) {
11165                onWindowVisibilityChanged(GONE);
11166            }
11167        }
11168
11169        onDetachedFromWindow();
11170
11171        ListenerInfo li = mListenerInfo;
11172        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11173                li != null ? li.mOnAttachStateChangeListeners : null;
11174        if (listeners != null && listeners.size() > 0) {
11175            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11176            // perform the dispatching. The iterator is a safe guard against listeners that
11177            // could mutate the list by calling the various add/remove methods. This prevents
11178            // the array from being modified while we iterate it.
11179            for (OnAttachStateChangeListener listener : listeners) {
11180                listener.onViewDetachedFromWindow(this);
11181            }
11182        }
11183
11184        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11185            mAttachInfo.mScrollContainers.remove(this);
11186            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11187        }
11188
11189        mAttachInfo = null;
11190    }
11191
11192    /**
11193     * Store this view hierarchy's frozen state into the given container.
11194     *
11195     * @param container The SparseArray in which to save the view's state.
11196     *
11197     * @see #restoreHierarchyState(android.util.SparseArray)
11198     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11199     * @see #onSaveInstanceState()
11200     */
11201    public void saveHierarchyState(SparseArray<Parcelable> container) {
11202        dispatchSaveInstanceState(container);
11203    }
11204
11205    /**
11206     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11207     * this view and its children. May be overridden to modify how freezing happens to a
11208     * view's children; for example, some views may want to not store state for their children.
11209     *
11210     * @param container The SparseArray in which to save the view's state.
11211     *
11212     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11213     * @see #saveHierarchyState(android.util.SparseArray)
11214     * @see #onSaveInstanceState()
11215     */
11216    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11217        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11218            mPrivateFlags &= ~SAVE_STATE_CALLED;
11219            Parcelable state = onSaveInstanceState();
11220            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11221                throw new IllegalStateException(
11222                        "Derived class did not call super.onSaveInstanceState()");
11223            }
11224            if (state != null) {
11225                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11226                // + ": " + state);
11227                container.put(mID, state);
11228            }
11229        }
11230    }
11231
11232    /**
11233     * Hook allowing a view to generate a representation of its internal state
11234     * that can later be used to create a new instance with that same state.
11235     * This state should only contain information that is not persistent or can
11236     * not be reconstructed later. For example, you will never store your
11237     * current position on screen because that will be computed again when a
11238     * new instance of the view is placed in its view hierarchy.
11239     * <p>
11240     * Some examples of things you may store here: the current cursor position
11241     * in a text view (but usually not the text itself since that is stored in a
11242     * content provider or other persistent storage), the currently selected
11243     * item in a list view.
11244     *
11245     * @return Returns a Parcelable object containing the view's current dynamic
11246     *         state, or null if there is nothing interesting to save. The
11247     *         default implementation returns null.
11248     * @see #onRestoreInstanceState(android.os.Parcelable)
11249     * @see #saveHierarchyState(android.util.SparseArray)
11250     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11251     * @see #setSaveEnabled(boolean)
11252     */
11253    protected Parcelable onSaveInstanceState() {
11254        mPrivateFlags |= SAVE_STATE_CALLED;
11255        return BaseSavedState.EMPTY_STATE;
11256    }
11257
11258    /**
11259     * Restore this view hierarchy's frozen state from the given container.
11260     *
11261     * @param container The SparseArray which holds previously frozen states.
11262     *
11263     * @see #saveHierarchyState(android.util.SparseArray)
11264     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11265     * @see #onRestoreInstanceState(android.os.Parcelable)
11266     */
11267    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11268        dispatchRestoreInstanceState(container);
11269    }
11270
11271    /**
11272     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11273     * state for this view and its children. May be overridden to modify how restoring
11274     * happens to a view's children; for example, some views may want to not store state
11275     * for their children.
11276     *
11277     * @param container The SparseArray which holds previously saved state.
11278     *
11279     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11280     * @see #restoreHierarchyState(android.util.SparseArray)
11281     * @see #onRestoreInstanceState(android.os.Parcelable)
11282     */
11283    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11284        if (mID != NO_ID) {
11285            Parcelable state = container.get(mID);
11286            if (state != null) {
11287                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11288                // + ": " + state);
11289                mPrivateFlags &= ~SAVE_STATE_CALLED;
11290                onRestoreInstanceState(state);
11291                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11292                    throw new IllegalStateException(
11293                            "Derived class did not call super.onRestoreInstanceState()");
11294                }
11295            }
11296        }
11297    }
11298
11299    /**
11300     * Hook allowing a view to re-apply a representation of its internal state that had previously
11301     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11302     * null state.
11303     *
11304     * @param state The frozen state that had previously been returned by
11305     *        {@link #onSaveInstanceState}.
11306     *
11307     * @see #onSaveInstanceState()
11308     * @see #restoreHierarchyState(android.util.SparseArray)
11309     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11310     */
11311    protected void onRestoreInstanceState(Parcelable state) {
11312        mPrivateFlags |= SAVE_STATE_CALLED;
11313        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11314            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11315                    + "received " + state.getClass().toString() + " instead. This usually happens "
11316                    + "when two views of different type have the same id in the same hierarchy. "
11317                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11318                    + "other views do not use the same id.");
11319        }
11320    }
11321
11322    /**
11323     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11324     *
11325     * @return the drawing start time in milliseconds
11326     */
11327    public long getDrawingTime() {
11328        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11329    }
11330
11331    /**
11332     * <p>Enables or disables the duplication of the parent's state into this view. When
11333     * duplication is enabled, this view gets its drawable state from its parent rather
11334     * than from its own internal properties.</p>
11335     *
11336     * <p>Note: in the current implementation, setting this property to true after the
11337     * view was added to a ViewGroup might have no effect at all. This property should
11338     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11339     *
11340     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11341     * property is enabled, an exception will be thrown.</p>
11342     *
11343     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11344     * parent, these states should not be affected by this method.</p>
11345     *
11346     * @param enabled True to enable duplication of the parent's drawable state, false
11347     *                to disable it.
11348     *
11349     * @see #getDrawableState()
11350     * @see #isDuplicateParentStateEnabled()
11351     */
11352    public void setDuplicateParentStateEnabled(boolean enabled) {
11353        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11354    }
11355
11356    /**
11357     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11358     *
11359     * @return True if this view's drawable state is duplicated from the parent,
11360     *         false otherwise
11361     *
11362     * @see #getDrawableState()
11363     * @see #setDuplicateParentStateEnabled(boolean)
11364     */
11365    public boolean isDuplicateParentStateEnabled() {
11366        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11367    }
11368
11369    /**
11370     * <p>Specifies the type of layer backing this view. The layer can be
11371     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11372     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11373     *
11374     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11375     * instance that controls how the layer is composed on screen. The following
11376     * properties of the paint are taken into account when composing the layer:</p>
11377     * <ul>
11378     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11379     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11380     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11381     * </ul>
11382     *
11383     * <p>If this view has an alpha value set to < 1.0 by calling
11384     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11385     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11386     * equivalent to setting a hardware layer on this view and providing a paint with
11387     * the desired alpha value.<p>
11388     *
11389     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11390     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11391     * for more information on when and how to use layers.</p>
11392     *
11393     * @param layerType The ype of layer to use with this view, must be one of
11394     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11395     *        {@link #LAYER_TYPE_HARDWARE}
11396     * @param paint The paint used to compose the layer. This argument is optional
11397     *        and can be null. It is ignored when the layer type is
11398     *        {@link #LAYER_TYPE_NONE}
11399     *
11400     * @see #getLayerType()
11401     * @see #LAYER_TYPE_NONE
11402     * @see #LAYER_TYPE_SOFTWARE
11403     * @see #LAYER_TYPE_HARDWARE
11404     * @see #setAlpha(float)
11405     *
11406     * @attr ref android.R.styleable#View_layerType
11407     */
11408    public void setLayerType(int layerType, Paint paint) {
11409        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11410            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11411                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11412        }
11413
11414        if (layerType == mLayerType) {
11415            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11416                mLayerPaint = paint == null ? new Paint() : paint;
11417                invalidateParentCaches();
11418                invalidate(true);
11419            }
11420            return;
11421        }
11422
11423        // Destroy any previous software drawing cache if needed
11424        switch (mLayerType) {
11425            case LAYER_TYPE_HARDWARE:
11426                destroyLayer(false);
11427                // fall through - non-accelerated views may use software layer mechanism instead
11428            case LAYER_TYPE_SOFTWARE:
11429                destroyDrawingCache();
11430                break;
11431            default:
11432                break;
11433        }
11434
11435        mLayerType = layerType;
11436        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11437        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11438        mLocalDirtyRect = layerDisabled ? null : new Rect();
11439
11440        invalidateParentCaches();
11441        invalidate(true);
11442    }
11443
11444    /**
11445     * Indicates whether this view has a static layer. A view with layer type
11446     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11447     * dynamic.
11448     */
11449    boolean hasStaticLayer() {
11450        return true;
11451    }
11452
11453    /**
11454     * Indicates what type of layer is currently associated with this view. By default
11455     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11456     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11457     * for more information on the different types of layers.
11458     *
11459     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11460     *         {@link #LAYER_TYPE_HARDWARE}
11461     *
11462     * @see #setLayerType(int, android.graphics.Paint)
11463     * @see #buildLayer()
11464     * @see #LAYER_TYPE_NONE
11465     * @see #LAYER_TYPE_SOFTWARE
11466     * @see #LAYER_TYPE_HARDWARE
11467     */
11468    public int getLayerType() {
11469        return mLayerType;
11470    }
11471
11472    /**
11473     * Forces this view's layer to be created and this view to be rendered
11474     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11475     * invoking this method will have no effect.
11476     *
11477     * This method can for instance be used to render a view into its layer before
11478     * starting an animation. If this view is complex, rendering into the layer
11479     * before starting the animation will avoid skipping frames.
11480     *
11481     * @throws IllegalStateException If this view is not attached to a window
11482     *
11483     * @see #setLayerType(int, android.graphics.Paint)
11484     */
11485    public void buildLayer() {
11486        if (mLayerType == LAYER_TYPE_NONE) return;
11487
11488        if (mAttachInfo == null) {
11489            throw new IllegalStateException("This view must be attached to a window first");
11490        }
11491
11492        switch (mLayerType) {
11493            case LAYER_TYPE_HARDWARE:
11494                if (mAttachInfo.mHardwareRenderer != null &&
11495                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11496                        mAttachInfo.mHardwareRenderer.validate()) {
11497                    getHardwareLayer();
11498                }
11499                break;
11500            case LAYER_TYPE_SOFTWARE:
11501                buildDrawingCache(true);
11502                break;
11503        }
11504    }
11505
11506    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11507    void flushLayer() {
11508        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11509            mHardwareLayer.flush();
11510        }
11511    }
11512
11513    /**
11514     * <p>Returns a hardware layer that can be used to draw this view again
11515     * without executing its draw method.</p>
11516     *
11517     * @return A HardwareLayer ready to render, or null if an error occurred.
11518     */
11519    HardwareLayer getHardwareLayer() {
11520        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11521                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11522            return null;
11523        }
11524
11525        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11526
11527        final int width = mRight - mLeft;
11528        final int height = mBottom - mTop;
11529
11530        if (width == 0 || height == 0) {
11531            return null;
11532        }
11533
11534        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11535            if (mHardwareLayer == null) {
11536                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11537                        width, height, isOpaque());
11538                mLocalDirtyRect.set(0, 0, width, height);
11539            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11540                mHardwareLayer.resize(width, height);
11541                mLocalDirtyRect.set(0, 0, width, height);
11542            }
11543
11544            // The layer is not valid if the underlying GPU resources cannot be allocated
11545            if (!mHardwareLayer.isValid()) {
11546                return null;
11547            }
11548
11549            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11550            mLocalDirtyRect.setEmpty();
11551        }
11552
11553        return mHardwareLayer;
11554    }
11555
11556    /**
11557     * Destroys this View's hardware layer if possible.
11558     *
11559     * @return True if the layer was destroyed, false otherwise.
11560     *
11561     * @see #setLayerType(int, android.graphics.Paint)
11562     * @see #LAYER_TYPE_HARDWARE
11563     */
11564    boolean destroyLayer(boolean valid) {
11565        if (mHardwareLayer != null) {
11566            AttachInfo info = mAttachInfo;
11567            if (info != null && info.mHardwareRenderer != null &&
11568                    info.mHardwareRenderer.isEnabled() &&
11569                    (valid || info.mHardwareRenderer.validate())) {
11570                mHardwareLayer.destroy();
11571                mHardwareLayer = null;
11572
11573                invalidate(true);
11574                invalidateParentCaches();
11575            }
11576            return true;
11577        }
11578        return false;
11579    }
11580
11581    /**
11582     * Destroys all hardware rendering resources. This method is invoked
11583     * when the system needs to reclaim resources. Upon execution of this
11584     * method, you should free any OpenGL resources created by the view.
11585     *
11586     * Note: you <strong>must</strong> call
11587     * <code>super.destroyHardwareResources()</code> when overriding
11588     * this method.
11589     *
11590     * @hide
11591     */
11592    protected void destroyHardwareResources() {
11593        destroyLayer(true);
11594    }
11595
11596    /**
11597     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11598     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11599     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11600     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11601     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11602     * null.</p>
11603     *
11604     * <p>Enabling the drawing cache is similar to
11605     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11606     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11607     * drawing cache has no effect on rendering because the system uses a different mechanism
11608     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11609     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11610     * for information on how to enable software and hardware layers.</p>
11611     *
11612     * <p>This API can be used to manually generate
11613     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11614     * {@link #getDrawingCache()}.</p>
11615     *
11616     * @param enabled true to enable the drawing cache, false otherwise
11617     *
11618     * @see #isDrawingCacheEnabled()
11619     * @see #getDrawingCache()
11620     * @see #buildDrawingCache()
11621     * @see #setLayerType(int, android.graphics.Paint)
11622     */
11623    public void setDrawingCacheEnabled(boolean enabled) {
11624        mCachingFailed = false;
11625        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11626    }
11627
11628    /**
11629     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11630     *
11631     * @return true if the drawing cache is enabled
11632     *
11633     * @see #setDrawingCacheEnabled(boolean)
11634     * @see #getDrawingCache()
11635     */
11636    @ViewDebug.ExportedProperty(category = "drawing")
11637    public boolean isDrawingCacheEnabled() {
11638        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11639    }
11640
11641    /**
11642     * Debugging utility which recursively outputs the dirty state of a view and its
11643     * descendants.
11644     *
11645     * @hide
11646     */
11647    @SuppressWarnings({"UnusedDeclaration"})
11648    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11649        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11650                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11651                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11652                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11653        if (clear) {
11654            mPrivateFlags &= clearMask;
11655        }
11656        if (this instanceof ViewGroup) {
11657            ViewGroup parent = (ViewGroup) this;
11658            final int count = parent.getChildCount();
11659            for (int i = 0; i < count; i++) {
11660                final View child = parent.getChildAt(i);
11661                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11662            }
11663        }
11664    }
11665
11666    /**
11667     * This method is used by ViewGroup to cause its children to restore or recreate their
11668     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11669     * to recreate its own display list, which would happen if it went through the normal
11670     * draw/dispatchDraw mechanisms.
11671     *
11672     * @hide
11673     */
11674    protected void dispatchGetDisplayList() {}
11675
11676    /**
11677     * A view that is not attached or hardware accelerated cannot create a display list.
11678     * This method checks these conditions and returns the appropriate result.
11679     *
11680     * @return true if view has the ability to create a display list, false otherwise.
11681     *
11682     * @hide
11683     */
11684    public boolean canHaveDisplayList() {
11685        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11686    }
11687
11688    /**
11689     * @return The HardwareRenderer associated with that view or null if hardware rendering
11690     * is not supported or this this has not been attached to a window.
11691     *
11692     * @hide
11693     */
11694    public HardwareRenderer getHardwareRenderer() {
11695        if (mAttachInfo != null) {
11696            return mAttachInfo.mHardwareRenderer;
11697        }
11698        return null;
11699    }
11700
11701    /**
11702     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11703     * Otherwise, the same display list will be returned (after having been rendered into
11704     * along the way, depending on the invalidation state of the view).
11705     *
11706     * @param displayList The previous version of this displayList, could be null.
11707     * @param isLayer Whether the requester of the display list is a layer. If so,
11708     * the view will avoid creating a layer inside the resulting display list.
11709     * @return A new or reused DisplayList object.
11710     */
11711    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11712        if (!canHaveDisplayList()) {
11713            return null;
11714        }
11715
11716        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11717                displayList == null || !displayList.isValid() ||
11718                (!isLayer && mRecreateDisplayList))) {
11719            // Don't need to recreate the display list, just need to tell our
11720            // children to restore/recreate theirs
11721            if (displayList != null && displayList.isValid() &&
11722                    !isLayer && !mRecreateDisplayList) {
11723                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11724                mPrivateFlags &= ~DIRTY_MASK;
11725                dispatchGetDisplayList();
11726
11727                return displayList;
11728            }
11729
11730            if (!isLayer) {
11731                // If we got here, we're recreating it. Mark it as such to ensure that
11732                // we copy in child display lists into ours in drawChild()
11733                mRecreateDisplayList = true;
11734            }
11735            if (displayList == null) {
11736                final String name = getClass().getSimpleName();
11737                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
11738                // If we're creating a new display list, make sure our parent gets invalidated
11739                // since they will need to recreate their display list to account for this
11740                // new child display list.
11741                invalidateParentCaches();
11742            }
11743
11744            boolean caching = false;
11745            final HardwareCanvas canvas = displayList.start();
11746            int restoreCount = 0;
11747            int width = mRight - mLeft;
11748            int height = mBottom - mTop;
11749
11750            try {
11751                canvas.setViewport(width, height);
11752                // The dirty rect should always be null for a display list
11753                canvas.onPreDraw(null);
11754                int layerType = (
11755                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
11756                        getLayerType() : LAYER_TYPE_NONE;
11757                if (!isLayer && layerType != LAYER_TYPE_NONE) {
11758                    if (layerType == LAYER_TYPE_HARDWARE) {
11759                        final HardwareLayer layer = getHardwareLayer();
11760                        if (layer != null && layer.isValid()) {
11761                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
11762                        } else {
11763                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
11764                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
11765                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11766                        }
11767                        caching = true;
11768                    } else {
11769                        buildDrawingCache(true);
11770                        Bitmap cache = getDrawingCache(true);
11771                        if (cache != null) {
11772                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
11773                            caching = true;
11774                        }
11775                    }
11776                } else {
11777
11778                    computeScroll();
11779
11780                    canvas.translate(-mScrollX, -mScrollY);
11781                    if (!isLayer) {
11782                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11783                        mPrivateFlags &= ~DIRTY_MASK;
11784                    }
11785
11786                    // Fast path for layouts with no backgrounds
11787                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11788                        dispatchDraw(canvas);
11789                    } else {
11790                        draw(canvas);
11791                    }
11792                }
11793            } finally {
11794                canvas.onPostDraw();
11795
11796                displayList.end();
11797                displayList.setCaching(caching);
11798                if (isLayer) {
11799                    displayList.setLeftTopRightBottom(0, 0, width, height);
11800                } else {
11801                    setDisplayListProperties(displayList);
11802                }
11803            }
11804        } else if (!isLayer) {
11805            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11806            mPrivateFlags &= ~DIRTY_MASK;
11807        }
11808
11809        return displayList;
11810    }
11811
11812    /**
11813     * Get the DisplayList for the HardwareLayer
11814     *
11815     * @param layer The HardwareLayer whose DisplayList we want
11816     * @return A DisplayList fopr the specified HardwareLayer
11817     */
11818    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
11819        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
11820        layer.setDisplayList(displayList);
11821        return displayList;
11822    }
11823
11824
11825    /**
11826     * <p>Returns a display list that can be used to draw this view again
11827     * without executing its draw method.</p>
11828     *
11829     * @return A DisplayList ready to replay, or null if caching is not enabled.
11830     *
11831     * @hide
11832     */
11833    public DisplayList getDisplayList() {
11834        mDisplayList = getDisplayList(mDisplayList, false);
11835        return mDisplayList;
11836    }
11837
11838    /**
11839     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11840     *
11841     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11842     *
11843     * @see #getDrawingCache(boolean)
11844     */
11845    public Bitmap getDrawingCache() {
11846        return getDrawingCache(false);
11847    }
11848
11849    /**
11850     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11851     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11852     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11853     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11854     * request the drawing cache by calling this method and draw it on screen if the
11855     * returned bitmap is not null.</p>
11856     *
11857     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11858     * this method will create a bitmap of the same size as this view. Because this bitmap
11859     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11860     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11861     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11862     * size than the view. This implies that your application must be able to handle this
11863     * size.</p>
11864     *
11865     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11866     *        the current density of the screen when the application is in compatibility
11867     *        mode.
11868     *
11869     * @return A bitmap representing this view or null if cache is disabled.
11870     *
11871     * @see #setDrawingCacheEnabled(boolean)
11872     * @see #isDrawingCacheEnabled()
11873     * @see #buildDrawingCache(boolean)
11874     * @see #destroyDrawingCache()
11875     */
11876    public Bitmap getDrawingCache(boolean autoScale) {
11877        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11878            return null;
11879        }
11880        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11881            buildDrawingCache(autoScale);
11882        }
11883        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11884    }
11885
11886    /**
11887     * <p>Frees the resources used by the drawing cache. If you call
11888     * {@link #buildDrawingCache()} manually without calling
11889     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11890     * should cleanup the cache with this method afterwards.</p>
11891     *
11892     * @see #setDrawingCacheEnabled(boolean)
11893     * @see #buildDrawingCache()
11894     * @see #getDrawingCache()
11895     */
11896    public void destroyDrawingCache() {
11897        if (mDrawingCache != null) {
11898            mDrawingCache.recycle();
11899            mDrawingCache = null;
11900        }
11901        if (mUnscaledDrawingCache != null) {
11902            mUnscaledDrawingCache.recycle();
11903            mUnscaledDrawingCache = null;
11904        }
11905    }
11906
11907    /**
11908     * Setting a solid background color for the drawing cache's bitmaps will improve
11909     * performance and memory usage. Note, though that this should only be used if this
11910     * view will always be drawn on top of a solid color.
11911     *
11912     * @param color The background color to use for the drawing cache's bitmap
11913     *
11914     * @see #setDrawingCacheEnabled(boolean)
11915     * @see #buildDrawingCache()
11916     * @see #getDrawingCache()
11917     */
11918    public void setDrawingCacheBackgroundColor(int color) {
11919        if (color != mDrawingCacheBackgroundColor) {
11920            mDrawingCacheBackgroundColor = color;
11921            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11922        }
11923    }
11924
11925    /**
11926     * @see #setDrawingCacheBackgroundColor(int)
11927     *
11928     * @return The background color to used for the drawing cache's bitmap
11929     */
11930    public int getDrawingCacheBackgroundColor() {
11931        return mDrawingCacheBackgroundColor;
11932    }
11933
11934    /**
11935     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11936     *
11937     * @see #buildDrawingCache(boolean)
11938     */
11939    public void buildDrawingCache() {
11940        buildDrawingCache(false);
11941    }
11942
11943    /**
11944     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
11945     *
11946     * <p>If you call {@link #buildDrawingCache()} manually without calling
11947     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11948     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
11949     *
11950     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11951     * this method will create a bitmap of the same size as this view. Because this bitmap
11952     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11953     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11954     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11955     * size than the view. This implies that your application must be able to handle this
11956     * size.</p>
11957     *
11958     * <p>You should avoid calling this method when hardware acceleration is enabled. If
11959     * you do not need the drawing cache bitmap, calling this method will increase memory
11960     * usage and cause the view to be rendered in software once, thus negatively impacting
11961     * performance.</p>
11962     *
11963     * @see #getDrawingCache()
11964     * @see #destroyDrawingCache()
11965     */
11966    public void buildDrawingCache(boolean autoScale) {
11967        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
11968                mDrawingCache == null : mUnscaledDrawingCache == null)) {
11969            mCachingFailed = false;
11970
11971            if (ViewDebug.TRACE_HIERARCHY) {
11972                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
11973            }
11974
11975            int width = mRight - mLeft;
11976            int height = mBottom - mTop;
11977
11978            final AttachInfo attachInfo = mAttachInfo;
11979            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
11980
11981            if (autoScale && scalingRequired) {
11982                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
11983                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
11984            }
11985
11986            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
11987            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
11988            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
11989
11990            if (width <= 0 || height <= 0 ||
11991                     // Projected bitmap size in bytes
11992                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
11993                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
11994                destroyDrawingCache();
11995                mCachingFailed = true;
11996                return;
11997            }
11998
11999            boolean clear = true;
12000            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12001
12002            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12003                Bitmap.Config quality;
12004                if (!opaque) {
12005                    // Never pick ARGB_4444 because it looks awful
12006                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12007                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12008                        case DRAWING_CACHE_QUALITY_AUTO:
12009                            quality = Bitmap.Config.ARGB_8888;
12010                            break;
12011                        case DRAWING_CACHE_QUALITY_LOW:
12012                            quality = Bitmap.Config.ARGB_8888;
12013                            break;
12014                        case DRAWING_CACHE_QUALITY_HIGH:
12015                            quality = Bitmap.Config.ARGB_8888;
12016                            break;
12017                        default:
12018                            quality = Bitmap.Config.ARGB_8888;
12019                            break;
12020                    }
12021                } else {
12022                    // Optimization for translucent windows
12023                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12024                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12025                }
12026
12027                // Try to cleanup memory
12028                if (bitmap != null) bitmap.recycle();
12029
12030                try {
12031                    bitmap = Bitmap.createBitmap(width, height, quality);
12032                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12033                    if (autoScale) {
12034                        mDrawingCache = bitmap;
12035                    } else {
12036                        mUnscaledDrawingCache = bitmap;
12037                    }
12038                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12039                } catch (OutOfMemoryError e) {
12040                    // If there is not enough memory to create the bitmap cache, just
12041                    // ignore the issue as bitmap caches are not required to draw the
12042                    // view hierarchy
12043                    if (autoScale) {
12044                        mDrawingCache = null;
12045                    } else {
12046                        mUnscaledDrawingCache = null;
12047                    }
12048                    mCachingFailed = true;
12049                    return;
12050                }
12051
12052                clear = drawingCacheBackgroundColor != 0;
12053            }
12054
12055            Canvas canvas;
12056            if (attachInfo != null) {
12057                canvas = attachInfo.mCanvas;
12058                if (canvas == null) {
12059                    canvas = new Canvas();
12060                }
12061                canvas.setBitmap(bitmap);
12062                // Temporarily clobber the cached Canvas in case one of our children
12063                // is also using a drawing cache. Without this, the children would
12064                // steal the canvas by attaching their own bitmap to it and bad, bad
12065                // thing would happen (invisible views, corrupted drawings, etc.)
12066                attachInfo.mCanvas = null;
12067            } else {
12068                // This case should hopefully never or seldom happen
12069                canvas = new Canvas(bitmap);
12070            }
12071
12072            if (clear) {
12073                bitmap.eraseColor(drawingCacheBackgroundColor);
12074            }
12075
12076            computeScroll();
12077            final int restoreCount = canvas.save();
12078
12079            if (autoScale && scalingRequired) {
12080                final float scale = attachInfo.mApplicationScale;
12081                canvas.scale(scale, scale);
12082            }
12083
12084            canvas.translate(-mScrollX, -mScrollY);
12085
12086            mPrivateFlags |= DRAWN;
12087            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12088                    mLayerType != LAYER_TYPE_NONE) {
12089                mPrivateFlags |= DRAWING_CACHE_VALID;
12090            }
12091
12092            // Fast path for layouts with no backgrounds
12093            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12094                if (ViewDebug.TRACE_HIERARCHY) {
12095                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12096                }
12097                mPrivateFlags &= ~DIRTY_MASK;
12098                dispatchDraw(canvas);
12099            } else {
12100                draw(canvas);
12101            }
12102
12103            canvas.restoreToCount(restoreCount);
12104            canvas.setBitmap(null);
12105
12106            if (attachInfo != null) {
12107                // Restore the cached Canvas for our siblings
12108                attachInfo.mCanvas = canvas;
12109            }
12110        }
12111    }
12112
12113    /**
12114     * Create a snapshot of the view into a bitmap.  We should probably make
12115     * some form of this public, but should think about the API.
12116     */
12117    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12118        int width = mRight - mLeft;
12119        int height = mBottom - mTop;
12120
12121        final AttachInfo attachInfo = mAttachInfo;
12122        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12123        width = (int) ((width * scale) + 0.5f);
12124        height = (int) ((height * scale) + 0.5f);
12125
12126        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12127        if (bitmap == null) {
12128            throw new OutOfMemoryError();
12129        }
12130
12131        Resources resources = getResources();
12132        if (resources != null) {
12133            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12134        }
12135
12136        Canvas canvas;
12137        if (attachInfo != null) {
12138            canvas = attachInfo.mCanvas;
12139            if (canvas == null) {
12140                canvas = new Canvas();
12141            }
12142            canvas.setBitmap(bitmap);
12143            // Temporarily clobber the cached Canvas in case one of our children
12144            // is also using a drawing cache. Without this, the children would
12145            // steal the canvas by attaching their own bitmap to it and bad, bad
12146            // things would happen (invisible views, corrupted drawings, etc.)
12147            attachInfo.mCanvas = null;
12148        } else {
12149            // This case should hopefully never or seldom happen
12150            canvas = new Canvas(bitmap);
12151        }
12152
12153        if ((backgroundColor & 0xff000000) != 0) {
12154            bitmap.eraseColor(backgroundColor);
12155        }
12156
12157        computeScroll();
12158        final int restoreCount = canvas.save();
12159        canvas.scale(scale, scale);
12160        canvas.translate(-mScrollX, -mScrollY);
12161
12162        // Temporarily remove the dirty mask
12163        int flags = mPrivateFlags;
12164        mPrivateFlags &= ~DIRTY_MASK;
12165
12166        // Fast path for layouts with no backgrounds
12167        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12168            dispatchDraw(canvas);
12169        } else {
12170            draw(canvas);
12171        }
12172
12173        mPrivateFlags = flags;
12174
12175        canvas.restoreToCount(restoreCount);
12176        canvas.setBitmap(null);
12177
12178        if (attachInfo != null) {
12179            // Restore the cached Canvas for our siblings
12180            attachInfo.mCanvas = canvas;
12181        }
12182
12183        return bitmap;
12184    }
12185
12186    /**
12187     * Indicates whether this View is currently in edit mode. A View is usually
12188     * in edit mode when displayed within a developer tool. For instance, if
12189     * this View is being drawn by a visual user interface builder, this method
12190     * should return true.
12191     *
12192     * Subclasses should check the return value of this method to provide
12193     * different behaviors if their normal behavior might interfere with the
12194     * host environment. For instance: the class spawns a thread in its
12195     * constructor, the drawing code relies on device-specific features, etc.
12196     *
12197     * This method is usually checked in the drawing code of custom widgets.
12198     *
12199     * @return True if this View is in edit mode, false otherwise.
12200     */
12201    public boolean isInEditMode() {
12202        return false;
12203    }
12204
12205    /**
12206     * If the View draws content inside its padding and enables fading edges,
12207     * it needs to support padding offsets. Padding offsets are added to the
12208     * fading edges to extend the length of the fade so that it covers pixels
12209     * drawn inside the padding.
12210     *
12211     * Subclasses of this class should override this method if they need
12212     * to draw content inside the padding.
12213     *
12214     * @return True if padding offset must be applied, false otherwise.
12215     *
12216     * @see #getLeftPaddingOffset()
12217     * @see #getRightPaddingOffset()
12218     * @see #getTopPaddingOffset()
12219     * @see #getBottomPaddingOffset()
12220     *
12221     * @since CURRENT
12222     */
12223    protected boolean isPaddingOffsetRequired() {
12224        return false;
12225    }
12226
12227    /**
12228     * Amount by which to extend the left fading region. Called only when
12229     * {@link #isPaddingOffsetRequired()} returns true.
12230     *
12231     * @return The left padding offset in pixels.
12232     *
12233     * @see #isPaddingOffsetRequired()
12234     *
12235     * @since CURRENT
12236     */
12237    protected int getLeftPaddingOffset() {
12238        return 0;
12239    }
12240
12241    /**
12242     * Amount by which to extend the right fading region. Called only when
12243     * {@link #isPaddingOffsetRequired()} returns true.
12244     *
12245     * @return The right padding offset in pixels.
12246     *
12247     * @see #isPaddingOffsetRequired()
12248     *
12249     * @since CURRENT
12250     */
12251    protected int getRightPaddingOffset() {
12252        return 0;
12253    }
12254
12255    /**
12256     * Amount by which to extend the top fading region. Called only when
12257     * {@link #isPaddingOffsetRequired()} returns true.
12258     *
12259     * @return The top padding offset in pixels.
12260     *
12261     * @see #isPaddingOffsetRequired()
12262     *
12263     * @since CURRENT
12264     */
12265    protected int getTopPaddingOffset() {
12266        return 0;
12267    }
12268
12269    /**
12270     * Amount by which to extend the bottom fading region. Called only when
12271     * {@link #isPaddingOffsetRequired()} returns true.
12272     *
12273     * @return The bottom padding offset in pixels.
12274     *
12275     * @see #isPaddingOffsetRequired()
12276     *
12277     * @since CURRENT
12278     */
12279    protected int getBottomPaddingOffset() {
12280        return 0;
12281    }
12282
12283    /**
12284     * @hide
12285     * @param offsetRequired
12286     */
12287    protected int getFadeTop(boolean offsetRequired) {
12288        int top = mPaddingTop;
12289        if (offsetRequired) top += getTopPaddingOffset();
12290        return top;
12291    }
12292
12293    /**
12294     * @hide
12295     * @param offsetRequired
12296     */
12297    protected int getFadeHeight(boolean offsetRequired) {
12298        int padding = mPaddingTop;
12299        if (offsetRequired) padding += getTopPaddingOffset();
12300        return mBottom - mTop - mPaddingBottom - padding;
12301    }
12302
12303    /**
12304     * <p>Indicates whether this view is attached to a hardware accelerated
12305     * window or not.</p>
12306     *
12307     * <p>Even if this method returns true, it does not mean that every call
12308     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12309     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12310     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12311     * window is hardware accelerated,
12312     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12313     * return false, and this method will return true.</p>
12314     *
12315     * @return True if the view is attached to a window and the window is
12316     *         hardware accelerated; false in any other case.
12317     */
12318    public boolean isHardwareAccelerated() {
12319        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12320    }
12321
12322    /**
12323     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12324     * case of an active Animation being run on the view.
12325     */
12326    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12327            Animation a, boolean scalingRequired) {
12328        Transformation invalidationTransform;
12329        final int flags = parent.mGroupFlags;
12330        final boolean initialized = a.isInitialized();
12331        if (!initialized) {
12332            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12333            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12334            onAnimationStart();
12335        }
12336
12337        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12338        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12339            if (parent.mInvalidationTransformation == null) {
12340                parent.mInvalidationTransformation = new Transformation();
12341            }
12342            invalidationTransform = parent.mInvalidationTransformation;
12343            a.getTransformation(drawingTime, invalidationTransform, 1f);
12344        } else {
12345            invalidationTransform = parent.mChildTransformation;
12346        }
12347        if (more) {
12348            if (!a.willChangeBounds()) {
12349                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12350                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12351                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12352                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12353                    // The child need to draw an animation, potentially offscreen, so
12354                    // make sure we do not cancel invalidate requests
12355                    parent.mPrivateFlags |= DRAW_ANIMATION;
12356                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12357                }
12358            } else {
12359                if (parent.mInvalidateRegion == null) {
12360                    parent.mInvalidateRegion = new RectF();
12361                }
12362                final RectF region = parent.mInvalidateRegion;
12363                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12364                        invalidationTransform);
12365
12366                // The child need to draw an animation, potentially offscreen, so
12367                // make sure we do not cancel invalidate requests
12368                parent.mPrivateFlags |= DRAW_ANIMATION;
12369
12370                final int left = mLeft + (int) region.left;
12371                final int top = mTop + (int) region.top;
12372                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12373                        top + (int) (region.height() + .5f));
12374            }
12375        }
12376        return more;
12377    }
12378
12379    void setDisplayListProperties() {
12380        setDisplayListProperties(mDisplayList);
12381    }
12382
12383    /**
12384     * This method is called by getDisplayList() when a display list is created or re-rendered.
12385     * It sets or resets the current value of all properties on that display list (resetting is
12386     * necessary when a display list is being re-created, because we need to make sure that
12387     * previously-set transform values
12388     */
12389    void setDisplayListProperties(DisplayList displayList) {
12390        if (displayList != null) {
12391            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12392            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12393            if (mParent instanceof ViewGroup) {
12394                displayList.setClipChildren(
12395                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12396            }
12397            float alpha = 1;
12398            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12399                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12400                ViewGroup parentVG = (ViewGroup) mParent;
12401                final boolean hasTransform =
12402                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12403                if (hasTransform) {
12404                    Transformation transform = parentVG.mChildTransformation;
12405                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12406                    if (transformType != Transformation.TYPE_IDENTITY) {
12407                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12408                            alpha = transform.getAlpha();
12409                        }
12410                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12411                            displayList.setStaticMatrix(transform.getMatrix());
12412                        }
12413                    }
12414                }
12415            }
12416            if (mTransformationInfo != null) {
12417                alpha *= mTransformationInfo.mAlpha;
12418                if (alpha < 1) {
12419                    final int multipliedAlpha = (int) (255 * alpha);
12420                    if (onSetAlpha(multipliedAlpha)) {
12421                        alpha = 1;
12422                    }
12423                }
12424                displayList.setTransformationInfo(alpha,
12425                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12426                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12427                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12428                        mTransformationInfo.mScaleY);
12429                if (mTransformationInfo.mCamera == null) {
12430                    mTransformationInfo.mCamera = new Camera();
12431                    mTransformationInfo.matrix3D = new Matrix();
12432                }
12433                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12434                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12435                    displayList.setPivotX(getPivotX());
12436                    displayList.setPivotY(getPivotY());
12437                }
12438            } else if (alpha < 1) {
12439                displayList.setAlpha(alpha);
12440            }
12441        }
12442    }
12443
12444    /**
12445     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12446     * This draw() method is an implementation detail and is not intended to be overridden or
12447     * to be called from anywhere else other than ViewGroup.drawChild().
12448     */
12449    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12450        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12451        boolean more = false;
12452        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12453        final int flags = parent.mGroupFlags;
12454
12455        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12456            parent.mChildTransformation.clear();
12457            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12458        }
12459
12460        Transformation transformToApply = null;
12461        boolean concatMatrix = false;
12462
12463        boolean scalingRequired = false;
12464        boolean caching;
12465        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12466
12467        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12468        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12469                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12470            caching = true;
12471            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12472            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12473        } else {
12474            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12475        }
12476
12477        final Animation a = getAnimation();
12478        if (a != null) {
12479            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12480            concatMatrix = a.willChangeTransformationMatrix();
12481            transformToApply = parent.mChildTransformation;
12482        } else if (!useDisplayListProperties &&
12483                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12484            final boolean hasTransform =
12485                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12486            if (hasTransform) {
12487                final int transformType = parent.mChildTransformation.getTransformationType();
12488                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12489                        parent.mChildTransformation : null;
12490                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12491            }
12492        }
12493
12494        concatMatrix |= !childHasIdentityMatrix;
12495
12496        // Sets the flag as early as possible to allow draw() implementations
12497        // to call invalidate() successfully when doing animations
12498        mPrivateFlags |= DRAWN;
12499
12500        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12501                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12502            return more;
12503        }
12504
12505        if (hardwareAccelerated) {
12506            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12507            // retain the flag's value temporarily in the mRecreateDisplayList flag
12508            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12509            mPrivateFlags &= ~INVALIDATED;
12510        }
12511
12512        computeScroll();
12513
12514        final int sx = mScrollX;
12515        final int sy = mScrollY;
12516
12517        DisplayList displayList = null;
12518        Bitmap cache = null;
12519        boolean hasDisplayList = false;
12520        if (caching) {
12521            if (!hardwareAccelerated) {
12522                if (layerType != LAYER_TYPE_NONE) {
12523                    layerType = LAYER_TYPE_SOFTWARE;
12524                    buildDrawingCache(true);
12525                }
12526                cache = getDrawingCache(true);
12527            } else {
12528                switch (layerType) {
12529                    case LAYER_TYPE_SOFTWARE:
12530                        if (useDisplayListProperties) {
12531                            hasDisplayList = canHaveDisplayList();
12532                        } else {
12533                            buildDrawingCache(true);
12534                            cache = getDrawingCache(true);
12535                        }
12536                        break;
12537                    case LAYER_TYPE_HARDWARE:
12538                        if (useDisplayListProperties) {
12539                            hasDisplayList = canHaveDisplayList();
12540                        }
12541                        break;
12542                    case LAYER_TYPE_NONE:
12543                        // Delay getting the display list until animation-driven alpha values are
12544                        // set up and possibly passed on to the view
12545                        hasDisplayList = canHaveDisplayList();
12546                        break;
12547                }
12548            }
12549        }
12550        useDisplayListProperties &= hasDisplayList;
12551        if (useDisplayListProperties) {
12552            displayList = getDisplayList();
12553            if (!displayList.isValid()) {
12554                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12555                // to getDisplayList(), the display list will be marked invalid and we should not
12556                // try to use it again.
12557                displayList = null;
12558                hasDisplayList = false;
12559                useDisplayListProperties = false;
12560            }
12561        }
12562
12563        final boolean hasNoCache = cache == null || hasDisplayList;
12564        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12565                layerType != LAYER_TYPE_HARDWARE;
12566
12567        int restoreTo = -1;
12568        if (!useDisplayListProperties || transformToApply != null) {
12569            restoreTo = canvas.save();
12570        }
12571        if (offsetForScroll) {
12572            canvas.translate(mLeft - sx, mTop - sy);
12573        } else {
12574            if (!useDisplayListProperties) {
12575                canvas.translate(mLeft, mTop);
12576            }
12577            if (scalingRequired) {
12578                if (useDisplayListProperties) {
12579                    // TODO: Might not need this if we put everything inside the DL
12580                    restoreTo = canvas.save();
12581                }
12582                // mAttachInfo cannot be null, otherwise scalingRequired == false
12583                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12584                canvas.scale(scale, scale);
12585            }
12586        }
12587
12588        float alpha = useDisplayListProperties ? 1 : getAlpha();
12589        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12590            if (transformToApply != null || !childHasIdentityMatrix) {
12591                int transX = 0;
12592                int transY = 0;
12593
12594                if (offsetForScroll) {
12595                    transX = -sx;
12596                    transY = -sy;
12597                }
12598
12599                if (transformToApply != null) {
12600                    if (concatMatrix) {
12601                        if (useDisplayListProperties) {
12602                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12603                        } else {
12604                            // Undo the scroll translation, apply the transformation matrix,
12605                            // then redo the scroll translate to get the correct result.
12606                            canvas.translate(-transX, -transY);
12607                            canvas.concat(transformToApply.getMatrix());
12608                            canvas.translate(transX, transY);
12609                        }
12610                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12611                    }
12612
12613                    float transformAlpha = transformToApply.getAlpha();
12614                    if (transformAlpha < 1) {
12615                        alpha *= transformToApply.getAlpha();
12616                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12617                    }
12618                }
12619
12620                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12621                    canvas.translate(-transX, -transY);
12622                    canvas.concat(getMatrix());
12623                    canvas.translate(transX, transY);
12624                }
12625            }
12626
12627            if (alpha < 1) {
12628                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12629                if (hasNoCache) {
12630                    final int multipliedAlpha = (int) (255 * alpha);
12631                    if (!onSetAlpha(multipliedAlpha)) {
12632                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12633                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12634                                layerType != LAYER_TYPE_NONE) {
12635                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12636                        }
12637                        if (useDisplayListProperties) {
12638                            displayList.setAlpha(alpha * getAlpha());
12639                        } else  if (layerType == LAYER_TYPE_NONE) {
12640                            final int scrollX = hasDisplayList ? 0 : sx;
12641                            final int scrollY = hasDisplayList ? 0 : sy;
12642                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12643                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12644                        }
12645                    } else {
12646                        // Alpha is handled by the child directly, clobber the layer's alpha
12647                        mPrivateFlags |= ALPHA_SET;
12648                    }
12649                }
12650            }
12651        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12652            onSetAlpha(255);
12653            mPrivateFlags &= ~ALPHA_SET;
12654        }
12655
12656        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12657                !useDisplayListProperties) {
12658            if (offsetForScroll) {
12659                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12660            } else {
12661                if (!scalingRequired || cache == null) {
12662                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12663                } else {
12664                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12665                }
12666            }
12667        }
12668
12669        if (!useDisplayListProperties && hasDisplayList) {
12670            displayList = getDisplayList();
12671            if (!displayList.isValid()) {
12672                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12673                // to getDisplayList(), the display list will be marked invalid and we should not
12674                // try to use it again.
12675                displayList = null;
12676                hasDisplayList = false;
12677            }
12678        }
12679
12680        if (hasNoCache) {
12681            boolean layerRendered = false;
12682            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12683                final HardwareLayer layer = getHardwareLayer();
12684                if (layer != null && layer.isValid()) {
12685                    mLayerPaint.setAlpha((int) (alpha * 255));
12686                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12687                    layerRendered = true;
12688                } else {
12689                    final int scrollX = hasDisplayList ? 0 : sx;
12690                    final int scrollY = hasDisplayList ? 0 : sy;
12691                    canvas.saveLayer(scrollX, scrollY,
12692                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12693                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12694                }
12695            }
12696
12697            if (!layerRendered) {
12698                if (!hasDisplayList) {
12699                    // Fast path for layouts with no backgrounds
12700                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12701                        if (ViewDebug.TRACE_HIERARCHY) {
12702                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12703                        }
12704                        mPrivateFlags &= ~DIRTY_MASK;
12705                        dispatchDraw(canvas);
12706                    } else {
12707                        draw(canvas);
12708                    }
12709                } else {
12710                    mPrivateFlags &= ~DIRTY_MASK;
12711                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12712                }
12713            }
12714        } else if (cache != null) {
12715            mPrivateFlags &= ~DIRTY_MASK;
12716            Paint cachePaint;
12717
12718            if (layerType == LAYER_TYPE_NONE) {
12719                cachePaint = parent.mCachePaint;
12720                if (cachePaint == null) {
12721                    cachePaint = new Paint();
12722                    cachePaint.setDither(false);
12723                    parent.mCachePaint = cachePaint;
12724                }
12725                if (alpha < 1) {
12726                    cachePaint.setAlpha((int) (alpha * 255));
12727                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12728                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12729                    cachePaint.setAlpha(255);
12730                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12731                }
12732            } else {
12733                cachePaint = mLayerPaint;
12734                cachePaint.setAlpha((int) (alpha * 255));
12735            }
12736            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12737        }
12738
12739        if (restoreTo >= 0) {
12740            canvas.restoreToCount(restoreTo);
12741        }
12742
12743        if (a != null && !more) {
12744            if (!hardwareAccelerated && !a.getFillAfter()) {
12745                onSetAlpha(255);
12746            }
12747            parent.finishAnimatingView(this, a);
12748        }
12749
12750        if (more && hardwareAccelerated) {
12751            // invalidation is the trigger to recreate display lists, so if we're using
12752            // display lists to render, force an invalidate to allow the animation to
12753            // continue drawing another frame
12754            parent.invalidate(true);
12755            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12756                // alpha animations should cause the child to recreate its display list
12757                invalidate(true);
12758            }
12759        }
12760
12761        mRecreateDisplayList = false;
12762
12763        return more;
12764    }
12765
12766    /**
12767     * Manually render this view (and all of its children) to the given Canvas.
12768     * The view must have already done a full layout before this function is
12769     * called.  When implementing a view, implement
12770     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
12771     * If you do need to override this method, call the superclass version.
12772     *
12773     * @param canvas The Canvas to which the View is rendered.
12774     */
12775    public void draw(Canvas canvas) {
12776        if (ViewDebug.TRACE_HIERARCHY) {
12777            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12778        }
12779
12780        final int privateFlags = mPrivateFlags;
12781        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
12782                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
12783        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
12784
12785        /*
12786         * Draw traversal performs several drawing steps which must be executed
12787         * in the appropriate order:
12788         *
12789         *      1. Draw the background
12790         *      2. If necessary, save the canvas' layers to prepare for fading
12791         *      3. Draw view's content
12792         *      4. Draw children
12793         *      5. If necessary, draw the fading edges and restore layers
12794         *      6. Draw decorations (scrollbars for instance)
12795         */
12796
12797        // Step 1, draw the background, if needed
12798        int saveCount;
12799
12800        if (!dirtyOpaque) {
12801            final Drawable background = mBackground;
12802            if (background != null) {
12803                final int scrollX = mScrollX;
12804                final int scrollY = mScrollY;
12805
12806                if (mBackgroundSizeChanged) {
12807                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
12808                    mBackgroundSizeChanged = false;
12809                }
12810
12811                if ((scrollX | scrollY) == 0) {
12812                    background.draw(canvas);
12813                } else {
12814                    canvas.translate(scrollX, scrollY);
12815                    background.draw(canvas);
12816                    canvas.translate(-scrollX, -scrollY);
12817                }
12818            }
12819        }
12820
12821        // skip step 2 & 5 if possible (common case)
12822        final int viewFlags = mViewFlags;
12823        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
12824        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
12825        if (!verticalEdges && !horizontalEdges) {
12826            // Step 3, draw the content
12827            if (!dirtyOpaque) onDraw(canvas);
12828
12829            // Step 4, draw the children
12830            dispatchDraw(canvas);
12831
12832            // Step 6, draw decorations (scrollbars)
12833            onDrawScrollBars(canvas);
12834
12835            // we're done...
12836            return;
12837        }
12838
12839        /*
12840         * Here we do the full fledged routine...
12841         * (this is an uncommon case where speed matters less,
12842         * this is why we repeat some of the tests that have been
12843         * done above)
12844         */
12845
12846        boolean drawTop = false;
12847        boolean drawBottom = false;
12848        boolean drawLeft = false;
12849        boolean drawRight = false;
12850
12851        float topFadeStrength = 0.0f;
12852        float bottomFadeStrength = 0.0f;
12853        float leftFadeStrength = 0.0f;
12854        float rightFadeStrength = 0.0f;
12855
12856        // Step 2, save the canvas' layers
12857        int paddingLeft = mPaddingLeft;
12858
12859        final boolean offsetRequired = isPaddingOffsetRequired();
12860        if (offsetRequired) {
12861            paddingLeft += getLeftPaddingOffset();
12862        }
12863
12864        int left = mScrollX + paddingLeft;
12865        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12866        int top = mScrollY + getFadeTop(offsetRequired);
12867        int bottom = top + getFadeHeight(offsetRequired);
12868
12869        if (offsetRequired) {
12870            right += getRightPaddingOffset();
12871            bottom += getBottomPaddingOffset();
12872        }
12873
12874        final ScrollabilityCache scrollabilityCache = mScrollCache;
12875        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12876        int length = (int) fadeHeight;
12877
12878        // clip the fade length if top and bottom fades overlap
12879        // overlapping fades produce odd-looking artifacts
12880        if (verticalEdges && (top + length > bottom - length)) {
12881            length = (bottom - top) / 2;
12882        }
12883
12884        // also clip horizontal fades if necessary
12885        if (horizontalEdges && (left + length > right - length)) {
12886            length = (right - left) / 2;
12887        }
12888
12889        if (verticalEdges) {
12890            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12891            drawTop = topFadeStrength * fadeHeight > 1.0f;
12892            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12893            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12894        }
12895
12896        if (horizontalEdges) {
12897            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12898            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12899            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12900            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12901        }
12902
12903        saveCount = canvas.getSaveCount();
12904
12905        int solidColor = getSolidColor();
12906        if (solidColor == 0) {
12907            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12908
12909            if (drawTop) {
12910                canvas.saveLayer(left, top, right, top + length, null, flags);
12911            }
12912
12913            if (drawBottom) {
12914                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12915            }
12916
12917            if (drawLeft) {
12918                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12919            }
12920
12921            if (drawRight) {
12922                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12923            }
12924        } else {
12925            scrollabilityCache.setFadeColor(solidColor);
12926        }
12927
12928        // Step 3, draw the content
12929        if (!dirtyOpaque) onDraw(canvas);
12930
12931        // Step 4, draw the children
12932        dispatchDraw(canvas);
12933
12934        // Step 5, draw the fade effect and restore layers
12935        final Paint p = scrollabilityCache.paint;
12936        final Matrix matrix = scrollabilityCache.matrix;
12937        final Shader fade = scrollabilityCache.shader;
12938
12939        if (drawTop) {
12940            matrix.setScale(1, fadeHeight * topFadeStrength);
12941            matrix.postTranslate(left, top);
12942            fade.setLocalMatrix(matrix);
12943            canvas.drawRect(left, top, right, top + length, p);
12944        }
12945
12946        if (drawBottom) {
12947            matrix.setScale(1, fadeHeight * bottomFadeStrength);
12948            matrix.postRotate(180);
12949            matrix.postTranslate(left, bottom);
12950            fade.setLocalMatrix(matrix);
12951            canvas.drawRect(left, bottom - length, right, bottom, p);
12952        }
12953
12954        if (drawLeft) {
12955            matrix.setScale(1, fadeHeight * leftFadeStrength);
12956            matrix.postRotate(-90);
12957            matrix.postTranslate(left, top);
12958            fade.setLocalMatrix(matrix);
12959            canvas.drawRect(left, top, left + length, bottom, p);
12960        }
12961
12962        if (drawRight) {
12963            matrix.setScale(1, fadeHeight * rightFadeStrength);
12964            matrix.postRotate(90);
12965            matrix.postTranslate(right, top);
12966            fade.setLocalMatrix(matrix);
12967            canvas.drawRect(right - length, top, right, bottom, p);
12968        }
12969
12970        canvas.restoreToCount(saveCount);
12971
12972        // Step 6, draw decorations (scrollbars)
12973        onDrawScrollBars(canvas);
12974    }
12975
12976    /**
12977     * Override this if your view is known to always be drawn on top of a solid color background,
12978     * and needs to draw fading edges. Returning a non-zero color enables the view system to
12979     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
12980     * should be set to 0xFF.
12981     *
12982     * @see #setVerticalFadingEdgeEnabled(boolean)
12983     * @see #setHorizontalFadingEdgeEnabled(boolean)
12984     *
12985     * @return The known solid color background for this view, or 0 if the color may vary
12986     */
12987    @ViewDebug.ExportedProperty(category = "drawing")
12988    public int getSolidColor() {
12989        return 0;
12990    }
12991
12992    /**
12993     * Build a human readable string representation of the specified view flags.
12994     *
12995     * @param flags the view flags to convert to a string
12996     * @return a String representing the supplied flags
12997     */
12998    private static String printFlags(int flags) {
12999        String output = "";
13000        int numFlags = 0;
13001        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13002            output += "TAKES_FOCUS";
13003            numFlags++;
13004        }
13005
13006        switch (flags & VISIBILITY_MASK) {
13007        case INVISIBLE:
13008            if (numFlags > 0) {
13009                output += " ";
13010            }
13011            output += "INVISIBLE";
13012            // USELESS HERE numFlags++;
13013            break;
13014        case GONE:
13015            if (numFlags > 0) {
13016                output += " ";
13017            }
13018            output += "GONE";
13019            // USELESS HERE numFlags++;
13020            break;
13021        default:
13022            break;
13023        }
13024        return output;
13025    }
13026
13027    /**
13028     * Build a human readable string representation of the specified private
13029     * view flags.
13030     *
13031     * @param privateFlags the private view flags to convert to a string
13032     * @return a String representing the supplied flags
13033     */
13034    private static String printPrivateFlags(int privateFlags) {
13035        String output = "";
13036        int numFlags = 0;
13037
13038        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13039            output += "WANTS_FOCUS";
13040            numFlags++;
13041        }
13042
13043        if ((privateFlags & FOCUSED) == FOCUSED) {
13044            if (numFlags > 0) {
13045                output += " ";
13046            }
13047            output += "FOCUSED";
13048            numFlags++;
13049        }
13050
13051        if ((privateFlags & SELECTED) == SELECTED) {
13052            if (numFlags > 0) {
13053                output += " ";
13054            }
13055            output += "SELECTED";
13056            numFlags++;
13057        }
13058
13059        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13060            if (numFlags > 0) {
13061                output += " ";
13062            }
13063            output += "IS_ROOT_NAMESPACE";
13064            numFlags++;
13065        }
13066
13067        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13068            if (numFlags > 0) {
13069                output += " ";
13070            }
13071            output += "HAS_BOUNDS";
13072            numFlags++;
13073        }
13074
13075        if ((privateFlags & DRAWN) == DRAWN) {
13076            if (numFlags > 0) {
13077                output += " ";
13078            }
13079            output += "DRAWN";
13080            // USELESS HERE numFlags++;
13081        }
13082        return output;
13083    }
13084
13085    /**
13086     * <p>Indicates whether or not this view's layout will be requested during
13087     * the next hierarchy layout pass.</p>
13088     *
13089     * @return true if the layout will be forced during next layout pass
13090     */
13091    public boolean isLayoutRequested() {
13092        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13093    }
13094
13095    /**
13096     * Assign a size and position to a view and all of its
13097     * descendants
13098     *
13099     * <p>This is the second phase of the layout mechanism.
13100     * (The first is measuring). In this phase, each parent calls
13101     * layout on all of its children to position them.
13102     * This is typically done using the child measurements
13103     * that were stored in the measure pass().</p>
13104     *
13105     * <p>Derived classes should not override this method.
13106     * Derived classes with children should override
13107     * onLayout. In that method, they should
13108     * call layout on each of their children.</p>
13109     *
13110     * @param l Left position, relative to parent
13111     * @param t Top position, relative to parent
13112     * @param r Right position, relative to parent
13113     * @param b Bottom position, relative to parent
13114     */
13115    @SuppressWarnings({"unchecked"})
13116    public void layout(int l, int t, int r, int b) {
13117        int oldL = mLeft;
13118        int oldT = mTop;
13119        int oldB = mBottom;
13120        int oldR = mRight;
13121        boolean changed = setFrame(l, t, r, b);
13122        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13123            if (ViewDebug.TRACE_HIERARCHY) {
13124                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13125            }
13126
13127            onLayout(changed, l, t, r, b);
13128            mPrivateFlags &= ~LAYOUT_REQUIRED;
13129
13130            ListenerInfo li = mListenerInfo;
13131            if (li != null && li.mOnLayoutChangeListeners != null) {
13132                ArrayList<OnLayoutChangeListener> listenersCopy =
13133                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13134                int numListeners = listenersCopy.size();
13135                for (int i = 0; i < numListeners; ++i) {
13136                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13137                }
13138            }
13139        }
13140        mPrivateFlags &= ~FORCE_LAYOUT;
13141    }
13142
13143    /**
13144     * Called from layout when this view should
13145     * assign a size and position to each of its children.
13146     *
13147     * Derived classes with children should override
13148     * this method and call layout on each of
13149     * their children.
13150     * @param changed This is a new size or position for this view
13151     * @param left Left position, relative to parent
13152     * @param top Top position, relative to parent
13153     * @param right Right position, relative to parent
13154     * @param bottom Bottom position, relative to parent
13155     */
13156    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13157    }
13158
13159    /**
13160     * Assign a size and position to this view.
13161     *
13162     * This is called from layout.
13163     *
13164     * @param left Left position, relative to parent
13165     * @param top Top position, relative to parent
13166     * @param right Right position, relative to parent
13167     * @param bottom Bottom position, relative to parent
13168     * @return true if the new size and position are different than the
13169     *         previous ones
13170     * {@hide}
13171     */
13172    protected boolean setFrame(int left, int top, int right, int bottom) {
13173        boolean changed = false;
13174
13175        if (DBG) {
13176            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13177                    + right + "," + bottom + ")");
13178        }
13179
13180        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13181            changed = true;
13182
13183            // Remember our drawn bit
13184            int drawn = mPrivateFlags & DRAWN;
13185
13186            int oldWidth = mRight - mLeft;
13187            int oldHeight = mBottom - mTop;
13188            int newWidth = right - left;
13189            int newHeight = bottom - top;
13190            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13191
13192            // Invalidate our old position
13193            invalidate(sizeChanged);
13194
13195            mLeft = left;
13196            mTop = top;
13197            mRight = right;
13198            mBottom = bottom;
13199            if (mDisplayList != null) {
13200                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13201            }
13202
13203            mPrivateFlags |= HAS_BOUNDS;
13204
13205
13206            if (sizeChanged) {
13207                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13208                    // A change in dimension means an auto-centered pivot point changes, too
13209                    if (mTransformationInfo != null) {
13210                        mTransformationInfo.mMatrixDirty = true;
13211                    }
13212                }
13213                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13214            }
13215
13216            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13217                // If we are visible, force the DRAWN bit to on so that
13218                // this invalidate will go through (at least to our parent).
13219                // This is because someone may have invalidated this view
13220                // before this call to setFrame came in, thereby clearing
13221                // the DRAWN bit.
13222                mPrivateFlags |= DRAWN;
13223                invalidate(sizeChanged);
13224                // parent display list may need to be recreated based on a change in the bounds
13225                // of any child
13226                invalidateParentCaches();
13227            }
13228
13229            // Reset drawn bit to original value (invalidate turns it off)
13230            mPrivateFlags |= drawn;
13231
13232            mBackgroundSizeChanged = true;
13233        }
13234        return changed;
13235    }
13236
13237    /**
13238     * Finalize inflating a view from XML.  This is called as the last phase
13239     * of inflation, after all child views have been added.
13240     *
13241     * <p>Even if the subclass overrides onFinishInflate, they should always be
13242     * sure to call the super method, so that we get called.
13243     */
13244    protected void onFinishInflate() {
13245    }
13246
13247    /**
13248     * Returns the resources associated with this view.
13249     *
13250     * @return Resources object.
13251     */
13252    public Resources getResources() {
13253        return mResources;
13254    }
13255
13256    /**
13257     * Invalidates the specified Drawable.
13258     *
13259     * @param drawable the drawable to invalidate
13260     */
13261    public void invalidateDrawable(Drawable drawable) {
13262        if (verifyDrawable(drawable)) {
13263            final Rect dirty = drawable.getBounds();
13264            final int scrollX = mScrollX;
13265            final int scrollY = mScrollY;
13266
13267            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13268                    dirty.right + scrollX, dirty.bottom + scrollY);
13269        }
13270    }
13271
13272    /**
13273     * Schedules an action on a drawable to occur at a specified time.
13274     *
13275     * @param who the recipient of the action
13276     * @param what the action to run on the drawable
13277     * @param when the time at which the action must occur. Uses the
13278     *        {@link SystemClock#uptimeMillis} timebase.
13279     */
13280    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13281        if (verifyDrawable(who) && what != null) {
13282            final long delay = when - SystemClock.uptimeMillis();
13283            if (mAttachInfo != null) {
13284                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13285                        Choreographer.CALLBACK_ANIMATION, what, who,
13286                        Choreographer.subtractFrameDelay(delay));
13287            } else {
13288                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13289            }
13290        }
13291    }
13292
13293    /**
13294     * Cancels a scheduled action on a drawable.
13295     *
13296     * @param who the recipient of the action
13297     * @param what the action to cancel
13298     */
13299    public void unscheduleDrawable(Drawable who, Runnable what) {
13300        if (verifyDrawable(who) && what != null) {
13301            if (mAttachInfo != null) {
13302                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13303                        Choreographer.CALLBACK_ANIMATION, what, who);
13304            } else {
13305                ViewRootImpl.getRunQueue().removeCallbacks(what);
13306            }
13307        }
13308    }
13309
13310    /**
13311     * Unschedule any events associated with the given Drawable.  This can be
13312     * used when selecting a new Drawable into a view, so that the previous
13313     * one is completely unscheduled.
13314     *
13315     * @param who The Drawable to unschedule.
13316     *
13317     * @see #drawableStateChanged
13318     */
13319    public void unscheduleDrawable(Drawable who) {
13320        if (mAttachInfo != null && who != null) {
13321            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13322                    Choreographer.CALLBACK_ANIMATION, null, who);
13323        }
13324    }
13325
13326    /**
13327    * Return the layout direction of a given Drawable.
13328    *
13329    * @param who the Drawable to query
13330    */
13331    public int getResolvedLayoutDirection(Drawable who) {
13332        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13333    }
13334
13335    /**
13336     * If your view subclass is displaying its own Drawable objects, it should
13337     * override this function and return true for any Drawable it is
13338     * displaying.  This allows animations for those drawables to be
13339     * scheduled.
13340     *
13341     * <p>Be sure to call through to the super class when overriding this
13342     * function.
13343     *
13344     * @param who The Drawable to verify.  Return true if it is one you are
13345     *            displaying, else return the result of calling through to the
13346     *            super class.
13347     *
13348     * @return boolean If true than the Drawable is being displayed in the
13349     *         view; else false and it is not allowed to animate.
13350     *
13351     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13352     * @see #drawableStateChanged()
13353     */
13354    protected boolean verifyDrawable(Drawable who) {
13355        return who == mBackground;
13356    }
13357
13358    /**
13359     * This function is called whenever the state of the view changes in such
13360     * a way that it impacts the state of drawables being shown.
13361     *
13362     * <p>Be sure to call through to the superclass when overriding this
13363     * function.
13364     *
13365     * @see Drawable#setState(int[])
13366     */
13367    protected void drawableStateChanged() {
13368        Drawable d = mBackground;
13369        if (d != null && d.isStateful()) {
13370            d.setState(getDrawableState());
13371        }
13372    }
13373
13374    /**
13375     * Call this to force a view to update its drawable state. This will cause
13376     * drawableStateChanged to be called on this view. Views that are interested
13377     * in the new state should call getDrawableState.
13378     *
13379     * @see #drawableStateChanged
13380     * @see #getDrawableState
13381     */
13382    public void refreshDrawableState() {
13383        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13384        drawableStateChanged();
13385
13386        ViewParent parent = mParent;
13387        if (parent != null) {
13388            parent.childDrawableStateChanged(this);
13389        }
13390    }
13391
13392    /**
13393     * Return an array of resource IDs of the drawable states representing the
13394     * current state of the view.
13395     *
13396     * @return The current drawable state
13397     *
13398     * @see Drawable#setState(int[])
13399     * @see #drawableStateChanged()
13400     * @see #onCreateDrawableState(int)
13401     */
13402    public final int[] getDrawableState() {
13403        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13404            return mDrawableState;
13405        } else {
13406            mDrawableState = onCreateDrawableState(0);
13407            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13408            return mDrawableState;
13409        }
13410    }
13411
13412    /**
13413     * Generate the new {@link android.graphics.drawable.Drawable} state for
13414     * this view. This is called by the view
13415     * system when the cached Drawable state is determined to be invalid.  To
13416     * retrieve the current state, you should use {@link #getDrawableState}.
13417     *
13418     * @param extraSpace if non-zero, this is the number of extra entries you
13419     * would like in the returned array in which you can place your own
13420     * states.
13421     *
13422     * @return Returns an array holding the current {@link Drawable} state of
13423     * the view.
13424     *
13425     * @see #mergeDrawableStates(int[], int[])
13426     */
13427    protected int[] onCreateDrawableState(int extraSpace) {
13428        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13429                mParent instanceof View) {
13430            return ((View) mParent).onCreateDrawableState(extraSpace);
13431        }
13432
13433        int[] drawableState;
13434
13435        int privateFlags = mPrivateFlags;
13436
13437        int viewStateIndex = 0;
13438        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13439        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13440        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13441        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13442        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13443        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13444        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13445                HardwareRenderer.isAvailable()) {
13446            // This is set if HW acceleration is requested, even if the current
13447            // process doesn't allow it.  This is just to allow app preview
13448            // windows to better match their app.
13449            viewStateIndex |= VIEW_STATE_ACCELERATED;
13450        }
13451        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13452
13453        final int privateFlags2 = mPrivateFlags2;
13454        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13455        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13456
13457        drawableState = VIEW_STATE_SETS[viewStateIndex];
13458
13459        //noinspection ConstantIfStatement
13460        if (false) {
13461            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13462            Log.i("View", toString()
13463                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13464                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13465                    + " fo=" + hasFocus()
13466                    + " sl=" + ((privateFlags & SELECTED) != 0)
13467                    + " wf=" + hasWindowFocus()
13468                    + ": " + Arrays.toString(drawableState));
13469        }
13470
13471        if (extraSpace == 0) {
13472            return drawableState;
13473        }
13474
13475        final int[] fullState;
13476        if (drawableState != null) {
13477            fullState = new int[drawableState.length + extraSpace];
13478            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13479        } else {
13480            fullState = new int[extraSpace];
13481        }
13482
13483        return fullState;
13484    }
13485
13486    /**
13487     * Merge your own state values in <var>additionalState</var> into the base
13488     * state values <var>baseState</var> that were returned by
13489     * {@link #onCreateDrawableState(int)}.
13490     *
13491     * @param baseState The base state values returned by
13492     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13493     * own additional state values.
13494     *
13495     * @param additionalState The additional state values you would like
13496     * added to <var>baseState</var>; this array is not modified.
13497     *
13498     * @return As a convenience, the <var>baseState</var> array you originally
13499     * passed into the function is returned.
13500     *
13501     * @see #onCreateDrawableState(int)
13502     */
13503    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13504        final int N = baseState.length;
13505        int i = N - 1;
13506        while (i >= 0 && baseState[i] == 0) {
13507            i--;
13508        }
13509        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13510        return baseState;
13511    }
13512
13513    /**
13514     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13515     * on all Drawable objects associated with this view.
13516     */
13517    public void jumpDrawablesToCurrentState() {
13518        if (mBackground != null) {
13519            mBackground.jumpToCurrentState();
13520        }
13521    }
13522
13523    /**
13524     * Sets the background color for this view.
13525     * @param color the color of the background
13526     */
13527    @RemotableViewMethod
13528    public void setBackgroundColor(int color) {
13529        if (mBackground instanceof ColorDrawable) {
13530            ((ColorDrawable) mBackground).setColor(color);
13531        } else {
13532            setBackground(new ColorDrawable(color));
13533        }
13534    }
13535
13536    /**
13537     * Set the background to a given resource. The resource should refer to
13538     * a Drawable object or 0 to remove the background.
13539     * @param resid The identifier of the resource.
13540     *
13541     * @attr ref android.R.styleable#View_background
13542     */
13543    @RemotableViewMethod
13544    public void setBackgroundResource(int resid) {
13545        if (resid != 0 && resid == mBackgroundResource) {
13546            return;
13547        }
13548
13549        Drawable d= null;
13550        if (resid != 0) {
13551            d = mResources.getDrawable(resid);
13552        }
13553        setBackground(d);
13554
13555        mBackgroundResource = resid;
13556    }
13557
13558    /**
13559     * Set the background to a given Drawable, or remove the background. If the
13560     * background has padding, this View's padding is set to the background's
13561     * padding. However, when a background is removed, this View's padding isn't
13562     * touched. If setting the padding is desired, please use
13563     * {@link #setPadding(int, int, int, int)}.
13564     *
13565     * @param background The Drawable to use as the background, or null to remove the
13566     *        background
13567     */
13568    public void setBackground(Drawable background) {
13569        //noinspection deprecation
13570        setBackgroundDrawable(background);
13571    }
13572
13573    /**
13574     * @deprecated use {@link #setBackground(Drawable)} instead
13575     */
13576    @Deprecated
13577    public void setBackgroundDrawable(Drawable background) {
13578        if (background == mBackground) {
13579            return;
13580        }
13581
13582        boolean requestLayout = false;
13583
13584        mBackgroundResource = 0;
13585
13586        /*
13587         * Regardless of whether we're setting a new background or not, we want
13588         * to clear the previous drawable.
13589         */
13590        if (mBackground != null) {
13591            mBackground.setCallback(null);
13592            unscheduleDrawable(mBackground);
13593        }
13594
13595        if (background != null) {
13596            Rect padding = sThreadLocal.get();
13597            if (padding == null) {
13598                padding = new Rect();
13599                sThreadLocal.set(padding);
13600            }
13601            if (background.getPadding(padding)) {
13602                switch (background.getResolvedLayoutDirectionSelf()) {
13603                    case LAYOUT_DIRECTION_RTL:
13604                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13605                        break;
13606                    case LAYOUT_DIRECTION_LTR:
13607                    default:
13608                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13609                }
13610            }
13611
13612            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13613            // if it has a different minimum size, we should layout again
13614            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13615                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13616                requestLayout = true;
13617            }
13618
13619            background.setCallback(this);
13620            if (background.isStateful()) {
13621                background.setState(getDrawableState());
13622            }
13623            background.setVisible(getVisibility() == VISIBLE, false);
13624            mBackground = background;
13625
13626            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13627                mPrivateFlags &= ~SKIP_DRAW;
13628                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13629                requestLayout = true;
13630            }
13631        } else {
13632            /* Remove the background */
13633            mBackground = null;
13634
13635            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13636                /*
13637                 * This view ONLY drew the background before and we're removing
13638                 * the background, so now it won't draw anything
13639                 * (hence we SKIP_DRAW)
13640                 */
13641                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13642                mPrivateFlags |= SKIP_DRAW;
13643            }
13644
13645            /*
13646             * When the background is set, we try to apply its padding to this
13647             * View. When the background is removed, we don't touch this View's
13648             * padding. This is noted in the Javadocs. Hence, we don't need to
13649             * requestLayout(), the invalidate() below is sufficient.
13650             */
13651
13652            // The old background's minimum size could have affected this
13653            // View's layout, so let's requestLayout
13654            requestLayout = true;
13655        }
13656
13657        computeOpaqueFlags();
13658
13659        if (requestLayout) {
13660            requestLayout();
13661        }
13662
13663        mBackgroundSizeChanged = true;
13664        invalidate(true);
13665    }
13666
13667    /**
13668     * Gets the background drawable
13669     *
13670     * @return The drawable used as the background for this view, if any.
13671     *
13672     * @see #setBackground(Drawable)
13673     *
13674     * @attr ref android.R.styleable#View_background
13675     */
13676    public Drawable getBackground() {
13677        return mBackground;
13678    }
13679
13680    /**
13681     * Sets the padding. The view may add on the space required to display
13682     * the scrollbars, depending on the style and visibility of the scrollbars.
13683     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13684     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13685     * from the values set in this call.
13686     *
13687     * @attr ref android.R.styleable#View_padding
13688     * @attr ref android.R.styleable#View_paddingBottom
13689     * @attr ref android.R.styleable#View_paddingLeft
13690     * @attr ref android.R.styleable#View_paddingRight
13691     * @attr ref android.R.styleable#View_paddingTop
13692     * @param left the left padding in pixels
13693     * @param top the top padding in pixels
13694     * @param right the right padding in pixels
13695     * @param bottom the bottom padding in pixels
13696     */
13697    public void setPadding(int left, int top, int right, int bottom) {
13698        mUserPaddingStart = -1;
13699        mUserPaddingEnd = -1;
13700        mUserPaddingRelative = false;
13701
13702        internalSetPadding(left, top, right, bottom);
13703    }
13704
13705    private void internalSetPadding(int left, int top, int right, int bottom) {
13706        mUserPaddingLeft = left;
13707        mUserPaddingRight = right;
13708        mUserPaddingBottom = bottom;
13709
13710        final int viewFlags = mViewFlags;
13711        boolean changed = false;
13712
13713        // Common case is there are no scroll bars.
13714        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13715            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13716                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13717                        ? 0 : getVerticalScrollbarWidth();
13718                switch (mVerticalScrollbarPosition) {
13719                    case SCROLLBAR_POSITION_DEFAULT:
13720                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13721                            left += offset;
13722                        } else {
13723                            right += offset;
13724                        }
13725                        break;
13726                    case SCROLLBAR_POSITION_RIGHT:
13727                        right += offset;
13728                        break;
13729                    case SCROLLBAR_POSITION_LEFT:
13730                        left += offset;
13731                        break;
13732                }
13733            }
13734            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13735                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13736                        ? 0 : getHorizontalScrollbarHeight();
13737            }
13738        }
13739
13740        if (mPaddingLeft != left) {
13741            changed = true;
13742            mPaddingLeft = left;
13743        }
13744        if (mPaddingTop != top) {
13745            changed = true;
13746            mPaddingTop = top;
13747        }
13748        if (mPaddingRight != right) {
13749            changed = true;
13750            mPaddingRight = right;
13751        }
13752        if (mPaddingBottom != bottom) {
13753            changed = true;
13754            mPaddingBottom = bottom;
13755        }
13756
13757        if (changed) {
13758            requestLayout();
13759        }
13760    }
13761
13762    /**
13763     * Sets the relative padding. The view may add on the space required to display
13764     * the scrollbars, depending on the style and visibility of the scrollbars.
13765     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
13766     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
13767     * from the values set in this call.
13768     *
13769     * @attr ref android.R.styleable#View_padding
13770     * @attr ref android.R.styleable#View_paddingBottom
13771     * @attr ref android.R.styleable#View_paddingStart
13772     * @attr ref android.R.styleable#View_paddingEnd
13773     * @attr ref android.R.styleable#View_paddingTop
13774     * @param start the start padding in pixels
13775     * @param top the top padding in pixels
13776     * @param end the end padding in pixels
13777     * @param bottom the bottom padding in pixels
13778     */
13779    public void setPaddingRelative(int start, int top, int end, int bottom) {
13780        mUserPaddingStart = start;
13781        mUserPaddingEnd = end;
13782        mUserPaddingRelative = true;
13783
13784        switch(getResolvedLayoutDirection()) {
13785            case LAYOUT_DIRECTION_RTL:
13786                internalSetPadding(end, top, start, bottom);
13787                break;
13788            case LAYOUT_DIRECTION_LTR:
13789            default:
13790                internalSetPadding(start, top, end, bottom);
13791        }
13792    }
13793
13794    /**
13795     * Returns the top padding of this view.
13796     *
13797     * @return the top padding in pixels
13798     */
13799    public int getPaddingTop() {
13800        return mPaddingTop;
13801    }
13802
13803    /**
13804     * Returns the bottom padding of this view. If there are inset and enabled
13805     * scrollbars, this value may include the space required to display the
13806     * scrollbars as well.
13807     *
13808     * @return the bottom padding in pixels
13809     */
13810    public int getPaddingBottom() {
13811        return mPaddingBottom;
13812    }
13813
13814    /**
13815     * Returns the left padding of this view. If there are inset and enabled
13816     * scrollbars, this value may include the space required to display the
13817     * scrollbars as well.
13818     *
13819     * @return the left padding in pixels
13820     */
13821    public int getPaddingLeft() {
13822        return mPaddingLeft;
13823    }
13824
13825    /**
13826     * Returns the start padding of this view depending on its resolved layout direction.
13827     * If there are inset and enabled scrollbars, this value may include the space
13828     * required to display the scrollbars as well.
13829     *
13830     * @return the start padding in pixels
13831     */
13832    public int getPaddingStart() {
13833        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13834                mPaddingRight : mPaddingLeft;
13835    }
13836
13837    /**
13838     * Returns the right padding of this view. If there are inset and enabled
13839     * scrollbars, this value may include the space required to display the
13840     * scrollbars as well.
13841     *
13842     * @return the right padding in pixels
13843     */
13844    public int getPaddingRight() {
13845        return mPaddingRight;
13846    }
13847
13848    /**
13849     * Returns the end padding of this view depending on its resolved layout direction.
13850     * If there are inset and enabled scrollbars, this value may include the space
13851     * required to display the scrollbars as well.
13852     *
13853     * @return the end padding in pixels
13854     */
13855    public int getPaddingEnd() {
13856        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13857                mPaddingLeft : mPaddingRight;
13858    }
13859
13860    /**
13861     * Return if the padding as been set thru relative values
13862     * {@link #setPaddingRelative(int, int, int, int)} or thru
13863     * @attr ref android.R.styleable#View_paddingStart or
13864     * @attr ref android.R.styleable#View_paddingEnd
13865     *
13866     * @return true if the padding is relative or false if it is not.
13867     */
13868    public boolean isPaddingRelative() {
13869        return mUserPaddingRelative;
13870    }
13871
13872    /**
13873     * @hide
13874     */
13875    public Insets getOpticalInsets() {
13876        if (mLayoutInsets == null) {
13877            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
13878        }
13879        return mLayoutInsets;
13880    }
13881
13882    /**
13883     * @hide
13884     */
13885    public void setLayoutInsets(Insets layoutInsets) {
13886        mLayoutInsets = layoutInsets;
13887    }
13888
13889    /**
13890     * Changes the selection state of this view. A view can be selected or not.
13891     * Note that selection is not the same as focus. Views are typically
13892     * selected in the context of an AdapterView like ListView or GridView;
13893     * the selected view is the view that is highlighted.
13894     *
13895     * @param selected true if the view must be selected, false otherwise
13896     */
13897    public void setSelected(boolean selected) {
13898        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13899            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13900            if (!selected) resetPressedState();
13901            invalidate(true);
13902            refreshDrawableState();
13903            dispatchSetSelected(selected);
13904            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13905                notifyAccessibilityStateChanged();
13906            }
13907        }
13908    }
13909
13910    /**
13911     * Dispatch setSelected to all of this View's children.
13912     *
13913     * @see #setSelected(boolean)
13914     *
13915     * @param selected The new selected state
13916     */
13917    protected void dispatchSetSelected(boolean selected) {
13918    }
13919
13920    /**
13921     * Indicates the selection state of this view.
13922     *
13923     * @return true if the view is selected, false otherwise
13924     */
13925    @ViewDebug.ExportedProperty
13926    public boolean isSelected() {
13927        return (mPrivateFlags & SELECTED) != 0;
13928    }
13929
13930    /**
13931     * Changes the activated state of this view. A view can be activated or not.
13932     * Note that activation is not the same as selection.  Selection is
13933     * a transient property, representing the view (hierarchy) the user is
13934     * currently interacting with.  Activation is a longer-term state that the
13935     * user can move views in and out of.  For example, in a list view with
13936     * single or multiple selection enabled, the views in the current selection
13937     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13938     * here.)  The activated state is propagated down to children of the view it
13939     * is set on.
13940     *
13941     * @param activated true if the view must be activated, false otherwise
13942     */
13943    public void setActivated(boolean activated) {
13944        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13945            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13946            invalidate(true);
13947            refreshDrawableState();
13948            dispatchSetActivated(activated);
13949        }
13950    }
13951
13952    /**
13953     * Dispatch setActivated to all of this View's children.
13954     *
13955     * @see #setActivated(boolean)
13956     *
13957     * @param activated The new activated state
13958     */
13959    protected void dispatchSetActivated(boolean activated) {
13960    }
13961
13962    /**
13963     * Indicates the activation state of this view.
13964     *
13965     * @return true if the view is activated, false otherwise
13966     */
13967    @ViewDebug.ExportedProperty
13968    public boolean isActivated() {
13969        return (mPrivateFlags & ACTIVATED) != 0;
13970    }
13971
13972    /**
13973     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
13974     * observer can be used to get notifications when global events, like
13975     * layout, happen.
13976     *
13977     * The returned ViewTreeObserver observer is not guaranteed to remain
13978     * valid for the lifetime of this View. If the caller of this method keeps
13979     * a long-lived reference to ViewTreeObserver, it should always check for
13980     * the return value of {@link ViewTreeObserver#isAlive()}.
13981     *
13982     * @return The ViewTreeObserver for this view's hierarchy.
13983     */
13984    public ViewTreeObserver getViewTreeObserver() {
13985        if (mAttachInfo != null) {
13986            return mAttachInfo.mTreeObserver;
13987        }
13988        if (mFloatingTreeObserver == null) {
13989            mFloatingTreeObserver = new ViewTreeObserver();
13990        }
13991        return mFloatingTreeObserver;
13992    }
13993
13994    /**
13995     * <p>Finds the topmost view in the current view hierarchy.</p>
13996     *
13997     * @return the topmost view containing this view
13998     */
13999    public View getRootView() {
14000        if (mAttachInfo != null) {
14001            final View v = mAttachInfo.mRootView;
14002            if (v != null) {
14003                return v;
14004            }
14005        }
14006
14007        View parent = this;
14008
14009        while (parent.mParent != null && parent.mParent instanceof View) {
14010            parent = (View) parent.mParent;
14011        }
14012
14013        return parent;
14014    }
14015
14016    /**
14017     * <p>Computes the coordinates of this view on the screen. The argument
14018     * must be an array of two integers. After the method returns, the array
14019     * contains the x and y location in that order.</p>
14020     *
14021     * @param location an array of two integers in which to hold the coordinates
14022     */
14023    public void getLocationOnScreen(int[] location) {
14024        getLocationInWindow(location);
14025
14026        final AttachInfo info = mAttachInfo;
14027        if (info != null) {
14028            location[0] += info.mWindowLeft;
14029            location[1] += info.mWindowTop;
14030        }
14031    }
14032
14033    /**
14034     * <p>Computes the coordinates of this view in its window. The argument
14035     * must be an array of two integers. After the method returns, the array
14036     * contains the x and y location in that order.</p>
14037     *
14038     * @param location an array of two integers in which to hold the coordinates
14039     */
14040    public void getLocationInWindow(int[] location) {
14041        if (location == null || location.length < 2) {
14042            throw new IllegalArgumentException("location must be an array of two integers");
14043        }
14044
14045        if (mAttachInfo == null) {
14046            // When the view is not attached to a window, this method does not make sense
14047            location[0] = location[1] = 0;
14048            return;
14049        }
14050
14051        float[] position = mAttachInfo.mTmpTransformLocation;
14052        position[0] = position[1] = 0.0f;
14053
14054        if (!hasIdentityMatrix()) {
14055            getMatrix().mapPoints(position);
14056        }
14057
14058        position[0] += mLeft;
14059        position[1] += mTop;
14060
14061        ViewParent viewParent = mParent;
14062        while (viewParent instanceof View) {
14063            final View view = (View) viewParent;
14064
14065            position[0] -= view.mScrollX;
14066            position[1] -= view.mScrollY;
14067
14068            if (!view.hasIdentityMatrix()) {
14069                view.getMatrix().mapPoints(position);
14070            }
14071
14072            position[0] += view.mLeft;
14073            position[1] += view.mTop;
14074
14075            viewParent = view.mParent;
14076         }
14077
14078        if (viewParent instanceof ViewRootImpl) {
14079            // *cough*
14080            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14081            position[1] -= vr.mCurScrollY;
14082        }
14083
14084        location[0] = (int) (position[0] + 0.5f);
14085        location[1] = (int) (position[1] + 0.5f);
14086    }
14087
14088    /**
14089     * {@hide}
14090     * @param id the id of the view to be found
14091     * @return the view of the specified id, null if cannot be found
14092     */
14093    protected View findViewTraversal(int id) {
14094        if (id == mID) {
14095            return this;
14096        }
14097        return null;
14098    }
14099
14100    /**
14101     * {@hide}
14102     * @param tag the tag of the view to be found
14103     * @return the view of specified tag, null if cannot be found
14104     */
14105    protected View findViewWithTagTraversal(Object tag) {
14106        if (tag != null && tag.equals(mTag)) {
14107            return this;
14108        }
14109        return null;
14110    }
14111
14112    /**
14113     * {@hide}
14114     * @param predicate The predicate to evaluate.
14115     * @param childToSkip If not null, ignores this child during the recursive traversal.
14116     * @return The first view that matches the predicate or null.
14117     */
14118    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14119        if (predicate.apply(this)) {
14120            return this;
14121        }
14122        return null;
14123    }
14124
14125    /**
14126     * Look for a child view with the given id.  If this view has the given
14127     * id, return this view.
14128     *
14129     * @param id The id to search for.
14130     * @return The view that has the given id in the hierarchy or null
14131     */
14132    public final View findViewById(int id) {
14133        if (id < 0) {
14134            return null;
14135        }
14136        return findViewTraversal(id);
14137    }
14138
14139    /**
14140     * Finds a view by its unuque and stable accessibility id.
14141     *
14142     * @param accessibilityId The searched accessibility id.
14143     * @return The found view.
14144     */
14145    final View findViewByAccessibilityId(int accessibilityId) {
14146        if (accessibilityId < 0) {
14147            return null;
14148        }
14149        return findViewByAccessibilityIdTraversal(accessibilityId);
14150    }
14151
14152    /**
14153     * Performs the traversal to find a view by its unuque and stable accessibility id.
14154     *
14155     * <strong>Note:</strong>This method does not stop at the root namespace
14156     * boundary since the user can touch the screen at an arbitrary location
14157     * potentially crossing the root namespace bounday which will send an
14158     * accessibility event to accessibility services and they should be able
14159     * to obtain the event source. Also accessibility ids are guaranteed to be
14160     * unique in the window.
14161     *
14162     * @param accessibilityId The accessibility id.
14163     * @return The found view.
14164     */
14165    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14166        if (getAccessibilityViewId() == accessibilityId) {
14167            return this;
14168        }
14169        return null;
14170    }
14171
14172    /**
14173     * Look for a child view with the given tag.  If this view has the given
14174     * tag, return this view.
14175     *
14176     * @param tag The tag to search for, using "tag.equals(getTag())".
14177     * @return The View that has the given tag in the hierarchy or null
14178     */
14179    public final View findViewWithTag(Object tag) {
14180        if (tag == null) {
14181            return null;
14182        }
14183        return findViewWithTagTraversal(tag);
14184    }
14185
14186    /**
14187     * {@hide}
14188     * Look for a child view that matches the specified predicate.
14189     * If this view matches the predicate, return this view.
14190     *
14191     * @param predicate The predicate to evaluate.
14192     * @return The first view that matches the predicate or null.
14193     */
14194    public final View findViewByPredicate(Predicate<View> predicate) {
14195        return findViewByPredicateTraversal(predicate, null);
14196    }
14197
14198    /**
14199     * {@hide}
14200     * Look for a child view that matches the specified predicate,
14201     * starting with the specified view and its descendents and then
14202     * recusively searching the ancestors and siblings of that view
14203     * until this view is reached.
14204     *
14205     * This method is useful in cases where the predicate does not match
14206     * a single unique view (perhaps multiple views use the same id)
14207     * and we are trying to find the view that is "closest" in scope to the
14208     * starting view.
14209     *
14210     * @param start The view to start from.
14211     * @param predicate The predicate to evaluate.
14212     * @return The first view that matches the predicate or null.
14213     */
14214    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14215        View childToSkip = null;
14216        for (;;) {
14217            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14218            if (view != null || start == this) {
14219                return view;
14220            }
14221
14222            ViewParent parent = start.getParent();
14223            if (parent == null || !(parent instanceof View)) {
14224                return null;
14225            }
14226
14227            childToSkip = start;
14228            start = (View) parent;
14229        }
14230    }
14231
14232    /**
14233     * Sets the identifier for this view. The identifier does not have to be
14234     * unique in this view's hierarchy. The identifier should be a positive
14235     * number.
14236     *
14237     * @see #NO_ID
14238     * @see #getId()
14239     * @see #findViewById(int)
14240     *
14241     * @param id a number used to identify the view
14242     *
14243     * @attr ref android.R.styleable#View_id
14244     */
14245    public void setId(int id) {
14246        mID = id;
14247    }
14248
14249    /**
14250     * {@hide}
14251     *
14252     * @param isRoot true if the view belongs to the root namespace, false
14253     *        otherwise
14254     */
14255    public void setIsRootNamespace(boolean isRoot) {
14256        if (isRoot) {
14257            mPrivateFlags |= IS_ROOT_NAMESPACE;
14258        } else {
14259            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14260        }
14261    }
14262
14263    /**
14264     * {@hide}
14265     *
14266     * @return true if the view belongs to the root namespace, false otherwise
14267     */
14268    public boolean isRootNamespace() {
14269        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14270    }
14271
14272    /**
14273     * Returns this view's identifier.
14274     *
14275     * @return a positive integer used to identify the view or {@link #NO_ID}
14276     *         if the view has no ID
14277     *
14278     * @see #setId(int)
14279     * @see #findViewById(int)
14280     * @attr ref android.R.styleable#View_id
14281     */
14282    @ViewDebug.CapturedViewProperty
14283    public int getId() {
14284        return mID;
14285    }
14286
14287    /**
14288     * Returns this view's tag.
14289     *
14290     * @return the Object stored in this view as a tag
14291     *
14292     * @see #setTag(Object)
14293     * @see #getTag(int)
14294     */
14295    @ViewDebug.ExportedProperty
14296    public Object getTag() {
14297        return mTag;
14298    }
14299
14300    /**
14301     * Sets the tag associated with this view. A tag can be used to mark
14302     * a view in its hierarchy and does not have to be unique within the
14303     * hierarchy. Tags can also be used to store data within a view without
14304     * resorting to another data structure.
14305     *
14306     * @param tag an Object to tag the view with
14307     *
14308     * @see #getTag()
14309     * @see #setTag(int, Object)
14310     */
14311    public void setTag(final Object tag) {
14312        mTag = tag;
14313    }
14314
14315    /**
14316     * Returns the tag associated with this view and the specified key.
14317     *
14318     * @param key The key identifying the tag
14319     *
14320     * @return the Object stored in this view as a tag
14321     *
14322     * @see #setTag(int, Object)
14323     * @see #getTag()
14324     */
14325    public Object getTag(int key) {
14326        if (mKeyedTags != null) return mKeyedTags.get(key);
14327        return null;
14328    }
14329
14330    /**
14331     * Sets a tag associated with this view and a key. A tag can be used
14332     * to mark a view in its hierarchy and does not have to be unique within
14333     * the hierarchy. Tags can also be used to store data within a view
14334     * without resorting to another data structure.
14335     *
14336     * The specified key should be an id declared in the resources of the
14337     * application to ensure it is unique (see the <a
14338     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14339     * Keys identified as belonging to
14340     * the Android framework or not associated with any package will cause
14341     * an {@link IllegalArgumentException} to be thrown.
14342     *
14343     * @param key The key identifying the tag
14344     * @param tag An Object to tag the view with
14345     *
14346     * @throws IllegalArgumentException If they specified key is not valid
14347     *
14348     * @see #setTag(Object)
14349     * @see #getTag(int)
14350     */
14351    public void setTag(int key, final Object tag) {
14352        // If the package id is 0x00 or 0x01, it's either an undefined package
14353        // or a framework id
14354        if ((key >>> 24) < 2) {
14355            throw new IllegalArgumentException("The key must be an application-specific "
14356                    + "resource id.");
14357        }
14358
14359        setKeyedTag(key, tag);
14360    }
14361
14362    /**
14363     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14364     * framework id.
14365     *
14366     * @hide
14367     */
14368    public void setTagInternal(int key, Object tag) {
14369        if ((key >>> 24) != 0x1) {
14370            throw new IllegalArgumentException("The key must be a framework-specific "
14371                    + "resource id.");
14372        }
14373
14374        setKeyedTag(key, tag);
14375    }
14376
14377    private void setKeyedTag(int key, Object tag) {
14378        if (mKeyedTags == null) {
14379            mKeyedTags = new SparseArray<Object>();
14380        }
14381
14382        mKeyedTags.put(key, tag);
14383    }
14384
14385    /**
14386     * @param consistency The type of consistency. See ViewDebug for more information.
14387     *
14388     * @hide
14389     */
14390    protected boolean dispatchConsistencyCheck(int consistency) {
14391        return onConsistencyCheck(consistency);
14392    }
14393
14394    /**
14395     * Method that subclasses should implement to check their consistency. The type of
14396     * consistency check is indicated by the bit field passed as a parameter.
14397     *
14398     * @param consistency The type of consistency. See ViewDebug for more information.
14399     *
14400     * @throws IllegalStateException if the view is in an inconsistent state.
14401     *
14402     * @hide
14403     */
14404    protected boolean onConsistencyCheck(int consistency) {
14405        boolean result = true;
14406
14407        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14408        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14409
14410        if (checkLayout) {
14411            if (getParent() == null) {
14412                result = false;
14413                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14414                        "View " + this + " does not have a parent.");
14415            }
14416
14417            if (mAttachInfo == null) {
14418                result = false;
14419                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14420                        "View " + this + " is not attached to a window.");
14421            }
14422        }
14423
14424        if (checkDrawing) {
14425            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14426            // from their draw() method
14427
14428            if ((mPrivateFlags & DRAWN) != DRAWN &&
14429                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14430                result = false;
14431                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14432                        "View " + this + " was invalidated but its drawing cache is valid.");
14433            }
14434        }
14435
14436        return result;
14437    }
14438
14439    /**
14440     * Prints information about this view in the log output, with the tag
14441     * {@link #VIEW_LOG_TAG}.
14442     *
14443     * @hide
14444     */
14445    public void debug() {
14446        debug(0);
14447    }
14448
14449    /**
14450     * Prints information about this view in the log output, with the tag
14451     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14452     * indentation defined by the <code>depth</code>.
14453     *
14454     * @param depth the indentation level
14455     *
14456     * @hide
14457     */
14458    protected void debug(int depth) {
14459        String output = debugIndent(depth - 1);
14460
14461        output += "+ " + this;
14462        int id = getId();
14463        if (id != -1) {
14464            output += " (id=" + id + ")";
14465        }
14466        Object tag = getTag();
14467        if (tag != null) {
14468            output += " (tag=" + tag + ")";
14469        }
14470        Log.d(VIEW_LOG_TAG, output);
14471
14472        if ((mPrivateFlags & FOCUSED) != 0) {
14473            output = debugIndent(depth) + " FOCUSED";
14474            Log.d(VIEW_LOG_TAG, output);
14475        }
14476
14477        output = debugIndent(depth);
14478        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14479                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14480                + "} ";
14481        Log.d(VIEW_LOG_TAG, output);
14482
14483        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14484                || mPaddingBottom != 0) {
14485            output = debugIndent(depth);
14486            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14487                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14488            Log.d(VIEW_LOG_TAG, output);
14489        }
14490
14491        output = debugIndent(depth);
14492        output += "mMeasureWidth=" + mMeasuredWidth +
14493                " mMeasureHeight=" + mMeasuredHeight;
14494        Log.d(VIEW_LOG_TAG, output);
14495
14496        output = debugIndent(depth);
14497        if (mLayoutParams == null) {
14498            output += "BAD! no layout params";
14499        } else {
14500            output = mLayoutParams.debug(output);
14501        }
14502        Log.d(VIEW_LOG_TAG, output);
14503
14504        output = debugIndent(depth);
14505        output += "flags={";
14506        output += View.printFlags(mViewFlags);
14507        output += "}";
14508        Log.d(VIEW_LOG_TAG, output);
14509
14510        output = debugIndent(depth);
14511        output += "privateFlags={";
14512        output += View.printPrivateFlags(mPrivateFlags);
14513        output += "}";
14514        Log.d(VIEW_LOG_TAG, output);
14515    }
14516
14517    /**
14518     * Creates a string of whitespaces used for indentation.
14519     *
14520     * @param depth the indentation level
14521     * @return a String containing (depth * 2 + 3) * 2 white spaces
14522     *
14523     * @hide
14524     */
14525    protected static String debugIndent(int depth) {
14526        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14527        for (int i = 0; i < (depth * 2) + 3; i++) {
14528            spaces.append(' ').append(' ');
14529        }
14530        return spaces.toString();
14531    }
14532
14533    /**
14534     * <p>Return the offset of the widget's text baseline from the widget's top
14535     * boundary. If this widget does not support baseline alignment, this
14536     * method returns -1. </p>
14537     *
14538     * @return the offset of the baseline within the widget's bounds or -1
14539     *         if baseline alignment is not supported
14540     */
14541    @ViewDebug.ExportedProperty(category = "layout")
14542    public int getBaseline() {
14543        return -1;
14544    }
14545
14546    /**
14547     * Call this when something has changed which has invalidated the
14548     * layout of this view. This will schedule a layout pass of the view
14549     * tree.
14550     */
14551    public void requestLayout() {
14552        if (ViewDebug.TRACE_HIERARCHY) {
14553            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14554        }
14555
14556        mPrivateFlags |= FORCE_LAYOUT;
14557        mPrivateFlags |= INVALIDATED;
14558
14559        if (mLayoutParams != null) {
14560            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14561        }
14562
14563        if (mParent != null && !mParent.isLayoutRequested()) {
14564            mParent.requestLayout();
14565        }
14566    }
14567
14568    /**
14569     * Forces this view to be laid out during the next layout pass.
14570     * This method does not call requestLayout() or forceLayout()
14571     * on the parent.
14572     */
14573    public void forceLayout() {
14574        mPrivateFlags |= FORCE_LAYOUT;
14575        mPrivateFlags |= INVALIDATED;
14576    }
14577
14578    /**
14579     * <p>
14580     * This is called to find out how big a view should be. The parent
14581     * supplies constraint information in the width and height parameters.
14582     * </p>
14583     *
14584     * <p>
14585     * The actual measurement work of a view is performed in
14586     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14587     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14588     * </p>
14589     *
14590     *
14591     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14592     *        parent
14593     * @param heightMeasureSpec Vertical space requirements as imposed by the
14594     *        parent
14595     *
14596     * @see #onMeasure(int, int)
14597     */
14598    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14599        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14600                widthMeasureSpec != mOldWidthMeasureSpec ||
14601                heightMeasureSpec != mOldHeightMeasureSpec) {
14602
14603            // first clears the measured dimension flag
14604            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14605
14606            if (ViewDebug.TRACE_HIERARCHY) {
14607                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14608            }
14609
14610            // measure ourselves, this should set the measured dimension flag back
14611            onMeasure(widthMeasureSpec, heightMeasureSpec);
14612
14613            // flag not set, setMeasuredDimension() was not invoked, we raise
14614            // an exception to warn the developer
14615            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14616                throw new IllegalStateException("onMeasure() did not set the"
14617                        + " measured dimension by calling"
14618                        + " setMeasuredDimension()");
14619            }
14620
14621            mPrivateFlags |= LAYOUT_REQUIRED;
14622        }
14623
14624        mOldWidthMeasureSpec = widthMeasureSpec;
14625        mOldHeightMeasureSpec = heightMeasureSpec;
14626    }
14627
14628    /**
14629     * <p>
14630     * Measure the view and its content to determine the measured width and the
14631     * measured height. This method is invoked by {@link #measure(int, int)} and
14632     * should be overriden by subclasses to provide accurate and efficient
14633     * measurement of their contents.
14634     * </p>
14635     *
14636     * <p>
14637     * <strong>CONTRACT:</strong> When overriding this method, you
14638     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14639     * measured width and height of this view. Failure to do so will trigger an
14640     * <code>IllegalStateException</code>, thrown by
14641     * {@link #measure(int, int)}. Calling the superclass'
14642     * {@link #onMeasure(int, int)} is a valid use.
14643     * </p>
14644     *
14645     * <p>
14646     * The base class implementation of measure defaults to the background size,
14647     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14648     * override {@link #onMeasure(int, int)} to provide better measurements of
14649     * their content.
14650     * </p>
14651     *
14652     * <p>
14653     * If this method is overridden, it is the subclass's responsibility to make
14654     * sure the measured height and width are at least the view's minimum height
14655     * and width ({@link #getSuggestedMinimumHeight()} and
14656     * {@link #getSuggestedMinimumWidth()}).
14657     * </p>
14658     *
14659     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14660     *                         The requirements are encoded with
14661     *                         {@link android.view.View.MeasureSpec}.
14662     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14663     *                         The requirements are encoded with
14664     *                         {@link android.view.View.MeasureSpec}.
14665     *
14666     * @see #getMeasuredWidth()
14667     * @see #getMeasuredHeight()
14668     * @see #setMeasuredDimension(int, int)
14669     * @see #getSuggestedMinimumHeight()
14670     * @see #getSuggestedMinimumWidth()
14671     * @see android.view.View.MeasureSpec#getMode(int)
14672     * @see android.view.View.MeasureSpec#getSize(int)
14673     */
14674    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14675        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14676                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14677    }
14678
14679    /**
14680     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14681     * measured width and measured height. Failing to do so will trigger an
14682     * exception at measurement time.</p>
14683     *
14684     * @param measuredWidth The measured width of this view.  May be a complex
14685     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14686     * {@link #MEASURED_STATE_TOO_SMALL}.
14687     * @param measuredHeight The measured height of this view.  May be a complex
14688     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14689     * {@link #MEASURED_STATE_TOO_SMALL}.
14690     */
14691    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14692        mMeasuredWidth = measuredWidth;
14693        mMeasuredHeight = measuredHeight;
14694
14695        mPrivateFlags |= MEASURED_DIMENSION_SET;
14696    }
14697
14698    /**
14699     * Merge two states as returned by {@link #getMeasuredState()}.
14700     * @param curState The current state as returned from a view or the result
14701     * of combining multiple views.
14702     * @param newState The new view state to combine.
14703     * @return Returns a new integer reflecting the combination of the two
14704     * states.
14705     */
14706    public static int combineMeasuredStates(int curState, int newState) {
14707        return curState | newState;
14708    }
14709
14710    /**
14711     * Version of {@link #resolveSizeAndState(int, int, int)}
14712     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14713     */
14714    public static int resolveSize(int size, int measureSpec) {
14715        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14716    }
14717
14718    /**
14719     * Utility to reconcile a desired size and state, with constraints imposed
14720     * by a MeasureSpec.  Will take the desired size, unless a different size
14721     * is imposed by the constraints.  The returned value is a compound integer,
14722     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14723     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14724     * size is smaller than the size the view wants to be.
14725     *
14726     * @param size How big the view wants to be
14727     * @param measureSpec Constraints imposed by the parent
14728     * @return Size information bit mask as defined by
14729     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14730     */
14731    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14732        int result = size;
14733        int specMode = MeasureSpec.getMode(measureSpec);
14734        int specSize =  MeasureSpec.getSize(measureSpec);
14735        switch (specMode) {
14736        case MeasureSpec.UNSPECIFIED:
14737            result = size;
14738            break;
14739        case MeasureSpec.AT_MOST:
14740            if (specSize < size) {
14741                result = specSize | MEASURED_STATE_TOO_SMALL;
14742            } else {
14743                result = size;
14744            }
14745            break;
14746        case MeasureSpec.EXACTLY:
14747            result = specSize;
14748            break;
14749        }
14750        return result | (childMeasuredState&MEASURED_STATE_MASK);
14751    }
14752
14753    /**
14754     * Utility to return a default size. Uses the supplied size if the
14755     * MeasureSpec imposed no constraints. Will get larger if allowed
14756     * by the MeasureSpec.
14757     *
14758     * @param size Default size for this view
14759     * @param measureSpec Constraints imposed by the parent
14760     * @return The size this view should be.
14761     */
14762    public static int getDefaultSize(int size, int measureSpec) {
14763        int result = size;
14764        int specMode = MeasureSpec.getMode(measureSpec);
14765        int specSize = MeasureSpec.getSize(measureSpec);
14766
14767        switch (specMode) {
14768        case MeasureSpec.UNSPECIFIED:
14769            result = size;
14770            break;
14771        case MeasureSpec.AT_MOST:
14772        case MeasureSpec.EXACTLY:
14773            result = specSize;
14774            break;
14775        }
14776        return result;
14777    }
14778
14779    /**
14780     * Returns the suggested minimum height that the view should use. This
14781     * returns the maximum of the view's minimum height
14782     * and the background's minimum height
14783     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
14784     * <p>
14785     * When being used in {@link #onMeasure(int, int)}, the caller should still
14786     * ensure the returned height is within the requirements of the parent.
14787     *
14788     * @return The suggested minimum height of the view.
14789     */
14790    protected int getSuggestedMinimumHeight() {
14791        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
14792
14793    }
14794
14795    /**
14796     * Returns the suggested minimum width that the view should use. This
14797     * returns the maximum of the view's minimum width)
14798     * and the background's minimum width
14799     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
14800     * <p>
14801     * When being used in {@link #onMeasure(int, int)}, the caller should still
14802     * ensure the returned width is within the requirements of the parent.
14803     *
14804     * @return The suggested minimum width of the view.
14805     */
14806    protected int getSuggestedMinimumWidth() {
14807        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14808    }
14809
14810    /**
14811     * Returns the minimum height of the view.
14812     *
14813     * @return the minimum height the view will try to be.
14814     *
14815     * @see #setMinimumHeight(int)
14816     *
14817     * @attr ref android.R.styleable#View_minHeight
14818     */
14819    public int getMinimumHeight() {
14820        return mMinHeight;
14821    }
14822
14823    /**
14824     * Sets the minimum height of the view. It is not guaranteed the view will
14825     * be able to achieve this minimum height (for example, if its parent layout
14826     * constrains it with less available height).
14827     *
14828     * @param minHeight The minimum height the view will try to be.
14829     *
14830     * @see #getMinimumHeight()
14831     *
14832     * @attr ref android.R.styleable#View_minHeight
14833     */
14834    public void setMinimumHeight(int minHeight) {
14835        mMinHeight = minHeight;
14836        requestLayout();
14837    }
14838
14839    /**
14840     * Returns the minimum width of the view.
14841     *
14842     * @return the minimum width the view will try to be.
14843     *
14844     * @see #setMinimumWidth(int)
14845     *
14846     * @attr ref android.R.styleable#View_minWidth
14847     */
14848    public int getMinimumWidth() {
14849        return mMinWidth;
14850    }
14851
14852    /**
14853     * Sets the minimum width of the view. It is not guaranteed the view will
14854     * be able to achieve this minimum width (for example, if its parent layout
14855     * constrains it with less available width).
14856     *
14857     * @param minWidth The minimum width the view will try to be.
14858     *
14859     * @see #getMinimumWidth()
14860     *
14861     * @attr ref android.R.styleable#View_minWidth
14862     */
14863    public void setMinimumWidth(int minWidth) {
14864        mMinWidth = minWidth;
14865        requestLayout();
14866
14867    }
14868
14869    /**
14870     * Get the animation currently associated with this view.
14871     *
14872     * @return The animation that is currently playing or
14873     *         scheduled to play for this view.
14874     */
14875    public Animation getAnimation() {
14876        return mCurrentAnimation;
14877    }
14878
14879    /**
14880     * Start the specified animation now.
14881     *
14882     * @param animation the animation to start now
14883     */
14884    public void startAnimation(Animation animation) {
14885        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
14886        setAnimation(animation);
14887        invalidateParentCaches();
14888        invalidate(true);
14889    }
14890
14891    /**
14892     * Cancels any animations for this view.
14893     */
14894    public void clearAnimation() {
14895        if (mCurrentAnimation != null) {
14896            mCurrentAnimation.detach();
14897        }
14898        mCurrentAnimation = null;
14899        invalidateParentIfNeeded();
14900    }
14901
14902    /**
14903     * Sets the next animation to play for this view.
14904     * If you want the animation to play immediately, use
14905     * startAnimation. This method provides allows fine-grained
14906     * control over the start time and invalidation, but you
14907     * must make sure that 1) the animation has a start time set, and
14908     * 2) the view will be invalidated when the animation is supposed to
14909     * start.
14910     *
14911     * @param animation The next animation, or null.
14912     */
14913    public void setAnimation(Animation animation) {
14914        mCurrentAnimation = animation;
14915
14916        if (animation != null) {
14917            // If the screen is off assume the animation start time is now instead of
14918            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
14919            // would cause the animation to start when the screen turns back on
14920            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
14921                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
14922                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
14923            }
14924            animation.reset();
14925        }
14926    }
14927
14928    /**
14929     * Invoked by a parent ViewGroup to notify the start of the animation
14930     * currently associated with this view. If you override this method,
14931     * always call super.onAnimationStart();
14932     *
14933     * @see #setAnimation(android.view.animation.Animation)
14934     * @see #getAnimation()
14935     */
14936    protected void onAnimationStart() {
14937        mPrivateFlags |= ANIMATION_STARTED;
14938    }
14939
14940    /**
14941     * Invoked by a parent ViewGroup to notify the end of the animation
14942     * currently associated with this view. If you override this method,
14943     * always call super.onAnimationEnd();
14944     *
14945     * @see #setAnimation(android.view.animation.Animation)
14946     * @see #getAnimation()
14947     */
14948    protected void onAnimationEnd() {
14949        mPrivateFlags &= ~ANIMATION_STARTED;
14950    }
14951
14952    /**
14953     * Invoked if there is a Transform that involves alpha. Subclass that can
14954     * draw themselves with the specified alpha should return true, and then
14955     * respect that alpha when their onDraw() is called. If this returns false
14956     * then the view may be redirected to draw into an offscreen buffer to
14957     * fulfill the request, which will look fine, but may be slower than if the
14958     * subclass handles it internally. The default implementation returns false.
14959     *
14960     * @param alpha The alpha (0..255) to apply to the view's drawing
14961     * @return true if the view can draw with the specified alpha.
14962     */
14963    protected boolean onSetAlpha(int alpha) {
14964        return false;
14965    }
14966
14967    /**
14968     * This is used by the RootView to perform an optimization when
14969     * the view hierarchy contains one or several SurfaceView.
14970     * SurfaceView is always considered transparent, but its children are not,
14971     * therefore all View objects remove themselves from the global transparent
14972     * region (passed as a parameter to this function).
14973     *
14974     * @param region The transparent region for this ViewAncestor (window).
14975     *
14976     * @return Returns true if the effective visibility of the view at this
14977     * point is opaque, regardless of the transparent region; returns false
14978     * if it is possible for underlying windows to be seen behind the view.
14979     *
14980     * {@hide}
14981     */
14982    public boolean gatherTransparentRegion(Region region) {
14983        final AttachInfo attachInfo = mAttachInfo;
14984        if (region != null && attachInfo != null) {
14985            final int pflags = mPrivateFlags;
14986            if ((pflags & SKIP_DRAW) == 0) {
14987                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
14988                // remove it from the transparent region.
14989                final int[] location = attachInfo.mTransparentLocation;
14990                getLocationInWindow(location);
14991                region.op(location[0], location[1], location[0] + mRight - mLeft,
14992                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
14993            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
14994                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
14995                // exists, so we remove the background drawable's non-transparent
14996                // parts from this transparent region.
14997                applyDrawableToTransparentRegion(mBackground, region);
14998            }
14999        }
15000        return true;
15001    }
15002
15003    /**
15004     * Play a sound effect for this view.
15005     *
15006     * <p>The framework will play sound effects for some built in actions, such as
15007     * clicking, but you may wish to play these effects in your widget,
15008     * for instance, for internal navigation.
15009     *
15010     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15011     * {@link #isSoundEffectsEnabled()} is true.
15012     *
15013     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15014     */
15015    public void playSoundEffect(int soundConstant) {
15016        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15017            return;
15018        }
15019        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15020    }
15021
15022    /**
15023     * BZZZTT!!1!
15024     *
15025     * <p>Provide haptic feedback to the user for this view.
15026     *
15027     * <p>The framework will provide haptic feedback for some built in actions,
15028     * such as long presses, but you may wish to provide feedback for your
15029     * own widget.
15030     *
15031     * <p>The feedback will only be performed if
15032     * {@link #isHapticFeedbackEnabled()} is true.
15033     *
15034     * @param feedbackConstant One of the constants defined in
15035     * {@link HapticFeedbackConstants}
15036     */
15037    public boolean performHapticFeedback(int feedbackConstant) {
15038        return performHapticFeedback(feedbackConstant, 0);
15039    }
15040
15041    /**
15042     * BZZZTT!!1!
15043     *
15044     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15045     *
15046     * @param feedbackConstant One of the constants defined in
15047     * {@link HapticFeedbackConstants}
15048     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15049     */
15050    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15051        if (mAttachInfo == null) {
15052            return false;
15053        }
15054        //noinspection SimplifiableIfStatement
15055        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15056                && !isHapticFeedbackEnabled()) {
15057            return false;
15058        }
15059        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15060                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15061    }
15062
15063    /**
15064     * Request that the visibility of the status bar or other screen/window
15065     * decorations be changed.
15066     *
15067     * <p>This method is used to put the over device UI into temporary modes
15068     * where the user's attention is focused more on the application content,
15069     * by dimming or hiding surrounding system affordances.  This is typically
15070     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15071     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15072     * to be placed behind the action bar (and with these flags other system
15073     * affordances) so that smooth transitions between hiding and showing them
15074     * can be done.
15075     *
15076     * <p>Two representative examples of the use of system UI visibility is
15077     * implementing a content browsing application (like a magazine reader)
15078     * and a video playing application.
15079     *
15080     * <p>The first code shows a typical implementation of a View in a content
15081     * browsing application.  In this implementation, the application goes
15082     * into a content-oriented mode by hiding the status bar and action bar,
15083     * and putting the navigation elements into lights out mode.  The user can
15084     * then interact with content while in this mode.  Such an application should
15085     * provide an easy way for the user to toggle out of the mode (such as to
15086     * check information in the status bar or access notifications).  In the
15087     * implementation here, this is done simply by tapping on the content.
15088     *
15089     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15090     *      content}
15091     *
15092     * <p>This second code sample shows a typical implementation of a View
15093     * in a video playing application.  In this situation, while the video is
15094     * playing the application would like to go into a complete full-screen mode,
15095     * to use as much of the display as possible for the video.  When in this state
15096     * the user can not interact with the application; the system intercepts
15097     * touching on the screen to pop the UI out of full screen mode.
15098     *
15099     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15100     *      content}
15101     *
15102     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15103     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15104     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15105     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15106     */
15107    public void setSystemUiVisibility(int visibility) {
15108        if (visibility != mSystemUiVisibility) {
15109            mSystemUiVisibility = visibility;
15110            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15111                mParent.recomputeViewAttributes(this);
15112            }
15113        }
15114    }
15115
15116    /**
15117     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15118     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15119     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15120     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15121     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15122     */
15123    public int getSystemUiVisibility() {
15124        return mSystemUiVisibility;
15125    }
15126
15127    /**
15128     * Returns the current system UI visibility that is currently set for
15129     * the entire window.  This is the combination of the
15130     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15131     * views in the window.
15132     */
15133    public int getWindowSystemUiVisibility() {
15134        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15135    }
15136
15137    /**
15138     * Override to find out when the window's requested system UI visibility
15139     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15140     * This is different from the callbacks recieved through
15141     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15142     * in that this is only telling you about the local request of the window,
15143     * not the actual values applied by the system.
15144     */
15145    public void onWindowSystemUiVisibilityChanged(int visible) {
15146    }
15147
15148    /**
15149     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15150     * the view hierarchy.
15151     */
15152    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15153        onWindowSystemUiVisibilityChanged(visible);
15154    }
15155
15156    /**
15157     * Set a listener to receive callbacks when the visibility of the system bar changes.
15158     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15159     */
15160    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15161        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15162        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15163            mParent.recomputeViewAttributes(this);
15164        }
15165    }
15166
15167    /**
15168     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15169     * the view hierarchy.
15170     */
15171    public void dispatchSystemUiVisibilityChanged(int visibility) {
15172        ListenerInfo li = mListenerInfo;
15173        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15174            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15175                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15176        }
15177    }
15178
15179    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15180        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15181        if (val != mSystemUiVisibility) {
15182            setSystemUiVisibility(val);
15183        }
15184    }
15185
15186    /**
15187     * Creates an image that the system displays during the drag and drop
15188     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15189     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15190     * appearance as the given View. The default also positions the center of the drag shadow
15191     * directly under the touch point. If no View is provided (the constructor with no parameters
15192     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15193     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15194     * default is an invisible drag shadow.
15195     * <p>
15196     * You are not required to use the View you provide to the constructor as the basis of the
15197     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15198     * anything you want as the drag shadow.
15199     * </p>
15200     * <p>
15201     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15202     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15203     *  size and position of the drag shadow. It uses this data to construct a
15204     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15205     *  so that your application can draw the shadow image in the Canvas.
15206     * </p>
15207     *
15208     * <div class="special reference">
15209     * <h3>Developer Guides</h3>
15210     * <p>For a guide to implementing drag and drop features, read the
15211     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15212     * </div>
15213     */
15214    public static class DragShadowBuilder {
15215        private final WeakReference<View> mView;
15216
15217        /**
15218         * Constructs a shadow image builder based on a View. By default, the resulting drag
15219         * shadow will have the same appearance and dimensions as the View, with the touch point
15220         * over the center of the View.
15221         * @param view A View. Any View in scope can be used.
15222         */
15223        public DragShadowBuilder(View view) {
15224            mView = new WeakReference<View>(view);
15225        }
15226
15227        /**
15228         * Construct a shadow builder object with no associated View.  This
15229         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15230         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15231         * to supply the drag shadow's dimensions and appearance without
15232         * reference to any View object. If they are not overridden, then the result is an
15233         * invisible drag shadow.
15234         */
15235        public DragShadowBuilder() {
15236            mView = new WeakReference<View>(null);
15237        }
15238
15239        /**
15240         * Returns the View object that had been passed to the
15241         * {@link #View.DragShadowBuilder(View)}
15242         * constructor.  If that View parameter was {@code null} or if the
15243         * {@link #View.DragShadowBuilder()}
15244         * constructor was used to instantiate the builder object, this method will return
15245         * null.
15246         *
15247         * @return The View object associate with this builder object.
15248         */
15249        @SuppressWarnings({"JavadocReference"})
15250        final public View getView() {
15251            return mView.get();
15252        }
15253
15254        /**
15255         * Provides the metrics for the shadow image. These include the dimensions of
15256         * the shadow image, and the point within that shadow that should
15257         * be centered under the touch location while dragging.
15258         * <p>
15259         * The default implementation sets the dimensions of the shadow to be the
15260         * same as the dimensions of the View itself and centers the shadow under
15261         * the touch point.
15262         * </p>
15263         *
15264         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15265         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15266         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15267         * image.
15268         *
15269         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15270         * shadow image that should be underneath the touch point during the drag and drop
15271         * operation. Your application must set {@link android.graphics.Point#x} to the
15272         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15273         */
15274        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15275            final View view = mView.get();
15276            if (view != null) {
15277                shadowSize.set(view.getWidth(), view.getHeight());
15278                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15279            } else {
15280                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15281            }
15282        }
15283
15284        /**
15285         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15286         * based on the dimensions it received from the
15287         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15288         *
15289         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15290         */
15291        public void onDrawShadow(Canvas canvas) {
15292            final View view = mView.get();
15293            if (view != null) {
15294                view.draw(canvas);
15295            } else {
15296                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15297            }
15298        }
15299    }
15300
15301    /**
15302     * Starts a drag and drop operation. When your application calls this method, it passes a
15303     * {@link android.view.View.DragShadowBuilder} object to the system. The
15304     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15305     * to get metrics for the drag shadow, and then calls the object's
15306     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15307     * <p>
15308     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15309     *  drag events to all the View objects in your application that are currently visible. It does
15310     *  this either by calling the View object's drag listener (an implementation of
15311     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15312     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15313     *  Both are passed a {@link android.view.DragEvent} object that has a
15314     *  {@link android.view.DragEvent#getAction()} value of
15315     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15316     * </p>
15317     * <p>
15318     * Your application can invoke startDrag() on any attached View object. The View object does not
15319     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15320     * be related to the View the user selected for dragging.
15321     * </p>
15322     * @param data A {@link android.content.ClipData} object pointing to the data to be
15323     * transferred by the drag and drop operation.
15324     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15325     * drag shadow.
15326     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15327     * drop operation. This Object is put into every DragEvent object sent by the system during the
15328     * current drag.
15329     * <p>
15330     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15331     * to the target Views. For example, it can contain flags that differentiate between a
15332     * a copy operation and a move operation.
15333     * </p>
15334     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15335     * so the parameter should be set to 0.
15336     * @return {@code true} if the method completes successfully, or
15337     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15338     * do a drag, and so no drag operation is in progress.
15339     */
15340    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15341            Object myLocalState, int flags) {
15342        if (ViewDebug.DEBUG_DRAG) {
15343            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15344        }
15345        boolean okay = false;
15346
15347        Point shadowSize = new Point();
15348        Point shadowTouchPoint = new Point();
15349        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15350
15351        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15352                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15353            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15354        }
15355
15356        if (ViewDebug.DEBUG_DRAG) {
15357            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15358                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15359        }
15360        Surface surface = new Surface();
15361        try {
15362            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15363                    flags, shadowSize.x, shadowSize.y, surface);
15364            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15365                    + " surface=" + surface);
15366            if (token != null) {
15367                Canvas canvas = surface.lockCanvas(null);
15368                try {
15369                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15370                    shadowBuilder.onDrawShadow(canvas);
15371                } finally {
15372                    surface.unlockCanvasAndPost(canvas);
15373                }
15374
15375                final ViewRootImpl root = getViewRootImpl();
15376
15377                // Cache the local state object for delivery with DragEvents
15378                root.setLocalDragState(myLocalState);
15379
15380                // repurpose 'shadowSize' for the last touch point
15381                root.getLastTouchPoint(shadowSize);
15382
15383                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15384                        shadowSize.x, shadowSize.y,
15385                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15386                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15387
15388                // Off and running!  Release our local surface instance; the drag
15389                // shadow surface is now managed by the system process.
15390                surface.release();
15391            }
15392        } catch (Exception e) {
15393            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15394            surface.destroy();
15395        }
15396
15397        return okay;
15398    }
15399
15400    /**
15401     * Handles drag events sent by the system following a call to
15402     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15403     *<p>
15404     * When the system calls this method, it passes a
15405     * {@link android.view.DragEvent} object. A call to
15406     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15407     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15408     * operation.
15409     * @param event The {@link android.view.DragEvent} sent by the system.
15410     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15411     * in DragEvent, indicating the type of drag event represented by this object.
15412     * @return {@code true} if the method was successful, otherwise {@code false}.
15413     * <p>
15414     *  The method should return {@code true} in response to an action type of
15415     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15416     *  operation.
15417     * </p>
15418     * <p>
15419     *  The method should also return {@code true} in response to an action type of
15420     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15421     *  {@code false} if it didn't.
15422     * </p>
15423     */
15424    public boolean onDragEvent(DragEvent event) {
15425        return false;
15426    }
15427
15428    /**
15429     * Detects if this View is enabled and has a drag event listener.
15430     * If both are true, then it calls the drag event listener with the
15431     * {@link android.view.DragEvent} it received. If the drag event listener returns
15432     * {@code true}, then dispatchDragEvent() returns {@code true}.
15433     * <p>
15434     * For all other cases, the method calls the
15435     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15436     * method and returns its result.
15437     * </p>
15438     * <p>
15439     * This ensures that a drag event is always consumed, even if the View does not have a drag
15440     * event listener. However, if the View has a listener and the listener returns true, then
15441     * onDragEvent() is not called.
15442     * </p>
15443     */
15444    public boolean dispatchDragEvent(DragEvent event) {
15445        //noinspection SimplifiableIfStatement
15446        ListenerInfo li = mListenerInfo;
15447        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15448                && li.mOnDragListener.onDrag(this, event)) {
15449            return true;
15450        }
15451        return onDragEvent(event);
15452    }
15453
15454    boolean canAcceptDrag() {
15455        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15456    }
15457
15458    /**
15459     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15460     * it is ever exposed at all.
15461     * @hide
15462     */
15463    public void onCloseSystemDialogs(String reason) {
15464    }
15465
15466    /**
15467     * Given a Drawable whose bounds have been set to draw into this view,
15468     * update a Region being computed for
15469     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15470     * that any non-transparent parts of the Drawable are removed from the
15471     * given transparent region.
15472     *
15473     * @param dr The Drawable whose transparency is to be applied to the region.
15474     * @param region A Region holding the current transparency information,
15475     * where any parts of the region that are set are considered to be
15476     * transparent.  On return, this region will be modified to have the
15477     * transparency information reduced by the corresponding parts of the
15478     * Drawable that are not transparent.
15479     * {@hide}
15480     */
15481    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15482        if (DBG) {
15483            Log.i("View", "Getting transparent region for: " + this);
15484        }
15485        final Region r = dr.getTransparentRegion();
15486        final Rect db = dr.getBounds();
15487        final AttachInfo attachInfo = mAttachInfo;
15488        if (r != null && attachInfo != null) {
15489            final int w = getRight()-getLeft();
15490            final int h = getBottom()-getTop();
15491            if (db.left > 0) {
15492                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15493                r.op(0, 0, db.left, h, Region.Op.UNION);
15494            }
15495            if (db.right < w) {
15496                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15497                r.op(db.right, 0, w, h, Region.Op.UNION);
15498            }
15499            if (db.top > 0) {
15500                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15501                r.op(0, 0, w, db.top, Region.Op.UNION);
15502            }
15503            if (db.bottom < h) {
15504                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15505                r.op(0, db.bottom, w, h, Region.Op.UNION);
15506            }
15507            final int[] location = attachInfo.mTransparentLocation;
15508            getLocationInWindow(location);
15509            r.translate(location[0], location[1]);
15510            region.op(r, Region.Op.INTERSECT);
15511        } else {
15512            region.op(db, Region.Op.DIFFERENCE);
15513        }
15514    }
15515
15516    private void checkForLongClick(int delayOffset) {
15517        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15518            mHasPerformedLongPress = false;
15519
15520            if (mPendingCheckForLongPress == null) {
15521                mPendingCheckForLongPress = new CheckForLongPress();
15522            }
15523            mPendingCheckForLongPress.rememberWindowAttachCount();
15524            postDelayed(mPendingCheckForLongPress,
15525                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15526        }
15527    }
15528
15529    /**
15530     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15531     * LayoutInflater} class, which provides a full range of options for view inflation.
15532     *
15533     * @param context The Context object for your activity or application.
15534     * @param resource The resource ID to inflate
15535     * @param root A view group that will be the parent.  Used to properly inflate the
15536     * layout_* parameters.
15537     * @see LayoutInflater
15538     */
15539    public static View inflate(Context context, int resource, ViewGroup root) {
15540        LayoutInflater factory = LayoutInflater.from(context);
15541        return factory.inflate(resource, root);
15542    }
15543
15544    /**
15545     * Scroll the view with standard behavior for scrolling beyond the normal
15546     * content boundaries. Views that call this method should override
15547     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15548     * results of an over-scroll operation.
15549     *
15550     * Views can use this method to handle any touch or fling-based scrolling.
15551     *
15552     * @param deltaX Change in X in pixels
15553     * @param deltaY Change in Y in pixels
15554     * @param scrollX Current X scroll value in pixels before applying deltaX
15555     * @param scrollY Current Y scroll value in pixels before applying deltaY
15556     * @param scrollRangeX Maximum content scroll range along the X axis
15557     * @param scrollRangeY Maximum content scroll range along the Y axis
15558     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15559     *          along the X axis.
15560     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15561     *          along the Y axis.
15562     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15563     * @return true if scrolling was clamped to an over-scroll boundary along either
15564     *          axis, false otherwise.
15565     */
15566    @SuppressWarnings({"UnusedParameters"})
15567    protected boolean overScrollBy(int deltaX, int deltaY,
15568            int scrollX, int scrollY,
15569            int scrollRangeX, int scrollRangeY,
15570            int maxOverScrollX, int maxOverScrollY,
15571            boolean isTouchEvent) {
15572        final int overScrollMode = mOverScrollMode;
15573        final boolean canScrollHorizontal =
15574                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15575        final boolean canScrollVertical =
15576                computeVerticalScrollRange() > computeVerticalScrollExtent();
15577        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15578                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15579        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15580                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15581
15582        int newScrollX = scrollX + deltaX;
15583        if (!overScrollHorizontal) {
15584            maxOverScrollX = 0;
15585        }
15586
15587        int newScrollY = scrollY + deltaY;
15588        if (!overScrollVertical) {
15589            maxOverScrollY = 0;
15590        }
15591
15592        // Clamp values if at the limits and record
15593        final int left = -maxOverScrollX;
15594        final int right = maxOverScrollX + scrollRangeX;
15595        final int top = -maxOverScrollY;
15596        final int bottom = maxOverScrollY + scrollRangeY;
15597
15598        boolean clampedX = false;
15599        if (newScrollX > right) {
15600            newScrollX = right;
15601            clampedX = true;
15602        } else if (newScrollX < left) {
15603            newScrollX = left;
15604            clampedX = true;
15605        }
15606
15607        boolean clampedY = false;
15608        if (newScrollY > bottom) {
15609            newScrollY = bottom;
15610            clampedY = true;
15611        } else if (newScrollY < top) {
15612            newScrollY = top;
15613            clampedY = true;
15614        }
15615
15616        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15617
15618        return clampedX || clampedY;
15619    }
15620
15621    /**
15622     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15623     * respond to the results of an over-scroll operation.
15624     *
15625     * @param scrollX New X scroll value in pixels
15626     * @param scrollY New Y scroll value in pixels
15627     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15628     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15629     */
15630    protected void onOverScrolled(int scrollX, int scrollY,
15631            boolean clampedX, boolean clampedY) {
15632        // Intentionally empty.
15633    }
15634
15635    /**
15636     * Returns the over-scroll mode for this view. The result will be
15637     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15638     * (allow over-scrolling only if the view content is larger than the container),
15639     * or {@link #OVER_SCROLL_NEVER}.
15640     *
15641     * @return This view's over-scroll mode.
15642     */
15643    public int getOverScrollMode() {
15644        return mOverScrollMode;
15645    }
15646
15647    /**
15648     * Set the over-scroll mode for this view. Valid over-scroll modes are
15649     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15650     * (allow over-scrolling only if the view content is larger than the container),
15651     * or {@link #OVER_SCROLL_NEVER}.
15652     *
15653     * Setting the over-scroll mode of a view will have an effect only if the
15654     * view is capable of scrolling.
15655     *
15656     * @param overScrollMode The new over-scroll mode for this view.
15657     */
15658    public void setOverScrollMode(int overScrollMode) {
15659        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15660                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15661                overScrollMode != OVER_SCROLL_NEVER) {
15662            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15663        }
15664        mOverScrollMode = overScrollMode;
15665    }
15666
15667    /**
15668     * Gets a scale factor that determines the distance the view should scroll
15669     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15670     * @return The vertical scroll scale factor.
15671     * @hide
15672     */
15673    protected float getVerticalScrollFactor() {
15674        if (mVerticalScrollFactor == 0) {
15675            TypedValue outValue = new TypedValue();
15676            if (!mContext.getTheme().resolveAttribute(
15677                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15678                throw new IllegalStateException(
15679                        "Expected theme to define listPreferredItemHeight.");
15680            }
15681            mVerticalScrollFactor = outValue.getDimension(
15682                    mContext.getResources().getDisplayMetrics());
15683        }
15684        return mVerticalScrollFactor;
15685    }
15686
15687    /**
15688     * Gets a scale factor that determines the distance the view should scroll
15689     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15690     * @return The horizontal scroll scale factor.
15691     * @hide
15692     */
15693    protected float getHorizontalScrollFactor() {
15694        // TODO: Should use something else.
15695        return getVerticalScrollFactor();
15696    }
15697
15698    /**
15699     * Return the value specifying the text direction or policy that was set with
15700     * {@link #setTextDirection(int)}.
15701     *
15702     * @return the defined text direction. It can be one of:
15703     *
15704     * {@link #TEXT_DIRECTION_INHERIT},
15705     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15706     * {@link #TEXT_DIRECTION_ANY_RTL},
15707     * {@link #TEXT_DIRECTION_LTR},
15708     * {@link #TEXT_DIRECTION_RTL},
15709     * {@link #TEXT_DIRECTION_LOCALE}
15710     */
15711    @ViewDebug.ExportedProperty(category = "text", mapping = {
15712            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15713            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15714            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15715            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15716            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15717            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15718    })
15719    public int getTextDirection() {
15720        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15721    }
15722
15723    /**
15724     * Set the text direction.
15725     *
15726     * @param textDirection the direction to set. Should be one of:
15727     *
15728     * {@link #TEXT_DIRECTION_INHERIT},
15729     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15730     * {@link #TEXT_DIRECTION_ANY_RTL},
15731     * {@link #TEXT_DIRECTION_LTR},
15732     * {@link #TEXT_DIRECTION_RTL},
15733     * {@link #TEXT_DIRECTION_LOCALE}
15734     */
15735    public void setTextDirection(int textDirection) {
15736        if (getTextDirection() != textDirection) {
15737            // Reset the current text direction and the resolved one
15738            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
15739            resetResolvedTextDirection();
15740            // Set the new text direction
15741            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
15742            // Refresh
15743            requestLayout();
15744            invalidate(true);
15745        }
15746    }
15747
15748    /**
15749     * Return the resolved text direction.
15750     *
15751     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
15752     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
15753     * up the parent chain of the view. if there is no parent, then it will return the default
15754     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
15755     *
15756     * @return the resolved text direction. Returns one of:
15757     *
15758     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15759     * {@link #TEXT_DIRECTION_ANY_RTL},
15760     * {@link #TEXT_DIRECTION_LTR},
15761     * {@link #TEXT_DIRECTION_RTL},
15762     * {@link #TEXT_DIRECTION_LOCALE}
15763     */
15764    public int getResolvedTextDirection() {
15765        // The text direction will be resolved only if needed
15766        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
15767            resolveTextDirection();
15768        }
15769        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
15770    }
15771
15772    /**
15773     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
15774     * resolution is done.
15775     */
15776    public void resolveTextDirection() {
15777        // Reset any previous text direction resolution
15778        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15779
15780        if (hasRtlSupport()) {
15781            // Set resolved text direction flag depending on text direction flag
15782            final int textDirection = getTextDirection();
15783            switch(textDirection) {
15784                case TEXT_DIRECTION_INHERIT:
15785                    if (canResolveTextDirection()) {
15786                        ViewGroup viewGroup = ((ViewGroup) mParent);
15787
15788                        // Set current resolved direction to the same value as the parent's one
15789                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
15790                        switch (parentResolvedDirection) {
15791                            case TEXT_DIRECTION_FIRST_STRONG:
15792                            case TEXT_DIRECTION_ANY_RTL:
15793                            case TEXT_DIRECTION_LTR:
15794                            case TEXT_DIRECTION_RTL:
15795                            case TEXT_DIRECTION_LOCALE:
15796                                mPrivateFlags2 |=
15797                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15798                                break;
15799                            default:
15800                                // Default resolved direction is "first strong" heuristic
15801                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15802                        }
15803                    } else {
15804                        // We cannot do the resolution if there is no parent, so use the default one
15805                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15806                    }
15807                    break;
15808                case TEXT_DIRECTION_FIRST_STRONG:
15809                case TEXT_DIRECTION_ANY_RTL:
15810                case TEXT_DIRECTION_LTR:
15811                case TEXT_DIRECTION_RTL:
15812                case TEXT_DIRECTION_LOCALE:
15813                    // Resolved direction is the same as text direction
15814                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15815                    break;
15816                default:
15817                    // Default resolved direction is "first strong" heuristic
15818                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15819            }
15820        } else {
15821            // Default resolved direction is "first strong" heuristic
15822            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15823        }
15824
15825        // Set to resolved
15826        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
15827        onResolvedTextDirectionChanged();
15828    }
15829
15830    /**
15831     * Called when text direction has been resolved. Subclasses that care about text direction
15832     * resolution should override this method.
15833     *
15834     * The default implementation does nothing.
15835     */
15836    public void onResolvedTextDirectionChanged() {
15837    }
15838
15839    /**
15840     * Check if text direction resolution can be done.
15841     *
15842     * @return true if text direction resolution can be done otherwise return false.
15843     */
15844    public boolean canResolveTextDirection() {
15845        switch (getTextDirection()) {
15846            case TEXT_DIRECTION_INHERIT:
15847                return (mParent != null) && (mParent instanceof ViewGroup);
15848            default:
15849                return true;
15850        }
15851    }
15852
15853    /**
15854     * Reset resolved text direction. Text direction can be resolved with a call to
15855     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
15856     * reset is done.
15857     */
15858    public void resetResolvedTextDirection() {
15859        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15860        onResolvedTextDirectionReset();
15861    }
15862
15863    /**
15864     * Called when text direction is reset. Subclasses that care about text direction reset should
15865     * override this method and do a reset of the text direction of their children. The default
15866     * implementation does nothing.
15867     */
15868    public void onResolvedTextDirectionReset() {
15869    }
15870
15871    /**
15872     * Return the value specifying the text alignment or policy that was set with
15873     * {@link #setTextAlignment(int)}.
15874     *
15875     * @return the defined text alignment. It can be one of:
15876     *
15877     * {@link #TEXT_ALIGNMENT_INHERIT},
15878     * {@link #TEXT_ALIGNMENT_GRAVITY},
15879     * {@link #TEXT_ALIGNMENT_CENTER},
15880     * {@link #TEXT_ALIGNMENT_TEXT_START},
15881     * {@link #TEXT_ALIGNMENT_TEXT_END},
15882     * {@link #TEXT_ALIGNMENT_VIEW_START},
15883     * {@link #TEXT_ALIGNMENT_VIEW_END}
15884     */
15885    @ViewDebug.ExportedProperty(category = "text", mapping = {
15886            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15887            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15888            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15889            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15890            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15891            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15892            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15893    })
15894    public int getTextAlignment() {
15895        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
15896    }
15897
15898    /**
15899     * Set the text alignment.
15900     *
15901     * @param textAlignment The text alignment to set. Should be one of
15902     *
15903     * {@link #TEXT_ALIGNMENT_INHERIT},
15904     * {@link #TEXT_ALIGNMENT_GRAVITY},
15905     * {@link #TEXT_ALIGNMENT_CENTER},
15906     * {@link #TEXT_ALIGNMENT_TEXT_START},
15907     * {@link #TEXT_ALIGNMENT_TEXT_END},
15908     * {@link #TEXT_ALIGNMENT_VIEW_START},
15909     * {@link #TEXT_ALIGNMENT_VIEW_END}
15910     *
15911     * @attr ref android.R.styleable#View_textAlignment
15912     */
15913    public void setTextAlignment(int textAlignment) {
15914        if (textAlignment != getTextAlignment()) {
15915            // Reset the current and resolved text alignment
15916            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
15917            resetResolvedTextAlignment();
15918            // Set the new text alignment
15919            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
15920            // Refresh
15921            requestLayout();
15922            invalidate(true);
15923        }
15924    }
15925
15926    /**
15927     * Return the resolved text alignment.
15928     *
15929     * The resolved text alignment. This needs resolution if the value is
15930     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
15931     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
15932     *
15933     * @return the resolved text alignment. Returns one of:
15934     *
15935     * {@link #TEXT_ALIGNMENT_GRAVITY},
15936     * {@link #TEXT_ALIGNMENT_CENTER},
15937     * {@link #TEXT_ALIGNMENT_TEXT_START},
15938     * {@link #TEXT_ALIGNMENT_TEXT_END},
15939     * {@link #TEXT_ALIGNMENT_VIEW_START},
15940     * {@link #TEXT_ALIGNMENT_VIEW_END}
15941     */
15942    @ViewDebug.ExportedProperty(category = "text", mapping = {
15943            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15944            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15945            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15946            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15947            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15948            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15949            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15950    })
15951    public int getResolvedTextAlignment() {
15952        // If text alignment is not resolved, then resolve it
15953        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
15954            resolveTextAlignment();
15955        }
15956        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
15957    }
15958
15959    /**
15960     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
15961     * resolution is done.
15962     */
15963    public void resolveTextAlignment() {
15964        // Reset any previous text alignment resolution
15965        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
15966
15967        if (hasRtlSupport()) {
15968            // Set resolved text alignment flag depending on text alignment flag
15969            final int textAlignment = getTextAlignment();
15970            switch (textAlignment) {
15971                case TEXT_ALIGNMENT_INHERIT:
15972                    // Check if we can resolve the text alignment
15973                    if (canResolveLayoutDirection() && mParent instanceof View) {
15974                        View view = (View) mParent;
15975
15976                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
15977                        switch (parentResolvedTextAlignment) {
15978                            case TEXT_ALIGNMENT_GRAVITY:
15979                            case TEXT_ALIGNMENT_TEXT_START:
15980                            case TEXT_ALIGNMENT_TEXT_END:
15981                            case TEXT_ALIGNMENT_CENTER:
15982                            case TEXT_ALIGNMENT_VIEW_START:
15983                            case TEXT_ALIGNMENT_VIEW_END:
15984                                // Resolved text alignment is the same as the parent resolved
15985                                // text alignment
15986                                mPrivateFlags2 |=
15987                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
15988                                break;
15989                            default:
15990                                // Use default resolved text alignment
15991                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15992                        }
15993                    }
15994                    else {
15995                        // We cannot do the resolution if there is no parent so use the default
15996                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15997                    }
15998                    break;
15999                case TEXT_ALIGNMENT_GRAVITY:
16000                case TEXT_ALIGNMENT_TEXT_START:
16001                case TEXT_ALIGNMENT_TEXT_END:
16002                case TEXT_ALIGNMENT_CENTER:
16003                case TEXT_ALIGNMENT_VIEW_START:
16004                case TEXT_ALIGNMENT_VIEW_END:
16005                    // Resolved text alignment is the same as text alignment
16006                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16007                    break;
16008                default:
16009                    // Use default resolved text alignment
16010                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16011            }
16012        } else {
16013            // Use default resolved text alignment
16014            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16015        }
16016
16017        // Set the resolved
16018        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16019        onResolvedTextAlignmentChanged();
16020    }
16021
16022    /**
16023     * Check if text alignment resolution can be done.
16024     *
16025     * @return true if text alignment resolution can be done otherwise return false.
16026     */
16027    public boolean canResolveTextAlignment() {
16028        switch (getTextAlignment()) {
16029            case TEXT_DIRECTION_INHERIT:
16030                return (mParent != null);
16031            default:
16032                return true;
16033        }
16034    }
16035
16036    /**
16037     * Called when text alignment has been resolved. Subclasses that care about text alignment
16038     * resolution should override this method.
16039     *
16040     * The default implementation does nothing.
16041     */
16042    public void onResolvedTextAlignmentChanged() {
16043    }
16044
16045    /**
16046     * Reset resolved text alignment. Text alignment can be resolved with a call to
16047     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16048     * reset is done.
16049     */
16050    public void resetResolvedTextAlignment() {
16051        // Reset any previous text alignment resolution
16052        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16053        onResolvedTextAlignmentReset();
16054    }
16055
16056    /**
16057     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16058     * override this method and do a reset of the text alignment of their children. The default
16059     * implementation does nothing.
16060     */
16061    public void onResolvedTextAlignmentReset() {
16062    }
16063
16064    //
16065    // Properties
16066    //
16067    /**
16068     * A Property wrapper around the <code>alpha</code> functionality handled by the
16069     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16070     */
16071    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16072        @Override
16073        public void setValue(View object, float value) {
16074            object.setAlpha(value);
16075        }
16076
16077        @Override
16078        public Float get(View object) {
16079            return object.getAlpha();
16080        }
16081    };
16082
16083    /**
16084     * A Property wrapper around the <code>translationX</code> functionality handled by the
16085     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16086     */
16087    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16088        @Override
16089        public void setValue(View object, float value) {
16090            object.setTranslationX(value);
16091        }
16092
16093                @Override
16094        public Float get(View object) {
16095            return object.getTranslationX();
16096        }
16097    };
16098
16099    /**
16100     * A Property wrapper around the <code>translationY</code> functionality handled by the
16101     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16102     */
16103    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16104        @Override
16105        public void setValue(View object, float value) {
16106            object.setTranslationY(value);
16107        }
16108
16109        @Override
16110        public Float get(View object) {
16111            return object.getTranslationY();
16112        }
16113    };
16114
16115    /**
16116     * A Property wrapper around the <code>x</code> functionality handled by the
16117     * {@link View#setX(float)} and {@link View#getX()} methods.
16118     */
16119    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16120        @Override
16121        public void setValue(View object, float value) {
16122            object.setX(value);
16123        }
16124
16125        @Override
16126        public Float get(View object) {
16127            return object.getX();
16128        }
16129    };
16130
16131    /**
16132     * A Property wrapper around the <code>y</code> functionality handled by the
16133     * {@link View#setY(float)} and {@link View#getY()} methods.
16134     */
16135    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16136        @Override
16137        public void setValue(View object, float value) {
16138            object.setY(value);
16139        }
16140
16141        @Override
16142        public Float get(View object) {
16143            return object.getY();
16144        }
16145    };
16146
16147    /**
16148     * A Property wrapper around the <code>rotation</code> functionality handled by the
16149     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16150     */
16151    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16152        @Override
16153        public void setValue(View object, float value) {
16154            object.setRotation(value);
16155        }
16156
16157        @Override
16158        public Float get(View object) {
16159            return object.getRotation();
16160        }
16161    };
16162
16163    /**
16164     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16165     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16166     */
16167    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16168        @Override
16169        public void setValue(View object, float value) {
16170            object.setRotationX(value);
16171        }
16172
16173        @Override
16174        public Float get(View object) {
16175            return object.getRotationX();
16176        }
16177    };
16178
16179    /**
16180     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16181     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16182     */
16183    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16184        @Override
16185        public void setValue(View object, float value) {
16186            object.setRotationY(value);
16187        }
16188
16189        @Override
16190        public Float get(View object) {
16191            return object.getRotationY();
16192        }
16193    };
16194
16195    /**
16196     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16197     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16198     */
16199    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16200        @Override
16201        public void setValue(View object, float value) {
16202            object.setScaleX(value);
16203        }
16204
16205        @Override
16206        public Float get(View object) {
16207            return object.getScaleX();
16208        }
16209    };
16210
16211    /**
16212     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16213     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16214     */
16215    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16216        @Override
16217        public void setValue(View object, float value) {
16218            object.setScaleY(value);
16219        }
16220
16221        @Override
16222        public Float get(View object) {
16223            return object.getScaleY();
16224        }
16225    };
16226
16227    /**
16228     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16229     * Each MeasureSpec represents a requirement for either the width or the height.
16230     * A MeasureSpec is comprised of a size and a mode. There are three possible
16231     * modes:
16232     * <dl>
16233     * <dt>UNSPECIFIED</dt>
16234     * <dd>
16235     * The parent has not imposed any constraint on the child. It can be whatever size
16236     * it wants.
16237     * </dd>
16238     *
16239     * <dt>EXACTLY</dt>
16240     * <dd>
16241     * The parent has determined an exact size for the child. The child is going to be
16242     * given those bounds regardless of how big it wants to be.
16243     * </dd>
16244     *
16245     * <dt>AT_MOST</dt>
16246     * <dd>
16247     * The child can be as large as it wants up to the specified size.
16248     * </dd>
16249     * </dl>
16250     *
16251     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16252     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16253     */
16254    public static class MeasureSpec {
16255        private static final int MODE_SHIFT = 30;
16256        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16257
16258        /**
16259         * Measure specification mode: The parent has not imposed any constraint
16260         * on the child. It can be whatever size it wants.
16261         */
16262        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16263
16264        /**
16265         * Measure specification mode: The parent has determined an exact size
16266         * for the child. The child is going to be given those bounds regardless
16267         * of how big it wants to be.
16268         */
16269        public static final int EXACTLY     = 1 << MODE_SHIFT;
16270
16271        /**
16272         * Measure specification mode: The child can be as large as it wants up
16273         * to the specified size.
16274         */
16275        public static final int AT_MOST     = 2 << MODE_SHIFT;
16276
16277        /**
16278         * Creates a measure specification based on the supplied size and mode.
16279         *
16280         * The mode must always be one of the following:
16281         * <ul>
16282         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16283         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16284         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16285         * </ul>
16286         *
16287         * @param size the size of the measure specification
16288         * @param mode the mode of the measure specification
16289         * @return the measure specification based on size and mode
16290         */
16291        public static int makeMeasureSpec(int size, int mode) {
16292            return size + mode;
16293        }
16294
16295        /**
16296         * Extracts the mode from the supplied measure specification.
16297         *
16298         * @param measureSpec the measure specification to extract the mode from
16299         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16300         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16301         *         {@link android.view.View.MeasureSpec#EXACTLY}
16302         */
16303        public static int getMode(int measureSpec) {
16304            return (measureSpec & MODE_MASK);
16305        }
16306
16307        /**
16308         * Extracts the size from the supplied measure specification.
16309         *
16310         * @param measureSpec the measure specification to extract the size from
16311         * @return the size in pixels defined in the supplied measure specification
16312         */
16313        public static int getSize(int measureSpec) {
16314            return (measureSpec & ~MODE_MASK);
16315        }
16316
16317        /**
16318         * Returns a String representation of the specified measure
16319         * specification.
16320         *
16321         * @param measureSpec the measure specification to convert to a String
16322         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16323         */
16324        public static String toString(int measureSpec) {
16325            int mode = getMode(measureSpec);
16326            int size = getSize(measureSpec);
16327
16328            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16329
16330            if (mode == UNSPECIFIED)
16331                sb.append("UNSPECIFIED ");
16332            else if (mode == EXACTLY)
16333                sb.append("EXACTLY ");
16334            else if (mode == AT_MOST)
16335                sb.append("AT_MOST ");
16336            else
16337                sb.append(mode).append(" ");
16338
16339            sb.append(size);
16340            return sb.toString();
16341        }
16342    }
16343
16344    class CheckForLongPress implements Runnable {
16345
16346        private int mOriginalWindowAttachCount;
16347
16348        public void run() {
16349            if (isPressed() && (mParent != null)
16350                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16351                if (performLongClick()) {
16352                    mHasPerformedLongPress = true;
16353                }
16354            }
16355        }
16356
16357        public void rememberWindowAttachCount() {
16358            mOriginalWindowAttachCount = mWindowAttachCount;
16359        }
16360    }
16361
16362    private final class CheckForTap implements Runnable {
16363        public void run() {
16364            mPrivateFlags &= ~PREPRESSED;
16365            setPressed(true);
16366            checkForLongClick(ViewConfiguration.getTapTimeout());
16367        }
16368    }
16369
16370    private final class PerformClick implements Runnable {
16371        public void run() {
16372            performClick();
16373        }
16374    }
16375
16376    /** @hide */
16377    public void hackTurnOffWindowResizeAnim(boolean off) {
16378        mAttachInfo.mTurnOffWindowResizeAnim = off;
16379    }
16380
16381    /**
16382     * This method returns a ViewPropertyAnimator object, which can be used to animate
16383     * specific properties on this View.
16384     *
16385     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16386     */
16387    public ViewPropertyAnimator animate() {
16388        if (mAnimator == null) {
16389            mAnimator = new ViewPropertyAnimator(this);
16390        }
16391        return mAnimator;
16392    }
16393
16394    /**
16395     * Interface definition for a callback to be invoked when a key event is
16396     * dispatched to this view. The callback will be invoked before the key
16397     * event is given to the view.
16398     */
16399    public interface OnKeyListener {
16400        /**
16401         * Called when a key is dispatched to a view. This allows listeners to
16402         * get a chance to respond before the target view.
16403         *
16404         * @param v The view the key has been dispatched to.
16405         * @param keyCode The code for the physical key that was pressed
16406         * @param event The KeyEvent object containing full information about
16407         *        the event.
16408         * @return True if the listener has consumed the event, false otherwise.
16409         */
16410        boolean onKey(View v, int keyCode, KeyEvent event);
16411    }
16412
16413    /**
16414     * Interface definition for a callback to be invoked when a touch event is
16415     * dispatched to this view. The callback will be invoked before the touch
16416     * event is given to the view.
16417     */
16418    public interface OnTouchListener {
16419        /**
16420         * Called when a touch event is dispatched to a view. This allows listeners to
16421         * get a chance to respond before the target view.
16422         *
16423         * @param v The view the touch event has been dispatched to.
16424         * @param event The MotionEvent object containing full information about
16425         *        the event.
16426         * @return True if the listener has consumed the event, false otherwise.
16427         */
16428        boolean onTouch(View v, MotionEvent event);
16429    }
16430
16431    /**
16432     * Interface definition for a callback to be invoked when a hover event is
16433     * dispatched to this view. The callback will be invoked before the hover
16434     * event is given to the view.
16435     */
16436    public interface OnHoverListener {
16437        /**
16438         * Called when a hover event is dispatched to a view. This allows listeners to
16439         * get a chance to respond before the target view.
16440         *
16441         * @param v The view the hover event has been dispatched to.
16442         * @param event The MotionEvent object containing full information about
16443         *        the event.
16444         * @return True if the listener has consumed the event, false otherwise.
16445         */
16446        boolean onHover(View v, MotionEvent event);
16447    }
16448
16449    /**
16450     * Interface definition for a callback to be invoked when a generic motion event is
16451     * dispatched to this view. The callback will be invoked before the generic motion
16452     * event is given to the view.
16453     */
16454    public interface OnGenericMotionListener {
16455        /**
16456         * Called when a generic motion event is dispatched to a view. This allows listeners to
16457         * get a chance to respond before the target view.
16458         *
16459         * @param v The view the generic motion event has been dispatched to.
16460         * @param event The MotionEvent object containing full information about
16461         *        the event.
16462         * @return True if the listener has consumed the event, false otherwise.
16463         */
16464        boolean onGenericMotion(View v, MotionEvent event);
16465    }
16466
16467    /**
16468     * Interface definition for a callback to be invoked when a view has been clicked and held.
16469     */
16470    public interface OnLongClickListener {
16471        /**
16472         * Called when a view has been clicked and held.
16473         *
16474         * @param v The view that was clicked and held.
16475         *
16476         * @return true if the callback consumed the long click, false otherwise.
16477         */
16478        boolean onLongClick(View v);
16479    }
16480
16481    /**
16482     * Interface definition for a callback to be invoked when a drag is being dispatched
16483     * to this view.  The callback will be invoked before the hosting view's own
16484     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16485     * onDrag(event) behavior, it should return 'false' from this callback.
16486     *
16487     * <div class="special reference">
16488     * <h3>Developer Guides</h3>
16489     * <p>For a guide to implementing drag and drop features, read the
16490     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16491     * </div>
16492     */
16493    public interface OnDragListener {
16494        /**
16495         * Called when a drag event is dispatched to a view. This allows listeners
16496         * to get a chance to override base View behavior.
16497         *
16498         * @param v The View that received the drag event.
16499         * @param event The {@link android.view.DragEvent} object for the drag event.
16500         * @return {@code true} if the drag event was handled successfully, or {@code false}
16501         * if the drag event was not handled. Note that {@code false} will trigger the View
16502         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16503         */
16504        boolean onDrag(View v, DragEvent event);
16505    }
16506
16507    /**
16508     * Interface definition for a callback to be invoked when the focus state of
16509     * a view changed.
16510     */
16511    public interface OnFocusChangeListener {
16512        /**
16513         * Called when the focus state of a view has changed.
16514         *
16515         * @param v The view whose state has changed.
16516         * @param hasFocus The new focus state of v.
16517         */
16518        void onFocusChange(View v, boolean hasFocus);
16519    }
16520
16521    /**
16522     * Interface definition for a callback to be invoked when a view is clicked.
16523     */
16524    public interface OnClickListener {
16525        /**
16526         * Called when a view has been clicked.
16527         *
16528         * @param v The view that was clicked.
16529         */
16530        void onClick(View v);
16531    }
16532
16533    /**
16534     * Interface definition for a callback to be invoked when the context menu
16535     * for this view is being built.
16536     */
16537    public interface OnCreateContextMenuListener {
16538        /**
16539         * Called when the context menu for this view is being built. It is not
16540         * safe to hold onto the menu after this method returns.
16541         *
16542         * @param menu The context menu that is being built
16543         * @param v The view for which the context menu is being built
16544         * @param menuInfo Extra information about the item for which the
16545         *            context menu should be shown. This information will vary
16546         *            depending on the class of v.
16547         */
16548        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16549    }
16550
16551    /**
16552     * Interface definition for a callback to be invoked when the status bar changes
16553     * visibility.  This reports <strong>global</strong> changes to the system UI
16554     * state, not just what the application is requesting.
16555     *
16556     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16557     */
16558    public interface OnSystemUiVisibilityChangeListener {
16559        /**
16560         * Called when the status bar changes visibility because of a call to
16561         * {@link View#setSystemUiVisibility(int)}.
16562         *
16563         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16564         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16565         * <strong>global</strong> state of the UI visibility flags, not what your
16566         * app is currently applying.
16567         */
16568        public void onSystemUiVisibilityChange(int visibility);
16569    }
16570
16571    /**
16572     * Interface definition for a callback to be invoked when this view is attached
16573     * or detached from its window.
16574     */
16575    public interface OnAttachStateChangeListener {
16576        /**
16577         * Called when the view is attached to a window.
16578         * @param v The view that was attached
16579         */
16580        public void onViewAttachedToWindow(View v);
16581        /**
16582         * Called when the view is detached from a window.
16583         * @param v The view that was detached
16584         */
16585        public void onViewDetachedFromWindow(View v);
16586    }
16587
16588    private final class UnsetPressedState implements Runnable {
16589        public void run() {
16590            setPressed(false);
16591        }
16592    }
16593
16594    /**
16595     * Base class for derived classes that want to save and restore their own
16596     * state in {@link android.view.View#onSaveInstanceState()}.
16597     */
16598    public static class BaseSavedState extends AbsSavedState {
16599        /**
16600         * Constructor used when reading from a parcel. Reads the state of the superclass.
16601         *
16602         * @param source
16603         */
16604        public BaseSavedState(Parcel source) {
16605            super(source);
16606        }
16607
16608        /**
16609         * Constructor called by derived classes when creating their SavedState objects
16610         *
16611         * @param superState The state of the superclass of this view
16612         */
16613        public BaseSavedState(Parcelable superState) {
16614            super(superState);
16615        }
16616
16617        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16618                new Parcelable.Creator<BaseSavedState>() {
16619            public BaseSavedState createFromParcel(Parcel in) {
16620                return new BaseSavedState(in);
16621            }
16622
16623            public BaseSavedState[] newArray(int size) {
16624                return new BaseSavedState[size];
16625            }
16626        };
16627    }
16628
16629    /**
16630     * A set of information given to a view when it is attached to its parent
16631     * window.
16632     */
16633    static class AttachInfo {
16634        interface Callbacks {
16635            void playSoundEffect(int effectId);
16636            boolean performHapticFeedback(int effectId, boolean always);
16637        }
16638
16639        /**
16640         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16641         * to a Handler. This class contains the target (View) to invalidate and
16642         * the coordinates of the dirty rectangle.
16643         *
16644         * For performance purposes, this class also implements a pool of up to
16645         * POOL_LIMIT objects that get reused. This reduces memory allocations
16646         * whenever possible.
16647         */
16648        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16649            private static final int POOL_LIMIT = 10;
16650            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16651                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16652                        public InvalidateInfo newInstance() {
16653                            return new InvalidateInfo();
16654                        }
16655
16656                        public void onAcquired(InvalidateInfo element) {
16657                        }
16658
16659                        public void onReleased(InvalidateInfo element) {
16660                            element.target = null;
16661                        }
16662                    }, POOL_LIMIT)
16663            );
16664
16665            private InvalidateInfo mNext;
16666            private boolean mIsPooled;
16667
16668            View target;
16669
16670            int left;
16671            int top;
16672            int right;
16673            int bottom;
16674
16675            public void setNextPoolable(InvalidateInfo element) {
16676                mNext = element;
16677            }
16678
16679            public InvalidateInfo getNextPoolable() {
16680                return mNext;
16681            }
16682
16683            static InvalidateInfo acquire() {
16684                return sPool.acquire();
16685            }
16686
16687            void release() {
16688                sPool.release(this);
16689            }
16690
16691            public boolean isPooled() {
16692                return mIsPooled;
16693            }
16694
16695            public void setPooled(boolean isPooled) {
16696                mIsPooled = isPooled;
16697            }
16698        }
16699
16700        final IWindowSession mSession;
16701
16702        final IWindow mWindow;
16703
16704        final IBinder mWindowToken;
16705
16706        final Callbacks mRootCallbacks;
16707
16708        HardwareCanvas mHardwareCanvas;
16709
16710        /**
16711         * The top view of the hierarchy.
16712         */
16713        View mRootView;
16714
16715        IBinder mPanelParentWindowToken;
16716        Surface mSurface;
16717
16718        boolean mHardwareAccelerated;
16719        boolean mHardwareAccelerationRequested;
16720        HardwareRenderer mHardwareRenderer;
16721
16722        boolean mScreenOn;
16723
16724        /**
16725         * Scale factor used by the compatibility mode
16726         */
16727        float mApplicationScale;
16728
16729        /**
16730         * Indicates whether the application is in compatibility mode
16731         */
16732        boolean mScalingRequired;
16733
16734        /**
16735         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
16736         */
16737        boolean mTurnOffWindowResizeAnim;
16738
16739        /**
16740         * Left position of this view's window
16741         */
16742        int mWindowLeft;
16743
16744        /**
16745         * Top position of this view's window
16746         */
16747        int mWindowTop;
16748
16749        /**
16750         * Indicates whether views need to use 32-bit drawing caches
16751         */
16752        boolean mUse32BitDrawingCache;
16753
16754        /**
16755         * For windows that are full-screen but using insets to layout inside
16756         * of the screen decorations, these are the current insets for the
16757         * content of the window.
16758         */
16759        final Rect mContentInsets = new Rect();
16760
16761        /**
16762         * For windows that are full-screen but using insets to layout inside
16763         * of the screen decorations, these are the current insets for the
16764         * actual visible parts of the window.
16765         */
16766        final Rect mVisibleInsets = new Rect();
16767
16768        /**
16769         * The internal insets given by this window.  This value is
16770         * supplied by the client (through
16771         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
16772         * be given to the window manager when changed to be used in laying
16773         * out windows behind it.
16774         */
16775        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
16776                = new ViewTreeObserver.InternalInsetsInfo();
16777
16778        /**
16779         * All views in the window's hierarchy that serve as scroll containers,
16780         * used to determine if the window can be resized or must be panned
16781         * to adjust for a soft input area.
16782         */
16783        final ArrayList<View> mScrollContainers = new ArrayList<View>();
16784
16785        final KeyEvent.DispatcherState mKeyDispatchState
16786                = new KeyEvent.DispatcherState();
16787
16788        /**
16789         * Indicates whether the view's window currently has the focus.
16790         */
16791        boolean mHasWindowFocus;
16792
16793        /**
16794         * The current visibility of the window.
16795         */
16796        int mWindowVisibility;
16797
16798        /**
16799         * Indicates the time at which drawing started to occur.
16800         */
16801        long mDrawingTime;
16802
16803        /**
16804         * Indicates whether or not ignoring the DIRTY_MASK flags.
16805         */
16806        boolean mIgnoreDirtyState;
16807
16808        /**
16809         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
16810         * to avoid clearing that flag prematurely.
16811         */
16812        boolean mSetIgnoreDirtyState = false;
16813
16814        /**
16815         * Indicates whether the view's window is currently in touch mode.
16816         */
16817        boolean mInTouchMode;
16818
16819        /**
16820         * Indicates that ViewAncestor should trigger a global layout change
16821         * the next time it performs a traversal
16822         */
16823        boolean mRecomputeGlobalAttributes;
16824
16825        /**
16826         * Always report new attributes at next traversal.
16827         */
16828        boolean mForceReportNewAttributes;
16829
16830        /**
16831         * Set during a traveral if any views want to keep the screen on.
16832         */
16833        boolean mKeepScreenOn;
16834
16835        /**
16836         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
16837         */
16838        int mSystemUiVisibility;
16839
16840        /**
16841         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
16842         * attached.
16843         */
16844        boolean mHasSystemUiListeners;
16845
16846        /**
16847         * Set if the visibility of any views has changed.
16848         */
16849        boolean mViewVisibilityChanged;
16850
16851        /**
16852         * Set to true if a view has been scrolled.
16853         */
16854        boolean mViewScrollChanged;
16855
16856        /**
16857         * Global to the view hierarchy used as a temporary for dealing with
16858         * x/y points in the transparent region computations.
16859         */
16860        final int[] mTransparentLocation = new int[2];
16861
16862        /**
16863         * Global to the view hierarchy used as a temporary for dealing with
16864         * x/y points in the ViewGroup.invalidateChild implementation.
16865         */
16866        final int[] mInvalidateChildLocation = new int[2];
16867
16868
16869        /**
16870         * Global to the view hierarchy used as a temporary for dealing with
16871         * x/y location when view is transformed.
16872         */
16873        final float[] mTmpTransformLocation = new float[2];
16874
16875        /**
16876         * The view tree observer used to dispatch global events like
16877         * layout, pre-draw, touch mode change, etc.
16878         */
16879        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
16880
16881        /**
16882         * A Canvas used by the view hierarchy to perform bitmap caching.
16883         */
16884        Canvas mCanvas;
16885
16886        /**
16887         * The view root impl.
16888         */
16889        final ViewRootImpl mViewRootImpl;
16890
16891        /**
16892         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
16893         * handler can be used to pump events in the UI events queue.
16894         */
16895        final Handler mHandler;
16896
16897        /**
16898         * Temporary for use in computing invalidate rectangles while
16899         * calling up the hierarchy.
16900         */
16901        final Rect mTmpInvalRect = new Rect();
16902
16903        /**
16904         * Temporary for use in computing hit areas with transformed views
16905         */
16906        final RectF mTmpTransformRect = new RectF();
16907
16908        /**
16909         * Temporary list for use in collecting focusable descendents of a view.
16910         */
16911        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
16912
16913        /**
16914         * The id of the window for accessibility purposes.
16915         */
16916        int mAccessibilityWindowId = View.NO_ID;
16917
16918        /**
16919         * Whether to ingore not exposed for accessibility Views when
16920         * reporting the view tree to accessibility services.
16921         */
16922        boolean mIncludeNotImportantViews;
16923
16924        /**
16925         * The drawable for highlighting accessibility focus.
16926         */
16927        Drawable mAccessibilityFocusDrawable;
16928
16929        /**
16930         * Show where the margins, bounds and layout bounds are for each view.
16931         */
16932        final boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
16933
16934        /**
16935         * Creates a new set of attachment information with the specified
16936         * events handler and thread.
16937         *
16938         * @param handler the events handler the view must use
16939         */
16940        AttachInfo(IWindowSession session, IWindow window,
16941                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
16942            mSession = session;
16943            mWindow = window;
16944            mWindowToken = window.asBinder();
16945            mViewRootImpl = viewRootImpl;
16946            mHandler = handler;
16947            mRootCallbacks = effectPlayer;
16948        }
16949    }
16950
16951    /**
16952     * <p>ScrollabilityCache holds various fields used by a View when scrolling
16953     * is supported. This avoids keeping too many unused fields in most
16954     * instances of View.</p>
16955     */
16956    private static class ScrollabilityCache implements Runnable {
16957
16958        /**
16959         * Scrollbars are not visible
16960         */
16961        public static final int OFF = 0;
16962
16963        /**
16964         * Scrollbars are visible
16965         */
16966        public static final int ON = 1;
16967
16968        /**
16969         * Scrollbars are fading away
16970         */
16971        public static final int FADING = 2;
16972
16973        public boolean fadeScrollBars;
16974
16975        public int fadingEdgeLength;
16976        public int scrollBarDefaultDelayBeforeFade;
16977        public int scrollBarFadeDuration;
16978
16979        public int scrollBarSize;
16980        public ScrollBarDrawable scrollBar;
16981        public float[] interpolatorValues;
16982        public View host;
16983
16984        public final Paint paint;
16985        public final Matrix matrix;
16986        public Shader shader;
16987
16988        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
16989
16990        private static final float[] OPAQUE = { 255 };
16991        private static final float[] TRANSPARENT = { 0.0f };
16992
16993        /**
16994         * When fading should start. This time moves into the future every time
16995         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
16996         */
16997        public long fadeStartTime;
16998
16999
17000        /**
17001         * The current state of the scrollbars: ON, OFF, or FADING
17002         */
17003        public int state = OFF;
17004
17005        private int mLastColor;
17006
17007        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17008            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17009            scrollBarSize = configuration.getScaledScrollBarSize();
17010            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17011            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17012
17013            paint = new Paint();
17014            matrix = new Matrix();
17015            // use use a height of 1, and then wack the matrix each time we
17016            // actually use it.
17017            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17018
17019            paint.setShader(shader);
17020            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17021            this.host = host;
17022        }
17023
17024        public void setFadeColor(int color) {
17025            if (color != 0 && color != mLastColor) {
17026                mLastColor = color;
17027                color |= 0xFF000000;
17028
17029                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17030                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17031
17032                paint.setShader(shader);
17033                // Restore the default transfer mode (src_over)
17034                paint.setXfermode(null);
17035            }
17036        }
17037
17038        public void run() {
17039            long now = AnimationUtils.currentAnimationTimeMillis();
17040            if (now >= fadeStartTime) {
17041
17042                // the animation fades the scrollbars out by changing
17043                // the opacity (alpha) from fully opaque to fully
17044                // transparent
17045                int nextFrame = (int) now;
17046                int framesCount = 0;
17047
17048                Interpolator interpolator = scrollBarInterpolator;
17049
17050                // Start opaque
17051                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17052
17053                // End transparent
17054                nextFrame += scrollBarFadeDuration;
17055                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17056
17057                state = FADING;
17058
17059                // Kick off the fade animation
17060                host.invalidate(true);
17061            }
17062        }
17063    }
17064
17065    /**
17066     * Resuable callback for sending
17067     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17068     */
17069    private class SendViewScrolledAccessibilityEvent implements Runnable {
17070        public volatile boolean mIsPending;
17071
17072        public void run() {
17073            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17074            mIsPending = false;
17075        }
17076    }
17077
17078    /**
17079     * <p>
17080     * This class represents a delegate that can be registered in a {@link View}
17081     * to enhance accessibility support via composition rather via inheritance.
17082     * It is specifically targeted to widget developers that extend basic View
17083     * classes i.e. classes in package android.view, that would like their
17084     * applications to be backwards compatible.
17085     * </p>
17086     * <div class="special reference">
17087     * <h3>Developer Guides</h3>
17088     * <p>For more information about making applications accessible, read the
17089     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17090     * developer guide.</p>
17091     * </div>
17092     * <p>
17093     * A scenario in which a developer would like to use an accessibility delegate
17094     * is overriding a method introduced in a later API version then the minimal API
17095     * version supported by the application. For example, the method
17096     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17097     * in API version 4 when the accessibility APIs were first introduced. If a
17098     * developer would like his application to run on API version 4 devices (assuming
17099     * all other APIs used by the application are version 4 or lower) and take advantage
17100     * of this method, instead of overriding the method which would break the application's
17101     * backwards compatibility, he can override the corresponding method in this
17102     * delegate and register the delegate in the target View if the API version of
17103     * the system is high enough i.e. the API version is same or higher to the API
17104     * version that introduced
17105     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17106     * </p>
17107     * <p>
17108     * Here is an example implementation:
17109     * </p>
17110     * <code><pre><p>
17111     * if (Build.VERSION.SDK_INT >= 14) {
17112     *     // If the API version is equal of higher than the version in
17113     *     // which onInitializeAccessibilityNodeInfo was introduced we
17114     *     // register a delegate with a customized implementation.
17115     *     View view = findViewById(R.id.view_id);
17116     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17117     *         public void onInitializeAccessibilityNodeInfo(View host,
17118     *                 AccessibilityNodeInfo info) {
17119     *             // Let the default implementation populate the info.
17120     *             super.onInitializeAccessibilityNodeInfo(host, info);
17121     *             // Set some other information.
17122     *             info.setEnabled(host.isEnabled());
17123     *         }
17124     *     });
17125     * }
17126     * </code></pre></p>
17127     * <p>
17128     * This delegate contains methods that correspond to the accessibility methods
17129     * in View. If a delegate has been specified the implementation in View hands
17130     * off handling to the corresponding method in this delegate. The default
17131     * implementation the delegate methods behaves exactly as the corresponding
17132     * method in View for the case of no accessibility delegate been set. Hence,
17133     * to customize the behavior of a View method, clients can override only the
17134     * corresponding delegate method without altering the behavior of the rest
17135     * accessibility related methods of the host view.
17136     * </p>
17137     */
17138    public static class AccessibilityDelegate {
17139
17140        /**
17141         * Sends an accessibility event of the given type. If accessibility is not
17142         * enabled this method has no effect.
17143         * <p>
17144         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17145         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17146         * been set.
17147         * </p>
17148         *
17149         * @param host The View hosting the delegate.
17150         * @param eventType The type of the event to send.
17151         *
17152         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17153         */
17154        public void sendAccessibilityEvent(View host, int eventType) {
17155            host.sendAccessibilityEventInternal(eventType);
17156        }
17157
17158        /**
17159         * Sends an accessibility event. This method behaves exactly as
17160         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17161         * empty {@link AccessibilityEvent} and does not perform a check whether
17162         * accessibility is enabled.
17163         * <p>
17164         * The default implementation behaves as
17165         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17166         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17167         * the case of no accessibility delegate been set.
17168         * </p>
17169         *
17170         * @param host The View hosting the delegate.
17171         * @param event The event to send.
17172         *
17173         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17174         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17175         */
17176        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17177            host.sendAccessibilityEventUncheckedInternal(event);
17178        }
17179
17180        /**
17181         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17182         * to its children for adding their text content to the event.
17183         * <p>
17184         * The default implementation behaves as
17185         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17186         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17187         * the case of no accessibility delegate been set.
17188         * </p>
17189         *
17190         * @param host The View hosting the delegate.
17191         * @param event The event.
17192         * @return True if the event population was completed.
17193         *
17194         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17195         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17196         */
17197        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17198            return host.dispatchPopulateAccessibilityEventInternal(event);
17199        }
17200
17201        /**
17202         * Gives a chance to the host View to populate the accessibility event with its
17203         * text content.
17204         * <p>
17205         * The default implementation behaves as
17206         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17207         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17208         * the case of no accessibility delegate been set.
17209         * </p>
17210         *
17211         * @param host The View hosting the delegate.
17212         * @param event The accessibility event which to populate.
17213         *
17214         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17215         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17216         */
17217        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17218            host.onPopulateAccessibilityEventInternal(event);
17219        }
17220
17221        /**
17222         * Initializes an {@link AccessibilityEvent} with information about the
17223         * the host View which is the event source.
17224         * <p>
17225         * The default implementation behaves as
17226         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17227         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17228         * the case of no accessibility delegate been set.
17229         * </p>
17230         *
17231         * @param host The View hosting the delegate.
17232         * @param event The event to initialize.
17233         *
17234         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17235         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17236         */
17237        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17238            host.onInitializeAccessibilityEventInternal(event);
17239        }
17240
17241        /**
17242         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17243         * <p>
17244         * The default implementation behaves as
17245         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17246         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17247         * the case of no accessibility delegate been set.
17248         * </p>
17249         *
17250         * @param host The View hosting the delegate.
17251         * @param info The instance to initialize.
17252         *
17253         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17254         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17255         */
17256        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17257            host.onInitializeAccessibilityNodeInfoInternal(info);
17258        }
17259
17260        /**
17261         * Called when a child of the host View has requested sending an
17262         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17263         * to augment the event.
17264         * <p>
17265         * The default implementation behaves as
17266         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17267         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17268         * the case of no accessibility delegate been set.
17269         * </p>
17270         *
17271         * @param host The View hosting the delegate.
17272         * @param child The child which requests sending the event.
17273         * @param event The event to be sent.
17274         * @return True if the event should be sent
17275         *
17276         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17277         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17278         */
17279        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17280                AccessibilityEvent event) {
17281            return host.onRequestSendAccessibilityEventInternal(child, event);
17282        }
17283
17284        /**
17285         * Gets the provider for managing a virtual view hierarchy rooted at this View
17286         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17287         * that explore the window content.
17288         * <p>
17289         * The default implementation behaves as
17290         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17291         * the case of no accessibility delegate been set.
17292         * </p>
17293         *
17294         * @return The provider.
17295         *
17296         * @see AccessibilityNodeProvider
17297         */
17298        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17299            return null;
17300        }
17301    }
17302}
17303