View.java revision b2b15716d8b5b5814e82575a592e76f522f6a4c6
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     * Used to mark a View that has no ID.
652     */
653    public static final int NO_ID = -1;
654
655    /**
656     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
657     * calling setFlags.
658     */
659    private static final int NOT_FOCUSABLE = 0x00000000;
660
661    /**
662     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
663     * setFlags.
664     */
665    private static final int FOCUSABLE = 0x00000001;
666
667    /**
668     * Mask for use with setFlags indicating bits used for focus.
669     */
670    private static final int FOCUSABLE_MASK = 0x00000001;
671
672    /**
673     * This view will adjust its padding to fit sytem windows (e.g. status bar)
674     */
675    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
676
677    /**
678     * This view is visible.
679     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
680     * android:visibility}.
681     */
682    public static final int VISIBLE = 0x00000000;
683
684    /**
685     * This view is invisible, but it still takes up space for layout purposes.
686     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
687     * android:visibility}.
688     */
689    public static final int INVISIBLE = 0x00000004;
690
691    /**
692     * This view is invisible, and it doesn't take any space for layout
693     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
694     * android:visibility}.
695     */
696    public static final int GONE = 0x00000008;
697
698    /**
699     * Mask for use with setFlags indicating bits used for visibility.
700     * {@hide}
701     */
702    static final int VISIBILITY_MASK = 0x0000000C;
703
704    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
705
706    /**
707     * This view is enabled. Interpretation varies by subclass.
708     * Use with ENABLED_MASK when calling setFlags.
709     * {@hide}
710     */
711    static final int ENABLED = 0x00000000;
712
713    /**
714     * This view is disabled. Interpretation varies by subclass.
715     * Use with ENABLED_MASK when calling setFlags.
716     * {@hide}
717     */
718    static final int DISABLED = 0x00000020;
719
720   /**
721    * Mask for use with setFlags indicating bits used for indicating whether
722    * this view is enabled
723    * {@hide}
724    */
725    static final int ENABLED_MASK = 0x00000020;
726
727    /**
728     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
729     * called and further optimizations will be performed. It is okay to have
730     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
731     * {@hide}
732     */
733    static final int WILL_NOT_DRAW = 0x00000080;
734
735    /**
736     * Mask for use with setFlags indicating bits used for indicating whether
737     * this view is will draw
738     * {@hide}
739     */
740    static final int DRAW_MASK = 0x00000080;
741
742    /**
743     * <p>This view doesn't show scrollbars.</p>
744     * {@hide}
745     */
746    static final int SCROLLBARS_NONE = 0x00000000;
747
748    /**
749     * <p>This view shows horizontal scrollbars.</p>
750     * {@hide}
751     */
752    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
753
754    /**
755     * <p>This view shows vertical scrollbars.</p>
756     * {@hide}
757     */
758    static final int SCROLLBARS_VERTICAL = 0x00000200;
759
760    /**
761     * <p>Mask for use with setFlags indicating bits used for indicating which
762     * scrollbars are enabled.</p>
763     * {@hide}
764     */
765    static final int SCROLLBARS_MASK = 0x00000300;
766
767    /**
768     * Indicates that the view should filter touches when its window is obscured.
769     * Refer to the class comments for more information about this security feature.
770     * {@hide}
771     */
772    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
773
774    /**
775     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
776     * that they are optional and should be skipped if the window has
777     * requested system UI flags that ignore those insets for layout.
778     */
779    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
780
781    /**
782     * <p>This view doesn't show fading edges.</p>
783     * {@hide}
784     */
785    static final int FADING_EDGE_NONE = 0x00000000;
786
787    /**
788     * <p>This view shows horizontal fading edges.</p>
789     * {@hide}
790     */
791    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
792
793    /**
794     * <p>This view shows vertical fading edges.</p>
795     * {@hide}
796     */
797    static final int FADING_EDGE_VERTICAL = 0x00002000;
798
799    /**
800     * <p>Mask for use with setFlags indicating bits used for indicating which
801     * fading edges are enabled.</p>
802     * {@hide}
803     */
804    static final int FADING_EDGE_MASK = 0x00003000;
805
806    /**
807     * <p>Indicates this view can be clicked. When clickable, a View reacts
808     * to clicks by notifying the OnClickListener.<p>
809     * {@hide}
810     */
811    static final int CLICKABLE = 0x00004000;
812
813    /**
814     * <p>Indicates this view is caching its drawing into a bitmap.</p>
815     * {@hide}
816     */
817    static final int DRAWING_CACHE_ENABLED = 0x00008000;
818
819    /**
820     * <p>Indicates that no icicle should be saved for this view.<p>
821     * {@hide}
822     */
823    static final int SAVE_DISABLED = 0x000010000;
824
825    /**
826     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
827     * property.</p>
828     * {@hide}
829     */
830    static final int SAVE_DISABLED_MASK = 0x000010000;
831
832    /**
833     * <p>Indicates that no drawing cache should ever be created for this view.<p>
834     * {@hide}
835     */
836    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
837
838    /**
839     * <p>Indicates this view can take / keep focus when int touch mode.</p>
840     * {@hide}
841     */
842    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
843
844    /**
845     * <p>Enables low quality mode for the drawing cache.</p>
846     */
847    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
848
849    /**
850     * <p>Enables high quality mode for the drawing cache.</p>
851     */
852    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
853
854    /**
855     * <p>Enables automatic quality mode for the drawing cache.</p>
856     */
857    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
858
859    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
860            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
861    };
862
863    /**
864     * <p>Mask for use with setFlags indicating bits used for the cache
865     * quality property.</p>
866     * {@hide}
867     */
868    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
869
870    /**
871     * <p>
872     * Indicates this view can be long clicked. When long clickable, a View
873     * reacts to long clicks by notifying the OnLongClickListener or showing a
874     * context menu.
875     * </p>
876     * {@hide}
877     */
878    static final int LONG_CLICKABLE = 0x00200000;
879
880    /**
881     * <p>Indicates that this view gets its drawable states from its direct parent
882     * and ignores its original internal states.</p>
883     *
884     * @hide
885     */
886    static final int DUPLICATE_PARENT_STATE = 0x00400000;
887
888    /**
889     * The scrollbar style to display the scrollbars inside the content area,
890     * without increasing the padding. The scrollbars will be overlaid with
891     * translucency on the view's content.
892     */
893    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
894
895    /**
896     * The scrollbar style to display the scrollbars inside the padded area,
897     * increasing the padding of the view. The scrollbars will not overlap the
898     * content area of the view.
899     */
900    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
901
902    /**
903     * The scrollbar style to display the scrollbars at the edge of the view,
904     * without increasing the padding. The scrollbars will be overlaid with
905     * translucency.
906     */
907    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
908
909    /**
910     * The scrollbar style to display the scrollbars at the edge of the view,
911     * increasing the padding of the view. The scrollbars will only overlap the
912     * background, if any.
913     */
914    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
915
916    /**
917     * Mask to check if the scrollbar style is overlay or inset.
918     * {@hide}
919     */
920    static final int SCROLLBARS_INSET_MASK = 0x01000000;
921
922    /**
923     * Mask to check if the scrollbar style is inside or outside.
924     * {@hide}
925     */
926    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
927
928    /**
929     * Mask for scrollbar style.
930     * {@hide}
931     */
932    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
933
934    /**
935     * View flag indicating that the screen should remain on while the
936     * window containing this view is visible to the user.  This effectively
937     * takes care of automatically setting the WindowManager's
938     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
939     */
940    public static final int KEEP_SCREEN_ON = 0x04000000;
941
942    /**
943     * View flag indicating whether this view should have sound effects enabled
944     * for events such as clicking and touching.
945     */
946    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
947
948    /**
949     * View flag indicating whether this view should have haptic feedback
950     * enabled for events such as long presses.
951     */
952    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
953
954    /**
955     * <p>Indicates that the view hierarchy should stop saving state when
956     * it reaches this view.  If state saving is initiated immediately at
957     * the view, it will be allowed.
958     * {@hide}
959     */
960    static final int PARENT_SAVE_DISABLED = 0x20000000;
961
962    /**
963     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
964     * {@hide}
965     */
966    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
967
968    /**
969     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
970     * should add all focusable Views regardless if they are focusable in touch mode.
971     */
972    public static final int FOCUSABLES_ALL = 0x00000000;
973
974    /**
975     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
976     * should add only Views focusable in touch mode.
977     */
978    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
979
980    /**
981     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
982     * should add only accessibility focusable Views.
983     *
984     * @hide
985     */
986    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
987
988    /**
989     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
990     * item.
991     */
992    public static final int FOCUS_BACKWARD = 0x00000001;
993
994    /**
995     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
996     * item.
997     */
998    public static final int FOCUS_FORWARD = 0x00000002;
999
1000    /**
1001     * Use with {@link #focusSearch(int)}. Move focus to the left.
1002     */
1003    public static final int FOCUS_LEFT = 0x00000011;
1004
1005    /**
1006     * Use with {@link #focusSearch(int)}. Move focus up.
1007     */
1008    public static final int FOCUS_UP = 0x00000021;
1009
1010    /**
1011     * Use with {@link #focusSearch(int)}. Move focus to the right.
1012     */
1013    public static final int FOCUS_RIGHT = 0x00000042;
1014
1015    /**
1016     * Use with {@link #focusSearch(int)}. Move focus down.
1017     */
1018    public static final int FOCUS_DOWN = 0x00000082;
1019
1020    // Accessibility focus directions.
1021
1022    /**
1023     * The accessibility focus which is the current user position when
1024     * interacting with the accessibility framework.
1025     */
1026    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1027
1028    /**
1029     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1030     */
1031    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1032
1033    /**
1034     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1035     */
1036    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1037
1038    /**
1039     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1040     */
1041    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1042
1043    /**
1044     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1045     */
1046    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1050     */
1051    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1052
1053    /**
1054     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1055     */
1056    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1057
1058    /**
1059     * Use with {@link #focusSearch(int)}. Move acessibility focus in a view.
1060     */
1061    public static final int ACCESSIBILITY_FOCUS_IN = 0x00000004 | FOCUS_ACCESSIBILITY;
1062
1063    /**
1064     * Use with {@link #focusSearch(int)}. Move acessibility focus out of a view.
1065     */
1066    public static final int ACCESSIBILITY_FOCUS_OUT = 0x00000008 | FOCUS_ACCESSIBILITY;
1067
1068    /**
1069     * Use with {@link #focusSearch(int)}. Move acessibility focus to the next view.
1070     */
1071    public static final int ACCESSIBILITY_FOCUS_NEXT = 0x00000010 | FOCUS_ACCESSIBILITY;
1072
1073    /**
1074     * Use with {@link #focusSearch(int)}. Move acessibility focus to the previous view.
1075     */
1076    public static final int ACCESSIBILITY_FOCUS_PREVIOUS = 0x00000020 | FOCUS_ACCESSIBILITY;
1077
1078    /**
1079     * Bits of {@link #getMeasuredWidthAndState()} and
1080     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1081     */
1082    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1083
1084    /**
1085     * Bits of {@link #getMeasuredWidthAndState()} and
1086     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1087     */
1088    public static final int MEASURED_STATE_MASK = 0xff000000;
1089
1090    /**
1091     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1092     * for functions that combine both width and height into a single int,
1093     * such as {@link #getMeasuredState()} and the childState argument of
1094     * {@link #resolveSizeAndState(int, int, int)}.
1095     */
1096    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1097
1098    /**
1099     * Bit of {@link #getMeasuredWidthAndState()} and
1100     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1101     * is smaller that the space the view would like to have.
1102     */
1103    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1104
1105    /**
1106     * Base View state sets
1107     */
1108    // Singles
1109    /**
1110     * Indicates the view has no states set. States are used with
1111     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1112     * view depending on its state.
1113     *
1114     * @see android.graphics.drawable.Drawable
1115     * @see #getDrawableState()
1116     */
1117    protected static final int[] EMPTY_STATE_SET;
1118    /**
1119     * Indicates the view is enabled. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     */
1126    protected static final int[] ENABLED_STATE_SET;
1127    /**
1128     * Indicates the view is focused. States are used with
1129     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1130     * view depending on its state.
1131     *
1132     * @see android.graphics.drawable.Drawable
1133     * @see #getDrawableState()
1134     */
1135    protected static final int[] FOCUSED_STATE_SET;
1136    /**
1137     * Indicates the view is selected. States are used with
1138     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1139     * view depending on its state.
1140     *
1141     * @see android.graphics.drawable.Drawable
1142     * @see #getDrawableState()
1143     */
1144    protected static final int[] SELECTED_STATE_SET;
1145    /**
1146     * Indicates the view is pressed. States are used with
1147     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1148     * view depending on its state.
1149     *
1150     * @see android.graphics.drawable.Drawable
1151     * @see #getDrawableState()
1152     * @hide
1153     */
1154    protected static final int[] PRESSED_STATE_SET;
1155    /**
1156     * Indicates the view's window has focus. States are used with
1157     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1158     * view depending on its state.
1159     *
1160     * @see android.graphics.drawable.Drawable
1161     * @see #getDrawableState()
1162     */
1163    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1164    // Doubles
1165    /**
1166     * Indicates the view is enabled and has the focus.
1167     *
1168     * @see #ENABLED_STATE_SET
1169     * @see #FOCUSED_STATE_SET
1170     */
1171    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1172    /**
1173     * Indicates the view is enabled and selected.
1174     *
1175     * @see #ENABLED_STATE_SET
1176     * @see #SELECTED_STATE_SET
1177     */
1178    protected static final int[] ENABLED_SELECTED_STATE_SET;
1179    /**
1180     * Indicates the view is enabled and that its window has focus.
1181     *
1182     * @see #ENABLED_STATE_SET
1183     * @see #WINDOW_FOCUSED_STATE_SET
1184     */
1185    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1186    /**
1187     * Indicates the view is focused and selected.
1188     *
1189     * @see #FOCUSED_STATE_SET
1190     * @see #SELECTED_STATE_SET
1191     */
1192    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1193    /**
1194     * Indicates the view has the focus and that its window has the focus.
1195     *
1196     * @see #FOCUSED_STATE_SET
1197     * @see #WINDOW_FOCUSED_STATE_SET
1198     */
1199    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1200    /**
1201     * Indicates the view is selected and that its window has the focus.
1202     *
1203     * @see #SELECTED_STATE_SET
1204     * @see #WINDOW_FOCUSED_STATE_SET
1205     */
1206    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1207    // Triples
1208    /**
1209     * Indicates the view is enabled, focused and selected.
1210     *
1211     * @see #ENABLED_STATE_SET
1212     * @see #FOCUSED_STATE_SET
1213     * @see #SELECTED_STATE_SET
1214     */
1215    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1216    /**
1217     * Indicates the view is enabled, focused and its window has the focus.
1218     *
1219     * @see #ENABLED_STATE_SET
1220     * @see #FOCUSED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is enabled, selected and its window has the focus.
1226     *
1227     * @see #ENABLED_STATE_SET
1228     * @see #SELECTED_STATE_SET
1229     * @see #WINDOW_FOCUSED_STATE_SET
1230     */
1231    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1232    /**
1233     * Indicates the view is focused, selected and its window has the focus.
1234     *
1235     * @see #FOCUSED_STATE_SET
1236     * @see #SELECTED_STATE_SET
1237     * @see #WINDOW_FOCUSED_STATE_SET
1238     */
1239    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1240    /**
1241     * Indicates the view is enabled, focused, selected and its window
1242     * has the focus.
1243     *
1244     * @see #ENABLED_STATE_SET
1245     * @see #FOCUSED_STATE_SET
1246     * @see #SELECTED_STATE_SET
1247     * @see #WINDOW_FOCUSED_STATE_SET
1248     */
1249    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is pressed and its window has the focus.
1252     *
1253     * @see #PRESSED_STATE_SET
1254     * @see #WINDOW_FOCUSED_STATE_SET
1255     */
1256    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1257    /**
1258     * Indicates the view is pressed and selected.
1259     *
1260     * @see #PRESSED_STATE_SET
1261     * @see #SELECTED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_SELECTED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, selected and its window has the focus.
1266     *
1267     * @see #PRESSED_STATE_SET
1268     * @see #SELECTED_STATE_SET
1269     * @see #WINDOW_FOCUSED_STATE_SET
1270     */
1271    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1272    /**
1273     * Indicates the view is pressed and focused.
1274     *
1275     * @see #PRESSED_STATE_SET
1276     * @see #FOCUSED_STATE_SET
1277     */
1278    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1279    /**
1280     * Indicates the view is pressed, focused and its window has the focus.
1281     *
1282     * @see #PRESSED_STATE_SET
1283     * @see #FOCUSED_STATE_SET
1284     * @see #WINDOW_FOCUSED_STATE_SET
1285     */
1286    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1287    /**
1288     * Indicates the view is pressed, focused and selected.
1289     *
1290     * @see #PRESSED_STATE_SET
1291     * @see #SELECTED_STATE_SET
1292     * @see #FOCUSED_STATE_SET
1293     */
1294    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1295    /**
1296     * Indicates the view is pressed, focused, selected and its window has the focus.
1297     *
1298     * @see #PRESSED_STATE_SET
1299     * @see #FOCUSED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #WINDOW_FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed and enabled.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #ENABLED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and its window has the focus.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #WINDOW_FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled and selected.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #ENABLED_STATE_SET
1324     * @see #SELECTED_STATE_SET
1325     */
1326    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1327    /**
1328     * Indicates the view is pressed, enabled, selected and its window has the
1329     * focus.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #WINDOW_FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, enabled and focused.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #ENABLED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     */
1344    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1345    /**
1346     * Indicates the view is pressed, enabled, focused and its window has the
1347     * focus.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #ENABLED_STATE_SET
1351     * @see #FOCUSED_STATE_SET
1352     * @see #WINDOW_FOCUSED_STATE_SET
1353     */
1354    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1355    /**
1356     * Indicates the view is pressed, enabled, focused and selected.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #ENABLED_STATE_SET
1360     * @see #SELECTED_STATE_SET
1361     * @see #FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled, focused, selected and its window
1366     * has the focus.
1367     *
1368     * @see #PRESSED_STATE_SET
1369     * @see #ENABLED_STATE_SET
1370     * @see #SELECTED_STATE_SET
1371     * @see #FOCUSED_STATE_SET
1372     * @see #WINDOW_FOCUSED_STATE_SET
1373     */
1374    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1375
1376    /**
1377     * The order here is very important to {@link #getDrawableState()}
1378     */
1379    private static final int[][] VIEW_STATE_SETS;
1380
1381    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1382    static final int VIEW_STATE_SELECTED = 1 << 1;
1383    static final int VIEW_STATE_FOCUSED = 1 << 2;
1384    static final int VIEW_STATE_ENABLED = 1 << 3;
1385    static final int VIEW_STATE_PRESSED = 1 << 4;
1386    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1387    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1388    static final int VIEW_STATE_HOVERED = 1 << 7;
1389    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1390    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1391
1392    static final int[] VIEW_STATE_IDS = new int[] {
1393        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1394        R.attr.state_selected,          VIEW_STATE_SELECTED,
1395        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1396        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1397        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1398        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1399        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1400        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1401        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1402        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1403    };
1404
1405    static {
1406        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1407            throw new IllegalStateException(
1408                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1409        }
1410        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1411        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1412            int viewState = R.styleable.ViewDrawableStates[i];
1413            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1414                if (VIEW_STATE_IDS[j] == viewState) {
1415                    orderedIds[i * 2] = viewState;
1416                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1417                }
1418            }
1419        }
1420        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1421        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1422        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1423            int numBits = Integer.bitCount(i);
1424            int[] set = new int[numBits];
1425            int pos = 0;
1426            for (int j = 0; j < orderedIds.length; j += 2) {
1427                if ((i & orderedIds[j+1]) != 0) {
1428                    set[pos++] = orderedIds[j];
1429                }
1430            }
1431            VIEW_STATE_SETS[i] = set;
1432        }
1433
1434        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1435        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1436        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1437        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1439        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1440        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1441                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1442        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1444        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1446                | VIEW_STATE_FOCUSED];
1447        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1448        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1450        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1452        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1454                | VIEW_STATE_ENABLED];
1455        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1457        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1459                | VIEW_STATE_ENABLED];
1460        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1462                | VIEW_STATE_ENABLED];
1463        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1465                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1466
1467        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1468        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1470        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1472        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_PRESSED];
1475        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1477        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_PRESSED];
1480        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1482                | VIEW_STATE_PRESSED];
1483        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1484                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1485                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1486        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1488        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1490                | VIEW_STATE_PRESSED];
1491        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1493                | VIEW_STATE_PRESSED];
1494        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1495                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1496                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1497        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1499                | VIEW_STATE_PRESSED];
1500        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1502                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1503        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1505                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1506        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1508                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1509                | VIEW_STATE_PRESSED];
1510    }
1511
1512    /**
1513     * Accessibility event types that are dispatched for text population.
1514     */
1515    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1516            AccessibilityEvent.TYPE_VIEW_CLICKED
1517            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1518            | AccessibilityEvent.TYPE_VIEW_SELECTED
1519            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1520            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1521            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1522            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1523            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1524            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1525            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
1526
1527    /**
1528     * Temporary Rect currently for use in setBackground().  This will probably
1529     * be extended in the future to hold our own class with more than just
1530     * a Rect. :)
1531     */
1532    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1533
1534    /**
1535     * Map used to store views' tags.
1536     */
1537    private SparseArray<Object> mKeyedTags;
1538
1539    /**
1540     * The next available accessiiblity id.
1541     */
1542    private static int sNextAccessibilityViewId;
1543
1544    /**
1545     * The animation currently associated with this view.
1546     * @hide
1547     */
1548    protected Animation mCurrentAnimation = null;
1549
1550    /**
1551     * Width as measured during measure pass.
1552     * {@hide}
1553     */
1554    @ViewDebug.ExportedProperty(category = "measurement")
1555    int mMeasuredWidth;
1556
1557    /**
1558     * Height as measured during measure pass.
1559     * {@hide}
1560     */
1561    @ViewDebug.ExportedProperty(category = "measurement")
1562    int mMeasuredHeight;
1563
1564    /**
1565     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1566     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1567     * its display list. This flag, used only when hw accelerated, allows us to clear the
1568     * flag while retaining this information until it's needed (at getDisplayList() time and
1569     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1570     *
1571     * {@hide}
1572     */
1573    boolean mRecreateDisplayList = false;
1574
1575    /**
1576     * The view's identifier.
1577     * {@hide}
1578     *
1579     * @see #setId(int)
1580     * @see #getId()
1581     */
1582    @ViewDebug.ExportedProperty(resolveId = true)
1583    int mID = NO_ID;
1584
1585    /**
1586     * The stable ID of this view for accessibility purposes.
1587     */
1588    int mAccessibilityViewId = NO_ID;
1589
1590    /**
1591     * The view's tag.
1592     * {@hide}
1593     *
1594     * @see #setTag(Object)
1595     * @see #getTag()
1596     */
1597    protected Object mTag;
1598
1599    // for mPrivateFlags:
1600    /** {@hide} */
1601    static final int WANTS_FOCUS                    = 0x00000001;
1602    /** {@hide} */
1603    static final int FOCUSED                        = 0x00000002;
1604    /** {@hide} */
1605    static final int SELECTED                       = 0x00000004;
1606    /** {@hide} */
1607    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1608    /** {@hide} */
1609    static final int HAS_BOUNDS                     = 0x00000010;
1610    /** {@hide} */
1611    static final int DRAWN                          = 0x00000020;
1612    /**
1613     * When this flag is set, this view is running an animation on behalf of its
1614     * children and should therefore not cancel invalidate requests, even if they
1615     * lie outside of this view's bounds.
1616     *
1617     * {@hide}
1618     */
1619    static final int DRAW_ANIMATION                 = 0x00000040;
1620    /** {@hide} */
1621    static final int SKIP_DRAW                      = 0x00000080;
1622    /** {@hide} */
1623    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1624    /** {@hide} */
1625    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1626    /** {@hide} */
1627    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1628    /** {@hide} */
1629    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1630    /** {@hide} */
1631    static final int FORCE_LAYOUT                   = 0x00001000;
1632    /** {@hide} */
1633    static final int LAYOUT_REQUIRED                = 0x00002000;
1634
1635    private static final int PRESSED                = 0x00004000;
1636
1637    /** {@hide} */
1638    static final int DRAWING_CACHE_VALID            = 0x00008000;
1639    /**
1640     * Flag used to indicate that this view should be drawn once more (and only once
1641     * more) after its animation has completed.
1642     * {@hide}
1643     */
1644    static final int ANIMATION_STARTED              = 0x00010000;
1645
1646    private static final int SAVE_STATE_CALLED      = 0x00020000;
1647
1648    /**
1649     * Indicates that the View returned true when onSetAlpha() was called and that
1650     * the alpha must be restored.
1651     * {@hide}
1652     */
1653    static final int ALPHA_SET                      = 0x00040000;
1654
1655    /**
1656     * Set by {@link #setScrollContainer(boolean)}.
1657     */
1658    static final int SCROLL_CONTAINER               = 0x00080000;
1659
1660    /**
1661     * Set by {@link #setScrollContainer(boolean)}.
1662     */
1663    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1664
1665    /**
1666     * View flag indicating whether this view was invalidated (fully or partially.)
1667     *
1668     * @hide
1669     */
1670    static final int DIRTY                          = 0x00200000;
1671
1672    /**
1673     * View flag indicating whether this view was invalidated by an opaque
1674     * invalidate request.
1675     *
1676     * @hide
1677     */
1678    static final int DIRTY_OPAQUE                   = 0x00400000;
1679
1680    /**
1681     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1682     *
1683     * @hide
1684     */
1685    static final int DIRTY_MASK                     = 0x00600000;
1686
1687    /**
1688     * Indicates whether the background is opaque.
1689     *
1690     * @hide
1691     */
1692    static final int OPAQUE_BACKGROUND              = 0x00800000;
1693
1694    /**
1695     * Indicates whether the scrollbars are opaque.
1696     *
1697     * @hide
1698     */
1699    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1700
1701    /**
1702     * Indicates whether the view is opaque.
1703     *
1704     * @hide
1705     */
1706    static final int OPAQUE_MASK                    = 0x01800000;
1707
1708    /**
1709     * Indicates a prepressed state;
1710     * the short time between ACTION_DOWN and recognizing
1711     * a 'real' press. Prepressed is used to recognize quick taps
1712     * even when they are shorter than ViewConfiguration.getTapTimeout().
1713     *
1714     * @hide
1715     */
1716    private static final int PREPRESSED             = 0x02000000;
1717
1718    /**
1719     * Indicates whether the view is temporarily detached.
1720     *
1721     * @hide
1722     */
1723    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1724
1725    /**
1726     * Indicates that we should awaken scroll bars once attached
1727     *
1728     * @hide
1729     */
1730    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1731
1732    /**
1733     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1734     * @hide
1735     */
1736    private static final int HOVERED              = 0x10000000;
1737
1738    /**
1739     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1740     * for transform operations
1741     *
1742     * @hide
1743     */
1744    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1745
1746    /** {@hide} */
1747    static final int ACTIVATED                    = 0x40000000;
1748
1749    /**
1750     * Indicates that this view was specifically invalidated, not just dirtied because some
1751     * child view was invalidated. The flag is used to determine when we need to recreate
1752     * a view's display list (as opposed to just returning a reference to its existing
1753     * display list).
1754     *
1755     * @hide
1756     */
1757    static final int INVALIDATED                  = 0x80000000;
1758
1759    /* Masks for mPrivateFlags2 */
1760
1761    /**
1762     * Indicates that this view has reported that it can accept the current drag's content.
1763     * Cleared when the drag operation concludes.
1764     * @hide
1765     */
1766    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1767
1768    /**
1769     * Indicates that this view is currently directly under the drag location in a
1770     * drag-and-drop operation involving content that it can accept.  Cleared when
1771     * the drag exits the view, or when the drag operation concludes.
1772     * @hide
1773     */
1774    static final int DRAG_HOVERED                 = 0x00000002;
1775
1776    /**
1777     * Horizontal layout direction of this view is from Left to Right.
1778     * Use with {@link #setLayoutDirection}.
1779     */
1780    public static final int LAYOUT_DIRECTION_LTR = 0;
1781
1782    /**
1783     * Horizontal layout direction of this view is from Right to Left.
1784     * Use with {@link #setLayoutDirection}.
1785     */
1786    public static final int LAYOUT_DIRECTION_RTL = 1;
1787
1788    /**
1789     * Horizontal layout direction of this view is inherited from its parent.
1790     * Use with {@link #setLayoutDirection}.
1791     */
1792    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1793
1794    /**
1795     * Horizontal layout direction of this view is from deduced from the default language
1796     * script for the locale. Use with {@link #setLayoutDirection}.
1797     */
1798    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1799
1800    /**
1801     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1802     * @hide
1803     */
1804    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1805
1806    /**
1807     * Mask for use with private flags indicating bits used for horizontal layout direction.
1808     * @hide
1809     */
1810    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1811
1812    /**
1813     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1814     * right-to-left direction.
1815     * @hide
1816     */
1817    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1818
1819    /**
1820     * Indicates whether the view horizontal layout direction has been resolved.
1821     * @hide
1822     */
1823    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1824
1825    /**
1826     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1827     * @hide
1828     */
1829    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1830
1831    /*
1832     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1833     * flag value.
1834     * @hide
1835     */
1836    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1837            LAYOUT_DIRECTION_LTR,
1838            LAYOUT_DIRECTION_RTL,
1839            LAYOUT_DIRECTION_INHERIT,
1840            LAYOUT_DIRECTION_LOCALE
1841    };
1842
1843    /**
1844     * Default horizontal layout direction.
1845     * @hide
1846     */
1847    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1848
1849    /**
1850     * Indicates that the view is tracking some sort of transient state
1851     * that the app should not need to be aware of, but that the framework
1852     * should take special care to preserve.
1853     *
1854     * @hide
1855     */
1856    static final int HAS_TRANSIENT_STATE = 0x00000100;
1857
1858
1859    /**
1860     * Text direction is inherited thru {@link ViewGroup}
1861     */
1862    public static final int TEXT_DIRECTION_INHERIT = 0;
1863
1864    /**
1865     * Text direction is using "first strong algorithm". The first strong directional character
1866     * determines the paragraph direction. If there is no strong directional character, the
1867     * paragraph direction is the view's resolved layout direction.
1868     */
1869    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1870
1871    /**
1872     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1873     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1874     * If there are neither, the paragraph direction is the view's resolved layout direction.
1875     */
1876    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1877
1878    /**
1879     * Text direction is forced to LTR.
1880     */
1881    public static final int TEXT_DIRECTION_LTR = 3;
1882
1883    /**
1884     * Text direction is forced to RTL.
1885     */
1886    public static final int TEXT_DIRECTION_RTL = 4;
1887
1888    /**
1889     * Text direction is coming from the system Locale.
1890     */
1891    public static final int TEXT_DIRECTION_LOCALE = 5;
1892
1893    /**
1894     * Default text direction is inherited
1895     */
1896    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1897
1898    /**
1899     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1900     * @hide
1901     */
1902    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1903
1904    /**
1905     * Mask for use with private flags indicating bits used for text direction.
1906     * @hide
1907     */
1908    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1909
1910    /**
1911     * Array of text direction flags for mapping attribute "textDirection" to correct
1912     * flag value.
1913     * @hide
1914     */
1915    private static final int[] TEXT_DIRECTION_FLAGS = {
1916            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1917            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1918            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1919            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1920            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1921            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1922    };
1923
1924    /**
1925     * Indicates whether the view text direction has been resolved.
1926     * @hide
1927     */
1928    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1929
1930    /**
1931     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1932     * @hide
1933     */
1934    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1935
1936    /**
1937     * Mask for use with private flags indicating bits used for resolved text direction.
1938     * @hide
1939     */
1940    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1941
1942    /**
1943     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1944     * @hide
1945     */
1946    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1947            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1948
1949    /*
1950     * Default text alignment. The text alignment of this View is inherited from its parent.
1951     * Use with {@link #setTextAlignment(int)}
1952     */
1953    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1954
1955    /**
1956     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1957     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1958     *
1959     * Use with {@link #setTextAlignment(int)}
1960     */
1961    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1962
1963    /**
1964     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1965     *
1966     * Use with {@link #setTextAlignment(int)}
1967     */
1968    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1969
1970    /**
1971     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1972     *
1973     * Use with {@link #setTextAlignment(int)}
1974     */
1975    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1976
1977    /**
1978     * Center the paragraph, e.g. ALIGN_CENTER.
1979     *
1980     * Use with {@link #setTextAlignment(int)}
1981     */
1982    public static final int TEXT_ALIGNMENT_CENTER = 4;
1983
1984    /**
1985     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1986     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1987     *
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1991
1992    /**
1993     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1994     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1995     *
1996     * Use with {@link #setTextAlignment(int)}
1997     */
1998    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1999
2000    /**
2001     * Default text alignment is inherited
2002     */
2003    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2004
2005    /**
2006      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2007      * @hide
2008      */
2009    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2010
2011    /**
2012      * Mask for use with private flags indicating bits used for text alignment.
2013      * @hide
2014      */
2015    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2016
2017    /**
2018     * Array of text direction flags for mapping attribute "textAlignment" to correct
2019     * flag value.
2020     * @hide
2021     */
2022    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2023            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2024            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2025            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2026            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2027            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2028            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2029            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2030    };
2031
2032    /**
2033     * Indicates whether the view text alignment has been resolved.
2034     * @hide
2035     */
2036    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2037
2038    /**
2039     * Bit shift to get the resolved text alignment.
2040     * @hide
2041     */
2042    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2043
2044    /**
2045     * Mask for use with private flags indicating bits used for text alignment.
2046     * @hide
2047     */
2048    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2049
2050    /**
2051     * Indicates whether if the view text alignment has been resolved to gravity
2052     */
2053    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2054            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2055
2056    // Accessiblity constants for mPrivateFlags2
2057
2058    /**
2059     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2060     */
2061    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2062
2063    /**
2064     * Automatically determine whether a view is important for accessibility.
2065     */
2066    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2067
2068    /**
2069     * The view is important for accessibility.
2070     */
2071    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2072
2073    /**
2074     * The view is not important for accessibility.
2075     */
2076    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2077
2078    /**
2079     * The default whether the view is important for accessiblity.
2080     */
2081    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2082
2083    /**
2084     * Mask for obtainig the bits which specify how to determine
2085     * whether a view is important for accessibility.
2086     */
2087    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2088        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2089        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2090
2091    /**
2092     * Flag indicating whether a view has accessibility focus.
2093     */
2094    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2095
2096    /**
2097     * Flag indicating whether a view state for accessibility has changed.
2098     */
2099    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2100
2101    /* End of masks for mPrivateFlags2 */
2102
2103    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2104
2105    /**
2106     * Always allow a user to over-scroll this view, provided it is a
2107     * view that can scroll.
2108     *
2109     * @see #getOverScrollMode()
2110     * @see #setOverScrollMode(int)
2111     */
2112    public static final int OVER_SCROLL_ALWAYS = 0;
2113
2114    /**
2115     * Allow a user to over-scroll this view only if the content is large
2116     * enough to meaningfully scroll, provided it is a view that can scroll.
2117     *
2118     * @see #getOverScrollMode()
2119     * @see #setOverScrollMode(int)
2120     */
2121    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2122
2123    /**
2124     * Never allow a user to over-scroll this view.
2125     *
2126     * @see #getOverScrollMode()
2127     * @see #setOverScrollMode(int)
2128     */
2129    public static final int OVER_SCROLL_NEVER = 2;
2130
2131    /**
2132     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2133     * requested the system UI (status bar) to be visible (the default).
2134     *
2135     * @see #setSystemUiVisibility(int)
2136     */
2137    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2138
2139    /**
2140     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2141     * system UI to enter an unobtrusive "low profile" mode.
2142     *
2143     * <p>This is for use in games, book readers, video players, or any other
2144     * "immersive" application where the usual system chrome is deemed too distracting.
2145     *
2146     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2147     *
2148     * @see #setSystemUiVisibility(int)
2149     */
2150    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2151
2152    /**
2153     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2154     * system navigation be temporarily hidden.
2155     *
2156     * <p>This is an even less obtrusive state than that called for by
2157     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2158     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2159     * those to disappear. This is useful (in conjunction with the
2160     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2161     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2162     * window flags) for displaying content using every last pixel on the display.
2163     *
2164     * <p>There is a limitation: because navigation controls are so important, the least user
2165     * interaction will cause them to reappear immediately.  When this happens, both
2166     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2167     * so that both elements reappear at the same time.
2168     *
2169     * @see #setSystemUiVisibility(int)
2170     */
2171    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2172
2173    /**
2174     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2175     * into the normal fullscreen mode so that its content can take over the screen
2176     * while still allowing the user to interact with the application.
2177     *
2178     * <p>This has the same visual effect as
2179     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2180     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2181     * meaning that non-critical screen decorations (such as the status bar) will be
2182     * hidden while the user is in the View's window, focusing the experience on
2183     * that content.  Unlike the window flag, if you are using ActionBar in
2184     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2185     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2186     * hide the action bar.
2187     *
2188     * <p>This approach to going fullscreen is best used over the window flag when
2189     * it is a transient state -- that is, the application does this at certain
2190     * points in its user interaction where it wants to allow the user to focus
2191     * on content, but not as a continuous state.  For situations where the application
2192     * would like to simply stay full screen the entire time (such as a game that
2193     * wants to take over the screen), the
2194     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2195     * is usually a better approach.  The state set here will be removed by the system
2196     * in various situations (such as the user moving to another application) like
2197     * the other system UI states.
2198     *
2199     * <p>When using this flag, the application should provide some easy facility
2200     * for the user to go out of it.  A common example would be in an e-book
2201     * reader, where tapping on the screen brings back whatever screen and UI
2202     * decorations that had been hidden while the user was immersed in reading
2203     * the book.
2204     *
2205     * @see #setSystemUiVisibility(int)
2206     */
2207    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2208
2209    /**
2210     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2211     * flags, we would like a stable view of the content insets given to
2212     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2213     * will always represent the worst case that the application can expect
2214     * as a continue state.  In practice this means with any of system bar,
2215     * nav bar, and status bar shown, but not the space that would be needed
2216     * for an input method.
2217     *
2218     * <p>If you are using ActionBar in
2219     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2220     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2221     * insets it adds to those given to the application.
2222     */
2223    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2224
2225    /**
2226     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2227     * to be layed out as if it has requested
2228     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2229     * allows it to avoid artifacts when switching in and out of that mode, at
2230     * the expense that some of its user interface may be covered by screen
2231     * decorations when they are shown.  You can perform layout of your inner
2232     * UI elements to account for the navagation system UI through the
2233     * {@link #fitSystemWindows(Rect)} method.
2234     */
2235    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2236
2237    /**
2238     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2239     * to be layed out as if it has requested
2240     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2241     * allows it to avoid artifacts when switching in and out of that mode, at
2242     * the expense that some of its user interface may be covered by screen
2243     * decorations when they are shown.  You can perform layout of your inner
2244     * UI elements to account for non-fullscreen system UI through the
2245     * {@link #fitSystemWindows(Rect)} method.
2246     */
2247    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2248
2249    /**
2250     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2251     */
2252    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2253
2254    /**
2255     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2256     */
2257    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2258
2259    /**
2260     * @hide
2261     *
2262     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2263     * out of the public fields to keep the undefined bits out of the developer's way.
2264     *
2265     * Flag to make the status bar not expandable.  Unless you also
2266     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2267     */
2268    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2269
2270    /**
2271     * @hide
2272     *
2273     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2274     * out of the public fields to keep the undefined bits out of the developer's way.
2275     *
2276     * Flag to hide notification icons and scrolling ticker text.
2277     */
2278    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2279
2280    /**
2281     * @hide
2282     *
2283     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2284     * out of the public fields to keep the undefined bits out of the developer's way.
2285     *
2286     * Flag to disable incoming notification alerts.  This will not block
2287     * icons, but it will block sound, vibrating and other visual or aural notifications.
2288     */
2289    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2290
2291    /**
2292     * @hide
2293     *
2294     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2295     * out of the public fields to keep the undefined bits out of the developer's way.
2296     *
2297     * Flag to hide only the scrolling ticker.  Note that
2298     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2299     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2300     */
2301    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2302
2303    /**
2304     * @hide
2305     *
2306     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2307     * out of the public fields to keep the undefined bits out of the developer's way.
2308     *
2309     * Flag to hide the center system info area.
2310     */
2311    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2312
2313    /**
2314     * @hide
2315     *
2316     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2317     * out of the public fields to keep the undefined bits out of the developer's way.
2318     *
2319     * Flag to hide only the home button.  Don't use this
2320     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2321     */
2322    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2323
2324    /**
2325     * @hide
2326     *
2327     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2328     * out of the public fields to keep the undefined bits out of the developer's way.
2329     *
2330     * Flag to hide only the back button. Don't use this
2331     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2332     */
2333    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2334
2335    /**
2336     * @hide
2337     *
2338     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2339     * out of the public fields to keep the undefined bits out of the developer's way.
2340     *
2341     * Flag to hide only the clock.  You might use this if your activity has
2342     * its own clock making the status bar's clock redundant.
2343     */
2344    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2345
2346    /**
2347     * @hide
2348     *
2349     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2350     * out of the public fields to keep the undefined bits out of the developer's way.
2351     *
2352     * Flag to hide only the recent apps button. Don't use this
2353     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2354     */
2355    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2356
2357    /**
2358     * @hide
2359     */
2360    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2361
2362    /**
2363     * These are the system UI flags that can be cleared by events outside
2364     * of an application.  Currently this is just the ability to tap on the
2365     * screen while hiding the navigation bar to have it return.
2366     * @hide
2367     */
2368    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2369            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2370            | SYSTEM_UI_FLAG_FULLSCREEN;
2371
2372    /**
2373     * Flags that can impact the layout in relation to system UI.
2374     */
2375    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2376            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2377            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2378
2379    /**
2380     * Find views that render the specified text.
2381     *
2382     * @see #findViewsWithText(ArrayList, CharSequence, int)
2383     */
2384    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2385
2386    /**
2387     * Find find views that contain the specified content description.
2388     *
2389     * @see #findViewsWithText(ArrayList, CharSequence, int)
2390     */
2391    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2392
2393    /**
2394     * Find views that contain {@link AccessibilityNodeProvider}. Such
2395     * a View is a root of virtual view hierarchy and may contain the searched
2396     * text. If this flag is set Views with providers are automatically
2397     * added and it is a responsibility of the client to call the APIs of
2398     * the provider to determine whether the virtual tree rooted at this View
2399     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2400     * represeting the virtual views with this text.
2401     *
2402     * @see #findViewsWithText(ArrayList, CharSequence, int)
2403     *
2404     * @hide
2405     */
2406    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2407
2408    /**
2409     * Indicates that the screen has changed state and is now off.
2410     *
2411     * @see #onScreenStateChanged(int)
2412     */
2413    public static final int SCREEN_STATE_OFF = 0x0;
2414
2415    /**
2416     * Indicates that the screen has changed state and is now on.
2417     *
2418     * @see #onScreenStateChanged(int)
2419     */
2420    public static final int SCREEN_STATE_ON = 0x1;
2421
2422    /**
2423     * Controls the over-scroll mode for this view.
2424     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2425     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2426     * and {@link #OVER_SCROLL_NEVER}.
2427     */
2428    private int mOverScrollMode;
2429
2430    /**
2431     * The parent this view is attached to.
2432     * {@hide}
2433     *
2434     * @see #getParent()
2435     */
2436    protected ViewParent mParent;
2437
2438    /**
2439     * {@hide}
2440     */
2441    AttachInfo mAttachInfo;
2442
2443    /**
2444     * {@hide}
2445     */
2446    @ViewDebug.ExportedProperty(flagMapping = {
2447        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2448                name = "FORCE_LAYOUT"),
2449        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2450                name = "LAYOUT_REQUIRED"),
2451        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2452            name = "DRAWING_CACHE_INVALID", outputIf = false),
2453        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2454        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2455        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2456        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2457    })
2458    int mPrivateFlags;
2459    int mPrivateFlags2;
2460
2461    /**
2462     * This view's request for the visibility of the status bar.
2463     * @hide
2464     */
2465    @ViewDebug.ExportedProperty(flagMapping = {
2466        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2467                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2468                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2469        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2470                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2471                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2472        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2473                                equals = SYSTEM_UI_FLAG_VISIBLE,
2474                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2475    })
2476    int mSystemUiVisibility;
2477
2478    /**
2479     * Reference count for transient state.
2480     * @see #setHasTransientState(boolean)
2481     */
2482    int mTransientStateCount = 0;
2483
2484    /**
2485     * Count of how many windows this view has been attached to.
2486     */
2487    int mWindowAttachCount;
2488
2489    /**
2490     * The layout parameters associated with this view and used by the parent
2491     * {@link android.view.ViewGroup} to determine how this view should be
2492     * laid out.
2493     * {@hide}
2494     */
2495    protected ViewGroup.LayoutParams mLayoutParams;
2496
2497    /**
2498     * The view flags hold various views states.
2499     * {@hide}
2500     */
2501    @ViewDebug.ExportedProperty
2502    int mViewFlags;
2503
2504    static class TransformationInfo {
2505        /**
2506         * The transform matrix for the View. This transform is calculated internally
2507         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2508         * is used by default. Do *not* use this variable directly; instead call
2509         * getMatrix(), which will automatically recalculate the matrix if necessary
2510         * to get the correct matrix based on the latest rotation and scale properties.
2511         */
2512        private final Matrix mMatrix = new Matrix();
2513
2514        /**
2515         * The transform matrix for the View. This transform is calculated internally
2516         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2517         * is used by default. Do *not* use this variable directly; instead call
2518         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2519         * to get the correct matrix based on the latest rotation and scale properties.
2520         */
2521        private Matrix mInverseMatrix;
2522
2523        /**
2524         * An internal variable that tracks whether we need to recalculate the
2525         * transform matrix, based on whether the rotation or scaleX/Y properties
2526         * have changed since the matrix was last calculated.
2527         */
2528        boolean mMatrixDirty = false;
2529
2530        /**
2531         * An internal variable that tracks whether we need to recalculate the
2532         * transform matrix, based on whether the rotation or scaleX/Y properties
2533         * have changed since the matrix was last calculated.
2534         */
2535        private boolean mInverseMatrixDirty = true;
2536
2537        /**
2538         * A variable that tracks whether we need to recalculate the
2539         * transform matrix, based on whether the rotation or scaleX/Y properties
2540         * have changed since the matrix was last calculated. This variable
2541         * is only valid after a call to updateMatrix() or to a function that
2542         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2543         */
2544        private boolean mMatrixIsIdentity = true;
2545
2546        /**
2547         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2548         */
2549        private Camera mCamera = null;
2550
2551        /**
2552         * This matrix is used when computing the matrix for 3D rotations.
2553         */
2554        private Matrix matrix3D = null;
2555
2556        /**
2557         * These prev values are used to recalculate a centered pivot point when necessary. The
2558         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2559         * set), so thes values are only used then as well.
2560         */
2561        private int mPrevWidth = -1;
2562        private int mPrevHeight = -1;
2563
2564        /**
2565         * The degrees rotation around the vertical axis through the pivot point.
2566         */
2567        @ViewDebug.ExportedProperty
2568        float mRotationY = 0f;
2569
2570        /**
2571         * The degrees rotation around the horizontal axis through the pivot point.
2572         */
2573        @ViewDebug.ExportedProperty
2574        float mRotationX = 0f;
2575
2576        /**
2577         * The degrees rotation around the pivot point.
2578         */
2579        @ViewDebug.ExportedProperty
2580        float mRotation = 0f;
2581
2582        /**
2583         * The amount of translation of the object away from its left property (post-layout).
2584         */
2585        @ViewDebug.ExportedProperty
2586        float mTranslationX = 0f;
2587
2588        /**
2589         * The amount of translation of the object away from its top property (post-layout).
2590         */
2591        @ViewDebug.ExportedProperty
2592        float mTranslationY = 0f;
2593
2594        /**
2595         * The amount of scale in the x direction around the pivot point. A
2596         * value of 1 means no scaling is applied.
2597         */
2598        @ViewDebug.ExportedProperty
2599        float mScaleX = 1f;
2600
2601        /**
2602         * The amount of scale in the y direction around the pivot point. A
2603         * value of 1 means no scaling is applied.
2604         */
2605        @ViewDebug.ExportedProperty
2606        float mScaleY = 1f;
2607
2608        /**
2609         * The x location of the point around which the view is rotated and scaled.
2610         */
2611        @ViewDebug.ExportedProperty
2612        float mPivotX = 0f;
2613
2614        /**
2615         * The y location of the point around which the view is rotated and scaled.
2616         */
2617        @ViewDebug.ExportedProperty
2618        float mPivotY = 0f;
2619
2620        /**
2621         * The opacity of the View. This is a value from 0 to 1, where 0 means
2622         * completely transparent and 1 means completely opaque.
2623         */
2624        @ViewDebug.ExportedProperty
2625        float mAlpha = 1f;
2626    }
2627
2628    TransformationInfo mTransformationInfo;
2629
2630    private boolean mLastIsOpaque;
2631
2632    /**
2633     * Convenience value to check for float values that are close enough to zero to be considered
2634     * zero.
2635     */
2636    private static final float NONZERO_EPSILON = .001f;
2637
2638    /**
2639     * The distance in pixels from the left edge of this view's parent
2640     * to the left edge of this view.
2641     * {@hide}
2642     */
2643    @ViewDebug.ExportedProperty(category = "layout")
2644    protected int mLeft;
2645    /**
2646     * The distance in pixels from the left edge of this view's parent
2647     * to the right edge of this view.
2648     * {@hide}
2649     */
2650    @ViewDebug.ExportedProperty(category = "layout")
2651    protected int mRight;
2652    /**
2653     * The distance in pixels from the top edge of this view's parent
2654     * to the top edge of this view.
2655     * {@hide}
2656     */
2657    @ViewDebug.ExportedProperty(category = "layout")
2658    protected int mTop;
2659    /**
2660     * The distance in pixels from the top edge of this view's parent
2661     * to the bottom edge of this view.
2662     * {@hide}
2663     */
2664    @ViewDebug.ExportedProperty(category = "layout")
2665    protected int mBottom;
2666
2667    /**
2668     * The offset, in pixels, by which the content of this view is scrolled
2669     * horizontally.
2670     * {@hide}
2671     */
2672    @ViewDebug.ExportedProperty(category = "scrolling")
2673    protected int mScrollX;
2674    /**
2675     * The offset, in pixels, by which the content of this view is scrolled
2676     * vertically.
2677     * {@hide}
2678     */
2679    @ViewDebug.ExportedProperty(category = "scrolling")
2680    protected int mScrollY;
2681
2682    /**
2683     * The left padding in pixels, that is the distance in pixels between the
2684     * left edge of this view and the left edge of its content.
2685     * {@hide}
2686     */
2687    @ViewDebug.ExportedProperty(category = "padding")
2688    protected int mPaddingLeft;
2689    /**
2690     * The right padding in pixels, that is the distance in pixels between the
2691     * right edge of this view and the right edge of its content.
2692     * {@hide}
2693     */
2694    @ViewDebug.ExportedProperty(category = "padding")
2695    protected int mPaddingRight;
2696    /**
2697     * The top padding in pixels, that is the distance in pixels between the
2698     * top edge of this view and the top edge of its content.
2699     * {@hide}
2700     */
2701    @ViewDebug.ExportedProperty(category = "padding")
2702    protected int mPaddingTop;
2703    /**
2704     * The bottom padding in pixels, that is the distance in pixels between the
2705     * bottom edge of this view and the bottom edge of its content.
2706     * {@hide}
2707     */
2708    @ViewDebug.ExportedProperty(category = "padding")
2709    protected int mPaddingBottom;
2710
2711    /**
2712     * The layout insets in pixels, that is the distance in pixels between the
2713     * visible edges of this view its bounds.
2714     */
2715    private Insets mLayoutInsets;
2716
2717    /**
2718     * Briefly describes the view and is primarily used for accessibility support.
2719     */
2720    private CharSequence mContentDescription;
2721
2722    /**
2723     * Cache the paddingRight set by the user to append to the scrollbar's size.
2724     *
2725     * @hide
2726     */
2727    @ViewDebug.ExportedProperty(category = "padding")
2728    protected int mUserPaddingRight;
2729
2730    /**
2731     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2732     *
2733     * @hide
2734     */
2735    @ViewDebug.ExportedProperty(category = "padding")
2736    protected int mUserPaddingBottom;
2737
2738    /**
2739     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2740     *
2741     * @hide
2742     */
2743    @ViewDebug.ExportedProperty(category = "padding")
2744    protected int mUserPaddingLeft;
2745
2746    /**
2747     * Cache if the user padding is relative.
2748     *
2749     */
2750    @ViewDebug.ExportedProperty(category = "padding")
2751    boolean mUserPaddingRelative;
2752
2753    /**
2754     * Cache the paddingStart set by the user to append to the scrollbar's size.
2755     *
2756     */
2757    @ViewDebug.ExportedProperty(category = "padding")
2758    int mUserPaddingStart;
2759
2760    /**
2761     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2762     *
2763     */
2764    @ViewDebug.ExportedProperty(category = "padding")
2765    int mUserPaddingEnd;
2766
2767    /**
2768     * @hide
2769     */
2770    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2771    /**
2772     * @hide
2773     */
2774    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2775
2776    private Drawable mBackground;
2777
2778    private int mBackgroundResource;
2779    private boolean mBackgroundSizeChanged;
2780
2781    static class ListenerInfo {
2782        /**
2783         * Listener used to dispatch focus change events.
2784         * This field should be made private, so it is hidden from the SDK.
2785         * {@hide}
2786         */
2787        protected OnFocusChangeListener mOnFocusChangeListener;
2788
2789        /**
2790         * Listeners for layout change events.
2791         */
2792        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2793
2794        /**
2795         * Listeners for attach events.
2796         */
2797        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2798
2799        /**
2800         * Listener used to dispatch click events.
2801         * This field should be made private, so it is hidden from the SDK.
2802         * {@hide}
2803         */
2804        public OnClickListener mOnClickListener;
2805
2806        /**
2807         * Listener used to dispatch long click events.
2808         * This field should be made private, so it is hidden from the SDK.
2809         * {@hide}
2810         */
2811        protected OnLongClickListener mOnLongClickListener;
2812
2813        /**
2814         * Listener used to build the context menu.
2815         * This field should be made private, so it is hidden from the SDK.
2816         * {@hide}
2817         */
2818        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2819
2820        private OnKeyListener mOnKeyListener;
2821
2822        private OnTouchListener mOnTouchListener;
2823
2824        private OnHoverListener mOnHoverListener;
2825
2826        private OnGenericMotionListener mOnGenericMotionListener;
2827
2828        private OnDragListener mOnDragListener;
2829
2830        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2831    }
2832
2833    ListenerInfo mListenerInfo;
2834
2835    /**
2836     * The application environment this view lives in.
2837     * This field should be made private, so it is hidden from the SDK.
2838     * {@hide}
2839     */
2840    protected Context mContext;
2841
2842    private final Resources mResources;
2843
2844    private ScrollabilityCache mScrollCache;
2845
2846    private int[] mDrawableState = null;
2847
2848    /**
2849     * Set to true when drawing cache is enabled and cannot be created.
2850     *
2851     * @hide
2852     */
2853    public boolean mCachingFailed;
2854
2855    private Bitmap mDrawingCache;
2856    private Bitmap mUnscaledDrawingCache;
2857    private HardwareLayer mHardwareLayer;
2858    DisplayList mDisplayList;
2859
2860    /**
2861     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2862     * the user may specify which view to go to next.
2863     */
2864    private int mNextFocusLeftId = View.NO_ID;
2865
2866    /**
2867     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2868     * the user may specify which view to go to next.
2869     */
2870    private int mNextFocusRightId = View.NO_ID;
2871
2872    /**
2873     * When this view has focus and the next focus is {@link #FOCUS_UP},
2874     * the user may specify which view to go to next.
2875     */
2876    private int mNextFocusUpId = View.NO_ID;
2877
2878    /**
2879     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2880     * the user may specify which view to go to next.
2881     */
2882    private int mNextFocusDownId = View.NO_ID;
2883
2884    /**
2885     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2886     * the user may specify which view to go to next.
2887     */
2888    int mNextFocusForwardId = View.NO_ID;
2889
2890    private CheckForLongPress mPendingCheckForLongPress;
2891    private CheckForTap mPendingCheckForTap = null;
2892    private PerformClick mPerformClick;
2893    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2894
2895    private UnsetPressedState mUnsetPressedState;
2896
2897    /**
2898     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2899     * up event while a long press is invoked as soon as the long press duration is reached, so
2900     * a long press could be performed before the tap is checked, in which case the tap's action
2901     * should not be invoked.
2902     */
2903    private boolean mHasPerformedLongPress;
2904
2905    /**
2906     * The minimum height of the view. We'll try our best to have the height
2907     * of this view to at least this amount.
2908     */
2909    @ViewDebug.ExportedProperty(category = "measurement")
2910    private int mMinHeight;
2911
2912    /**
2913     * The minimum width of the view. We'll try our best to have the width
2914     * of this view to at least this amount.
2915     */
2916    @ViewDebug.ExportedProperty(category = "measurement")
2917    private int mMinWidth;
2918
2919    /**
2920     * The delegate to handle touch events that are physically in this view
2921     * but should be handled by another view.
2922     */
2923    private TouchDelegate mTouchDelegate = null;
2924
2925    /**
2926     * Solid color to use as a background when creating the drawing cache. Enables
2927     * the cache to use 16 bit bitmaps instead of 32 bit.
2928     */
2929    private int mDrawingCacheBackgroundColor = 0;
2930
2931    /**
2932     * Special tree observer used when mAttachInfo is null.
2933     */
2934    private ViewTreeObserver mFloatingTreeObserver;
2935
2936    /**
2937     * Cache the touch slop from the context that created the view.
2938     */
2939    private int mTouchSlop;
2940
2941    /**
2942     * Object that handles automatic animation of view properties.
2943     */
2944    private ViewPropertyAnimator mAnimator = null;
2945
2946    /**
2947     * Flag indicating that a drag can cross window boundaries.  When
2948     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2949     * with this flag set, all visible applications will be able to participate
2950     * in the drag operation and receive the dragged content.
2951     *
2952     * @hide
2953     */
2954    public static final int DRAG_FLAG_GLOBAL = 1;
2955
2956    /**
2957     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2958     */
2959    private float mVerticalScrollFactor;
2960
2961    /**
2962     * Position of the vertical scroll bar.
2963     */
2964    private int mVerticalScrollbarPosition;
2965
2966    /**
2967     * Position the scroll bar at the default position as determined by the system.
2968     */
2969    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2970
2971    /**
2972     * Position the scroll bar along the left edge.
2973     */
2974    public static final int SCROLLBAR_POSITION_LEFT = 1;
2975
2976    /**
2977     * Position the scroll bar along the right edge.
2978     */
2979    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2980
2981    /**
2982     * Indicates that the view does not have a layer.
2983     *
2984     * @see #getLayerType()
2985     * @see #setLayerType(int, android.graphics.Paint)
2986     * @see #LAYER_TYPE_SOFTWARE
2987     * @see #LAYER_TYPE_HARDWARE
2988     */
2989    public static final int LAYER_TYPE_NONE = 0;
2990
2991    /**
2992     * <p>Indicates that the view has a software layer. A software layer is backed
2993     * by a bitmap and causes the view to be rendered using Android's software
2994     * rendering pipeline, even if hardware acceleration is enabled.</p>
2995     *
2996     * <p>Software layers have various usages:</p>
2997     * <p>When the application is not using hardware acceleration, a software layer
2998     * is useful to apply a specific color filter and/or blending mode and/or
2999     * translucency to a view and all its children.</p>
3000     * <p>When the application is using hardware acceleration, a software layer
3001     * is useful to render drawing primitives not supported by the hardware
3002     * accelerated pipeline. It can also be used to cache a complex view tree
3003     * into a texture and reduce the complexity of drawing operations. For instance,
3004     * when animating a complex view tree with a translation, a software layer can
3005     * be used to render the view tree only once.</p>
3006     * <p>Software layers should be avoided when the affected view tree updates
3007     * often. Every update will require to re-render the software layer, which can
3008     * potentially be slow (particularly when hardware acceleration is turned on
3009     * since the layer will have to be uploaded into a hardware texture after every
3010     * update.)</p>
3011     *
3012     * @see #getLayerType()
3013     * @see #setLayerType(int, android.graphics.Paint)
3014     * @see #LAYER_TYPE_NONE
3015     * @see #LAYER_TYPE_HARDWARE
3016     */
3017    public static final int LAYER_TYPE_SOFTWARE = 1;
3018
3019    /**
3020     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3021     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3022     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3023     * rendering pipeline, but only if hardware acceleration is turned on for the
3024     * view hierarchy. When hardware acceleration is turned off, hardware layers
3025     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3026     *
3027     * <p>A hardware layer is useful to apply a specific color filter and/or
3028     * blending mode and/or translucency to a view and all its children.</p>
3029     * <p>A hardware layer can be used to cache a complex view tree into a
3030     * texture and reduce the complexity of drawing operations. For instance,
3031     * when animating a complex view tree with a translation, a hardware layer can
3032     * be used to render the view tree only once.</p>
3033     * <p>A hardware layer can also be used to increase the rendering quality when
3034     * rotation transformations are applied on a view. It can also be used to
3035     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3036     *
3037     * @see #getLayerType()
3038     * @see #setLayerType(int, android.graphics.Paint)
3039     * @see #LAYER_TYPE_NONE
3040     * @see #LAYER_TYPE_SOFTWARE
3041     */
3042    public static final int LAYER_TYPE_HARDWARE = 2;
3043
3044    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3045            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3046            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3047            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3048    })
3049    int mLayerType = LAYER_TYPE_NONE;
3050    Paint mLayerPaint;
3051    Rect mLocalDirtyRect;
3052
3053    /**
3054     * Set to true when the view is sending hover accessibility events because it
3055     * is the innermost hovered view.
3056     */
3057    private boolean mSendingHoverAccessibilityEvents;
3058
3059    /**
3060     * Simple constructor to use when creating a view from code.
3061     *
3062     * @param context The Context the view is running in, through which it can
3063     *        access the current theme, resources, etc.
3064     */
3065    public View(Context context) {
3066        mContext = context;
3067        mResources = context != null ? context.getResources() : null;
3068        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3069        // Set layout and text direction defaults
3070        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3071                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3072                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3073                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3074        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3075        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3076        mUserPaddingStart = -1;
3077        mUserPaddingEnd = -1;
3078        mUserPaddingRelative = false;
3079    }
3080
3081    /**
3082     * Delegate for injecting accessiblity functionality.
3083     */
3084    AccessibilityDelegate mAccessibilityDelegate;
3085
3086    /**
3087     * Consistency verifier for debugging purposes.
3088     * @hide
3089     */
3090    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3091            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3092                    new InputEventConsistencyVerifier(this, 0) : null;
3093
3094    /**
3095     * Constructor that is called when inflating a view from XML. This is called
3096     * when a view is being constructed from an XML file, supplying attributes
3097     * that were specified in the XML file. This version uses a default style of
3098     * 0, so the only attribute values applied are those in the Context's Theme
3099     * and the given AttributeSet.
3100     *
3101     * <p>
3102     * The method onFinishInflate() will be called after all children have been
3103     * added.
3104     *
3105     * @param context The Context the view is running in, through which it can
3106     *        access the current theme, resources, etc.
3107     * @param attrs The attributes of the XML tag that is inflating the view.
3108     * @see #View(Context, AttributeSet, int)
3109     */
3110    public View(Context context, AttributeSet attrs) {
3111        this(context, attrs, 0);
3112    }
3113
3114    /**
3115     * Perform inflation from XML and apply a class-specific base style. This
3116     * constructor of View allows subclasses to use their own base style when
3117     * they are inflating. For example, a Button class's constructor would call
3118     * this version of the super class constructor and supply
3119     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3120     * the theme's button style to modify all of the base view attributes (in
3121     * particular its background) as well as the Button class's attributes.
3122     *
3123     * @param context The Context the view is running in, through which it can
3124     *        access the current theme, resources, etc.
3125     * @param attrs The attributes of the XML tag that is inflating the view.
3126     * @param defStyle The default style to apply to this view. If 0, no style
3127     *        will be applied (beyond what is included in the theme). This may
3128     *        either be an attribute resource, whose value will be retrieved
3129     *        from the current theme, or an explicit style resource.
3130     * @see #View(Context, AttributeSet)
3131     */
3132    public View(Context context, AttributeSet attrs, int defStyle) {
3133        this(context);
3134
3135        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3136                defStyle, 0);
3137
3138        Drawable background = null;
3139
3140        int leftPadding = -1;
3141        int topPadding = -1;
3142        int rightPadding = -1;
3143        int bottomPadding = -1;
3144        int startPadding = -1;
3145        int endPadding = -1;
3146
3147        int padding = -1;
3148
3149        int viewFlagValues = 0;
3150        int viewFlagMasks = 0;
3151
3152        boolean setScrollContainer = false;
3153
3154        int x = 0;
3155        int y = 0;
3156
3157        float tx = 0;
3158        float ty = 0;
3159        float rotation = 0;
3160        float rotationX = 0;
3161        float rotationY = 0;
3162        float sx = 1f;
3163        float sy = 1f;
3164        boolean transformSet = false;
3165
3166        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3167
3168        int overScrollMode = mOverScrollMode;
3169        final int N = a.getIndexCount();
3170        for (int i = 0; i < N; i++) {
3171            int attr = a.getIndex(i);
3172            switch (attr) {
3173                case com.android.internal.R.styleable.View_background:
3174                    background = a.getDrawable(attr);
3175                    break;
3176                case com.android.internal.R.styleable.View_padding:
3177                    padding = a.getDimensionPixelSize(attr, -1);
3178                    break;
3179                 case com.android.internal.R.styleable.View_paddingLeft:
3180                    leftPadding = a.getDimensionPixelSize(attr, -1);
3181                    break;
3182                case com.android.internal.R.styleable.View_paddingTop:
3183                    topPadding = a.getDimensionPixelSize(attr, -1);
3184                    break;
3185                case com.android.internal.R.styleable.View_paddingRight:
3186                    rightPadding = a.getDimensionPixelSize(attr, -1);
3187                    break;
3188                case com.android.internal.R.styleable.View_paddingBottom:
3189                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3190                    break;
3191                case com.android.internal.R.styleable.View_paddingStart:
3192                    startPadding = a.getDimensionPixelSize(attr, -1);
3193                    break;
3194                case com.android.internal.R.styleable.View_paddingEnd:
3195                    endPadding = a.getDimensionPixelSize(attr, -1);
3196                    break;
3197                case com.android.internal.R.styleable.View_scrollX:
3198                    x = a.getDimensionPixelOffset(attr, 0);
3199                    break;
3200                case com.android.internal.R.styleable.View_scrollY:
3201                    y = a.getDimensionPixelOffset(attr, 0);
3202                    break;
3203                case com.android.internal.R.styleable.View_alpha:
3204                    setAlpha(a.getFloat(attr, 1f));
3205                    break;
3206                case com.android.internal.R.styleable.View_transformPivotX:
3207                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3208                    break;
3209                case com.android.internal.R.styleable.View_transformPivotY:
3210                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3211                    break;
3212                case com.android.internal.R.styleable.View_translationX:
3213                    tx = a.getDimensionPixelOffset(attr, 0);
3214                    transformSet = true;
3215                    break;
3216                case com.android.internal.R.styleable.View_translationY:
3217                    ty = a.getDimensionPixelOffset(attr, 0);
3218                    transformSet = true;
3219                    break;
3220                case com.android.internal.R.styleable.View_rotation:
3221                    rotation = a.getFloat(attr, 0);
3222                    transformSet = true;
3223                    break;
3224                case com.android.internal.R.styleable.View_rotationX:
3225                    rotationX = a.getFloat(attr, 0);
3226                    transformSet = true;
3227                    break;
3228                case com.android.internal.R.styleable.View_rotationY:
3229                    rotationY = a.getFloat(attr, 0);
3230                    transformSet = true;
3231                    break;
3232                case com.android.internal.R.styleable.View_scaleX:
3233                    sx = a.getFloat(attr, 1f);
3234                    transformSet = true;
3235                    break;
3236                case com.android.internal.R.styleable.View_scaleY:
3237                    sy = a.getFloat(attr, 1f);
3238                    transformSet = true;
3239                    break;
3240                case com.android.internal.R.styleable.View_id:
3241                    mID = a.getResourceId(attr, NO_ID);
3242                    break;
3243                case com.android.internal.R.styleable.View_tag:
3244                    mTag = a.getText(attr);
3245                    break;
3246                case com.android.internal.R.styleable.View_fitsSystemWindows:
3247                    if (a.getBoolean(attr, false)) {
3248                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3249                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3250                    }
3251                    break;
3252                case com.android.internal.R.styleable.View_focusable:
3253                    if (a.getBoolean(attr, false)) {
3254                        viewFlagValues |= FOCUSABLE;
3255                        viewFlagMasks |= FOCUSABLE_MASK;
3256                    }
3257                    break;
3258                case com.android.internal.R.styleable.View_focusableInTouchMode:
3259                    if (a.getBoolean(attr, false)) {
3260                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3261                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3262                    }
3263                    break;
3264                case com.android.internal.R.styleable.View_clickable:
3265                    if (a.getBoolean(attr, false)) {
3266                        viewFlagValues |= CLICKABLE;
3267                        viewFlagMasks |= CLICKABLE;
3268                    }
3269                    break;
3270                case com.android.internal.R.styleable.View_longClickable:
3271                    if (a.getBoolean(attr, false)) {
3272                        viewFlagValues |= LONG_CLICKABLE;
3273                        viewFlagMasks |= LONG_CLICKABLE;
3274                    }
3275                    break;
3276                case com.android.internal.R.styleable.View_saveEnabled:
3277                    if (!a.getBoolean(attr, true)) {
3278                        viewFlagValues |= SAVE_DISABLED;
3279                        viewFlagMasks |= SAVE_DISABLED_MASK;
3280                    }
3281                    break;
3282                case com.android.internal.R.styleable.View_duplicateParentState:
3283                    if (a.getBoolean(attr, false)) {
3284                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3285                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3286                    }
3287                    break;
3288                case com.android.internal.R.styleable.View_visibility:
3289                    final int visibility = a.getInt(attr, 0);
3290                    if (visibility != 0) {
3291                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3292                        viewFlagMasks |= VISIBILITY_MASK;
3293                    }
3294                    break;
3295                case com.android.internal.R.styleable.View_layoutDirection:
3296                    // Clear any layout direction flags (included resolved bits) already set
3297                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3298                    // Set the layout direction flags depending on the value of the attribute
3299                    final int layoutDirection = a.getInt(attr, -1);
3300                    final int value = (layoutDirection != -1) ?
3301                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3302                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3303                    break;
3304                case com.android.internal.R.styleable.View_drawingCacheQuality:
3305                    final int cacheQuality = a.getInt(attr, 0);
3306                    if (cacheQuality != 0) {
3307                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3308                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3309                    }
3310                    break;
3311                case com.android.internal.R.styleable.View_contentDescription:
3312                    mContentDescription = a.getString(attr);
3313                    break;
3314                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3315                    if (!a.getBoolean(attr, true)) {
3316                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3317                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3318                    }
3319                    break;
3320                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3321                    if (!a.getBoolean(attr, true)) {
3322                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3323                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3324                    }
3325                    break;
3326                case R.styleable.View_scrollbars:
3327                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3328                    if (scrollbars != SCROLLBARS_NONE) {
3329                        viewFlagValues |= scrollbars;
3330                        viewFlagMasks |= SCROLLBARS_MASK;
3331                        initializeScrollbars(a);
3332                    }
3333                    break;
3334                //noinspection deprecation
3335                case R.styleable.View_fadingEdge:
3336                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3337                        // Ignore the attribute starting with ICS
3338                        break;
3339                    }
3340                    // With builds < ICS, fall through and apply fading edges
3341                case R.styleable.View_requiresFadingEdge:
3342                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3343                    if (fadingEdge != FADING_EDGE_NONE) {
3344                        viewFlagValues |= fadingEdge;
3345                        viewFlagMasks |= FADING_EDGE_MASK;
3346                        initializeFadingEdge(a);
3347                    }
3348                    break;
3349                case R.styleable.View_scrollbarStyle:
3350                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3351                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3352                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3353                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3354                    }
3355                    break;
3356                case R.styleable.View_isScrollContainer:
3357                    setScrollContainer = true;
3358                    if (a.getBoolean(attr, false)) {
3359                        setScrollContainer(true);
3360                    }
3361                    break;
3362                case com.android.internal.R.styleable.View_keepScreenOn:
3363                    if (a.getBoolean(attr, false)) {
3364                        viewFlagValues |= KEEP_SCREEN_ON;
3365                        viewFlagMasks |= KEEP_SCREEN_ON;
3366                    }
3367                    break;
3368                case R.styleable.View_filterTouchesWhenObscured:
3369                    if (a.getBoolean(attr, false)) {
3370                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3371                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3372                    }
3373                    break;
3374                case R.styleable.View_nextFocusLeft:
3375                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3376                    break;
3377                case R.styleable.View_nextFocusRight:
3378                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3379                    break;
3380                case R.styleable.View_nextFocusUp:
3381                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3382                    break;
3383                case R.styleable.View_nextFocusDown:
3384                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3385                    break;
3386                case R.styleable.View_nextFocusForward:
3387                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3388                    break;
3389                case R.styleable.View_minWidth:
3390                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3391                    break;
3392                case R.styleable.View_minHeight:
3393                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3394                    break;
3395                case R.styleable.View_onClick:
3396                    if (context.isRestricted()) {
3397                        throw new IllegalStateException("The android:onClick attribute cannot "
3398                                + "be used within a restricted context");
3399                    }
3400
3401                    final String handlerName = a.getString(attr);
3402                    if (handlerName != null) {
3403                        setOnClickListener(new OnClickListener() {
3404                            private Method mHandler;
3405
3406                            public void onClick(View v) {
3407                                if (mHandler == null) {
3408                                    try {
3409                                        mHandler = getContext().getClass().getMethod(handlerName,
3410                                                View.class);
3411                                    } catch (NoSuchMethodException e) {
3412                                        int id = getId();
3413                                        String idText = id == NO_ID ? "" : " with id '"
3414                                                + getContext().getResources().getResourceEntryName(
3415                                                    id) + "'";
3416                                        throw new IllegalStateException("Could not find a method " +
3417                                                handlerName + "(View) in the activity "
3418                                                + getContext().getClass() + " for onClick handler"
3419                                                + " on view " + View.this.getClass() + idText, e);
3420                                    }
3421                                }
3422
3423                                try {
3424                                    mHandler.invoke(getContext(), View.this);
3425                                } catch (IllegalAccessException e) {
3426                                    throw new IllegalStateException("Could not execute non "
3427                                            + "public method of the activity", e);
3428                                } catch (InvocationTargetException e) {
3429                                    throw new IllegalStateException("Could not execute "
3430                                            + "method of the activity", e);
3431                                }
3432                            }
3433                        });
3434                    }
3435                    break;
3436                case R.styleable.View_overScrollMode:
3437                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3438                    break;
3439                case R.styleable.View_verticalScrollbarPosition:
3440                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3441                    break;
3442                case R.styleable.View_layerType:
3443                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3444                    break;
3445                case R.styleable.View_textDirection:
3446                    // Clear any text direction flag already set
3447                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3448                    // Set the text direction flags depending on the value of the attribute
3449                    final int textDirection = a.getInt(attr, -1);
3450                    if (textDirection != -1) {
3451                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3452                    }
3453                    break;
3454                case R.styleable.View_textAlignment:
3455                    // Clear any text alignment flag already set
3456                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3457                    // Set the text alignment flag depending on the value of the attribute
3458                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3459                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3460                    break;
3461                case R.styleable.View_importantForAccessibility:
3462                    setImportantForAccessibility(a.getInt(attr,
3463                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3464            }
3465        }
3466
3467        a.recycle();
3468
3469        setOverScrollMode(overScrollMode);
3470
3471        if (background != null) {
3472            setBackground(background);
3473        }
3474
3475        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3476        // layout direction). Those cached values will be used later during padding resolution.
3477        mUserPaddingStart = startPadding;
3478        mUserPaddingEnd = endPadding;
3479
3480        updateUserPaddingRelative();
3481
3482        if (padding >= 0) {
3483            leftPadding = padding;
3484            topPadding = padding;
3485            rightPadding = padding;
3486            bottomPadding = padding;
3487        }
3488
3489        // If the user specified the padding (either with android:padding or
3490        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3491        // use the default padding or the padding from the background drawable
3492        // (stored at this point in mPadding*)
3493        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3494                topPadding >= 0 ? topPadding : mPaddingTop,
3495                rightPadding >= 0 ? rightPadding : mPaddingRight,
3496                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3497
3498        if (viewFlagMasks != 0) {
3499            setFlags(viewFlagValues, viewFlagMasks);
3500        }
3501
3502        // Needs to be called after mViewFlags is set
3503        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3504            recomputePadding();
3505        }
3506
3507        if (x != 0 || y != 0) {
3508            scrollTo(x, y);
3509        }
3510
3511        if (transformSet) {
3512            setTranslationX(tx);
3513            setTranslationY(ty);
3514            setRotation(rotation);
3515            setRotationX(rotationX);
3516            setRotationY(rotationY);
3517            setScaleX(sx);
3518            setScaleY(sy);
3519        }
3520
3521        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3522            setScrollContainer(true);
3523        }
3524
3525        computeOpaqueFlags();
3526    }
3527
3528    private void updateUserPaddingRelative() {
3529        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3530    }
3531
3532    /**
3533     * Non-public constructor for use in testing
3534     */
3535    View() {
3536        mResources = null;
3537    }
3538
3539    /**
3540     * <p>
3541     * Initializes the fading edges from a given set of styled attributes. This
3542     * method should be called by subclasses that need fading edges and when an
3543     * instance of these subclasses is created programmatically rather than
3544     * being inflated from XML. This method is automatically called when the XML
3545     * is inflated.
3546     * </p>
3547     *
3548     * @param a the styled attributes set to initialize the fading edges from
3549     */
3550    protected void initializeFadingEdge(TypedArray a) {
3551        initScrollCache();
3552
3553        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3554                R.styleable.View_fadingEdgeLength,
3555                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3556    }
3557
3558    /**
3559     * Returns the size of the vertical faded edges used to indicate that more
3560     * content in this view is visible.
3561     *
3562     * @return The size in pixels of the vertical faded edge or 0 if vertical
3563     *         faded edges are not enabled for this view.
3564     * @attr ref android.R.styleable#View_fadingEdgeLength
3565     */
3566    public int getVerticalFadingEdgeLength() {
3567        if (isVerticalFadingEdgeEnabled()) {
3568            ScrollabilityCache cache = mScrollCache;
3569            if (cache != null) {
3570                return cache.fadingEdgeLength;
3571            }
3572        }
3573        return 0;
3574    }
3575
3576    /**
3577     * Set the size of the faded edge used to indicate that more content in this
3578     * view is available.  Will not change whether the fading edge is enabled; use
3579     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3580     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3581     * for the vertical or horizontal fading edges.
3582     *
3583     * @param length The size in pixels of the faded edge used to indicate that more
3584     *        content in this view is visible.
3585     */
3586    public void setFadingEdgeLength(int length) {
3587        initScrollCache();
3588        mScrollCache.fadingEdgeLength = length;
3589    }
3590
3591    /**
3592     * Returns the size of the horizontal faded edges used to indicate that more
3593     * content in this view is visible.
3594     *
3595     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3596     *         faded edges are not enabled for this view.
3597     * @attr ref android.R.styleable#View_fadingEdgeLength
3598     */
3599    public int getHorizontalFadingEdgeLength() {
3600        if (isHorizontalFadingEdgeEnabled()) {
3601            ScrollabilityCache cache = mScrollCache;
3602            if (cache != null) {
3603                return cache.fadingEdgeLength;
3604            }
3605        }
3606        return 0;
3607    }
3608
3609    /**
3610     * Returns the width of the vertical scrollbar.
3611     *
3612     * @return The width in pixels of the vertical scrollbar or 0 if there
3613     *         is no vertical scrollbar.
3614     */
3615    public int getVerticalScrollbarWidth() {
3616        ScrollabilityCache cache = mScrollCache;
3617        if (cache != null) {
3618            ScrollBarDrawable scrollBar = cache.scrollBar;
3619            if (scrollBar != null) {
3620                int size = scrollBar.getSize(true);
3621                if (size <= 0) {
3622                    size = cache.scrollBarSize;
3623                }
3624                return size;
3625            }
3626            return 0;
3627        }
3628        return 0;
3629    }
3630
3631    /**
3632     * Returns the height of the horizontal scrollbar.
3633     *
3634     * @return The height in pixels of the horizontal scrollbar or 0 if
3635     *         there is no horizontal scrollbar.
3636     */
3637    protected int getHorizontalScrollbarHeight() {
3638        ScrollabilityCache cache = mScrollCache;
3639        if (cache != null) {
3640            ScrollBarDrawable scrollBar = cache.scrollBar;
3641            if (scrollBar != null) {
3642                int size = scrollBar.getSize(false);
3643                if (size <= 0) {
3644                    size = cache.scrollBarSize;
3645                }
3646                return size;
3647            }
3648            return 0;
3649        }
3650        return 0;
3651    }
3652
3653    /**
3654     * <p>
3655     * Initializes the scrollbars from a given set of styled attributes. This
3656     * method should be called by subclasses that need scrollbars and when an
3657     * instance of these subclasses is created programmatically rather than
3658     * being inflated from XML. This method is automatically called when the XML
3659     * is inflated.
3660     * </p>
3661     *
3662     * @param a the styled attributes set to initialize the scrollbars from
3663     */
3664    protected void initializeScrollbars(TypedArray a) {
3665        initScrollCache();
3666
3667        final ScrollabilityCache scrollabilityCache = mScrollCache;
3668
3669        if (scrollabilityCache.scrollBar == null) {
3670            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3671        }
3672
3673        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3674
3675        if (!fadeScrollbars) {
3676            scrollabilityCache.state = ScrollabilityCache.ON;
3677        }
3678        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3679
3680
3681        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3682                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3683                        .getScrollBarFadeDuration());
3684        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3685                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3686                ViewConfiguration.getScrollDefaultDelay());
3687
3688
3689        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3690                com.android.internal.R.styleable.View_scrollbarSize,
3691                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3692
3693        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3694        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3695
3696        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3697        if (thumb != null) {
3698            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3699        }
3700
3701        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3702                false);
3703        if (alwaysDraw) {
3704            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3705        }
3706
3707        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3708        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3709
3710        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3711        if (thumb != null) {
3712            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3713        }
3714
3715        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3716                false);
3717        if (alwaysDraw) {
3718            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3719        }
3720
3721        // Re-apply user/background padding so that scrollbar(s) get added
3722        resolvePadding();
3723    }
3724
3725    /**
3726     * <p>
3727     * Initalizes the scrollability cache if necessary.
3728     * </p>
3729     */
3730    private void initScrollCache() {
3731        if (mScrollCache == null) {
3732            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3733        }
3734    }
3735
3736    private ScrollabilityCache getScrollCache() {
3737        initScrollCache();
3738        return mScrollCache;
3739    }
3740
3741    /**
3742     * Set the position of the vertical scroll bar. Should be one of
3743     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3744     * {@link #SCROLLBAR_POSITION_RIGHT}.
3745     *
3746     * @param position Where the vertical scroll bar should be positioned.
3747     */
3748    public void setVerticalScrollbarPosition(int position) {
3749        if (mVerticalScrollbarPosition != position) {
3750            mVerticalScrollbarPosition = position;
3751            computeOpaqueFlags();
3752            resolvePadding();
3753        }
3754    }
3755
3756    /**
3757     * @return The position where the vertical scroll bar will show, if applicable.
3758     * @see #setVerticalScrollbarPosition(int)
3759     */
3760    public int getVerticalScrollbarPosition() {
3761        return mVerticalScrollbarPosition;
3762    }
3763
3764    ListenerInfo getListenerInfo() {
3765        if (mListenerInfo != null) {
3766            return mListenerInfo;
3767        }
3768        mListenerInfo = new ListenerInfo();
3769        return mListenerInfo;
3770    }
3771
3772    /**
3773     * Register a callback to be invoked when focus of this view changed.
3774     *
3775     * @param l The callback that will run.
3776     */
3777    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3778        getListenerInfo().mOnFocusChangeListener = l;
3779    }
3780
3781    /**
3782     * Add a listener that will be called when the bounds of the view change due to
3783     * layout processing.
3784     *
3785     * @param listener The listener that will be called when layout bounds change.
3786     */
3787    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3788        ListenerInfo li = getListenerInfo();
3789        if (li.mOnLayoutChangeListeners == null) {
3790            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3791        }
3792        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3793            li.mOnLayoutChangeListeners.add(listener);
3794        }
3795    }
3796
3797    /**
3798     * Remove a listener for layout changes.
3799     *
3800     * @param listener The listener for layout bounds change.
3801     */
3802    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3803        ListenerInfo li = mListenerInfo;
3804        if (li == null || li.mOnLayoutChangeListeners == null) {
3805            return;
3806        }
3807        li.mOnLayoutChangeListeners.remove(listener);
3808    }
3809
3810    /**
3811     * Add a listener for attach state changes.
3812     *
3813     * This listener will be called whenever this view is attached or detached
3814     * from a window. Remove the listener using
3815     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3816     *
3817     * @param listener Listener to attach
3818     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3819     */
3820    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3821        ListenerInfo li = getListenerInfo();
3822        if (li.mOnAttachStateChangeListeners == null) {
3823            li.mOnAttachStateChangeListeners
3824                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3825        }
3826        li.mOnAttachStateChangeListeners.add(listener);
3827    }
3828
3829    /**
3830     * Remove a listener for attach state changes. The listener will receive no further
3831     * notification of window attach/detach events.
3832     *
3833     * @param listener Listener to remove
3834     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3835     */
3836    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3837        ListenerInfo li = mListenerInfo;
3838        if (li == null || li.mOnAttachStateChangeListeners == null) {
3839            return;
3840        }
3841        li.mOnAttachStateChangeListeners.remove(listener);
3842    }
3843
3844    /**
3845     * Returns the focus-change callback registered for this view.
3846     *
3847     * @return The callback, or null if one is not registered.
3848     */
3849    public OnFocusChangeListener getOnFocusChangeListener() {
3850        ListenerInfo li = mListenerInfo;
3851        return li != null ? li.mOnFocusChangeListener : null;
3852    }
3853
3854    /**
3855     * Register a callback to be invoked when this view is clicked. If this view is not
3856     * clickable, it becomes clickable.
3857     *
3858     * @param l The callback that will run
3859     *
3860     * @see #setClickable(boolean)
3861     */
3862    public void setOnClickListener(OnClickListener l) {
3863        if (!isClickable()) {
3864            setClickable(true);
3865        }
3866        getListenerInfo().mOnClickListener = l;
3867    }
3868
3869    /**
3870     * Return whether this view has an attached OnClickListener.  Returns
3871     * true if there is a listener, false if there is none.
3872     */
3873    public boolean hasOnClickListeners() {
3874        ListenerInfo li = mListenerInfo;
3875        return (li != null && li.mOnClickListener != null);
3876    }
3877
3878    /**
3879     * Register a callback to be invoked when this view is clicked and held. If this view is not
3880     * long clickable, it becomes long clickable.
3881     *
3882     * @param l The callback that will run
3883     *
3884     * @see #setLongClickable(boolean)
3885     */
3886    public void setOnLongClickListener(OnLongClickListener l) {
3887        if (!isLongClickable()) {
3888            setLongClickable(true);
3889        }
3890        getListenerInfo().mOnLongClickListener = l;
3891    }
3892
3893    /**
3894     * Register a callback to be invoked when the context menu for this view is
3895     * being built. If this view is not long clickable, it becomes long clickable.
3896     *
3897     * @param l The callback that will run
3898     *
3899     */
3900    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3901        if (!isLongClickable()) {
3902            setLongClickable(true);
3903        }
3904        getListenerInfo().mOnCreateContextMenuListener = l;
3905    }
3906
3907    /**
3908     * Call this view's OnClickListener, if it is defined.  Performs all normal
3909     * actions associated with clicking: reporting accessibility event, playing
3910     * a sound, etc.
3911     *
3912     * @return True there was an assigned OnClickListener that was called, false
3913     *         otherwise is returned.
3914     */
3915    public boolean performClick() {
3916        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3917
3918        ListenerInfo li = mListenerInfo;
3919        if (li != null && li.mOnClickListener != null) {
3920            playSoundEffect(SoundEffectConstants.CLICK);
3921            li.mOnClickListener.onClick(this);
3922            return true;
3923        }
3924
3925        return false;
3926    }
3927
3928    /**
3929     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3930     * this only calls the listener, and does not do any associated clicking
3931     * actions like reporting an accessibility event.
3932     *
3933     * @return True there was an assigned OnClickListener that was called, false
3934     *         otherwise is returned.
3935     */
3936    public boolean callOnClick() {
3937        ListenerInfo li = mListenerInfo;
3938        if (li != null && li.mOnClickListener != null) {
3939            li.mOnClickListener.onClick(this);
3940            return true;
3941        }
3942        return false;
3943    }
3944
3945    /**
3946     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3947     * OnLongClickListener did not consume the event.
3948     *
3949     * @return True if one of the above receivers consumed the event, false otherwise.
3950     */
3951    public boolean performLongClick() {
3952        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3953
3954        boolean handled = false;
3955        ListenerInfo li = mListenerInfo;
3956        if (li != null && li.mOnLongClickListener != null) {
3957            handled = li.mOnLongClickListener.onLongClick(View.this);
3958        }
3959        if (!handled) {
3960            handled = showContextMenu();
3961        }
3962        if (handled) {
3963            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3964        }
3965        return handled;
3966    }
3967
3968    /**
3969     * Performs button-related actions during a touch down event.
3970     *
3971     * @param event The event.
3972     * @return True if the down was consumed.
3973     *
3974     * @hide
3975     */
3976    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3977        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3978            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3979                return true;
3980            }
3981        }
3982        return false;
3983    }
3984
3985    /**
3986     * Bring up the context menu for this view.
3987     *
3988     * @return Whether a context menu was displayed.
3989     */
3990    public boolean showContextMenu() {
3991        return getParent().showContextMenuForChild(this);
3992    }
3993
3994    /**
3995     * Bring up the context menu for this view, referring to the item under the specified point.
3996     *
3997     * @param x The referenced x coordinate.
3998     * @param y The referenced y coordinate.
3999     * @param metaState The keyboard modifiers that were pressed.
4000     * @return Whether a context menu was displayed.
4001     *
4002     * @hide
4003     */
4004    public boolean showContextMenu(float x, float y, int metaState) {
4005        return showContextMenu();
4006    }
4007
4008    /**
4009     * Start an action mode.
4010     *
4011     * @param callback Callback that will control the lifecycle of the action mode
4012     * @return The new action mode if it is started, null otherwise
4013     *
4014     * @see ActionMode
4015     */
4016    public ActionMode startActionMode(ActionMode.Callback callback) {
4017        ViewParent parent = getParent();
4018        if (parent == null) return null;
4019        return parent.startActionModeForChild(this, callback);
4020    }
4021
4022    /**
4023     * Register a callback to be invoked when a key is pressed in this view.
4024     * @param l the key listener to attach to this view
4025     */
4026    public void setOnKeyListener(OnKeyListener l) {
4027        getListenerInfo().mOnKeyListener = l;
4028    }
4029
4030    /**
4031     * Register a callback to be invoked when a touch event is sent to this view.
4032     * @param l the touch listener to attach to this view
4033     */
4034    public void setOnTouchListener(OnTouchListener l) {
4035        getListenerInfo().mOnTouchListener = l;
4036    }
4037
4038    /**
4039     * Register a callback to be invoked when a generic motion event is sent to this view.
4040     * @param l the generic motion listener to attach to this view
4041     */
4042    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4043        getListenerInfo().mOnGenericMotionListener = l;
4044    }
4045
4046    /**
4047     * Register a callback to be invoked when a hover event is sent to this view.
4048     * @param l the hover listener to attach to this view
4049     */
4050    public void setOnHoverListener(OnHoverListener l) {
4051        getListenerInfo().mOnHoverListener = l;
4052    }
4053
4054    /**
4055     * Register a drag event listener callback object for this View. The parameter is
4056     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4057     * View, the system calls the
4058     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4059     * @param l An implementation of {@link android.view.View.OnDragListener}.
4060     */
4061    public void setOnDragListener(OnDragListener l) {
4062        getListenerInfo().mOnDragListener = l;
4063    }
4064
4065    /**
4066     * Give this view focus. This will cause
4067     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4068     *
4069     * Note: this does not check whether this {@link View} should get focus, it just
4070     * gives it focus no matter what.  It should only be called internally by framework
4071     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4072     *
4073     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4074     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4075     *        focus moved when requestFocus() is called. It may not always
4076     *        apply, in which case use the default View.FOCUS_DOWN.
4077     * @param previouslyFocusedRect The rectangle of the view that had focus
4078     *        prior in this View's coordinate system.
4079     */
4080    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4081        if (DBG) {
4082            System.out.println(this + " requestFocus()");
4083        }
4084
4085        if ((mPrivateFlags & FOCUSED) == 0) {
4086            mPrivateFlags |= FOCUSED;
4087
4088            if (mParent != null) {
4089                mParent.requestChildFocus(this, this);
4090            }
4091
4092            onFocusChanged(true, direction, previouslyFocusedRect);
4093            refreshDrawableState();
4094
4095            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4096                notifyAccessibilityStateChanged();
4097            }
4098        }
4099    }
4100
4101    /**
4102     * Request that a rectangle of this view be visible on the screen,
4103     * scrolling if necessary just enough.
4104     *
4105     * <p>A View should call this if it maintains some notion of which part
4106     * of its content is interesting.  For example, a text editing view
4107     * should call this when its cursor moves.
4108     *
4109     * @param rectangle The rectangle.
4110     * @return Whether any parent scrolled.
4111     */
4112    public boolean requestRectangleOnScreen(Rect rectangle) {
4113        return requestRectangleOnScreen(rectangle, false);
4114    }
4115
4116    /**
4117     * Request that a rectangle of this view be visible on the screen,
4118     * scrolling if necessary just enough.
4119     *
4120     * <p>A View should call this if it maintains some notion of which part
4121     * of its content is interesting.  For example, a text editing view
4122     * should call this when its cursor moves.
4123     *
4124     * <p>When <code>immediate</code> is set to true, scrolling will not be
4125     * animated.
4126     *
4127     * @param rectangle The rectangle.
4128     * @param immediate True to forbid animated scrolling, false otherwise
4129     * @return Whether any parent scrolled.
4130     */
4131    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4132        View child = this;
4133        ViewParent parent = mParent;
4134        boolean scrolled = false;
4135        while (parent != null) {
4136            scrolled |= parent.requestChildRectangleOnScreen(child,
4137                    rectangle, immediate);
4138
4139            // offset rect so next call has the rectangle in the
4140            // coordinate system of its direct child.
4141            rectangle.offset(child.getLeft(), child.getTop());
4142            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4143
4144            if (!(parent instanceof View)) {
4145                break;
4146            }
4147
4148            child = (View) parent;
4149            parent = child.getParent();
4150        }
4151        return scrolled;
4152    }
4153
4154    /**
4155     * Called when this view wants to give up focus. If focus is cleared
4156     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4157     * <p>
4158     * <strong>Note:</strong> When a View clears focus the framework is trying
4159     * to give focus to the first focusable View from the top. Hence, if this
4160     * View is the first from the top that can take focus, then all callbacks
4161     * related to clearing focus will be invoked after wich the framework will
4162     * give focus to this view.
4163     * </p>
4164     */
4165    public void clearFocus() {
4166        if (DBG) {
4167            System.out.println(this + " clearFocus()");
4168        }
4169
4170        if ((mPrivateFlags & FOCUSED) != 0) {
4171            mPrivateFlags &= ~FOCUSED;
4172
4173            if (mParent != null) {
4174                mParent.clearChildFocus(this);
4175            }
4176
4177            onFocusChanged(false, 0, null);
4178
4179            refreshDrawableState();
4180
4181            ensureInputFocusOnFirstFocusable();
4182
4183            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4184                notifyAccessibilityStateChanged();
4185            }
4186        }
4187    }
4188
4189    void ensureInputFocusOnFirstFocusable() {
4190        View root = getRootView();
4191        if (root != null) {
4192            root.requestFocus();
4193        }
4194    }
4195
4196    /**
4197     * Called internally by the view system when a new view is getting focus.
4198     * This is what clears the old focus.
4199     */
4200    void unFocus() {
4201        if (DBG) {
4202            System.out.println(this + " unFocus()");
4203        }
4204
4205        if ((mPrivateFlags & FOCUSED) != 0) {
4206            mPrivateFlags &= ~FOCUSED;
4207
4208            onFocusChanged(false, 0, null);
4209            refreshDrawableState();
4210
4211            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4212                notifyAccessibilityStateChanged();
4213            }
4214        }
4215    }
4216
4217    /**
4218     * Returns true if this view has focus iteself, or is the ancestor of the
4219     * view that has focus.
4220     *
4221     * @return True if this view has or contains focus, false otherwise.
4222     */
4223    @ViewDebug.ExportedProperty(category = "focus")
4224    public boolean hasFocus() {
4225        return (mPrivateFlags & FOCUSED) != 0;
4226    }
4227
4228    /**
4229     * Returns true if this view is focusable or if it contains a reachable View
4230     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4231     * is a View whose parents do not block descendants focus.
4232     *
4233     * Only {@link #VISIBLE} views are considered focusable.
4234     *
4235     * @return True if the view is focusable or if the view contains a focusable
4236     *         View, false otherwise.
4237     *
4238     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4239     */
4240    public boolean hasFocusable() {
4241        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4242    }
4243
4244    /**
4245     * Called by the view system when the focus state of this view changes.
4246     * When the focus change event is caused by directional navigation, direction
4247     * and previouslyFocusedRect provide insight into where the focus is coming from.
4248     * When overriding, be sure to call up through to the super class so that
4249     * the standard focus handling will occur.
4250     *
4251     * @param gainFocus True if the View has focus; false otherwise.
4252     * @param direction The direction focus has moved when requestFocus()
4253     *                  is called to give this view focus. Values are
4254     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4255     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4256     *                  It may not always apply, in which case use the default.
4257     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4258     *        system, of the previously focused view.  If applicable, this will be
4259     *        passed in as finer grained information about where the focus is coming
4260     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4261     */
4262    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4263        if (gainFocus) {
4264            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4265                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4266                requestAccessibilityFocus();
4267            }
4268        }
4269
4270        InputMethodManager imm = InputMethodManager.peekInstance();
4271        if (!gainFocus) {
4272            if (isPressed()) {
4273                setPressed(false);
4274            }
4275            if (imm != null && mAttachInfo != null
4276                    && mAttachInfo.mHasWindowFocus) {
4277                imm.focusOut(this);
4278            }
4279            onFocusLost();
4280        } else if (imm != null && mAttachInfo != null
4281                && mAttachInfo.mHasWindowFocus) {
4282            imm.focusIn(this);
4283        }
4284
4285        invalidate(true);
4286        ListenerInfo li = mListenerInfo;
4287        if (li != null && li.mOnFocusChangeListener != null) {
4288            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4289        }
4290
4291        if (mAttachInfo != null) {
4292            mAttachInfo.mKeyDispatchState.reset(this);
4293        }
4294    }
4295
4296    /**
4297     * Sends an accessibility event of the given type. If accessiiblity is
4298     * not enabled this method has no effect. The default implementation calls
4299     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4300     * to populate information about the event source (this View), then calls
4301     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4302     * populate the text content of the event source including its descendants,
4303     * and last calls
4304     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4305     * on its parent to resuest sending of the event to interested parties.
4306     * <p>
4307     * If an {@link AccessibilityDelegate} has been specified via calling
4308     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4309     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4310     * responsible for handling this call.
4311     * </p>
4312     *
4313     * @param eventType The type of the event to send, as defined by several types from
4314     * {@link android.view.accessibility.AccessibilityEvent}, such as
4315     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4316     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4317     *
4318     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4319     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4320     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4321     * @see AccessibilityDelegate
4322     */
4323    public void sendAccessibilityEvent(int eventType) {
4324        if (mAccessibilityDelegate != null) {
4325            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4326        } else {
4327            sendAccessibilityEventInternal(eventType);
4328        }
4329    }
4330
4331    /**
4332     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4333     * {@link AccessibilityEvent} to make an announcement which is related to some
4334     * sort of a context change for which none of the events representing UI transitions
4335     * is a good fit. For example, announcing a new page in a book. If accessibility
4336     * is not enabled this method does nothing.
4337     *
4338     * @param text The announcement text.
4339     */
4340    public void announceForAccessibility(CharSequence text) {
4341        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4342            AccessibilityEvent event = AccessibilityEvent.obtain(
4343                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4344            event.getText().add(text);
4345            sendAccessibilityEventUnchecked(event);
4346        }
4347    }
4348
4349    /**
4350     * @see #sendAccessibilityEvent(int)
4351     *
4352     * Note: Called from the default {@link AccessibilityDelegate}.
4353     */
4354    void sendAccessibilityEventInternal(int eventType) {
4355        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4356            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4357        }
4358    }
4359
4360    /**
4361     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4362     * takes as an argument an empty {@link AccessibilityEvent} and does not
4363     * perform a check whether accessibility is enabled.
4364     * <p>
4365     * If an {@link AccessibilityDelegate} has been specified via calling
4366     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4367     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4368     * is responsible for handling this call.
4369     * </p>
4370     *
4371     * @param event The event to send.
4372     *
4373     * @see #sendAccessibilityEvent(int)
4374     */
4375    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4376        if (mAccessibilityDelegate != null) {
4377            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4378        } else {
4379            sendAccessibilityEventUncheckedInternal(event);
4380        }
4381    }
4382
4383    /**
4384     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4385     *
4386     * Note: Called from the default {@link AccessibilityDelegate}.
4387     */
4388    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4389        if (!isShown()) {
4390            return;
4391        }
4392        onInitializeAccessibilityEvent(event);
4393        // Only a subset of accessibility events populates text content.
4394        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4395            dispatchPopulateAccessibilityEvent(event);
4396        }
4397        // Intercept accessibility focus events fired by virtual nodes to keep
4398        // track of accessibility focus position in such nodes.
4399        final int eventType = event.getEventType();
4400        switch (eventType) {
4401            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4402                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4403                        event.getSourceNodeId());
4404                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4405                    ViewRootImpl viewRootImpl = getViewRootImpl();
4406                    if (viewRootImpl != null) {
4407                        viewRootImpl.setAccessibilityFocusedHost(this);
4408                    }
4409                }
4410            } break;
4411            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4412                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4413                        event.getSourceNodeId());
4414                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4415                    ViewRootImpl viewRootImpl = getViewRootImpl();
4416                    if (viewRootImpl != null) {
4417                        viewRootImpl.setAccessibilityFocusedHost(null);
4418                    }
4419                }
4420            } break;
4421        }
4422        // In the beginning we called #isShown(), so we know that getParent() is not null.
4423        getParent().requestSendAccessibilityEvent(this, event);
4424    }
4425
4426    /**
4427     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4428     * to its children for adding their text content to the event. Note that the
4429     * event text is populated in a separate dispatch path since we add to the
4430     * event not only the text of the source but also the text of all its descendants.
4431     * A typical implementation will call
4432     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4433     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4434     * on each child. Override this method if custom population of the event text
4435     * content is required.
4436     * <p>
4437     * If an {@link AccessibilityDelegate} has been specified via calling
4438     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4439     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4440     * is responsible for handling this call.
4441     * </p>
4442     * <p>
4443     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4444     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4445     * </p>
4446     *
4447     * @param event The event.
4448     *
4449     * @return True if the event population was completed.
4450     */
4451    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4452        if (mAccessibilityDelegate != null) {
4453            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4454        } else {
4455            return dispatchPopulateAccessibilityEventInternal(event);
4456        }
4457    }
4458
4459    /**
4460     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4461     *
4462     * Note: Called from the default {@link AccessibilityDelegate}.
4463     */
4464    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4465        onPopulateAccessibilityEvent(event);
4466        return false;
4467    }
4468
4469    /**
4470     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4471     * giving a chance to this View to populate the accessibility event with its
4472     * text content. While this method is free to modify event
4473     * attributes other than text content, doing so should normally be performed in
4474     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4475     * <p>
4476     * Example: Adding formatted date string to an accessibility event in addition
4477     *          to the text added by the super implementation:
4478     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4479     *     super.onPopulateAccessibilityEvent(event);
4480     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4481     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4482     *         mCurrentDate.getTimeInMillis(), flags);
4483     *     event.getText().add(selectedDateUtterance);
4484     * }</pre>
4485     * <p>
4486     * If an {@link AccessibilityDelegate} has been specified via calling
4487     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4488     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4489     * is responsible for handling this call.
4490     * </p>
4491     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4492     * information to the event, in case the default implementation has basic information to add.
4493     * </p>
4494     *
4495     * @param event The accessibility event which to populate.
4496     *
4497     * @see #sendAccessibilityEvent(int)
4498     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4499     */
4500    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4501        if (mAccessibilityDelegate != null) {
4502            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4503        } else {
4504            onPopulateAccessibilityEventInternal(event);
4505        }
4506    }
4507
4508    /**
4509     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4510     *
4511     * Note: Called from the default {@link AccessibilityDelegate}.
4512     */
4513    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4514
4515    }
4516
4517    /**
4518     * Initializes an {@link AccessibilityEvent} with information about
4519     * this View which is the event source. In other words, the source of
4520     * an accessibility event is the view whose state change triggered firing
4521     * the event.
4522     * <p>
4523     * Example: Setting the password property of an event in addition
4524     *          to properties set by the super implementation:
4525     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4526     *     super.onInitializeAccessibilityEvent(event);
4527     *     event.setPassword(true);
4528     * }</pre>
4529     * <p>
4530     * If an {@link AccessibilityDelegate} has been specified via calling
4531     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4532     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4533     * is responsible for handling this call.
4534     * </p>
4535     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4536     * information to the event, in case the default implementation has basic information to add.
4537     * </p>
4538     * @param event The event to initialize.
4539     *
4540     * @see #sendAccessibilityEvent(int)
4541     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4542     */
4543    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4544        if (mAccessibilityDelegate != null) {
4545            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4546        } else {
4547            onInitializeAccessibilityEventInternal(event);
4548        }
4549    }
4550
4551    /**
4552     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4553     *
4554     * Note: Called from the default {@link AccessibilityDelegate}.
4555     */
4556    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4557        event.setSource(this);
4558        event.setClassName(View.class.getName());
4559        event.setPackageName(getContext().getPackageName());
4560        event.setEnabled(isEnabled());
4561        event.setContentDescription(mContentDescription);
4562
4563        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4564            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4565            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4566                    FOCUSABLES_ALL);
4567            event.setItemCount(focusablesTempList.size());
4568            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4569            focusablesTempList.clear();
4570        }
4571    }
4572
4573    /**
4574     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4575     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4576     * This method is responsible for obtaining an accessibility node info from a
4577     * pool of reusable instances and calling
4578     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4579     * initialize the former.
4580     * <p>
4581     * Note: The client is responsible for recycling the obtained instance by calling
4582     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4583     * </p>
4584     *
4585     * @return A populated {@link AccessibilityNodeInfo}.
4586     *
4587     * @see AccessibilityNodeInfo
4588     */
4589    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4590        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4591        if (provider != null) {
4592            return provider.createAccessibilityNodeInfo(View.NO_ID);
4593        } else {
4594            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4595            onInitializeAccessibilityNodeInfo(info);
4596            return info;
4597        }
4598    }
4599
4600    /**
4601     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4602     * The base implementation sets:
4603     * <ul>
4604     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4605     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4606     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4607     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4608     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4609     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4610     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4611     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4612     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4613     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4614     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4615     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4616     * </ul>
4617     * <p>
4618     * Subclasses should override this method, call the super implementation,
4619     * and set additional attributes.
4620     * </p>
4621     * <p>
4622     * If an {@link AccessibilityDelegate} has been specified via calling
4623     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4624     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4625     * is responsible for handling this call.
4626     * </p>
4627     *
4628     * @param info The instance to initialize.
4629     */
4630    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4631        if (mAccessibilityDelegate != null) {
4632            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4633        } else {
4634            onInitializeAccessibilityNodeInfoInternal(info);
4635        }
4636    }
4637
4638    /**
4639     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4640     *
4641     * Note: Called from the default {@link AccessibilityDelegate}.
4642     */
4643    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4644        Rect bounds = mAttachInfo.mTmpInvalRect;
4645        getDrawingRect(bounds);
4646        info.setBoundsInParent(bounds);
4647
4648        getGlobalVisibleRect(bounds);
4649        bounds.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4650        info.setBoundsInScreen(bounds);
4651
4652        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4653            ViewParent parent = getParentForAccessibility();
4654            if (parent instanceof View) {
4655                info.setParent((View) parent);
4656            }
4657        }
4658
4659        info.setPackageName(mContext.getPackageName());
4660        info.setClassName(View.class.getName());
4661        info.setContentDescription(getContentDescription());
4662
4663        info.setEnabled(isEnabled());
4664        info.setClickable(isClickable());
4665        info.setFocusable(isFocusable());
4666        info.setFocused(isFocused());
4667        info.setAccessibilityFocused(isAccessibilityFocused());
4668        info.setSelected(isSelected());
4669        info.setLongClickable(isLongClickable());
4670
4671        // TODO: These make sense only if we are in an AdapterView but all
4672        // views can be selected. Maybe from accessiiblity perspective
4673        // we should report as selectable view in an AdapterView.
4674        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4675        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4676
4677        if (isFocusable()) {
4678            if (isFocused()) {
4679                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4680            } else {
4681                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4682            }
4683        }
4684    }
4685
4686    /**
4687     * Computes whether this view is visible on the screen.
4688     *
4689     * @return Whether the view is visible on the screen.
4690     */
4691    boolean isDisplayedOnScreen() {
4692        // The first two checks are made also made by isShown() which
4693        // however traverses the tree up to the parent to catch that.
4694        // Therefore, we do some fail fast check to minimize the up
4695        // tree traversal.
4696        return (mAttachInfo != null
4697                && mAttachInfo.mWindowVisibility == View.VISIBLE
4698                && getAlpha() > 0
4699                && isShown()
4700                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4701    }
4702
4703    /**
4704     * Sets a delegate for implementing accessibility support via compositon as
4705     * opposed to inheritance. The delegate's primary use is for implementing
4706     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4707     *
4708     * @param delegate The delegate instance.
4709     *
4710     * @see AccessibilityDelegate
4711     */
4712    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4713        mAccessibilityDelegate = delegate;
4714    }
4715
4716    /**
4717     * Gets the provider for managing a virtual view hierarchy rooted at this View
4718     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4719     * that explore the window content.
4720     * <p>
4721     * If this method returns an instance, this instance is responsible for managing
4722     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4723     * View including the one representing the View itself. Similarly the returned
4724     * instance is responsible for performing accessibility actions on any virtual
4725     * view or the root view itself.
4726     * </p>
4727     * <p>
4728     * If an {@link AccessibilityDelegate} has been specified via calling
4729     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4730     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4731     * is responsible for handling this call.
4732     * </p>
4733     *
4734     * @return The provider.
4735     *
4736     * @see AccessibilityNodeProvider
4737     */
4738    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4739        if (mAccessibilityDelegate != null) {
4740            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4741        } else {
4742            return null;
4743        }
4744    }
4745
4746    /**
4747     * Gets the unique identifier of this view on the screen for accessibility purposes.
4748     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4749     *
4750     * @return The view accessibility id.
4751     *
4752     * @hide
4753     */
4754    public int getAccessibilityViewId() {
4755        if (mAccessibilityViewId == NO_ID) {
4756            mAccessibilityViewId = sNextAccessibilityViewId++;
4757        }
4758        return mAccessibilityViewId;
4759    }
4760
4761    /**
4762     * Gets the unique identifier of the window in which this View reseides.
4763     *
4764     * @return The window accessibility id.
4765     *
4766     * @hide
4767     */
4768    public int getAccessibilityWindowId() {
4769        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4770    }
4771
4772    /**
4773     * Gets the {@link View} description. It briefly describes the view and is
4774     * primarily used for accessibility support. Set this property to enable
4775     * better accessibility support for your application. This is especially
4776     * true for views that do not have textual representation (For example,
4777     * ImageButton).
4778     *
4779     * @return The content description.
4780     *
4781     * @attr ref android.R.styleable#View_contentDescription
4782     */
4783    @ViewDebug.ExportedProperty(category = "accessibility")
4784    public CharSequence getContentDescription() {
4785        return mContentDescription;
4786    }
4787
4788    /**
4789     * Sets the {@link View} description. It briefly describes the view and is
4790     * primarily used for accessibility support. Set this property to enable
4791     * better accessibility support for your application. This is especially
4792     * true for views that do not have textual representation (For example,
4793     * ImageButton).
4794     *
4795     * @param contentDescription The content description.
4796     *
4797     * @attr ref android.R.styleable#View_contentDescription
4798     */
4799    @RemotableViewMethod
4800    public void setContentDescription(CharSequence contentDescription) {
4801        mContentDescription = contentDescription;
4802    }
4803
4804    /**
4805     * Invoked whenever this view loses focus, either by losing window focus or by losing
4806     * focus within its window. This method can be used to clear any state tied to the
4807     * focus. For instance, if a button is held pressed with the trackball and the window
4808     * loses focus, this method can be used to cancel the press.
4809     *
4810     * Subclasses of View overriding this method should always call super.onFocusLost().
4811     *
4812     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4813     * @see #onWindowFocusChanged(boolean)
4814     *
4815     * @hide pending API council approval
4816     */
4817    protected void onFocusLost() {
4818        resetPressedState();
4819    }
4820
4821    private void resetPressedState() {
4822        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4823            return;
4824        }
4825
4826        if (isPressed()) {
4827            setPressed(false);
4828
4829            if (!mHasPerformedLongPress) {
4830                removeLongPressCallback();
4831            }
4832        }
4833    }
4834
4835    /**
4836     * Returns true if this view has focus
4837     *
4838     * @return True if this view has focus, false otherwise.
4839     */
4840    @ViewDebug.ExportedProperty(category = "focus")
4841    public boolean isFocused() {
4842        return (mPrivateFlags & FOCUSED) != 0;
4843    }
4844
4845    /**
4846     * Find the view in the hierarchy rooted at this view that currently has
4847     * focus.
4848     *
4849     * @return The view that currently has focus, or null if no focused view can
4850     *         be found.
4851     */
4852    public View findFocus() {
4853        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4854    }
4855
4856    /**
4857     * Indicates whether this view is one of the set of scrollable containers in
4858     * its window.
4859     *
4860     * @return whether this view is one of the set of scrollable containers in
4861     * its window
4862     *
4863     * @attr ref android.R.styleable#View_isScrollContainer
4864     */
4865    public boolean isScrollContainer() {
4866        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4867    }
4868
4869    /**
4870     * Change whether this view is one of the set of scrollable containers in
4871     * its window.  This will be used to determine whether the window can
4872     * resize or must pan when a soft input area is open -- scrollable
4873     * containers allow the window to use resize mode since the container
4874     * will appropriately shrink.
4875     *
4876     * @attr ref android.R.styleable#View_isScrollContainer
4877     */
4878    public void setScrollContainer(boolean isScrollContainer) {
4879        if (isScrollContainer) {
4880            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4881                mAttachInfo.mScrollContainers.add(this);
4882                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4883            }
4884            mPrivateFlags |= SCROLL_CONTAINER;
4885        } else {
4886            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4887                mAttachInfo.mScrollContainers.remove(this);
4888            }
4889            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4890        }
4891    }
4892
4893    /**
4894     * Returns the quality of the drawing cache.
4895     *
4896     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4897     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4898     *
4899     * @see #setDrawingCacheQuality(int)
4900     * @see #setDrawingCacheEnabled(boolean)
4901     * @see #isDrawingCacheEnabled()
4902     *
4903     * @attr ref android.R.styleable#View_drawingCacheQuality
4904     */
4905    public int getDrawingCacheQuality() {
4906        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4907    }
4908
4909    /**
4910     * Set the drawing cache quality of this view. This value is used only when the
4911     * drawing cache is enabled
4912     *
4913     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4914     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4915     *
4916     * @see #getDrawingCacheQuality()
4917     * @see #setDrawingCacheEnabled(boolean)
4918     * @see #isDrawingCacheEnabled()
4919     *
4920     * @attr ref android.R.styleable#View_drawingCacheQuality
4921     */
4922    public void setDrawingCacheQuality(int quality) {
4923        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4924    }
4925
4926    /**
4927     * Returns whether the screen should remain on, corresponding to the current
4928     * value of {@link #KEEP_SCREEN_ON}.
4929     *
4930     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4931     *
4932     * @see #setKeepScreenOn(boolean)
4933     *
4934     * @attr ref android.R.styleable#View_keepScreenOn
4935     */
4936    public boolean getKeepScreenOn() {
4937        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4938    }
4939
4940    /**
4941     * Controls whether the screen should remain on, modifying the
4942     * value of {@link #KEEP_SCREEN_ON}.
4943     *
4944     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4945     *
4946     * @see #getKeepScreenOn()
4947     *
4948     * @attr ref android.R.styleable#View_keepScreenOn
4949     */
4950    public void setKeepScreenOn(boolean keepScreenOn) {
4951        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4952    }
4953
4954    /**
4955     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4956     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4957     *
4958     * @attr ref android.R.styleable#View_nextFocusLeft
4959     */
4960    public int getNextFocusLeftId() {
4961        return mNextFocusLeftId;
4962    }
4963
4964    /**
4965     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4966     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4967     * decide automatically.
4968     *
4969     * @attr ref android.R.styleable#View_nextFocusLeft
4970     */
4971    public void setNextFocusLeftId(int nextFocusLeftId) {
4972        mNextFocusLeftId = nextFocusLeftId;
4973    }
4974
4975    /**
4976     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4977     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4978     *
4979     * @attr ref android.R.styleable#View_nextFocusRight
4980     */
4981    public int getNextFocusRightId() {
4982        return mNextFocusRightId;
4983    }
4984
4985    /**
4986     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4987     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4988     * decide automatically.
4989     *
4990     * @attr ref android.R.styleable#View_nextFocusRight
4991     */
4992    public void setNextFocusRightId(int nextFocusRightId) {
4993        mNextFocusRightId = nextFocusRightId;
4994    }
4995
4996    /**
4997     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4998     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4999     *
5000     * @attr ref android.R.styleable#View_nextFocusUp
5001     */
5002    public int getNextFocusUpId() {
5003        return mNextFocusUpId;
5004    }
5005
5006    /**
5007     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5008     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5009     * decide automatically.
5010     *
5011     * @attr ref android.R.styleable#View_nextFocusUp
5012     */
5013    public void setNextFocusUpId(int nextFocusUpId) {
5014        mNextFocusUpId = nextFocusUpId;
5015    }
5016
5017    /**
5018     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5019     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5020     *
5021     * @attr ref android.R.styleable#View_nextFocusDown
5022     */
5023    public int getNextFocusDownId() {
5024        return mNextFocusDownId;
5025    }
5026
5027    /**
5028     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5029     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5030     * decide automatically.
5031     *
5032     * @attr ref android.R.styleable#View_nextFocusDown
5033     */
5034    public void setNextFocusDownId(int nextFocusDownId) {
5035        mNextFocusDownId = nextFocusDownId;
5036    }
5037
5038    /**
5039     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5040     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5041     *
5042     * @attr ref android.R.styleable#View_nextFocusForward
5043     */
5044    public int getNextFocusForwardId() {
5045        return mNextFocusForwardId;
5046    }
5047
5048    /**
5049     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5050     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5051     * decide automatically.
5052     *
5053     * @attr ref android.R.styleable#View_nextFocusForward
5054     */
5055    public void setNextFocusForwardId(int nextFocusForwardId) {
5056        mNextFocusForwardId = nextFocusForwardId;
5057    }
5058
5059    /**
5060     * Returns the visibility of this view and all of its ancestors
5061     *
5062     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5063     */
5064    public boolean isShown() {
5065        View current = this;
5066        //noinspection ConstantConditions
5067        do {
5068            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5069                return false;
5070            }
5071            ViewParent parent = current.mParent;
5072            if (parent == null) {
5073                return false; // We are not attached to the view root
5074            }
5075            if (!(parent instanceof View)) {
5076                return true;
5077            }
5078            current = (View) parent;
5079        } while (current != null);
5080
5081        return false;
5082    }
5083
5084    /**
5085     * Called by the view hierarchy when the content insets for a window have
5086     * changed, to allow it to adjust its content to fit within those windows.
5087     * The content insets tell you the space that the status bar, input method,
5088     * and other system windows infringe on the application's window.
5089     *
5090     * <p>You do not normally need to deal with this function, since the default
5091     * window decoration given to applications takes care of applying it to the
5092     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5093     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5094     * and your content can be placed under those system elements.  You can then
5095     * use this method within your view hierarchy if you have parts of your UI
5096     * which you would like to ensure are not being covered.
5097     *
5098     * <p>The default implementation of this method simply applies the content
5099     * inset's to the view's padding.  This can be enabled through
5100     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5101     * the method and handle the insets however you would like.  Note that the
5102     * insets provided by the framework are always relative to the far edges
5103     * of the window, not accounting for the location of the called view within
5104     * that window.  (In fact when this method is called you do not yet know
5105     * where the layout will place the view, as it is done before layout happens.)
5106     *
5107     * <p>Note: unlike many View methods, there is no dispatch phase to this
5108     * call.  If you are overriding it in a ViewGroup and want to allow the
5109     * call to continue to your children, you must be sure to call the super
5110     * implementation.
5111     *
5112     * @param insets Current content insets of the window.  Prior to
5113     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5114     * the insets or else you and Android will be unhappy.
5115     *
5116     * @return Return true if this view applied the insets and it should not
5117     * continue propagating further down the hierarchy, false otherwise.
5118     */
5119    protected boolean fitSystemWindows(Rect insets) {
5120        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5121            mUserPaddingStart = -1;
5122            mUserPaddingEnd = -1;
5123            mUserPaddingRelative = false;
5124            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5125                    || mAttachInfo == null
5126                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5127                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5128                return true;
5129            } else {
5130                internalSetPadding(0, 0, 0, 0);
5131                return false;
5132            }
5133        }
5134        return false;
5135    }
5136
5137    /**
5138     * Set whether or not this view should account for system screen decorations
5139     * such as the status bar and inset its content. This allows this view to be
5140     * positioned in absolute screen coordinates and remain visible to the user.
5141     *
5142     * <p>This should only be used by top-level window decor views.
5143     *
5144     * @param fitSystemWindows true to inset content for system screen decorations, false for
5145     *                         default behavior.
5146     *
5147     * @attr ref android.R.styleable#View_fitsSystemWindows
5148     */
5149    public void setFitsSystemWindows(boolean fitSystemWindows) {
5150        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5151    }
5152
5153    /**
5154     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5155     * will account for system screen decorations such as the status bar and inset its
5156     * content. This allows the view to be positioned in absolute screen coordinates
5157     * and remain visible to the user.
5158     *
5159     * @return true if this view will adjust its content bounds for system screen decorations.
5160     *
5161     * @attr ref android.R.styleable#View_fitsSystemWindows
5162     */
5163    public boolean fitsSystemWindows() {
5164        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5165    }
5166
5167    /**
5168     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5169     */
5170    public void requestFitSystemWindows() {
5171        if (mParent != null) {
5172            mParent.requestFitSystemWindows();
5173        }
5174    }
5175
5176    /**
5177     * For use by PhoneWindow to make its own system window fitting optional.
5178     * @hide
5179     */
5180    public void makeOptionalFitsSystemWindows() {
5181        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5182    }
5183
5184    /**
5185     * Returns the visibility status for this view.
5186     *
5187     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5188     * @attr ref android.R.styleable#View_visibility
5189     */
5190    @ViewDebug.ExportedProperty(mapping = {
5191        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5192        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5193        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5194    })
5195    public int getVisibility() {
5196        return mViewFlags & VISIBILITY_MASK;
5197    }
5198
5199    /**
5200     * Set the enabled state of this view.
5201     *
5202     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5203     * @attr ref android.R.styleable#View_visibility
5204     */
5205    @RemotableViewMethod
5206    public void setVisibility(int visibility) {
5207        setFlags(visibility, VISIBILITY_MASK);
5208        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5209    }
5210
5211    /**
5212     * Returns the enabled status for this view. The interpretation of the
5213     * enabled state varies by subclass.
5214     *
5215     * @return True if this view is enabled, false otherwise.
5216     */
5217    @ViewDebug.ExportedProperty
5218    public boolean isEnabled() {
5219        return (mViewFlags & ENABLED_MASK) == ENABLED;
5220    }
5221
5222    /**
5223     * Set the enabled state of this view. The interpretation of the enabled
5224     * state varies by subclass.
5225     *
5226     * @param enabled True if this view is enabled, false otherwise.
5227     */
5228    @RemotableViewMethod
5229    public void setEnabled(boolean enabled) {
5230        if (enabled == isEnabled()) return;
5231
5232        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5233
5234        /*
5235         * The View most likely has to change its appearance, so refresh
5236         * the drawable state.
5237         */
5238        refreshDrawableState();
5239
5240        // Invalidate too, since the default behavior for views is to be
5241        // be drawn at 50% alpha rather than to change the drawable.
5242        invalidate(true);
5243    }
5244
5245    /**
5246     * Set whether this view can receive the focus.
5247     *
5248     * Setting this to false will also ensure that this view is not focusable
5249     * in touch mode.
5250     *
5251     * @param focusable If true, this view can receive the focus.
5252     *
5253     * @see #setFocusableInTouchMode(boolean)
5254     * @attr ref android.R.styleable#View_focusable
5255     */
5256    public void setFocusable(boolean focusable) {
5257        if (!focusable) {
5258            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5259        }
5260        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5261    }
5262
5263    /**
5264     * Set whether this view can receive focus while in touch mode.
5265     *
5266     * Setting this to true will also ensure that this view is focusable.
5267     *
5268     * @param focusableInTouchMode If true, this view can receive the focus while
5269     *   in touch mode.
5270     *
5271     * @see #setFocusable(boolean)
5272     * @attr ref android.R.styleable#View_focusableInTouchMode
5273     */
5274    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5275        // Focusable in touch mode should always be set before the focusable flag
5276        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5277        // which, in touch mode, will not successfully request focus on this view
5278        // because the focusable in touch mode flag is not set
5279        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5280        if (focusableInTouchMode) {
5281            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5282        }
5283    }
5284
5285    /**
5286     * Set whether this view should have sound effects enabled for events such as
5287     * clicking and touching.
5288     *
5289     * <p>You may wish to disable sound effects for a view if you already play sounds,
5290     * for instance, a dial key that plays dtmf tones.
5291     *
5292     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5293     * @see #isSoundEffectsEnabled()
5294     * @see #playSoundEffect(int)
5295     * @attr ref android.R.styleable#View_soundEffectsEnabled
5296     */
5297    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5298        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5299    }
5300
5301    /**
5302     * @return whether this view should have sound effects enabled for events such as
5303     *     clicking and touching.
5304     *
5305     * @see #setSoundEffectsEnabled(boolean)
5306     * @see #playSoundEffect(int)
5307     * @attr ref android.R.styleable#View_soundEffectsEnabled
5308     */
5309    @ViewDebug.ExportedProperty
5310    public boolean isSoundEffectsEnabled() {
5311        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5312    }
5313
5314    /**
5315     * Set whether this view should have haptic feedback for events such as
5316     * long presses.
5317     *
5318     * <p>You may wish to disable haptic feedback if your view already controls
5319     * its own haptic feedback.
5320     *
5321     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5322     * @see #isHapticFeedbackEnabled()
5323     * @see #performHapticFeedback(int)
5324     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5325     */
5326    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5327        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5328    }
5329
5330    /**
5331     * @return whether this view should have haptic feedback enabled for events
5332     * long presses.
5333     *
5334     * @see #setHapticFeedbackEnabled(boolean)
5335     * @see #performHapticFeedback(int)
5336     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5337     */
5338    @ViewDebug.ExportedProperty
5339    public boolean isHapticFeedbackEnabled() {
5340        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5341    }
5342
5343    /**
5344     * Returns the layout direction for this view.
5345     *
5346     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5347     *   {@link #LAYOUT_DIRECTION_RTL},
5348     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5349     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5350     * @attr ref android.R.styleable#View_layoutDirection
5351     */
5352    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5353        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5354        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5355        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5356        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5357    })
5358    public int getLayoutDirection() {
5359        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5360    }
5361
5362    /**
5363     * Set the layout direction for this view. This will propagate a reset of layout direction
5364     * resolution to the view's children and resolve layout direction for this view.
5365     *
5366     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5367     *   {@link #LAYOUT_DIRECTION_RTL},
5368     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5369     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5370     *
5371     * @attr ref android.R.styleable#View_layoutDirection
5372     */
5373    @RemotableViewMethod
5374    public void setLayoutDirection(int layoutDirection) {
5375        if (getLayoutDirection() != layoutDirection) {
5376            // Reset the current layout direction and the resolved one
5377            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5378            resetResolvedLayoutDirection();
5379            // Set the new layout direction (filtered) and ask for a layout pass
5380            mPrivateFlags2 |=
5381                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5382            requestLayout();
5383        }
5384    }
5385
5386    /**
5387     * Returns the resolved layout direction for this view.
5388     *
5389     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5390     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5391     */
5392    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5393        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5394        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5395    })
5396    public int getResolvedLayoutDirection() {
5397        // The layout diretion will be resolved only if needed
5398        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5399            resolveLayoutDirection();
5400        }
5401        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5402                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5403    }
5404
5405    /**
5406     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5407     * layout attribute and/or the inherited value from the parent
5408     *
5409     * @return true if the layout is right-to-left.
5410     */
5411    @ViewDebug.ExportedProperty(category = "layout")
5412    public boolean isLayoutRtl() {
5413        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5414    }
5415
5416    /**
5417     * Indicates whether the view is currently tracking transient state that the
5418     * app should not need to concern itself with saving and restoring, but that
5419     * the framework should take special note to preserve when possible.
5420     *
5421     * @return true if the view has transient state
5422     */
5423    @ViewDebug.ExportedProperty(category = "layout")
5424    public boolean hasTransientState() {
5425        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5426    }
5427
5428    /**
5429     * Set whether this view is currently tracking transient state that the
5430     * framework should attempt to preserve when possible. This flag is reference counted,
5431     * so every call to setHasTransientState(true) should be paired with a later call
5432     * to setHasTransientState(false).
5433     *
5434     * @param hasTransientState true if this view has transient state
5435     */
5436    public void setHasTransientState(boolean hasTransientState) {
5437        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5438                mTransientStateCount - 1;
5439        if (mTransientStateCount < 0) {
5440            mTransientStateCount = 0;
5441            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5442                    "unmatched pair of setHasTransientState calls");
5443        }
5444        if ((hasTransientState && mTransientStateCount == 1) ||
5445                (hasTransientState && mTransientStateCount == 0)) {
5446            // update flag if we've just incremented up from 0 or decremented down to 0
5447            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5448                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5449            if (mParent != null) {
5450                try {
5451                    mParent.childHasTransientStateChanged(this, hasTransientState);
5452                } catch (AbstractMethodError e) {
5453                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5454                            " does not fully implement ViewParent", e);
5455                }
5456            }
5457        }
5458    }
5459
5460    /**
5461     * If this view doesn't do any drawing on its own, set this flag to
5462     * allow further optimizations. By default, this flag is not set on
5463     * View, but could be set on some View subclasses such as ViewGroup.
5464     *
5465     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5466     * you should clear this flag.
5467     *
5468     * @param willNotDraw whether or not this View draw on its own
5469     */
5470    public void setWillNotDraw(boolean willNotDraw) {
5471        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5472    }
5473
5474    /**
5475     * Returns whether or not this View draws on its own.
5476     *
5477     * @return true if this view has nothing to draw, false otherwise
5478     */
5479    @ViewDebug.ExportedProperty(category = "drawing")
5480    public boolean willNotDraw() {
5481        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5482    }
5483
5484    /**
5485     * When a View's drawing cache is enabled, drawing is redirected to an
5486     * offscreen bitmap. Some views, like an ImageView, must be able to
5487     * bypass this mechanism if they already draw a single bitmap, to avoid
5488     * unnecessary usage of the memory.
5489     *
5490     * @param willNotCacheDrawing true if this view does not cache its
5491     *        drawing, false otherwise
5492     */
5493    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5494        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5495    }
5496
5497    /**
5498     * Returns whether or not this View can cache its drawing or not.
5499     *
5500     * @return true if this view does not cache its drawing, false otherwise
5501     */
5502    @ViewDebug.ExportedProperty(category = "drawing")
5503    public boolean willNotCacheDrawing() {
5504        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5505    }
5506
5507    /**
5508     * Indicates whether this view reacts to click events or not.
5509     *
5510     * @return true if the view is clickable, false otherwise
5511     *
5512     * @see #setClickable(boolean)
5513     * @attr ref android.R.styleable#View_clickable
5514     */
5515    @ViewDebug.ExportedProperty
5516    public boolean isClickable() {
5517        return (mViewFlags & CLICKABLE) == CLICKABLE;
5518    }
5519
5520    /**
5521     * Enables or disables click events for this view. When a view
5522     * is clickable it will change its state to "pressed" on every click.
5523     * Subclasses should set the view clickable to visually react to
5524     * user's clicks.
5525     *
5526     * @param clickable true to make the view clickable, false otherwise
5527     *
5528     * @see #isClickable()
5529     * @attr ref android.R.styleable#View_clickable
5530     */
5531    public void setClickable(boolean clickable) {
5532        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5533    }
5534
5535    /**
5536     * Indicates whether this view reacts to long click events or not.
5537     *
5538     * @return true if the view is long clickable, false otherwise
5539     *
5540     * @see #setLongClickable(boolean)
5541     * @attr ref android.R.styleable#View_longClickable
5542     */
5543    public boolean isLongClickable() {
5544        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5545    }
5546
5547    /**
5548     * Enables or disables long click events for this view. When a view is long
5549     * clickable it reacts to the user holding down the button for a longer
5550     * duration than a tap. This event can either launch the listener or a
5551     * context menu.
5552     *
5553     * @param longClickable true to make the view long clickable, false otherwise
5554     * @see #isLongClickable()
5555     * @attr ref android.R.styleable#View_longClickable
5556     */
5557    public void setLongClickable(boolean longClickable) {
5558        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5559    }
5560
5561    /**
5562     * Sets the pressed state for this view.
5563     *
5564     * @see #isClickable()
5565     * @see #setClickable(boolean)
5566     *
5567     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5568     *        the View's internal state from a previously set "pressed" state.
5569     */
5570    public void setPressed(boolean pressed) {
5571        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5572
5573        if (pressed) {
5574            mPrivateFlags |= PRESSED;
5575        } else {
5576            mPrivateFlags &= ~PRESSED;
5577        }
5578
5579        if (needsRefresh) {
5580            refreshDrawableState();
5581        }
5582        dispatchSetPressed(pressed);
5583    }
5584
5585    /**
5586     * Dispatch setPressed to all of this View's children.
5587     *
5588     * @see #setPressed(boolean)
5589     *
5590     * @param pressed The new pressed state
5591     */
5592    protected void dispatchSetPressed(boolean pressed) {
5593    }
5594
5595    /**
5596     * Indicates whether the view is currently in pressed state. Unless
5597     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5598     * the pressed state.
5599     *
5600     * @see #setPressed(boolean)
5601     * @see #isClickable()
5602     * @see #setClickable(boolean)
5603     *
5604     * @return true if the view is currently pressed, false otherwise
5605     */
5606    public boolean isPressed() {
5607        return (mPrivateFlags & PRESSED) == PRESSED;
5608    }
5609
5610    /**
5611     * Indicates whether this view will save its state (that is,
5612     * whether its {@link #onSaveInstanceState} method will be called).
5613     *
5614     * @return Returns true if the view state saving is enabled, else false.
5615     *
5616     * @see #setSaveEnabled(boolean)
5617     * @attr ref android.R.styleable#View_saveEnabled
5618     */
5619    public boolean isSaveEnabled() {
5620        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5621    }
5622
5623    /**
5624     * Controls whether the saving of this view's state is
5625     * enabled (that is, whether its {@link #onSaveInstanceState} method
5626     * will be called).  Note that even if freezing is enabled, the
5627     * view still must have an id assigned to it (via {@link #setId(int)})
5628     * for its state to be saved.  This flag can only disable the
5629     * saving of this view; any child views may still have their state saved.
5630     *
5631     * @param enabled Set to false to <em>disable</em> state saving, or true
5632     * (the default) to allow it.
5633     *
5634     * @see #isSaveEnabled()
5635     * @see #setId(int)
5636     * @see #onSaveInstanceState()
5637     * @attr ref android.R.styleable#View_saveEnabled
5638     */
5639    public void setSaveEnabled(boolean enabled) {
5640        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5641    }
5642
5643    /**
5644     * Gets whether the framework should discard touches when the view's
5645     * window is obscured by another visible window.
5646     * Refer to the {@link View} security documentation for more details.
5647     *
5648     * @return True if touch filtering is enabled.
5649     *
5650     * @see #setFilterTouchesWhenObscured(boolean)
5651     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5652     */
5653    @ViewDebug.ExportedProperty
5654    public boolean getFilterTouchesWhenObscured() {
5655        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5656    }
5657
5658    /**
5659     * Sets whether the framework should discard touches when the view's
5660     * window is obscured by another visible window.
5661     * Refer to the {@link View} security documentation for more details.
5662     *
5663     * @param enabled True if touch filtering should be enabled.
5664     *
5665     * @see #getFilterTouchesWhenObscured
5666     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5667     */
5668    public void setFilterTouchesWhenObscured(boolean enabled) {
5669        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5670                FILTER_TOUCHES_WHEN_OBSCURED);
5671    }
5672
5673    /**
5674     * Indicates whether the entire hierarchy under this view will save its
5675     * state when a state saving traversal occurs from its parent.  The default
5676     * is true; if false, these views will not be saved unless
5677     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5678     *
5679     * @return Returns true if the view state saving from parent is enabled, else false.
5680     *
5681     * @see #setSaveFromParentEnabled(boolean)
5682     */
5683    public boolean isSaveFromParentEnabled() {
5684        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5685    }
5686
5687    /**
5688     * Controls whether the entire hierarchy under this view will save its
5689     * state when a state saving traversal occurs from its parent.  The default
5690     * is true; if false, these views will not be saved unless
5691     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5692     *
5693     * @param enabled Set to false to <em>disable</em> state saving, or true
5694     * (the default) to allow it.
5695     *
5696     * @see #isSaveFromParentEnabled()
5697     * @see #setId(int)
5698     * @see #onSaveInstanceState()
5699     */
5700    public void setSaveFromParentEnabled(boolean enabled) {
5701        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5702    }
5703
5704
5705    /**
5706     * Returns whether this View is able to take focus.
5707     *
5708     * @return True if this view can take focus, or false otherwise.
5709     * @attr ref android.R.styleable#View_focusable
5710     */
5711    @ViewDebug.ExportedProperty(category = "focus")
5712    public final boolean isFocusable() {
5713        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5714    }
5715
5716    /**
5717     * When a view is focusable, it may not want to take focus when in touch mode.
5718     * For example, a button would like focus when the user is navigating via a D-pad
5719     * so that the user can click on it, but once the user starts touching the screen,
5720     * the button shouldn't take focus
5721     * @return Whether the view is focusable in touch mode.
5722     * @attr ref android.R.styleable#View_focusableInTouchMode
5723     */
5724    @ViewDebug.ExportedProperty
5725    public final boolean isFocusableInTouchMode() {
5726        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5727    }
5728
5729    /**
5730     * Find the nearest view in the specified direction that can take focus.
5731     * This does not actually give focus to that view.
5732     *
5733     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5734     *
5735     * @return The nearest focusable in the specified direction, or null if none
5736     *         can be found.
5737     */
5738    public View focusSearch(int direction) {
5739        if (mParent != null) {
5740            return mParent.focusSearch(this, direction);
5741        } else {
5742            return null;
5743        }
5744    }
5745
5746    /**
5747     * This method is the last chance for the focused view and its ancestors to
5748     * respond to an arrow key. This is called when the focused view did not
5749     * consume the key internally, nor could the view system find a new view in
5750     * the requested direction to give focus to.
5751     *
5752     * @param focused The currently focused view.
5753     * @param direction The direction focus wants to move. One of FOCUS_UP,
5754     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5755     * @return True if the this view consumed this unhandled move.
5756     */
5757    public boolean dispatchUnhandledMove(View focused, int direction) {
5758        return false;
5759    }
5760
5761    /**
5762     * If a user manually specified the next view id for a particular direction,
5763     * use the root to look up the view.
5764     * @param root The root view of the hierarchy containing this view.
5765     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5766     * or FOCUS_BACKWARD.
5767     * @return The user specified next view, or null if there is none.
5768     */
5769    View findUserSetNextFocus(View root, int direction) {
5770        switch (direction) {
5771            case FOCUS_LEFT:
5772                if (mNextFocusLeftId == View.NO_ID) return null;
5773                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5774            case FOCUS_RIGHT:
5775                if (mNextFocusRightId == View.NO_ID) return null;
5776                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5777            case FOCUS_UP:
5778                if (mNextFocusUpId == View.NO_ID) return null;
5779                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5780            case FOCUS_DOWN:
5781                if (mNextFocusDownId == View.NO_ID) return null;
5782                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5783            case FOCUS_FORWARD:
5784                if (mNextFocusForwardId == View.NO_ID) return null;
5785                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5786            case FOCUS_BACKWARD: {
5787                if (mID == View.NO_ID) return null;
5788                final int id = mID;
5789                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5790                    @Override
5791                    public boolean apply(View t) {
5792                        return t.mNextFocusForwardId == id;
5793                    }
5794                });
5795            }
5796        }
5797        return null;
5798    }
5799
5800    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5801        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5802            @Override
5803            public boolean apply(View t) {
5804                return t.mID == childViewId;
5805            }
5806        });
5807
5808        if (result == null) {
5809            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5810                    + "by user for id " + childViewId);
5811        }
5812        return result;
5813    }
5814
5815    /**
5816     * Find and return all focusable views that are descendants of this view,
5817     * possibly including this view if it is focusable itself.
5818     *
5819     * @param direction The direction of the focus
5820     * @return A list of focusable views
5821     */
5822    public ArrayList<View> getFocusables(int direction) {
5823        ArrayList<View> result = new ArrayList<View>(24);
5824        addFocusables(result, direction);
5825        return result;
5826    }
5827
5828    /**
5829     * Add any focusable views that are descendants of this view (possibly
5830     * including this view if it is focusable itself) to views.  If we are in touch mode,
5831     * only add views that are also focusable in touch mode.
5832     *
5833     * @param views Focusable views found so far
5834     * @param direction The direction of the focus
5835     */
5836    public void addFocusables(ArrayList<View> views, int direction) {
5837        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5838    }
5839
5840    /**
5841     * Adds any focusable views that are descendants of this view (possibly
5842     * including this view if it is focusable itself) to views. This method
5843     * adds all focusable views regardless if we are in touch mode or
5844     * only views focusable in touch mode if we are in touch mode or
5845     * only views that can take accessibility focus if accessibility is enabeld
5846     * depending on the focusable mode paramater.
5847     *
5848     * @param views Focusable views found so far or null if all we are interested is
5849     *        the number of focusables.
5850     * @param direction The direction of the focus.
5851     * @param focusableMode The type of focusables to be added.
5852     *
5853     * @see #FOCUSABLES_ALL
5854     * @see #FOCUSABLES_TOUCH_MODE
5855     */
5856    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5857        if (views == null) {
5858            return;
5859        }
5860        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5861            if (AccessibilityManager.getInstance(mContext).isEnabled()
5862                    && includeForAccessibility()) {
5863                views.add(this);
5864                return;
5865            }
5866        }
5867        if (!isFocusable()) {
5868            return;
5869        }
5870        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5871                && isInTouchMode() && !isFocusableInTouchMode()) {
5872            return;
5873        }
5874        views.add(this);
5875    }
5876
5877    /**
5878     * Finds the Views that contain given text. The containment is case insensitive.
5879     * The search is performed by either the text that the View renders or the content
5880     * description that describes the view for accessibility purposes and the view does
5881     * not render or both. Clients can specify how the search is to be performed via
5882     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5883     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5884     *
5885     * @param outViews The output list of matching Views.
5886     * @param searched The text to match against.
5887     *
5888     * @see #FIND_VIEWS_WITH_TEXT
5889     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5890     * @see #setContentDescription(CharSequence)
5891     */
5892    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5893        if (getAccessibilityNodeProvider() != null) {
5894            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5895                outViews.add(this);
5896            }
5897        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5898                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5899            String searchedLowerCase = searched.toString().toLowerCase();
5900            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5901            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5902                outViews.add(this);
5903            }
5904        }
5905    }
5906
5907    /**
5908     * Find and return all touchable views that are descendants of this view,
5909     * possibly including this view if it is touchable itself.
5910     *
5911     * @return A list of touchable views
5912     */
5913    public ArrayList<View> getTouchables() {
5914        ArrayList<View> result = new ArrayList<View>();
5915        addTouchables(result);
5916        return result;
5917    }
5918
5919    /**
5920     * Add any touchable views that are descendants of this view (possibly
5921     * including this view if it is touchable itself) to views.
5922     *
5923     * @param views Touchable views found so far
5924     */
5925    public void addTouchables(ArrayList<View> views) {
5926        final int viewFlags = mViewFlags;
5927
5928        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5929                && (viewFlags & ENABLED_MASK) == ENABLED) {
5930            views.add(this);
5931        }
5932    }
5933
5934    /**
5935     * Returns whether this View is accessibility focused.
5936     *
5937     * @return True if this View is accessibility focused.
5938     */
5939    boolean isAccessibilityFocused() {
5940        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
5941    }
5942
5943    /**
5944     * Call this to try to give accessibility focus to this view.
5945     *
5946     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
5947     * returns false or the view is no visible or the view already has accessibility
5948     * focus.
5949     *
5950     * See also {@link #focusSearch(int)}, which is what you call to say that you
5951     * have focus, and you want your parent to look for the next one.
5952     *
5953     * @return Whether this view actually took accessibility focus.
5954     *
5955     * @hide
5956     */
5957    public boolean requestAccessibilityFocus() {
5958        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
5959            return false;
5960        }
5961        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5962            return false;
5963        }
5964        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
5965            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
5966            ViewRootImpl viewRootImpl = getViewRootImpl();
5967            if (viewRootImpl != null) {
5968                viewRootImpl.setAccessibilityFocusedHost(this);
5969            }
5970            invalidate();
5971            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
5972            notifyAccessibilityStateChanged();
5973            // Try to give input focus to this view - not a descendant.
5974            requestFocusNoSearch(View.FOCUS_DOWN, null);
5975            return true;
5976        }
5977        return false;
5978    }
5979
5980    /**
5981     * Call this to try to clear accessibility focus of this view.
5982     *
5983     * See also {@link #focusSearch(int)}, which is what you call to say that you
5984     * have focus, and you want your parent to look for the next one.
5985     *
5986     * @hide
5987     */
5988    public void clearAccessibilityFocus() {
5989        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
5990            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
5991            ViewRootImpl viewRootImpl = getViewRootImpl();
5992            if (viewRootImpl != null) {
5993                viewRootImpl.setAccessibilityFocusedHost(null);
5994            }
5995            invalidate();
5996            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
5997            notifyAccessibilityStateChanged();
5998            // Try to move accessibility focus to the input focus.
5999            View rootView = getRootView();
6000            if (rootView != null) {
6001                View inputFocus = rootView.findFocus();
6002                if (inputFocus != null) {
6003                    inputFocus.requestAccessibilityFocus();
6004                }
6005            }
6006        }
6007    }
6008
6009    /**
6010     * Find the best view to take accessibility focus from a hover.
6011     * This function finds the deepest actionable view and if that
6012     * fails ask the parent to take accessibility focus from hover.
6013     *
6014     * @param x The X hovered location in this view coorditantes.
6015     * @param y The Y hovered location in this view coorditantes.
6016     * @return Whether the request was handled.
6017     *
6018     * @hide
6019     */
6020    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6021        if (onRequestAccessibilityFocusFromHover(x, y)) {
6022            return true;
6023        }
6024        ViewParent parent = mParent;
6025        if (parent instanceof View) {
6026            View parentView = (View) parent;
6027
6028            float[] position = mAttachInfo.mTmpTransformLocation;
6029            position[0] = x;
6030            position[1] = y;
6031
6032            // Compensate for the transformation of the current matrix.
6033            if (!hasIdentityMatrix()) {
6034                getMatrix().mapPoints(position);
6035            }
6036
6037            // Compensate for the parent scroll and the offset
6038            // of this view stop from the parent top.
6039            position[0] += mLeft - parentView.mScrollX;
6040            position[1] += mTop - parentView.mScrollY;
6041
6042            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6043        }
6044        return false;
6045    }
6046
6047    /**
6048     * Requests to give this View focus from hover.
6049     *
6050     * @param x The X hovered location in this view coorditantes.
6051     * @param y The Y hovered location in this view coorditantes.
6052     * @return Whether the request was handled.
6053     *
6054     * @hide
6055     */
6056    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6057        if (includeForAccessibility()
6058                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6059            return requestAccessibilityFocus();
6060        }
6061        return false;
6062    }
6063
6064    /**
6065     * Clears accessibility focus without calling any callback methods
6066     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6067     * is used for clearing accessibility focus when giving this focus to
6068     * another view.
6069     */
6070    void clearAccessibilityFocusNoCallbacks() {
6071        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6072            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6073            invalidate();
6074        }
6075    }
6076
6077    /**
6078     * Call this to try to give focus to a specific view or to one of its
6079     * descendants.
6080     *
6081     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6082     * false), or if it is focusable and it is not focusable in touch mode
6083     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6084     *
6085     * See also {@link #focusSearch(int)}, which is what you call to say that you
6086     * have focus, and you want your parent to look for the next one.
6087     *
6088     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6089     * {@link #FOCUS_DOWN} and <code>null</code>.
6090     *
6091     * @return Whether this view or one of its descendants actually took focus.
6092     */
6093    public final boolean requestFocus() {
6094        return requestFocus(View.FOCUS_DOWN);
6095    }
6096
6097    /**
6098     * Call this to try to give focus to a specific view or to one of its
6099     * descendants and give it a hint about what direction focus is heading.
6100     *
6101     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6102     * false), or if it is focusable and it is not focusable in touch mode
6103     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6104     *
6105     * See also {@link #focusSearch(int)}, which is what you call to say that you
6106     * have focus, and you want your parent to look for the next one.
6107     *
6108     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6109     * <code>null</code> set for the previously focused rectangle.
6110     *
6111     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6112     * @return Whether this view or one of its descendants actually took focus.
6113     */
6114    public final boolean requestFocus(int direction) {
6115        return requestFocus(direction, null);
6116    }
6117
6118    /**
6119     * Call this to try to give focus to a specific view or to one of its descendants
6120     * and give it hints about the direction and a specific rectangle that the focus
6121     * is coming from.  The rectangle can help give larger views a finer grained hint
6122     * about where focus is coming from, and therefore, where to show selection, or
6123     * forward focus change internally.
6124     *
6125     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6126     * false), or if it is focusable and it is not focusable in touch mode
6127     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6128     *
6129     * A View will not take focus if it is not visible.
6130     *
6131     * A View will not take focus if one of its parents has
6132     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6133     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6134     *
6135     * See also {@link #focusSearch(int)}, which is what you call to say that you
6136     * have focus, and you want your parent to look for the next one.
6137     *
6138     * You may wish to override this method if your custom {@link View} has an internal
6139     * {@link View} that it wishes to forward the request to.
6140     *
6141     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6142     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6143     *        to give a finer grained hint about where focus is coming from.  May be null
6144     *        if there is no hint.
6145     * @return Whether this view or one of its descendants actually took focus.
6146     */
6147    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6148        return requestFocusNoSearch(direction, previouslyFocusedRect);
6149    }
6150
6151    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6152        // need to be focusable
6153        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6154                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6155            return false;
6156        }
6157
6158        // need to be focusable in touch mode if in touch mode
6159        if (isInTouchMode() &&
6160            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6161               return false;
6162        }
6163
6164        // need to not have any parents blocking us
6165        if (hasAncestorThatBlocksDescendantFocus()) {
6166            return false;
6167        }
6168
6169        handleFocusGainInternal(direction, previouslyFocusedRect);
6170        return true;
6171    }
6172
6173    /**
6174     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6175     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6176     * touch mode to request focus when they are touched.
6177     *
6178     * @return Whether this view or one of its descendants actually took focus.
6179     *
6180     * @see #isInTouchMode()
6181     *
6182     */
6183    public final boolean requestFocusFromTouch() {
6184        // Leave touch mode if we need to
6185        if (isInTouchMode()) {
6186            ViewRootImpl viewRoot = getViewRootImpl();
6187            if (viewRoot != null) {
6188                viewRoot.ensureTouchMode(false);
6189            }
6190        }
6191        return requestFocus(View.FOCUS_DOWN);
6192    }
6193
6194    /**
6195     * @return Whether any ancestor of this view blocks descendant focus.
6196     */
6197    private boolean hasAncestorThatBlocksDescendantFocus() {
6198        ViewParent ancestor = mParent;
6199        while (ancestor instanceof ViewGroup) {
6200            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6201            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6202                return true;
6203            } else {
6204                ancestor = vgAncestor.getParent();
6205            }
6206        }
6207        return false;
6208    }
6209
6210    /**
6211     * Gets the mode for determining whether this View is important for accessibility
6212     * which is if it fires accessibility events and if it is reported to
6213     * accessibility services that query the screen.
6214     *
6215     * @return The mode for determining whether a View is important for accessibility.
6216     *
6217     * @attr ref android.R.styleable#View_importantForAccessibility
6218     *
6219     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6220     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6221     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6222     */
6223    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6224            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6225                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6226            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6227                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6228            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6229                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6230        })
6231    public int getImportantForAccessibility() {
6232        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6233                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6234    }
6235
6236    /**
6237     * Sets how to determine whether this view is important for accessibility
6238     * which is if it fires accessibility events and if it is reported to
6239     * accessibility services that query the screen.
6240     *
6241     * @param mode How to determine whether this view is important for accessibility.
6242     *
6243     * @attr ref android.R.styleable#View_importantForAccessibility
6244     *
6245     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6246     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6247     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6248     */
6249    public void setImportantForAccessibility(int mode) {
6250        if (mode != getImportantForAccessibility()) {
6251            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6252            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6253                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6254            notifyAccessibilityStateChanged();
6255        }
6256    }
6257
6258    /**
6259     * Gets whether this view should be exposed for accessibility.
6260     *
6261     * @return Whether the view is exposed for accessibility.
6262     *
6263     * @hide
6264     */
6265    public boolean isImportantForAccessibility() {
6266        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6267                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6268        switch (mode) {
6269            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6270                return true;
6271            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6272                return false;
6273            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6274                return isActionableForAccessibility() || hasListenersForAccessibility();
6275            default:
6276                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6277                        + mode);
6278        }
6279    }
6280
6281    /**
6282     * Gets the parent for accessibility purposes. Note that the parent for
6283     * accessibility is not necessary the immediate parent. It is the first
6284     * predecessor that is important for accessibility.
6285     *
6286     * @return The parent for accessibility purposes.
6287     */
6288    public ViewParent getParentForAccessibility() {
6289        if (mParent instanceof View) {
6290            View parentView = (View) mParent;
6291            if (parentView.includeForAccessibility()) {
6292                return mParent;
6293            } else {
6294                return mParent.getParentForAccessibility();
6295            }
6296        }
6297        return null;
6298    }
6299
6300    /**
6301     * Adds the children of a given View for accessibility. Since some Views are
6302     * not important for accessibility the children for accessibility are not
6303     * necessarily direct children of the riew, rather they are the first level of
6304     * descendants important for accessibility.
6305     *
6306     * @param children The list of children for accessibility.
6307     */
6308    public void addChildrenForAccessibility(ArrayList<View> children) {
6309        if (includeForAccessibility()) {
6310            children.add(this);
6311        }
6312    }
6313
6314    /**
6315     * Whether to regard this view for accessibility. A view is regarded for
6316     * accessibility if it is important for accessibility or the querying
6317     * accessibility service has explicitly requested that view not
6318     * important for accessibility are regarded.
6319     *
6320     * @return Whether to regard the view for accessibility.
6321     */
6322    boolean includeForAccessibility() {
6323        if (mAttachInfo != null) {
6324            if (!mAttachInfo.mIncludeNotImportantViews) {
6325                return isImportantForAccessibility() && isDisplayedOnScreen();
6326            } else {
6327                return isDisplayedOnScreen();
6328            }
6329        }
6330        return false;
6331    }
6332
6333    /**
6334     * Returns whether the View is considered actionable from
6335     * accessibility perspective. Such view are important for
6336     * accessiiblity.
6337     *
6338     * @return True if the view is actionable for accessibility.
6339     */
6340    private boolean isActionableForAccessibility() {
6341        return (isClickable() || isLongClickable() || isFocusable());
6342    }
6343
6344    /**
6345     * Returns whether the View has registered callbacks wich makes it
6346     * important for accessiiblity.
6347     *
6348     * @return True if the view is actionable for accessibility.
6349     */
6350    private boolean hasListenersForAccessibility() {
6351        ListenerInfo info = getListenerInfo();
6352        return mTouchDelegate != null || info.mOnKeyListener != null
6353                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6354                || info.mOnHoverListener != null || info.mOnDragListener != null;
6355    }
6356
6357    /**
6358     * Notifies accessibility services that some view's important for
6359     * accessibility state has changed. Note that such notifications
6360     * are made at most once every
6361     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6362     * to avoid unnecessary load to the system. Also once a view has
6363     * made a notifucation this method is a NOP until the notification has
6364     * been sent to clients.
6365     *
6366     * @hide
6367     *
6368     * TODO: Makse sure this method is called for any view state change
6369     *       that is interesting for accessilility purposes.
6370     */
6371    public void notifyAccessibilityStateChanged() {
6372        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6373            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6374            if (mParent != null) {
6375                mParent.childAccessibilityStateChanged(this);
6376            }
6377        }
6378    }
6379
6380    /**
6381     * Reset the state indicating the this view has requested clients
6382     * interested in its accessiblity state to be notified.
6383     *
6384     * @hide
6385     */
6386    public void resetAccessibilityStateChanged() {
6387        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6388    }
6389
6390    /**
6391     * Performs the specified accessibility action on the view. For
6392     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6393     *
6394     * @param action The action to perform.
6395     * @return Whether the action was performed.
6396     */
6397    public boolean performAccessibilityAction(int action, Bundle args) {
6398        switch (action) {
6399            case AccessibilityNodeInfo.ACTION_CLICK: {
6400                if (isClickable()) {
6401                    performClick();
6402                }
6403            } break;
6404            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6405                if (isLongClickable()) {
6406                    performLongClick();
6407                }
6408            } break;
6409            case AccessibilityNodeInfo.ACTION_FOCUS: {
6410                if (!hasFocus()) {
6411                    // Get out of touch mode since accessibility
6412                    // wants to move focus around.
6413                    getViewRootImpl().ensureTouchMode(false);
6414                    return requestFocus();
6415                }
6416            } break;
6417            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6418                if (hasFocus()) {
6419                    clearFocus();
6420                    return !isFocused();
6421                }
6422            } break;
6423            case AccessibilityNodeInfo.ACTION_SELECT: {
6424                if (!isSelected()) {
6425                    setSelected(true);
6426                    return isSelected();
6427                }
6428            } break;
6429            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6430                if (isSelected()) {
6431                    setSelected(false);
6432                    return !isSelected();
6433                }
6434            } break;
6435            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6436                if (!isAccessibilityFocused()) {
6437                    return requestAccessibilityFocus();
6438                }
6439            } break;
6440            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6441                if (isAccessibilityFocused()) {
6442                    clearAccessibilityFocus();
6443                    return true;
6444                }
6445            } break;
6446        }
6447        return false;
6448    }
6449
6450    /**
6451     * @hide
6452     */
6453    public void dispatchStartTemporaryDetach() {
6454        onStartTemporaryDetach();
6455    }
6456
6457    /**
6458     * This is called when a container is going to temporarily detach a child, with
6459     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6460     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6461     * {@link #onDetachedFromWindow()} when the container is done.
6462     */
6463    public void onStartTemporaryDetach() {
6464        removeUnsetPressCallback();
6465        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6466    }
6467
6468    /**
6469     * @hide
6470     */
6471    public void dispatchFinishTemporaryDetach() {
6472        onFinishTemporaryDetach();
6473    }
6474
6475    /**
6476     * Called after {@link #onStartTemporaryDetach} when the container is done
6477     * changing the view.
6478     */
6479    public void onFinishTemporaryDetach() {
6480    }
6481
6482    /**
6483     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6484     * for this view's window.  Returns null if the view is not currently attached
6485     * to the window.  Normally you will not need to use this directly, but
6486     * just use the standard high-level event callbacks like
6487     * {@link #onKeyDown(int, KeyEvent)}.
6488     */
6489    public KeyEvent.DispatcherState getKeyDispatcherState() {
6490        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6491    }
6492
6493    /**
6494     * Dispatch a key event before it is processed by any input method
6495     * associated with the view hierarchy.  This can be used to intercept
6496     * key events in special situations before the IME consumes them; a
6497     * typical example would be handling the BACK key to update the application's
6498     * UI instead of allowing the IME to see it and close itself.
6499     *
6500     * @param event The key event to be dispatched.
6501     * @return True if the event was handled, false otherwise.
6502     */
6503    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6504        return onKeyPreIme(event.getKeyCode(), event);
6505    }
6506
6507    /**
6508     * Dispatch a key event to the next view on the focus path. This path runs
6509     * from the top of the view tree down to the currently focused view. If this
6510     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6511     * the next node down the focus path. This method also fires any key
6512     * listeners.
6513     *
6514     * @param event The key event to be dispatched.
6515     * @return True if the event was handled, false otherwise.
6516     */
6517    public boolean dispatchKeyEvent(KeyEvent event) {
6518        if (mInputEventConsistencyVerifier != null) {
6519            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6520        }
6521
6522        // Give any attached key listener a first crack at the event.
6523        //noinspection SimplifiableIfStatement
6524        ListenerInfo li = mListenerInfo;
6525        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6526                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6527            return true;
6528        }
6529
6530        if (event.dispatch(this, mAttachInfo != null
6531                ? mAttachInfo.mKeyDispatchState : null, this)) {
6532            return true;
6533        }
6534
6535        if (mInputEventConsistencyVerifier != null) {
6536            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6537        }
6538        return false;
6539    }
6540
6541    /**
6542     * Dispatches a key shortcut event.
6543     *
6544     * @param event The key event to be dispatched.
6545     * @return True if the event was handled by the view, false otherwise.
6546     */
6547    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6548        return onKeyShortcut(event.getKeyCode(), event);
6549    }
6550
6551    /**
6552     * Pass the touch screen motion event down to the target view, or this
6553     * view if it is the target.
6554     *
6555     * @param event The motion event to be dispatched.
6556     * @return True if the event was handled by the view, false otherwise.
6557     */
6558    public boolean dispatchTouchEvent(MotionEvent event) {
6559        if (mInputEventConsistencyVerifier != null) {
6560            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6561        }
6562
6563        if (onFilterTouchEventForSecurity(event)) {
6564            //noinspection SimplifiableIfStatement
6565            ListenerInfo li = mListenerInfo;
6566            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6567                    && li.mOnTouchListener.onTouch(this, event)) {
6568                return true;
6569            }
6570
6571            if (onTouchEvent(event)) {
6572                return true;
6573            }
6574        }
6575
6576        if (mInputEventConsistencyVerifier != null) {
6577            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6578        }
6579        return false;
6580    }
6581
6582    /**
6583     * Filter the touch event to apply security policies.
6584     *
6585     * @param event The motion event to be filtered.
6586     * @return True if the event should be dispatched, false if the event should be dropped.
6587     *
6588     * @see #getFilterTouchesWhenObscured
6589     */
6590    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6591        //noinspection RedundantIfStatement
6592        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6593                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6594            // Window is obscured, drop this touch.
6595            return false;
6596        }
6597        return true;
6598    }
6599
6600    /**
6601     * Pass a trackball motion event down to the focused view.
6602     *
6603     * @param event The motion event to be dispatched.
6604     * @return True if the event was handled by the view, false otherwise.
6605     */
6606    public boolean dispatchTrackballEvent(MotionEvent event) {
6607        if (mInputEventConsistencyVerifier != null) {
6608            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6609        }
6610
6611        return onTrackballEvent(event);
6612    }
6613
6614    /**
6615     * Dispatch a generic motion event.
6616     * <p>
6617     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6618     * are delivered to the view under the pointer.  All other generic motion events are
6619     * delivered to the focused view.  Hover events are handled specially and are delivered
6620     * to {@link #onHoverEvent(MotionEvent)}.
6621     * </p>
6622     *
6623     * @param event The motion event to be dispatched.
6624     * @return True if the event was handled by the view, false otherwise.
6625     */
6626    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6627        if (mInputEventConsistencyVerifier != null) {
6628            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6629        }
6630
6631        final int source = event.getSource();
6632        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6633            final int action = event.getAction();
6634            if (action == MotionEvent.ACTION_HOVER_ENTER
6635                    || action == MotionEvent.ACTION_HOVER_MOVE
6636                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6637                if (dispatchHoverEvent(event)) {
6638                    return true;
6639                }
6640            } else if (dispatchGenericPointerEvent(event)) {
6641                return true;
6642            }
6643        } else if (dispatchGenericFocusedEvent(event)) {
6644            return true;
6645        }
6646
6647        if (dispatchGenericMotionEventInternal(event)) {
6648            return true;
6649        }
6650
6651        if (mInputEventConsistencyVerifier != null) {
6652            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6653        }
6654        return false;
6655    }
6656
6657    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6658        //noinspection SimplifiableIfStatement
6659        ListenerInfo li = mListenerInfo;
6660        if (li != null && li.mOnGenericMotionListener != null
6661                && (mViewFlags & ENABLED_MASK) == ENABLED
6662                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6663            return true;
6664        }
6665
6666        if (onGenericMotionEvent(event)) {
6667            return true;
6668        }
6669
6670        if (mInputEventConsistencyVerifier != null) {
6671            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6672        }
6673        return false;
6674    }
6675
6676    /**
6677     * Dispatch a hover event.
6678     * <p>
6679     * Do not call this method directly.
6680     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6681     * </p>
6682     *
6683     * @param event The motion event to be dispatched.
6684     * @return True if the event was handled by the view, false otherwise.
6685     */
6686    protected boolean dispatchHoverEvent(MotionEvent event) {
6687        //noinspection SimplifiableIfStatement
6688        ListenerInfo li = mListenerInfo;
6689        if (li != null && li.mOnHoverListener != null
6690                && (mViewFlags & ENABLED_MASK) == ENABLED
6691                && li.mOnHoverListener.onHover(this, event)) {
6692            return true;
6693        }
6694
6695        return onHoverEvent(event);
6696    }
6697
6698    /**
6699     * Returns true if the view has a child to which it has recently sent
6700     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6701     * it does not have a hovered child, then it must be the innermost hovered view.
6702     * @hide
6703     */
6704    protected boolean hasHoveredChild() {
6705        return false;
6706    }
6707
6708    /**
6709     * Dispatch a generic motion event to the view under the first pointer.
6710     * <p>
6711     * Do not call this method directly.
6712     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6713     * </p>
6714     *
6715     * @param event The motion event to be dispatched.
6716     * @return True if the event was handled by the view, false otherwise.
6717     */
6718    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6719        return false;
6720    }
6721
6722    /**
6723     * Dispatch a generic motion event to the currently focused view.
6724     * <p>
6725     * Do not call this method directly.
6726     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6727     * </p>
6728     *
6729     * @param event The motion event to be dispatched.
6730     * @return True if the event was handled by the view, false otherwise.
6731     */
6732    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6733        return false;
6734    }
6735
6736    /**
6737     * Dispatch a pointer event.
6738     * <p>
6739     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6740     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6741     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6742     * and should not be expected to handle other pointing device features.
6743     * </p>
6744     *
6745     * @param event The motion event to be dispatched.
6746     * @return True if the event was handled by the view, false otherwise.
6747     * @hide
6748     */
6749    public final boolean dispatchPointerEvent(MotionEvent event) {
6750        if (event.isTouchEvent()) {
6751            return dispatchTouchEvent(event);
6752        } else {
6753            return dispatchGenericMotionEvent(event);
6754        }
6755    }
6756
6757    /**
6758     * Called when the window containing this view gains or loses window focus.
6759     * ViewGroups should override to route to their children.
6760     *
6761     * @param hasFocus True if the window containing this view now has focus,
6762     *        false otherwise.
6763     */
6764    public void dispatchWindowFocusChanged(boolean hasFocus) {
6765        onWindowFocusChanged(hasFocus);
6766    }
6767
6768    /**
6769     * Called when the window containing this view gains or loses focus.  Note
6770     * that this is separate from view focus: to receive key events, both
6771     * your view and its window must have focus.  If a window is displayed
6772     * on top of yours that takes input focus, then your own window will lose
6773     * focus but the view focus will remain unchanged.
6774     *
6775     * @param hasWindowFocus True if the window containing this view now has
6776     *        focus, false otherwise.
6777     */
6778    public void onWindowFocusChanged(boolean hasWindowFocus) {
6779        InputMethodManager imm = InputMethodManager.peekInstance();
6780        if (!hasWindowFocus) {
6781            if (isPressed()) {
6782                setPressed(false);
6783            }
6784            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6785                imm.focusOut(this);
6786            }
6787            removeLongPressCallback();
6788            removeTapCallback();
6789            onFocusLost();
6790        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6791            imm.focusIn(this);
6792        }
6793        refreshDrawableState();
6794    }
6795
6796    /**
6797     * Returns true if this view is in a window that currently has window focus.
6798     * Note that this is not the same as the view itself having focus.
6799     *
6800     * @return True if this view is in a window that currently has window focus.
6801     */
6802    public boolean hasWindowFocus() {
6803        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6804    }
6805
6806    /**
6807     * Dispatch a view visibility change down the view hierarchy.
6808     * ViewGroups should override to route to their children.
6809     * @param changedView The view whose visibility changed. Could be 'this' or
6810     * an ancestor view.
6811     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6812     * {@link #INVISIBLE} or {@link #GONE}.
6813     */
6814    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6815        onVisibilityChanged(changedView, visibility);
6816    }
6817
6818    /**
6819     * Called when the visibility of the view or an ancestor of the view is changed.
6820     * @param changedView The view whose visibility changed. Could be 'this' or
6821     * an ancestor view.
6822     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6823     * {@link #INVISIBLE} or {@link #GONE}.
6824     */
6825    protected void onVisibilityChanged(View changedView, int visibility) {
6826        if (visibility == VISIBLE) {
6827            if (mAttachInfo != null) {
6828                initialAwakenScrollBars();
6829            } else {
6830                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6831            }
6832        }
6833    }
6834
6835    /**
6836     * Dispatch a hint about whether this view is displayed. For instance, when
6837     * a View moves out of the screen, it might receives a display hint indicating
6838     * the view is not displayed. Applications should not <em>rely</em> on this hint
6839     * as there is no guarantee that they will receive one.
6840     *
6841     * @param hint A hint about whether or not this view is displayed:
6842     * {@link #VISIBLE} or {@link #INVISIBLE}.
6843     */
6844    public void dispatchDisplayHint(int hint) {
6845        onDisplayHint(hint);
6846    }
6847
6848    /**
6849     * Gives this view a hint about whether is displayed or not. For instance, when
6850     * a View moves out of the screen, it might receives a display hint indicating
6851     * the view is not displayed. Applications should not <em>rely</em> on this hint
6852     * as there is no guarantee that they will receive one.
6853     *
6854     * @param hint A hint about whether or not this view is displayed:
6855     * {@link #VISIBLE} or {@link #INVISIBLE}.
6856     */
6857    protected void onDisplayHint(int hint) {
6858    }
6859
6860    /**
6861     * Dispatch a window visibility change down the view hierarchy.
6862     * ViewGroups should override to route to their children.
6863     *
6864     * @param visibility The new visibility of the window.
6865     *
6866     * @see #onWindowVisibilityChanged(int)
6867     */
6868    public void dispatchWindowVisibilityChanged(int visibility) {
6869        onWindowVisibilityChanged(visibility);
6870    }
6871
6872    /**
6873     * Called when the window containing has change its visibility
6874     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6875     * that this tells you whether or not your window is being made visible
6876     * to the window manager; this does <em>not</em> tell you whether or not
6877     * your window is obscured by other windows on the screen, even if it
6878     * is itself visible.
6879     *
6880     * @param visibility The new visibility of the window.
6881     */
6882    protected void onWindowVisibilityChanged(int visibility) {
6883        if (visibility == VISIBLE) {
6884            initialAwakenScrollBars();
6885        }
6886    }
6887
6888    /**
6889     * Returns the current visibility of the window this view is attached to
6890     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6891     *
6892     * @return Returns the current visibility of the view's window.
6893     */
6894    public int getWindowVisibility() {
6895        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6896    }
6897
6898    /**
6899     * Retrieve the overall visible display size in which the window this view is
6900     * attached to has been positioned in.  This takes into account screen
6901     * decorations above the window, for both cases where the window itself
6902     * is being position inside of them or the window is being placed under
6903     * then and covered insets are used for the window to position its content
6904     * inside.  In effect, this tells you the available area where content can
6905     * be placed and remain visible to users.
6906     *
6907     * <p>This function requires an IPC back to the window manager to retrieve
6908     * the requested information, so should not be used in performance critical
6909     * code like drawing.
6910     *
6911     * @param outRect Filled in with the visible display frame.  If the view
6912     * is not attached to a window, this is simply the raw display size.
6913     */
6914    public void getWindowVisibleDisplayFrame(Rect outRect) {
6915        if (mAttachInfo != null) {
6916            try {
6917                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6918            } catch (RemoteException e) {
6919                return;
6920            }
6921            // XXX This is really broken, and probably all needs to be done
6922            // in the window manager, and we need to know more about whether
6923            // we want the area behind or in front of the IME.
6924            final Rect insets = mAttachInfo.mVisibleInsets;
6925            outRect.left += insets.left;
6926            outRect.top += insets.top;
6927            outRect.right -= insets.right;
6928            outRect.bottom -= insets.bottom;
6929            return;
6930        }
6931        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6932        d.getRectSize(outRect);
6933    }
6934
6935    /**
6936     * Dispatch a notification about a resource configuration change down
6937     * the view hierarchy.
6938     * ViewGroups should override to route to their children.
6939     *
6940     * @param newConfig The new resource configuration.
6941     *
6942     * @see #onConfigurationChanged(android.content.res.Configuration)
6943     */
6944    public void dispatchConfigurationChanged(Configuration newConfig) {
6945        onConfigurationChanged(newConfig);
6946    }
6947
6948    /**
6949     * Called when the current configuration of the resources being used
6950     * by the application have changed.  You can use this to decide when
6951     * to reload resources that can changed based on orientation and other
6952     * configuration characterstics.  You only need to use this if you are
6953     * not relying on the normal {@link android.app.Activity} mechanism of
6954     * recreating the activity instance upon a configuration change.
6955     *
6956     * @param newConfig The new resource configuration.
6957     */
6958    protected void onConfigurationChanged(Configuration newConfig) {
6959    }
6960
6961    /**
6962     * Private function to aggregate all per-view attributes in to the view
6963     * root.
6964     */
6965    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6966        performCollectViewAttributes(attachInfo, visibility);
6967    }
6968
6969    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6970        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
6971            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6972                attachInfo.mKeepScreenOn = true;
6973            }
6974            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6975            ListenerInfo li = mListenerInfo;
6976            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6977                attachInfo.mHasSystemUiListeners = true;
6978            }
6979        }
6980    }
6981
6982    void needGlobalAttributesUpdate(boolean force) {
6983        final AttachInfo ai = mAttachInfo;
6984        if (ai != null) {
6985            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6986                    || ai.mHasSystemUiListeners) {
6987                ai.mRecomputeGlobalAttributes = true;
6988            }
6989        }
6990    }
6991
6992    /**
6993     * Returns whether the device is currently in touch mode.  Touch mode is entered
6994     * once the user begins interacting with the device by touch, and affects various
6995     * things like whether focus is always visible to the user.
6996     *
6997     * @return Whether the device is in touch mode.
6998     */
6999    @ViewDebug.ExportedProperty
7000    public boolean isInTouchMode() {
7001        if (mAttachInfo != null) {
7002            return mAttachInfo.mInTouchMode;
7003        } else {
7004            return ViewRootImpl.isInTouchMode();
7005        }
7006    }
7007
7008    /**
7009     * Returns the context the view is running in, through which it can
7010     * access the current theme, resources, etc.
7011     *
7012     * @return The view's Context.
7013     */
7014    @ViewDebug.CapturedViewProperty
7015    public final Context getContext() {
7016        return mContext;
7017    }
7018
7019    /**
7020     * Handle a key event before it is processed by any input method
7021     * associated with the view hierarchy.  This can be used to intercept
7022     * key events in special situations before the IME consumes them; a
7023     * typical example would be handling the BACK key to update the application's
7024     * UI instead of allowing the IME to see it and close itself.
7025     *
7026     * @param keyCode The value in event.getKeyCode().
7027     * @param event Description of the key event.
7028     * @return If you handled the event, return true. If you want to allow the
7029     *         event to be handled by the next receiver, return false.
7030     */
7031    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7032        return false;
7033    }
7034
7035    /**
7036     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7037     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7038     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7039     * is released, if the view is enabled and clickable.
7040     *
7041     * @param keyCode A key code that represents the button pressed, from
7042     *                {@link android.view.KeyEvent}.
7043     * @param event   The KeyEvent object that defines the button action.
7044     */
7045    public boolean onKeyDown(int keyCode, KeyEvent event) {
7046        boolean result = false;
7047
7048        switch (keyCode) {
7049            case KeyEvent.KEYCODE_DPAD_CENTER:
7050            case KeyEvent.KEYCODE_ENTER: {
7051                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7052                    return true;
7053                }
7054                // Long clickable items don't necessarily have to be clickable
7055                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7056                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7057                        (event.getRepeatCount() == 0)) {
7058                    setPressed(true);
7059                    checkForLongClick(0);
7060                    return true;
7061                }
7062                break;
7063            }
7064        }
7065        return result;
7066    }
7067
7068    /**
7069     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7070     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7071     * the event).
7072     */
7073    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7074        return false;
7075    }
7076
7077    /**
7078     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7079     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7080     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7081     * {@link KeyEvent#KEYCODE_ENTER} is released.
7082     *
7083     * @param keyCode A key code that represents the button pressed, from
7084     *                {@link android.view.KeyEvent}.
7085     * @param event   The KeyEvent object that defines the button action.
7086     */
7087    public boolean onKeyUp(int keyCode, KeyEvent event) {
7088        boolean result = false;
7089
7090        switch (keyCode) {
7091            case KeyEvent.KEYCODE_DPAD_CENTER:
7092            case KeyEvent.KEYCODE_ENTER: {
7093                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7094                    return true;
7095                }
7096                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7097                    setPressed(false);
7098
7099                    if (!mHasPerformedLongPress) {
7100                        // This is a tap, so remove the longpress check
7101                        removeLongPressCallback();
7102
7103                        result = performClick();
7104                    }
7105                }
7106                break;
7107            }
7108        }
7109        return result;
7110    }
7111
7112    /**
7113     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7114     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7115     * the event).
7116     *
7117     * @param keyCode     A key code that represents the button pressed, from
7118     *                    {@link android.view.KeyEvent}.
7119     * @param repeatCount The number of times the action was made.
7120     * @param event       The KeyEvent object that defines the button action.
7121     */
7122    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7123        return false;
7124    }
7125
7126    /**
7127     * Called on the focused view when a key shortcut event is not handled.
7128     * Override this method to implement local key shortcuts for the View.
7129     * Key shortcuts can also be implemented by setting the
7130     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7131     *
7132     * @param keyCode The value in event.getKeyCode().
7133     * @param event Description of the key event.
7134     * @return If you handled the event, return true. If you want to allow the
7135     *         event to be handled by the next receiver, return false.
7136     */
7137    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7138        return false;
7139    }
7140
7141    /**
7142     * Check whether the called view is a text editor, in which case it
7143     * would make sense to automatically display a soft input window for
7144     * it.  Subclasses should override this if they implement
7145     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7146     * a call on that method would return a non-null InputConnection, and
7147     * they are really a first-class editor that the user would normally
7148     * start typing on when the go into a window containing your view.
7149     *
7150     * <p>The default implementation always returns false.  This does
7151     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7152     * will not be called or the user can not otherwise perform edits on your
7153     * view; it is just a hint to the system that this is not the primary
7154     * purpose of this view.
7155     *
7156     * @return Returns true if this view is a text editor, else false.
7157     */
7158    public boolean onCheckIsTextEditor() {
7159        return false;
7160    }
7161
7162    /**
7163     * Create a new InputConnection for an InputMethod to interact
7164     * with the view.  The default implementation returns null, since it doesn't
7165     * support input methods.  You can override this to implement such support.
7166     * This is only needed for views that take focus and text input.
7167     *
7168     * <p>When implementing this, you probably also want to implement
7169     * {@link #onCheckIsTextEditor()} to indicate you will return a
7170     * non-null InputConnection.
7171     *
7172     * @param outAttrs Fill in with attribute information about the connection.
7173     */
7174    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7175        return null;
7176    }
7177
7178    /**
7179     * Called by the {@link android.view.inputmethod.InputMethodManager}
7180     * when a view who is not the current
7181     * input connection target is trying to make a call on the manager.  The
7182     * default implementation returns false; you can override this to return
7183     * true for certain views if you are performing InputConnection proxying
7184     * to them.
7185     * @param view The View that is making the InputMethodManager call.
7186     * @return Return true to allow the call, false to reject.
7187     */
7188    public boolean checkInputConnectionProxy(View view) {
7189        return false;
7190    }
7191
7192    /**
7193     * Show the context menu for this view. It is not safe to hold on to the
7194     * menu after returning from this method.
7195     *
7196     * You should normally not overload this method. Overload
7197     * {@link #onCreateContextMenu(ContextMenu)} or define an
7198     * {@link OnCreateContextMenuListener} to add items to the context menu.
7199     *
7200     * @param menu The context menu to populate
7201     */
7202    public void createContextMenu(ContextMenu menu) {
7203        ContextMenuInfo menuInfo = getContextMenuInfo();
7204
7205        // Sets the current menu info so all items added to menu will have
7206        // my extra info set.
7207        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7208
7209        onCreateContextMenu(menu);
7210        ListenerInfo li = mListenerInfo;
7211        if (li != null && li.mOnCreateContextMenuListener != null) {
7212            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7213        }
7214
7215        // Clear the extra information so subsequent items that aren't mine don't
7216        // have my extra info.
7217        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7218
7219        if (mParent != null) {
7220            mParent.createContextMenu(menu);
7221        }
7222    }
7223
7224    /**
7225     * Views should implement this if they have extra information to associate
7226     * with the context menu. The return result is supplied as a parameter to
7227     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7228     * callback.
7229     *
7230     * @return Extra information about the item for which the context menu
7231     *         should be shown. This information will vary across different
7232     *         subclasses of View.
7233     */
7234    protected ContextMenuInfo getContextMenuInfo() {
7235        return null;
7236    }
7237
7238    /**
7239     * Views should implement this if the view itself is going to add items to
7240     * the context menu.
7241     *
7242     * @param menu the context menu to populate
7243     */
7244    protected void onCreateContextMenu(ContextMenu menu) {
7245    }
7246
7247    /**
7248     * Implement this method to handle trackball motion events.  The
7249     * <em>relative</em> movement of the trackball since the last event
7250     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7251     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7252     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7253     * they will often be fractional values, representing the more fine-grained
7254     * movement information available from a trackball).
7255     *
7256     * @param event The motion event.
7257     * @return True if the event was handled, false otherwise.
7258     */
7259    public boolean onTrackballEvent(MotionEvent event) {
7260        return false;
7261    }
7262
7263    /**
7264     * Implement this method to handle generic motion events.
7265     * <p>
7266     * Generic motion events describe joystick movements, mouse hovers, track pad
7267     * touches, scroll wheel movements and other input events.  The
7268     * {@link MotionEvent#getSource() source} of the motion event specifies
7269     * the class of input that was received.  Implementations of this method
7270     * must examine the bits in the source before processing the event.
7271     * The following code example shows how this is done.
7272     * </p><p>
7273     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7274     * are delivered to the view under the pointer.  All other generic motion events are
7275     * delivered to the focused view.
7276     * </p>
7277     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7278     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7279     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7280     *             // process the joystick movement...
7281     *             return true;
7282     *         }
7283     *     }
7284     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7285     *         switch (event.getAction()) {
7286     *             case MotionEvent.ACTION_HOVER_MOVE:
7287     *                 // process the mouse hover movement...
7288     *                 return true;
7289     *             case MotionEvent.ACTION_SCROLL:
7290     *                 // process the scroll wheel movement...
7291     *                 return true;
7292     *         }
7293     *     }
7294     *     return super.onGenericMotionEvent(event);
7295     * }</pre>
7296     *
7297     * @param event The generic motion event being processed.
7298     * @return True if the event was handled, false otherwise.
7299     */
7300    public boolean onGenericMotionEvent(MotionEvent event) {
7301        return false;
7302    }
7303
7304    /**
7305     * Implement this method to handle hover events.
7306     * <p>
7307     * This method is called whenever a pointer is hovering into, over, or out of the
7308     * bounds of a view and the view is not currently being touched.
7309     * Hover events are represented as pointer events with action
7310     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7311     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7312     * </p>
7313     * <ul>
7314     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7315     * when the pointer enters the bounds of the view.</li>
7316     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7317     * when the pointer has already entered the bounds of the view and has moved.</li>
7318     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7319     * when the pointer has exited the bounds of the view or when the pointer is
7320     * about to go down due to a button click, tap, or similar user action that
7321     * causes the view to be touched.</li>
7322     * </ul>
7323     * <p>
7324     * The view should implement this method to return true to indicate that it is
7325     * handling the hover event, such as by changing its drawable state.
7326     * </p><p>
7327     * The default implementation calls {@link #setHovered} to update the hovered state
7328     * of the view when a hover enter or hover exit event is received, if the view
7329     * is enabled and is clickable.  The default implementation also sends hover
7330     * accessibility events.
7331     * </p>
7332     *
7333     * @param event The motion event that describes the hover.
7334     * @return True if the view handled the hover event.
7335     *
7336     * @see #isHovered
7337     * @see #setHovered
7338     * @see #onHoverChanged
7339     */
7340    public boolean onHoverEvent(MotionEvent event) {
7341        // The root view may receive hover (or touch) events that are outside the bounds of
7342        // the window.  This code ensures that we only send accessibility events for
7343        // hovers that are actually within the bounds of the root view.
7344        final int action = event.getActionMasked();
7345        if (!mSendingHoverAccessibilityEvents) {
7346            if ((action == MotionEvent.ACTION_HOVER_ENTER
7347                    || action == MotionEvent.ACTION_HOVER_MOVE)
7348                    && !hasHoveredChild()
7349                    && pointInView(event.getX(), event.getY())) {
7350                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7351                mSendingHoverAccessibilityEvents = true;
7352                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7353            }
7354        } else {
7355            if (action == MotionEvent.ACTION_HOVER_EXIT
7356                    || (action == MotionEvent.ACTION_MOVE
7357                            && !pointInView(event.getX(), event.getY()))) {
7358                mSendingHoverAccessibilityEvents = false;
7359                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7360                // If the window does not have input focus we take away accessibility
7361                // focus as soon as the user stop hovering over the view.
7362                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7363                    getViewRootImpl().setAccessibilityFocusedHost(null);
7364                }
7365            }
7366        }
7367
7368        if (isHoverable()) {
7369            switch (action) {
7370                case MotionEvent.ACTION_HOVER_ENTER:
7371                    setHovered(true);
7372                    break;
7373                case MotionEvent.ACTION_HOVER_EXIT:
7374                    setHovered(false);
7375                    break;
7376            }
7377
7378            // Dispatch the event to onGenericMotionEvent before returning true.
7379            // This is to provide compatibility with existing applications that
7380            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7381            // break because of the new default handling for hoverable views
7382            // in onHoverEvent.
7383            // Note that onGenericMotionEvent will be called by default when
7384            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7385            dispatchGenericMotionEventInternal(event);
7386            return true;
7387        }
7388
7389        return false;
7390    }
7391
7392    /**
7393     * Returns true if the view should handle {@link #onHoverEvent}
7394     * by calling {@link #setHovered} to change its hovered state.
7395     *
7396     * @return True if the view is hoverable.
7397     */
7398    private boolean isHoverable() {
7399        final int viewFlags = mViewFlags;
7400        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7401            return false;
7402        }
7403
7404        return (viewFlags & CLICKABLE) == CLICKABLE
7405                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7406    }
7407
7408    /**
7409     * Returns true if the view is currently hovered.
7410     *
7411     * @return True if the view is currently hovered.
7412     *
7413     * @see #setHovered
7414     * @see #onHoverChanged
7415     */
7416    @ViewDebug.ExportedProperty
7417    public boolean isHovered() {
7418        return (mPrivateFlags & HOVERED) != 0;
7419    }
7420
7421    /**
7422     * Sets whether the view is currently hovered.
7423     * <p>
7424     * Calling this method also changes the drawable state of the view.  This
7425     * enables the view to react to hover by using different drawable resources
7426     * to change its appearance.
7427     * </p><p>
7428     * The {@link #onHoverChanged} method is called when the hovered state changes.
7429     * </p>
7430     *
7431     * @param hovered True if the view is hovered.
7432     *
7433     * @see #isHovered
7434     * @see #onHoverChanged
7435     */
7436    public void setHovered(boolean hovered) {
7437        if (hovered) {
7438            if ((mPrivateFlags & HOVERED) == 0) {
7439                mPrivateFlags |= HOVERED;
7440                refreshDrawableState();
7441                onHoverChanged(true);
7442            }
7443        } else {
7444            if ((mPrivateFlags & HOVERED) != 0) {
7445                mPrivateFlags &= ~HOVERED;
7446                refreshDrawableState();
7447                onHoverChanged(false);
7448            }
7449        }
7450    }
7451
7452    /**
7453     * Implement this method to handle hover state changes.
7454     * <p>
7455     * This method is called whenever the hover state changes as a result of a
7456     * call to {@link #setHovered}.
7457     * </p>
7458     *
7459     * @param hovered The current hover state, as returned by {@link #isHovered}.
7460     *
7461     * @see #isHovered
7462     * @see #setHovered
7463     */
7464    public void onHoverChanged(boolean hovered) {
7465    }
7466
7467    /**
7468     * Implement this method to handle touch screen motion events.
7469     *
7470     * @param event The motion event.
7471     * @return True if the event was handled, false otherwise.
7472     */
7473    public boolean onTouchEvent(MotionEvent event) {
7474        final int viewFlags = mViewFlags;
7475
7476        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7477            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7478                setPressed(false);
7479            }
7480            // A disabled view that is clickable still consumes the touch
7481            // events, it just doesn't respond to them.
7482            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7483                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7484        }
7485
7486        if (mTouchDelegate != null) {
7487            if (mTouchDelegate.onTouchEvent(event)) {
7488                return true;
7489            }
7490        }
7491
7492        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7493                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7494            switch (event.getAction()) {
7495                case MotionEvent.ACTION_UP:
7496                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7497                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7498                        // take focus if we don't have it already and we should in
7499                        // touch mode.
7500                        boolean focusTaken = false;
7501                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7502                            focusTaken = requestFocus();
7503                        }
7504
7505                        if (prepressed) {
7506                            // The button is being released before we actually
7507                            // showed it as pressed.  Make it show the pressed
7508                            // state now (before scheduling the click) to ensure
7509                            // the user sees it.
7510                            setPressed(true);
7511                       }
7512
7513                        if (!mHasPerformedLongPress) {
7514                            // This is a tap, so remove the longpress check
7515                            removeLongPressCallback();
7516
7517                            // Only perform take click actions if we were in the pressed state
7518                            if (!focusTaken) {
7519                                // Use a Runnable and post this rather than calling
7520                                // performClick directly. This lets other visual state
7521                                // of the view update before click actions start.
7522                                if (mPerformClick == null) {
7523                                    mPerformClick = new PerformClick();
7524                                }
7525                                if (!post(mPerformClick)) {
7526                                    performClick();
7527                                }
7528                            }
7529                        }
7530
7531                        if (mUnsetPressedState == null) {
7532                            mUnsetPressedState = new UnsetPressedState();
7533                        }
7534
7535                        if (prepressed) {
7536                            postDelayed(mUnsetPressedState,
7537                                    ViewConfiguration.getPressedStateDuration());
7538                        } else if (!post(mUnsetPressedState)) {
7539                            // If the post failed, unpress right now
7540                            mUnsetPressedState.run();
7541                        }
7542                        removeTapCallback();
7543                    }
7544                    break;
7545
7546                case MotionEvent.ACTION_DOWN:
7547                    mHasPerformedLongPress = false;
7548
7549                    if (performButtonActionOnTouchDown(event)) {
7550                        break;
7551                    }
7552
7553                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7554                    boolean isInScrollingContainer = isInScrollingContainer();
7555
7556                    // For views inside a scrolling container, delay the pressed feedback for
7557                    // a short period in case this is a scroll.
7558                    if (isInScrollingContainer) {
7559                        mPrivateFlags |= PREPRESSED;
7560                        if (mPendingCheckForTap == null) {
7561                            mPendingCheckForTap = new CheckForTap();
7562                        }
7563                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7564                    } else {
7565                        // Not inside a scrolling container, so show the feedback right away
7566                        setPressed(true);
7567                        checkForLongClick(0);
7568                    }
7569                    break;
7570
7571                case MotionEvent.ACTION_CANCEL:
7572                    setPressed(false);
7573                    removeTapCallback();
7574                    break;
7575
7576                case MotionEvent.ACTION_MOVE:
7577                    final int x = (int) event.getX();
7578                    final int y = (int) event.getY();
7579
7580                    // Be lenient about moving outside of buttons
7581                    if (!pointInView(x, y, mTouchSlop)) {
7582                        // Outside button
7583                        removeTapCallback();
7584                        if ((mPrivateFlags & PRESSED) != 0) {
7585                            // Remove any future long press/tap checks
7586                            removeLongPressCallback();
7587
7588                            setPressed(false);
7589                        }
7590                    }
7591                    break;
7592            }
7593            return true;
7594        }
7595
7596        return false;
7597    }
7598
7599    /**
7600     * @hide
7601     */
7602    public boolean isInScrollingContainer() {
7603        ViewParent p = getParent();
7604        while (p != null && p instanceof ViewGroup) {
7605            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7606                return true;
7607            }
7608            p = p.getParent();
7609        }
7610        return false;
7611    }
7612
7613    /**
7614     * Remove the longpress detection timer.
7615     */
7616    private void removeLongPressCallback() {
7617        if (mPendingCheckForLongPress != null) {
7618          removeCallbacks(mPendingCheckForLongPress);
7619        }
7620    }
7621
7622    /**
7623     * Remove the pending click action
7624     */
7625    private void removePerformClickCallback() {
7626        if (mPerformClick != null) {
7627            removeCallbacks(mPerformClick);
7628        }
7629    }
7630
7631    /**
7632     * Remove the prepress detection timer.
7633     */
7634    private void removeUnsetPressCallback() {
7635        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7636            setPressed(false);
7637            removeCallbacks(mUnsetPressedState);
7638        }
7639    }
7640
7641    /**
7642     * Remove the tap detection timer.
7643     */
7644    private void removeTapCallback() {
7645        if (mPendingCheckForTap != null) {
7646            mPrivateFlags &= ~PREPRESSED;
7647            removeCallbacks(mPendingCheckForTap);
7648        }
7649    }
7650
7651    /**
7652     * Cancels a pending long press.  Your subclass can use this if you
7653     * want the context menu to come up if the user presses and holds
7654     * at the same place, but you don't want it to come up if they press
7655     * and then move around enough to cause scrolling.
7656     */
7657    public void cancelLongPress() {
7658        removeLongPressCallback();
7659
7660        /*
7661         * The prepressed state handled by the tap callback is a display
7662         * construct, but the tap callback will post a long press callback
7663         * less its own timeout. Remove it here.
7664         */
7665        removeTapCallback();
7666    }
7667
7668    /**
7669     * Remove the pending callback for sending a
7670     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7671     */
7672    private void removeSendViewScrolledAccessibilityEventCallback() {
7673        if (mSendViewScrolledAccessibilityEvent != null) {
7674            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7675        }
7676    }
7677
7678    /**
7679     * Sets the TouchDelegate for this View.
7680     */
7681    public void setTouchDelegate(TouchDelegate delegate) {
7682        mTouchDelegate = delegate;
7683    }
7684
7685    /**
7686     * Gets the TouchDelegate for this View.
7687     */
7688    public TouchDelegate getTouchDelegate() {
7689        return mTouchDelegate;
7690    }
7691
7692    /**
7693     * Set flags controlling behavior of this view.
7694     *
7695     * @param flags Constant indicating the value which should be set
7696     * @param mask Constant indicating the bit range that should be changed
7697     */
7698    void setFlags(int flags, int mask) {
7699        int old = mViewFlags;
7700        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7701
7702        int changed = mViewFlags ^ old;
7703        if (changed == 0) {
7704            return;
7705        }
7706        int privateFlags = mPrivateFlags;
7707
7708        /* Check if the FOCUSABLE bit has changed */
7709        if (((changed & FOCUSABLE_MASK) != 0) &&
7710                ((privateFlags & HAS_BOUNDS) !=0)) {
7711            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7712                    && ((privateFlags & FOCUSED) != 0)) {
7713                /* Give up focus if we are no longer focusable */
7714                clearFocus();
7715            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7716                    && ((privateFlags & FOCUSED) == 0)) {
7717                /*
7718                 * Tell the view system that we are now available to take focus
7719                 * if no one else already has it.
7720                 */
7721                if (mParent != null) mParent.focusableViewAvailable(this);
7722            }
7723            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7724                notifyAccessibilityStateChanged();
7725            }
7726        }
7727
7728        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7729            if ((changed & VISIBILITY_MASK) != 0) {
7730                /*
7731                 * If this view is becoming visible, invalidate it in case it changed while
7732                 * it was not visible. Marking it drawn ensures that the invalidation will
7733                 * go through.
7734                 */
7735                mPrivateFlags |= DRAWN;
7736                invalidate(true);
7737
7738                needGlobalAttributesUpdate(true);
7739
7740                // a view becoming visible is worth notifying the parent
7741                // about in case nothing has focus.  even if this specific view
7742                // isn't focusable, it may contain something that is, so let
7743                // the root view try to give this focus if nothing else does.
7744                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7745                    mParent.focusableViewAvailable(this);
7746                }
7747            }
7748        }
7749
7750        /* Check if the GONE bit has changed */
7751        if ((changed & GONE) != 0) {
7752            needGlobalAttributesUpdate(false);
7753            requestLayout();
7754
7755            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7756                if (hasFocus()) clearFocus();
7757                clearAccessibilityFocus();
7758                destroyDrawingCache();
7759                if (mParent instanceof View) {
7760                    // GONE views noop invalidation, so invalidate the parent
7761                    ((View) mParent).invalidate(true);
7762                }
7763                // Mark the view drawn to ensure that it gets invalidated properly the next
7764                // time it is visible and gets invalidated
7765                mPrivateFlags |= DRAWN;
7766            }
7767            if (mAttachInfo != null) {
7768                mAttachInfo.mViewVisibilityChanged = true;
7769            }
7770        }
7771
7772        /* Check if the VISIBLE bit has changed */
7773        if ((changed & INVISIBLE) != 0) {
7774            needGlobalAttributesUpdate(false);
7775            /*
7776             * If this view is becoming invisible, set the DRAWN flag so that
7777             * the next invalidate() will not be skipped.
7778             */
7779            mPrivateFlags |= DRAWN;
7780
7781            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7782                // root view becoming invisible shouldn't clear focus and accessibility focus
7783                if (getRootView() != this) {
7784                    clearFocus();
7785                    clearAccessibilityFocus();
7786                }
7787            }
7788            if (mAttachInfo != null) {
7789                mAttachInfo.mViewVisibilityChanged = true;
7790            }
7791        }
7792
7793        if ((changed & VISIBILITY_MASK) != 0) {
7794            if (mParent instanceof ViewGroup) {
7795                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7796                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7797                ((View) mParent).invalidate(true);
7798            } else if (mParent != null) {
7799                mParent.invalidateChild(this, null);
7800            }
7801            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7802        }
7803
7804        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7805            destroyDrawingCache();
7806        }
7807
7808        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7809            destroyDrawingCache();
7810            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7811            invalidateParentCaches();
7812        }
7813
7814        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7815            destroyDrawingCache();
7816            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7817        }
7818
7819        if ((changed & DRAW_MASK) != 0) {
7820            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7821                if (mBackground != null) {
7822                    mPrivateFlags &= ~SKIP_DRAW;
7823                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7824                } else {
7825                    mPrivateFlags |= SKIP_DRAW;
7826                }
7827            } else {
7828                mPrivateFlags &= ~SKIP_DRAW;
7829            }
7830            requestLayout();
7831            invalidate(true);
7832        }
7833
7834        if ((changed & KEEP_SCREEN_ON) != 0) {
7835            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7836                mParent.recomputeViewAttributes(this);
7837            }
7838        }
7839
7840        if (AccessibilityManager.getInstance(mContext).isEnabled()
7841                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
7842                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
7843            notifyAccessibilityStateChanged();
7844        }
7845    }
7846
7847    /**
7848     * Change the view's z order in the tree, so it's on top of other sibling
7849     * views
7850     */
7851    public void bringToFront() {
7852        if (mParent != null) {
7853            mParent.bringChildToFront(this);
7854        }
7855    }
7856
7857    /**
7858     * This is called in response to an internal scroll in this view (i.e., the
7859     * view scrolled its own contents). This is typically as a result of
7860     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7861     * called.
7862     *
7863     * @param l Current horizontal scroll origin.
7864     * @param t Current vertical scroll origin.
7865     * @param oldl Previous horizontal scroll origin.
7866     * @param oldt Previous vertical scroll origin.
7867     */
7868    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7869        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7870            postSendViewScrolledAccessibilityEventCallback();
7871        }
7872
7873        mBackgroundSizeChanged = true;
7874
7875        final AttachInfo ai = mAttachInfo;
7876        if (ai != null) {
7877            ai.mViewScrollChanged = true;
7878        }
7879    }
7880
7881    /**
7882     * Interface definition for a callback to be invoked when the layout bounds of a view
7883     * changes due to layout processing.
7884     */
7885    public interface OnLayoutChangeListener {
7886        /**
7887         * Called when the focus state of a view has changed.
7888         *
7889         * @param v The view whose state has changed.
7890         * @param left The new value of the view's left property.
7891         * @param top The new value of the view's top property.
7892         * @param right The new value of the view's right property.
7893         * @param bottom The new value of the view's bottom property.
7894         * @param oldLeft The previous value of the view's left property.
7895         * @param oldTop The previous value of the view's top property.
7896         * @param oldRight The previous value of the view's right property.
7897         * @param oldBottom The previous value of the view's bottom property.
7898         */
7899        void onLayoutChange(View v, int left, int top, int right, int bottom,
7900            int oldLeft, int oldTop, int oldRight, int oldBottom);
7901    }
7902
7903    /**
7904     * This is called during layout when the size of this view has changed. If
7905     * you were just added to the view hierarchy, you're called with the old
7906     * values of 0.
7907     *
7908     * @param w Current width of this view.
7909     * @param h Current height of this view.
7910     * @param oldw Old width of this view.
7911     * @param oldh Old height of this view.
7912     */
7913    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7914    }
7915
7916    /**
7917     * Called by draw to draw the child views. This may be overridden
7918     * by derived classes to gain control just before its children are drawn
7919     * (but after its own view has been drawn).
7920     * @param canvas the canvas on which to draw the view
7921     */
7922    protected void dispatchDraw(Canvas canvas) {
7923
7924    }
7925
7926    /**
7927     * Gets the parent of this view. Note that the parent is a
7928     * ViewParent and not necessarily a View.
7929     *
7930     * @return Parent of this view.
7931     */
7932    public final ViewParent getParent() {
7933        return mParent;
7934    }
7935
7936    /**
7937     * Set the horizontal scrolled position of your view. This will cause a call to
7938     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7939     * invalidated.
7940     * @param value the x position to scroll to
7941     */
7942    public void setScrollX(int value) {
7943        scrollTo(value, mScrollY);
7944    }
7945
7946    /**
7947     * Set the vertical scrolled position of your view. This will cause a call to
7948     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7949     * invalidated.
7950     * @param value the y position to scroll to
7951     */
7952    public void setScrollY(int value) {
7953        scrollTo(mScrollX, value);
7954    }
7955
7956    /**
7957     * Return the scrolled left position of this view. This is the left edge of
7958     * the displayed part of your view. You do not need to draw any pixels
7959     * farther left, since those are outside of the frame of your view on
7960     * screen.
7961     *
7962     * @return The left edge of the displayed part of your view, in pixels.
7963     */
7964    public final int getScrollX() {
7965        return mScrollX;
7966    }
7967
7968    /**
7969     * Return the scrolled top position of this view. This is the top edge of
7970     * the displayed part of your view. You do not need to draw any pixels above
7971     * it, since those are outside of the frame of your view on screen.
7972     *
7973     * @return The top edge of the displayed part of your view, in pixels.
7974     */
7975    public final int getScrollY() {
7976        return mScrollY;
7977    }
7978
7979    /**
7980     * Return the width of the your view.
7981     *
7982     * @return The width of your view, in pixels.
7983     */
7984    @ViewDebug.ExportedProperty(category = "layout")
7985    public final int getWidth() {
7986        return mRight - mLeft;
7987    }
7988
7989    /**
7990     * Return the height of your view.
7991     *
7992     * @return The height of your view, in pixels.
7993     */
7994    @ViewDebug.ExportedProperty(category = "layout")
7995    public final int getHeight() {
7996        return mBottom - mTop;
7997    }
7998
7999    /**
8000     * Return the visible drawing bounds of your view. Fills in the output
8001     * rectangle with the values from getScrollX(), getScrollY(),
8002     * getWidth(), and getHeight().
8003     *
8004     * @param outRect The (scrolled) drawing bounds of the view.
8005     */
8006    public void getDrawingRect(Rect outRect) {
8007        outRect.left = mScrollX;
8008        outRect.top = mScrollY;
8009        outRect.right = mScrollX + (mRight - mLeft);
8010        outRect.bottom = mScrollY + (mBottom - mTop);
8011    }
8012
8013    /**
8014     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8015     * raw width component (that is the result is masked by
8016     * {@link #MEASURED_SIZE_MASK}).
8017     *
8018     * @return The raw measured width of this view.
8019     */
8020    public final int getMeasuredWidth() {
8021        return mMeasuredWidth & MEASURED_SIZE_MASK;
8022    }
8023
8024    /**
8025     * Return the full width measurement information for this view as computed
8026     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8027     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8028     * This should be used during measurement and layout calculations only. Use
8029     * {@link #getWidth()} to see how wide a view is after layout.
8030     *
8031     * @return The measured width of this view as a bit mask.
8032     */
8033    public final int getMeasuredWidthAndState() {
8034        return mMeasuredWidth;
8035    }
8036
8037    /**
8038     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8039     * raw width component (that is the result is masked by
8040     * {@link #MEASURED_SIZE_MASK}).
8041     *
8042     * @return The raw measured height of this view.
8043     */
8044    public final int getMeasuredHeight() {
8045        return mMeasuredHeight & MEASURED_SIZE_MASK;
8046    }
8047
8048    /**
8049     * Return the full height measurement information for this view as computed
8050     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8051     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8052     * This should be used during measurement and layout calculations only. Use
8053     * {@link #getHeight()} to see how wide a view is after layout.
8054     *
8055     * @return The measured width of this view as a bit mask.
8056     */
8057    public final int getMeasuredHeightAndState() {
8058        return mMeasuredHeight;
8059    }
8060
8061    /**
8062     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8063     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8064     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8065     * and the height component is at the shifted bits
8066     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8067     */
8068    public final int getMeasuredState() {
8069        return (mMeasuredWidth&MEASURED_STATE_MASK)
8070                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8071                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8072    }
8073
8074    /**
8075     * The transform matrix of this view, which is calculated based on the current
8076     * roation, scale, and pivot properties.
8077     *
8078     * @see #getRotation()
8079     * @see #getScaleX()
8080     * @see #getScaleY()
8081     * @see #getPivotX()
8082     * @see #getPivotY()
8083     * @return The current transform matrix for the view
8084     */
8085    public Matrix getMatrix() {
8086        if (mTransformationInfo != null) {
8087            updateMatrix();
8088            return mTransformationInfo.mMatrix;
8089        }
8090        return Matrix.IDENTITY_MATRIX;
8091    }
8092
8093    /**
8094     * Utility function to determine if the value is far enough away from zero to be
8095     * considered non-zero.
8096     * @param value A floating point value to check for zero-ness
8097     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8098     */
8099    private static boolean nonzero(float value) {
8100        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8101    }
8102
8103    /**
8104     * Returns true if the transform matrix is the identity matrix.
8105     * Recomputes the matrix if necessary.
8106     *
8107     * @return True if the transform matrix is the identity matrix, false otherwise.
8108     */
8109    final boolean hasIdentityMatrix() {
8110        if (mTransformationInfo != null) {
8111            updateMatrix();
8112            return mTransformationInfo.mMatrixIsIdentity;
8113        }
8114        return true;
8115    }
8116
8117    void ensureTransformationInfo() {
8118        if (mTransformationInfo == null) {
8119            mTransformationInfo = new TransformationInfo();
8120        }
8121    }
8122
8123    /**
8124     * Recomputes the transform matrix if necessary.
8125     */
8126    private void updateMatrix() {
8127        final TransformationInfo info = mTransformationInfo;
8128        if (info == null) {
8129            return;
8130        }
8131        if (info.mMatrixDirty) {
8132            // transform-related properties have changed since the last time someone
8133            // asked for the matrix; recalculate it with the current values
8134
8135            // Figure out if we need to update the pivot point
8136            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8137                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8138                    info.mPrevWidth = mRight - mLeft;
8139                    info.mPrevHeight = mBottom - mTop;
8140                    info.mPivotX = info.mPrevWidth / 2f;
8141                    info.mPivotY = info.mPrevHeight / 2f;
8142                }
8143            }
8144            info.mMatrix.reset();
8145            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8146                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8147                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8148                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8149            } else {
8150                if (info.mCamera == null) {
8151                    info.mCamera = new Camera();
8152                    info.matrix3D = new Matrix();
8153                }
8154                info.mCamera.save();
8155                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8156                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8157                info.mCamera.getMatrix(info.matrix3D);
8158                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8159                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8160                        info.mPivotY + info.mTranslationY);
8161                info.mMatrix.postConcat(info.matrix3D);
8162                info.mCamera.restore();
8163            }
8164            info.mMatrixDirty = false;
8165            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8166            info.mInverseMatrixDirty = true;
8167        }
8168    }
8169
8170    /**
8171     * Utility method to retrieve the inverse of the current mMatrix property.
8172     * We cache the matrix to avoid recalculating it when transform properties
8173     * have not changed.
8174     *
8175     * @return The inverse of the current matrix of this view.
8176     */
8177    final Matrix getInverseMatrix() {
8178        final TransformationInfo info = mTransformationInfo;
8179        if (info != null) {
8180            updateMatrix();
8181            if (info.mInverseMatrixDirty) {
8182                if (info.mInverseMatrix == null) {
8183                    info.mInverseMatrix = new Matrix();
8184                }
8185                info.mMatrix.invert(info.mInverseMatrix);
8186                info.mInverseMatrixDirty = false;
8187            }
8188            return info.mInverseMatrix;
8189        }
8190        return Matrix.IDENTITY_MATRIX;
8191    }
8192
8193    /**
8194     * Gets the distance along the Z axis from the camera to this view.
8195     *
8196     * @see #setCameraDistance(float)
8197     *
8198     * @return The distance along the Z axis.
8199     */
8200    public float getCameraDistance() {
8201        ensureTransformationInfo();
8202        final float dpi = mResources.getDisplayMetrics().densityDpi;
8203        final TransformationInfo info = mTransformationInfo;
8204        if (info.mCamera == null) {
8205            info.mCamera = new Camera();
8206            info.matrix3D = new Matrix();
8207        }
8208        return -(info.mCamera.getLocationZ() * dpi);
8209    }
8210
8211    /**
8212     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8213     * views are drawn) from the camera to this view. The camera's distance
8214     * affects 3D transformations, for instance rotations around the X and Y
8215     * axis. If the rotationX or rotationY properties are changed and this view is
8216     * large (more than half the size of the screen), it is recommended to always
8217     * use a camera distance that's greater than the height (X axis rotation) or
8218     * the width (Y axis rotation) of this view.</p>
8219     *
8220     * <p>The distance of the camera from the view plane can have an affect on the
8221     * perspective distortion of the view when it is rotated around the x or y axis.
8222     * For example, a large distance will result in a large viewing angle, and there
8223     * will not be much perspective distortion of the view as it rotates. A short
8224     * distance may cause much more perspective distortion upon rotation, and can
8225     * also result in some drawing artifacts if the rotated view ends up partially
8226     * behind the camera (which is why the recommendation is to use a distance at
8227     * least as far as the size of the view, if the view is to be rotated.)</p>
8228     *
8229     * <p>The distance is expressed in "depth pixels." The default distance depends
8230     * on the screen density. For instance, on a medium density display, the
8231     * default distance is 1280. On a high density display, the default distance
8232     * is 1920.</p>
8233     *
8234     * <p>If you want to specify a distance that leads to visually consistent
8235     * results across various densities, use the following formula:</p>
8236     * <pre>
8237     * float scale = context.getResources().getDisplayMetrics().density;
8238     * view.setCameraDistance(distance * scale);
8239     * </pre>
8240     *
8241     * <p>The density scale factor of a high density display is 1.5,
8242     * and 1920 = 1280 * 1.5.</p>
8243     *
8244     * @param distance The distance in "depth pixels", if negative the opposite
8245     *        value is used
8246     *
8247     * @see #setRotationX(float)
8248     * @see #setRotationY(float)
8249     */
8250    public void setCameraDistance(float distance) {
8251        invalidateViewProperty(true, false);
8252
8253        ensureTransformationInfo();
8254        final float dpi = mResources.getDisplayMetrics().densityDpi;
8255        final TransformationInfo info = mTransformationInfo;
8256        if (info.mCamera == null) {
8257            info.mCamera = new Camera();
8258            info.matrix3D = new Matrix();
8259        }
8260
8261        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8262        info.mMatrixDirty = true;
8263
8264        invalidateViewProperty(false, false);
8265        if (mDisplayList != null) {
8266            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8267        }
8268    }
8269
8270    /**
8271     * The degrees that the view is rotated around the pivot point.
8272     *
8273     * @see #setRotation(float)
8274     * @see #getPivotX()
8275     * @see #getPivotY()
8276     *
8277     * @return The degrees of rotation.
8278     */
8279    @ViewDebug.ExportedProperty(category = "drawing")
8280    public float getRotation() {
8281        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8282    }
8283
8284    /**
8285     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8286     * result in clockwise rotation.
8287     *
8288     * @param rotation The degrees of rotation.
8289     *
8290     * @see #getRotation()
8291     * @see #getPivotX()
8292     * @see #getPivotY()
8293     * @see #setRotationX(float)
8294     * @see #setRotationY(float)
8295     *
8296     * @attr ref android.R.styleable#View_rotation
8297     */
8298    public void setRotation(float rotation) {
8299        ensureTransformationInfo();
8300        final TransformationInfo info = mTransformationInfo;
8301        if (info.mRotation != rotation) {
8302            // Double-invalidation is necessary to capture view's old and new areas
8303            invalidateViewProperty(true, false);
8304            info.mRotation = rotation;
8305            info.mMatrixDirty = true;
8306            invalidateViewProperty(false, true);
8307            if (mDisplayList != null) {
8308                mDisplayList.setRotation(rotation);
8309            }
8310        }
8311    }
8312
8313    /**
8314     * The degrees that the view is rotated around the vertical axis through the pivot point.
8315     *
8316     * @see #getPivotX()
8317     * @see #getPivotY()
8318     * @see #setRotationY(float)
8319     *
8320     * @return The degrees of Y rotation.
8321     */
8322    @ViewDebug.ExportedProperty(category = "drawing")
8323    public float getRotationY() {
8324        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8325    }
8326
8327    /**
8328     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8329     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8330     * down the y axis.
8331     *
8332     * When rotating large views, it is recommended to adjust the camera distance
8333     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8334     *
8335     * @param rotationY The degrees of Y rotation.
8336     *
8337     * @see #getRotationY()
8338     * @see #getPivotX()
8339     * @see #getPivotY()
8340     * @see #setRotation(float)
8341     * @see #setRotationX(float)
8342     * @see #setCameraDistance(float)
8343     *
8344     * @attr ref android.R.styleable#View_rotationY
8345     */
8346    public void setRotationY(float rotationY) {
8347        ensureTransformationInfo();
8348        final TransformationInfo info = mTransformationInfo;
8349        if (info.mRotationY != rotationY) {
8350            invalidateViewProperty(true, false);
8351            info.mRotationY = rotationY;
8352            info.mMatrixDirty = true;
8353            invalidateViewProperty(false, true);
8354            if (mDisplayList != null) {
8355                mDisplayList.setRotationY(rotationY);
8356            }
8357        }
8358    }
8359
8360    /**
8361     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8362     *
8363     * @see #getPivotX()
8364     * @see #getPivotY()
8365     * @see #setRotationX(float)
8366     *
8367     * @return The degrees of X rotation.
8368     */
8369    @ViewDebug.ExportedProperty(category = "drawing")
8370    public float getRotationX() {
8371        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8372    }
8373
8374    /**
8375     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8376     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8377     * x axis.
8378     *
8379     * When rotating large views, it is recommended to adjust the camera distance
8380     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8381     *
8382     * @param rotationX The degrees of X rotation.
8383     *
8384     * @see #getRotationX()
8385     * @see #getPivotX()
8386     * @see #getPivotY()
8387     * @see #setRotation(float)
8388     * @see #setRotationY(float)
8389     * @see #setCameraDistance(float)
8390     *
8391     * @attr ref android.R.styleable#View_rotationX
8392     */
8393    public void setRotationX(float rotationX) {
8394        ensureTransformationInfo();
8395        final TransformationInfo info = mTransformationInfo;
8396        if (info.mRotationX != rotationX) {
8397            invalidateViewProperty(true, false);
8398            info.mRotationX = rotationX;
8399            info.mMatrixDirty = true;
8400            invalidateViewProperty(false, true);
8401            if (mDisplayList != null) {
8402                mDisplayList.setRotationX(rotationX);
8403            }
8404        }
8405    }
8406
8407    /**
8408     * The amount that the view is scaled in x around the pivot point, as a proportion of
8409     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8410     *
8411     * <p>By default, this is 1.0f.
8412     *
8413     * @see #getPivotX()
8414     * @see #getPivotY()
8415     * @return The scaling factor.
8416     */
8417    @ViewDebug.ExportedProperty(category = "drawing")
8418    public float getScaleX() {
8419        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8420    }
8421
8422    /**
8423     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8424     * the view's unscaled width. A value of 1 means that no scaling is applied.
8425     *
8426     * @param scaleX The scaling factor.
8427     * @see #getPivotX()
8428     * @see #getPivotY()
8429     *
8430     * @attr ref android.R.styleable#View_scaleX
8431     */
8432    public void setScaleX(float scaleX) {
8433        ensureTransformationInfo();
8434        final TransformationInfo info = mTransformationInfo;
8435        if (info.mScaleX != scaleX) {
8436            invalidateViewProperty(true, false);
8437            info.mScaleX = scaleX;
8438            info.mMatrixDirty = true;
8439            invalidateViewProperty(false, true);
8440            if (mDisplayList != null) {
8441                mDisplayList.setScaleX(scaleX);
8442            }
8443        }
8444    }
8445
8446    /**
8447     * The amount that the view is scaled in y around the pivot point, as a proportion of
8448     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8449     *
8450     * <p>By default, this is 1.0f.
8451     *
8452     * @see #getPivotX()
8453     * @see #getPivotY()
8454     * @return The scaling factor.
8455     */
8456    @ViewDebug.ExportedProperty(category = "drawing")
8457    public float getScaleY() {
8458        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8459    }
8460
8461    /**
8462     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8463     * the view's unscaled width. A value of 1 means that no scaling is applied.
8464     *
8465     * @param scaleY The scaling factor.
8466     * @see #getPivotX()
8467     * @see #getPivotY()
8468     *
8469     * @attr ref android.R.styleable#View_scaleY
8470     */
8471    public void setScaleY(float scaleY) {
8472        ensureTransformationInfo();
8473        final TransformationInfo info = mTransformationInfo;
8474        if (info.mScaleY != scaleY) {
8475            invalidateViewProperty(true, false);
8476            info.mScaleY = scaleY;
8477            info.mMatrixDirty = true;
8478            invalidateViewProperty(false, true);
8479            if (mDisplayList != null) {
8480                mDisplayList.setScaleY(scaleY);
8481            }
8482        }
8483    }
8484
8485    /**
8486     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8487     * and {@link #setScaleX(float) scaled}.
8488     *
8489     * @see #getRotation()
8490     * @see #getScaleX()
8491     * @see #getScaleY()
8492     * @see #getPivotY()
8493     * @return The x location of the pivot point.
8494     *
8495     * @attr ref android.R.styleable#View_transformPivotX
8496     */
8497    @ViewDebug.ExportedProperty(category = "drawing")
8498    public float getPivotX() {
8499        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8500    }
8501
8502    /**
8503     * Sets the x location of the point around which the view is
8504     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8505     * By default, the pivot point is centered on the object.
8506     * Setting this property disables this behavior and causes the view to use only the
8507     * explicitly set pivotX and pivotY values.
8508     *
8509     * @param pivotX The x location of the pivot point.
8510     * @see #getRotation()
8511     * @see #getScaleX()
8512     * @see #getScaleY()
8513     * @see #getPivotY()
8514     *
8515     * @attr ref android.R.styleable#View_transformPivotX
8516     */
8517    public void setPivotX(float pivotX) {
8518        ensureTransformationInfo();
8519        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8520        final TransformationInfo info = mTransformationInfo;
8521        if (info.mPivotX != pivotX) {
8522            invalidateViewProperty(true, false);
8523            info.mPivotX = pivotX;
8524            info.mMatrixDirty = true;
8525            invalidateViewProperty(false, true);
8526            if (mDisplayList != null) {
8527                mDisplayList.setPivotX(pivotX);
8528            }
8529        }
8530    }
8531
8532    /**
8533     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8534     * and {@link #setScaleY(float) scaled}.
8535     *
8536     * @see #getRotation()
8537     * @see #getScaleX()
8538     * @see #getScaleY()
8539     * @see #getPivotY()
8540     * @return The y location of the pivot point.
8541     *
8542     * @attr ref android.R.styleable#View_transformPivotY
8543     */
8544    @ViewDebug.ExportedProperty(category = "drawing")
8545    public float getPivotY() {
8546        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8547    }
8548
8549    /**
8550     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8551     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8552     * Setting this property disables this behavior and causes the view to use only the
8553     * explicitly set pivotX and pivotY values.
8554     *
8555     * @param pivotY The y location of the pivot point.
8556     * @see #getRotation()
8557     * @see #getScaleX()
8558     * @see #getScaleY()
8559     * @see #getPivotY()
8560     *
8561     * @attr ref android.R.styleable#View_transformPivotY
8562     */
8563    public void setPivotY(float pivotY) {
8564        ensureTransformationInfo();
8565        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8566        final TransformationInfo info = mTransformationInfo;
8567        if (info.mPivotY != pivotY) {
8568            invalidateViewProperty(true, false);
8569            info.mPivotY = pivotY;
8570            info.mMatrixDirty = true;
8571            invalidateViewProperty(false, true);
8572            if (mDisplayList != null) {
8573                mDisplayList.setPivotY(pivotY);
8574            }
8575        }
8576    }
8577
8578    /**
8579     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8580     * completely transparent and 1 means the view is completely opaque.
8581     *
8582     * <p>By default this is 1.0f.
8583     * @return The opacity of the view.
8584     */
8585    @ViewDebug.ExportedProperty(category = "drawing")
8586    public float getAlpha() {
8587        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8588    }
8589
8590    /**
8591     * Returns whether this View has content which overlaps. This function, intended to be
8592     * overridden by specific View types, is an optimization when alpha is set on a view. If
8593     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8594     * and then composited it into place, which can be expensive. If the view has no overlapping
8595     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8596     * An example of overlapping rendering is a TextView with a background image, such as a
8597     * Button. An example of non-overlapping rendering is a TextView with no background, or
8598     * an ImageView with only the foreground image. The default implementation returns true;
8599     * subclasses should override if they have cases which can be optimized.
8600     *
8601     * @return true if the content in this view might overlap, false otherwise.
8602     */
8603    public boolean hasOverlappingRendering() {
8604        return true;
8605    }
8606
8607    /**
8608     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8609     * completely transparent and 1 means the view is completely opaque.</p>
8610     *
8611     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8612     * responsible for applying the opacity itself. Otherwise, calling this method is
8613     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8614     * setting a hardware layer.</p>
8615     *
8616     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8617     * performance implications. It is generally best to use the alpha property sparingly and
8618     * transiently, as in the case of fading animations.</p>
8619     *
8620     * @param alpha The opacity of the view.
8621     *
8622     * @see #setLayerType(int, android.graphics.Paint)
8623     *
8624     * @attr ref android.R.styleable#View_alpha
8625     */
8626    public void setAlpha(float alpha) {
8627        ensureTransformationInfo();
8628        if (mTransformationInfo.mAlpha != alpha) {
8629            mTransformationInfo.mAlpha = alpha;
8630            if (onSetAlpha((int) (alpha * 255))) {
8631                mPrivateFlags |= ALPHA_SET;
8632                // subclass is handling alpha - don't optimize rendering cache invalidation
8633                invalidateParentCaches();
8634                invalidate(true);
8635            } else {
8636                mPrivateFlags &= ~ALPHA_SET;
8637                invalidateViewProperty(true, false);
8638                if (mDisplayList != null) {
8639                    mDisplayList.setAlpha(alpha);
8640                }
8641            }
8642        }
8643    }
8644
8645    /**
8646     * Faster version of setAlpha() which performs the same steps except there are
8647     * no calls to invalidate(). The caller of this function should perform proper invalidation
8648     * on the parent and this object. The return value indicates whether the subclass handles
8649     * alpha (the return value for onSetAlpha()).
8650     *
8651     * @param alpha The new value for the alpha property
8652     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8653     *         the new value for the alpha property is different from the old value
8654     */
8655    boolean setAlphaNoInvalidation(float alpha) {
8656        ensureTransformationInfo();
8657        if (mTransformationInfo.mAlpha != alpha) {
8658            mTransformationInfo.mAlpha = alpha;
8659            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8660            if (subclassHandlesAlpha) {
8661                mPrivateFlags |= ALPHA_SET;
8662                return true;
8663            } else {
8664                mPrivateFlags &= ~ALPHA_SET;
8665                if (mDisplayList != null) {
8666                    mDisplayList.setAlpha(alpha);
8667                }
8668            }
8669        }
8670        return false;
8671    }
8672
8673    /**
8674     * Top position of this view relative to its parent.
8675     *
8676     * @return The top of this view, in pixels.
8677     */
8678    @ViewDebug.CapturedViewProperty
8679    public final int getTop() {
8680        return mTop;
8681    }
8682
8683    /**
8684     * Sets the top position of this view relative to its parent. This method is meant to be called
8685     * by the layout system and should not generally be called otherwise, because the property
8686     * may be changed at any time by the layout.
8687     *
8688     * @param top The top of this view, in pixels.
8689     */
8690    public final void setTop(int top) {
8691        if (top != mTop) {
8692            updateMatrix();
8693            final boolean matrixIsIdentity = mTransformationInfo == null
8694                    || mTransformationInfo.mMatrixIsIdentity;
8695            if (matrixIsIdentity) {
8696                if (mAttachInfo != null) {
8697                    int minTop;
8698                    int yLoc;
8699                    if (top < mTop) {
8700                        minTop = top;
8701                        yLoc = top - mTop;
8702                    } else {
8703                        minTop = mTop;
8704                        yLoc = 0;
8705                    }
8706                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8707                }
8708            } else {
8709                // Double-invalidation is necessary to capture view's old and new areas
8710                invalidate(true);
8711            }
8712
8713            int width = mRight - mLeft;
8714            int oldHeight = mBottom - mTop;
8715
8716            mTop = top;
8717            if (mDisplayList != null) {
8718                mDisplayList.setTop(mTop);
8719            }
8720
8721            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8722
8723            if (!matrixIsIdentity) {
8724                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8725                    // A change in dimension means an auto-centered pivot point changes, too
8726                    mTransformationInfo.mMatrixDirty = true;
8727                }
8728                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8729                invalidate(true);
8730            }
8731            mBackgroundSizeChanged = true;
8732            invalidateParentIfNeeded();
8733        }
8734    }
8735
8736    /**
8737     * Bottom position of this view relative to its parent.
8738     *
8739     * @return The bottom of this view, in pixels.
8740     */
8741    @ViewDebug.CapturedViewProperty
8742    public final int getBottom() {
8743        return mBottom;
8744    }
8745
8746    /**
8747     * True if this view has changed since the last time being drawn.
8748     *
8749     * @return The dirty state of this view.
8750     */
8751    public boolean isDirty() {
8752        return (mPrivateFlags & DIRTY_MASK) != 0;
8753    }
8754
8755    /**
8756     * Sets the bottom position of this view relative to its parent. This method is meant to be
8757     * called by the layout system and should not generally be called otherwise, because the
8758     * property may be changed at any time by the layout.
8759     *
8760     * @param bottom The bottom of this view, in pixels.
8761     */
8762    public final void setBottom(int bottom) {
8763        if (bottom != mBottom) {
8764            updateMatrix();
8765            final boolean matrixIsIdentity = mTransformationInfo == null
8766                    || mTransformationInfo.mMatrixIsIdentity;
8767            if (matrixIsIdentity) {
8768                if (mAttachInfo != null) {
8769                    int maxBottom;
8770                    if (bottom < mBottom) {
8771                        maxBottom = mBottom;
8772                    } else {
8773                        maxBottom = bottom;
8774                    }
8775                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8776                }
8777            } else {
8778                // Double-invalidation is necessary to capture view's old and new areas
8779                invalidate(true);
8780            }
8781
8782            int width = mRight - mLeft;
8783            int oldHeight = mBottom - mTop;
8784
8785            mBottom = bottom;
8786            if (mDisplayList != null) {
8787                mDisplayList.setBottom(mBottom);
8788            }
8789
8790            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8791
8792            if (!matrixIsIdentity) {
8793                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8794                    // A change in dimension means an auto-centered pivot point changes, too
8795                    mTransformationInfo.mMatrixDirty = true;
8796                }
8797                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8798                invalidate(true);
8799            }
8800            mBackgroundSizeChanged = true;
8801            invalidateParentIfNeeded();
8802        }
8803    }
8804
8805    /**
8806     * Left position of this view relative to its parent.
8807     *
8808     * @return The left edge of this view, in pixels.
8809     */
8810    @ViewDebug.CapturedViewProperty
8811    public final int getLeft() {
8812        return mLeft;
8813    }
8814
8815    /**
8816     * Sets the left position of this view relative to its parent. This method is meant to be called
8817     * by the layout system and should not generally be called otherwise, because the property
8818     * may be changed at any time by the layout.
8819     *
8820     * @param left The bottom of this view, in pixels.
8821     */
8822    public final void setLeft(int left) {
8823        if (left != mLeft) {
8824            updateMatrix();
8825            final boolean matrixIsIdentity = mTransformationInfo == null
8826                    || mTransformationInfo.mMatrixIsIdentity;
8827            if (matrixIsIdentity) {
8828                if (mAttachInfo != null) {
8829                    int minLeft;
8830                    int xLoc;
8831                    if (left < mLeft) {
8832                        minLeft = left;
8833                        xLoc = left - mLeft;
8834                    } else {
8835                        minLeft = mLeft;
8836                        xLoc = 0;
8837                    }
8838                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8839                }
8840            } else {
8841                // Double-invalidation is necessary to capture view's old and new areas
8842                invalidate(true);
8843            }
8844
8845            int oldWidth = mRight - mLeft;
8846            int height = mBottom - mTop;
8847
8848            mLeft = left;
8849            if (mDisplayList != null) {
8850                mDisplayList.setLeft(left);
8851            }
8852
8853            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8854
8855            if (!matrixIsIdentity) {
8856                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8857                    // A change in dimension means an auto-centered pivot point changes, too
8858                    mTransformationInfo.mMatrixDirty = true;
8859                }
8860                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8861                invalidate(true);
8862            }
8863            mBackgroundSizeChanged = true;
8864            invalidateParentIfNeeded();
8865        }
8866    }
8867
8868    /**
8869     * Right position of this view relative to its parent.
8870     *
8871     * @return The right edge of this view, in pixels.
8872     */
8873    @ViewDebug.CapturedViewProperty
8874    public final int getRight() {
8875        return mRight;
8876    }
8877
8878    /**
8879     * Sets the right position of this view relative to its parent. This method is meant to be called
8880     * by the layout system and should not generally be called otherwise, because the property
8881     * may be changed at any time by the layout.
8882     *
8883     * @param right The bottom of this view, in pixels.
8884     */
8885    public final void setRight(int right) {
8886        if (right != mRight) {
8887            updateMatrix();
8888            final boolean matrixIsIdentity = mTransformationInfo == null
8889                    || mTransformationInfo.mMatrixIsIdentity;
8890            if (matrixIsIdentity) {
8891                if (mAttachInfo != null) {
8892                    int maxRight;
8893                    if (right < mRight) {
8894                        maxRight = mRight;
8895                    } else {
8896                        maxRight = right;
8897                    }
8898                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8899                }
8900            } else {
8901                // Double-invalidation is necessary to capture view's old and new areas
8902                invalidate(true);
8903            }
8904
8905            int oldWidth = mRight - mLeft;
8906            int height = mBottom - mTop;
8907
8908            mRight = right;
8909            if (mDisplayList != null) {
8910                mDisplayList.setRight(mRight);
8911            }
8912
8913            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8914
8915            if (!matrixIsIdentity) {
8916                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8917                    // A change in dimension means an auto-centered pivot point changes, too
8918                    mTransformationInfo.mMatrixDirty = true;
8919                }
8920                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8921                invalidate(true);
8922            }
8923            mBackgroundSizeChanged = true;
8924            invalidateParentIfNeeded();
8925        }
8926    }
8927
8928    /**
8929     * The visual x position of this view, in pixels. This is equivalent to the
8930     * {@link #setTranslationX(float) translationX} property plus the current
8931     * {@link #getLeft() left} property.
8932     *
8933     * @return The visual x position of this view, in pixels.
8934     */
8935    @ViewDebug.ExportedProperty(category = "drawing")
8936    public float getX() {
8937        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8938    }
8939
8940    /**
8941     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8942     * {@link #setTranslationX(float) translationX} property to be the difference between
8943     * the x value passed in and the current {@link #getLeft() left} property.
8944     *
8945     * @param x The visual x position of this view, in pixels.
8946     */
8947    public void setX(float x) {
8948        setTranslationX(x - mLeft);
8949    }
8950
8951    /**
8952     * The visual y position of this view, in pixels. This is equivalent to the
8953     * {@link #setTranslationY(float) translationY} property plus the current
8954     * {@link #getTop() top} property.
8955     *
8956     * @return The visual y position of this view, in pixels.
8957     */
8958    @ViewDebug.ExportedProperty(category = "drawing")
8959    public float getY() {
8960        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8961    }
8962
8963    /**
8964     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8965     * {@link #setTranslationY(float) translationY} property to be the difference between
8966     * the y value passed in and the current {@link #getTop() top} property.
8967     *
8968     * @param y The visual y position of this view, in pixels.
8969     */
8970    public void setY(float y) {
8971        setTranslationY(y - mTop);
8972    }
8973
8974
8975    /**
8976     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8977     * This position is post-layout, in addition to wherever the object's
8978     * layout placed it.
8979     *
8980     * @return The horizontal position of this view relative to its left position, in pixels.
8981     */
8982    @ViewDebug.ExportedProperty(category = "drawing")
8983    public float getTranslationX() {
8984        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8985    }
8986
8987    /**
8988     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8989     * This effectively positions the object post-layout, in addition to wherever the object's
8990     * layout placed it.
8991     *
8992     * @param translationX The horizontal position of this view relative to its left position,
8993     * in pixels.
8994     *
8995     * @attr ref android.R.styleable#View_translationX
8996     */
8997    public void setTranslationX(float translationX) {
8998        ensureTransformationInfo();
8999        final TransformationInfo info = mTransformationInfo;
9000        if (info.mTranslationX != translationX) {
9001            // Double-invalidation is necessary to capture view's old and new areas
9002            invalidateViewProperty(true, false);
9003            info.mTranslationX = translationX;
9004            info.mMatrixDirty = true;
9005            invalidateViewProperty(false, true);
9006            if (mDisplayList != null) {
9007                mDisplayList.setTranslationX(translationX);
9008            }
9009        }
9010    }
9011
9012    /**
9013     * The horizontal location of this view relative to its {@link #getTop() top} position.
9014     * This position is post-layout, in addition to wherever the object's
9015     * layout placed it.
9016     *
9017     * @return The vertical position of this view relative to its top position,
9018     * in pixels.
9019     */
9020    @ViewDebug.ExportedProperty(category = "drawing")
9021    public float getTranslationY() {
9022        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9023    }
9024
9025    /**
9026     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9027     * This effectively positions the object post-layout, in addition to wherever the object's
9028     * layout placed it.
9029     *
9030     * @param translationY The vertical position of this view relative to its top position,
9031     * in pixels.
9032     *
9033     * @attr ref android.R.styleable#View_translationY
9034     */
9035    public void setTranslationY(float translationY) {
9036        ensureTransformationInfo();
9037        final TransformationInfo info = mTransformationInfo;
9038        if (info.mTranslationY != translationY) {
9039            invalidateViewProperty(true, false);
9040            info.mTranslationY = translationY;
9041            info.mMatrixDirty = true;
9042            invalidateViewProperty(false, true);
9043            if (mDisplayList != null) {
9044                mDisplayList.setTranslationY(translationY);
9045            }
9046        }
9047    }
9048
9049    /**
9050     * Hit rectangle in parent's coordinates
9051     *
9052     * @param outRect The hit rectangle of the view.
9053     */
9054    public void getHitRect(Rect outRect) {
9055        updateMatrix();
9056        final TransformationInfo info = mTransformationInfo;
9057        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9058            outRect.set(mLeft, mTop, mRight, mBottom);
9059        } else {
9060            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9061            tmpRect.set(-info.mPivotX, -info.mPivotY,
9062                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9063            info.mMatrix.mapRect(tmpRect);
9064            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9065                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9066        }
9067    }
9068
9069    /**
9070     * Determines whether the given point, in local coordinates is inside the view.
9071     */
9072    /*package*/ final boolean pointInView(float localX, float localY) {
9073        return localX >= 0 && localX < (mRight - mLeft)
9074                && localY >= 0 && localY < (mBottom - mTop);
9075    }
9076
9077    /**
9078     * Utility method to determine whether the given point, in local coordinates,
9079     * is inside the view, where the area of the view is expanded by the slop factor.
9080     * This method is called while processing touch-move events to determine if the event
9081     * is still within the view.
9082     */
9083    private boolean pointInView(float localX, float localY, float slop) {
9084        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9085                localY < ((mBottom - mTop) + slop);
9086    }
9087
9088    /**
9089     * When a view has focus and the user navigates away from it, the next view is searched for
9090     * starting from the rectangle filled in by this method.
9091     *
9092     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9093     * of the view.  However, if your view maintains some idea of internal selection,
9094     * such as a cursor, or a selected row or column, you should override this method and
9095     * fill in a more specific rectangle.
9096     *
9097     * @param r The rectangle to fill in, in this view's coordinates.
9098     */
9099    public void getFocusedRect(Rect r) {
9100        getDrawingRect(r);
9101    }
9102
9103    /**
9104     * If some part of this view is not clipped by any of its parents, then
9105     * return that area in r in global (root) coordinates. To convert r to local
9106     * coordinates (without taking possible View rotations into account), offset
9107     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9108     * If the view is completely clipped or translated out, return false.
9109     *
9110     * @param r If true is returned, r holds the global coordinates of the
9111     *        visible portion of this view.
9112     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9113     *        between this view and its root. globalOffet may be null.
9114     * @return true if r is non-empty (i.e. part of the view is visible at the
9115     *         root level.
9116     */
9117    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9118        int width = mRight - mLeft;
9119        int height = mBottom - mTop;
9120        if (width > 0 && height > 0) {
9121            r.set(0, 0, width, height);
9122            if (globalOffset != null) {
9123                globalOffset.set(-mScrollX, -mScrollY);
9124            }
9125            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9126        }
9127        return false;
9128    }
9129
9130    public final boolean getGlobalVisibleRect(Rect r) {
9131        return getGlobalVisibleRect(r, null);
9132    }
9133
9134    public final boolean getLocalVisibleRect(Rect r) {
9135        Point offset = new Point();
9136        if (getGlobalVisibleRect(r, offset)) {
9137            r.offset(-offset.x, -offset.y); // make r local
9138            return true;
9139        }
9140        return false;
9141    }
9142
9143    /**
9144     * Offset this view's vertical location by the specified number of pixels.
9145     *
9146     * @param offset the number of pixels to offset the view by
9147     */
9148    public void offsetTopAndBottom(int offset) {
9149        if (offset != 0) {
9150            updateMatrix();
9151            final boolean matrixIsIdentity = mTransformationInfo == null
9152                    || mTransformationInfo.mMatrixIsIdentity;
9153            if (matrixIsIdentity) {
9154                if (mDisplayList != null) {
9155                    invalidateViewProperty(false, false);
9156                } else {
9157                    final ViewParent p = mParent;
9158                    if (p != null && mAttachInfo != null) {
9159                        final Rect r = mAttachInfo.mTmpInvalRect;
9160                        int minTop;
9161                        int maxBottom;
9162                        int yLoc;
9163                        if (offset < 0) {
9164                            minTop = mTop + offset;
9165                            maxBottom = mBottom;
9166                            yLoc = offset;
9167                        } else {
9168                            minTop = mTop;
9169                            maxBottom = mBottom + offset;
9170                            yLoc = 0;
9171                        }
9172                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9173                        p.invalidateChild(this, r);
9174                    }
9175                }
9176            } else {
9177                invalidateViewProperty(false, false);
9178            }
9179
9180            mTop += offset;
9181            mBottom += offset;
9182            if (mDisplayList != null) {
9183                mDisplayList.offsetTopBottom(offset);
9184                invalidateViewProperty(false, false);
9185            } else {
9186                if (!matrixIsIdentity) {
9187                    invalidateViewProperty(false, true);
9188                }
9189                invalidateParentIfNeeded();
9190            }
9191        }
9192    }
9193
9194    /**
9195     * Offset this view's horizontal location by the specified amount of pixels.
9196     *
9197     * @param offset the numer of pixels to offset the view by
9198     */
9199    public void offsetLeftAndRight(int offset) {
9200        if (offset != 0) {
9201            updateMatrix();
9202            final boolean matrixIsIdentity = mTransformationInfo == null
9203                    || mTransformationInfo.mMatrixIsIdentity;
9204            if (matrixIsIdentity) {
9205                if (mDisplayList != null) {
9206                    invalidateViewProperty(false, false);
9207                } else {
9208                    final ViewParent p = mParent;
9209                    if (p != null && mAttachInfo != null) {
9210                        final Rect r = mAttachInfo.mTmpInvalRect;
9211                        int minLeft;
9212                        int maxRight;
9213                        if (offset < 0) {
9214                            minLeft = mLeft + offset;
9215                            maxRight = mRight;
9216                        } else {
9217                            minLeft = mLeft;
9218                            maxRight = mRight + offset;
9219                        }
9220                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9221                        p.invalidateChild(this, r);
9222                    }
9223                }
9224            } else {
9225                invalidateViewProperty(false, false);
9226            }
9227
9228            mLeft += offset;
9229            mRight += offset;
9230            if (mDisplayList != null) {
9231                mDisplayList.offsetLeftRight(offset);
9232                invalidateViewProperty(false, false);
9233            } else {
9234                if (!matrixIsIdentity) {
9235                    invalidateViewProperty(false, true);
9236                }
9237                invalidateParentIfNeeded();
9238            }
9239        }
9240    }
9241
9242    /**
9243     * Get the LayoutParams associated with this view. All views should have
9244     * layout parameters. These supply parameters to the <i>parent</i> of this
9245     * view specifying how it should be arranged. There are many subclasses of
9246     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9247     * of ViewGroup that are responsible for arranging their children.
9248     *
9249     * This method may return null if this View is not attached to a parent
9250     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9251     * was not invoked successfully. When a View is attached to a parent
9252     * ViewGroup, this method must not return null.
9253     *
9254     * @return The LayoutParams associated with this view, or null if no
9255     *         parameters have been set yet
9256     */
9257    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9258    public ViewGroup.LayoutParams getLayoutParams() {
9259        return mLayoutParams;
9260    }
9261
9262    /**
9263     * Set the layout parameters associated with this view. These supply
9264     * parameters to the <i>parent</i> of this view specifying how it should be
9265     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9266     * correspond to the different subclasses of ViewGroup that are responsible
9267     * for arranging their children.
9268     *
9269     * @param params The layout parameters for this view, cannot be null
9270     */
9271    public void setLayoutParams(ViewGroup.LayoutParams params) {
9272        if (params == null) {
9273            throw new NullPointerException("Layout parameters cannot be null");
9274        }
9275        mLayoutParams = params;
9276        if (mParent instanceof ViewGroup) {
9277            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9278        }
9279        requestLayout();
9280    }
9281
9282    /**
9283     * Set the scrolled position of your view. This will cause a call to
9284     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9285     * invalidated.
9286     * @param x the x position to scroll to
9287     * @param y the y position to scroll to
9288     */
9289    public void scrollTo(int x, int y) {
9290        if (mScrollX != x || mScrollY != y) {
9291            int oldX = mScrollX;
9292            int oldY = mScrollY;
9293            mScrollX = x;
9294            mScrollY = y;
9295            invalidateParentCaches();
9296            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9297            if (!awakenScrollBars()) {
9298                postInvalidateOnAnimation();
9299            }
9300        }
9301    }
9302
9303    /**
9304     * Move the scrolled position of your view. This will cause a call to
9305     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9306     * invalidated.
9307     * @param x the amount of pixels to scroll by horizontally
9308     * @param y the amount of pixels to scroll by vertically
9309     */
9310    public void scrollBy(int x, int y) {
9311        scrollTo(mScrollX + x, mScrollY + y);
9312    }
9313
9314    /**
9315     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9316     * animation to fade the scrollbars out after a default delay. If a subclass
9317     * provides animated scrolling, the start delay should equal the duration
9318     * of the scrolling animation.</p>
9319     *
9320     * <p>The animation starts only if at least one of the scrollbars is
9321     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9322     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9323     * this method returns true, and false otherwise. If the animation is
9324     * started, this method calls {@link #invalidate()}; in that case the
9325     * caller should not call {@link #invalidate()}.</p>
9326     *
9327     * <p>This method should be invoked every time a subclass directly updates
9328     * the scroll parameters.</p>
9329     *
9330     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9331     * and {@link #scrollTo(int, int)}.</p>
9332     *
9333     * @return true if the animation is played, false otherwise
9334     *
9335     * @see #awakenScrollBars(int)
9336     * @see #scrollBy(int, int)
9337     * @see #scrollTo(int, int)
9338     * @see #isHorizontalScrollBarEnabled()
9339     * @see #isVerticalScrollBarEnabled()
9340     * @see #setHorizontalScrollBarEnabled(boolean)
9341     * @see #setVerticalScrollBarEnabled(boolean)
9342     */
9343    protected boolean awakenScrollBars() {
9344        return mScrollCache != null &&
9345                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9346    }
9347
9348    /**
9349     * Trigger the scrollbars to draw.
9350     * This method differs from awakenScrollBars() only in its default duration.
9351     * initialAwakenScrollBars() will show the scroll bars for longer than
9352     * usual to give the user more of a chance to notice them.
9353     *
9354     * @return true if the animation is played, false otherwise.
9355     */
9356    private boolean initialAwakenScrollBars() {
9357        return mScrollCache != null &&
9358                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9359    }
9360
9361    /**
9362     * <p>
9363     * Trigger the scrollbars to draw. When invoked this method starts an
9364     * animation to fade the scrollbars out after a fixed delay. If a subclass
9365     * provides animated scrolling, the start delay should equal the duration of
9366     * the scrolling animation.
9367     * </p>
9368     *
9369     * <p>
9370     * The animation starts only if at least one of the scrollbars is enabled,
9371     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9372     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9373     * this method returns true, and false otherwise. If the animation is
9374     * started, this method calls {@link #invalidate()}; in that case the caller
9375     * should not call {@link #invalidate()}.
9376     * </p>
9377     *
9378     * <p>
9379     * This method should be invoked everytime a subclass directly updates the
9380     * scroll parameters.
9381     * </p>
9382     *
9383     * @param startDelay the delay, in milliseconds, after which the animation
9384     *        should start; when the delay is 0, the animation starts
9385     *        immediately
9386     * @return true if the animation is played, false otherwise
9387     *
9388     * @see #scrollBy(int, int)
9389     * @see #scrollTo(int, int)
9390     * @see #isHorizontalScrollBarEnabled()
9391     * @see #isVerticalScrollBarEnabled()
9392     * @see #setHorizontalScrollBarEnabled(boolean)
9393     * @see #setVerticalScrollBarEnabled(boolean)
9394     */
9395    protected boolean awakenScrollBars(int startDelay) {
9396        return awakenScrollBars(startDelay, true);
9397    }
9398
9399    /**
9400     * <p>
9401     * Trigger the scrollbars to draw. When invoked this method starts an
9402     * animation to fade the scrollbars out after a fixed delay. If a subclass
9403     * provides animated scrolling, the start delay should equal the duration of
9404     * the scrolling animation.
9405     * </p>
9406     *
9407     * <p>
9408     * The animation starts only if at least one of the scrollbars is enabled,
9409     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9410     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9411     * this method returns true, and false otherwise. If the animation is
9412     * started, this method calls {@link #invalidate()} if the invalidate parameter
9413     * is set to true; in that case the caller
9414     * should not call {@link #invalidate()}.
9415     * </p>
9416     *
9417     * <p>
9418     * This method should be invoked everytime a subclass directly updates the
9419     * scroll parameters.
9420     * </p>
9421     *
9422     * @param startDelay the delay, in milliseconds, after which the animation
9423     *        should start; when the delay is 0, the animation starts
9424     *        immediately
9425     *
9426     * @param invalidate Wheter this method should call invalidate
9427     *
9428     * @return true if the animation is played, false otherwise
9429     *
9430     * @see #scrollBy(int, int)
9431     * @see #scrollTo(int, int)
9432     * @see #isHorizontalScrollBarEnabled()
9433     * @see #isVerticalScrollBarEnabled()
9434     * @see #setHorizontalScrollBarEnabled(boolean)
9435     * @see #setVerticalScrollBarEnabled(boolean)
9436     */
9437    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9438        final ScrollabilityCache scrollCache = mScrollCache;
9439
9440        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9441            return false;
9442        }
9443
9444        if (scrollCache.scrollBar == null) {
9445            scrollCache.scrollBar = new ScrollBarDrawable();
9446        }
9447
9448        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9449
9450            if (invalidate) {
9451                // Invalidate to show the scrollbars
9452                postInvalidateOnAnimation();
9453            }
9454
9455            if (scrollCache.state == ScrollabilityCache.OFF) {
9456                // FIXME: this is copied from WindowManagerService.
9457                // We should get this value from the system when it
9458                // is possible to do so.
9459                final int KEY_REPEAT_FIRST_DELAY = 750;
9460                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9461            }
9462
9463            // Tell mScrollCache when we should start fading. This may
9464            // extend the fade start time if one was already scheduled
9465            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9466            scrollCache.fadeStartTime = fadeStartTime;
9467            scrollCache.state = ScrollabilityCache.ON;
9468
9469            // Schedule our fader to run, unscheduling any old ones first
9470            if (mAttachInfo != null) {
9471                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9472                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9473            }
9474
9475            return true;
9476        }
9477
9478        return false;
9479    }
9480
9481    /**
9482     * Do not invalidate views which are not visible and which are not running an animation. They
9483     * will not get drawn and they should not set dirty flags as if they will be drawn
9484     */
9485    private boolean skipInvalidate() {
9486        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9487                (!(mParent instanceof ViewGroup) ||
9488                        !((ViewGroup) mParent).isViewTransitioning(this));
9489    }
9490    /**
9491     * Mark the area defined by dirty as needing to be drawn. If the view is
9492     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9493     * in the future. This must be called from a UI thread. To call from a non-UI
9494     * thread, call {@link #postInvalidate()}.
9495     *
9496     * WARNING: This method is destructive to dirty.
9497     * @param dirty the rectangle representing the bounds of the dirty region
9498     */
9499    public void invalidate(Rect dirty) {
9500        if (ViewDebug.TRACE_HIERARCHY) {
9501            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9502        }
9503
9504        if (skipInvalidate()) {
9505            return;
9506        }
9507        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9508                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9509                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9510            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9511            mPrivateFlags |= INVALIDATED;
9512            mPrivateFlags |= DIRTY;
9513            final ViewParent p = mParent;
9514            final AttachInfo ai = mAttachInfo;
9515            //noinspection PointlessBooleanExpression,ConstantConditions
9516            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9517                if (p != null && ai != null && ai.mHardwareAccelerated) {
9518                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9519                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9520                    p.invalidateChild(this, null);
9521                    return;
9522                }
9523            }
9524            if (p != null && ai != null) {
9525                final int scrollX = mScrollX;
9526                final int scrollY = mScrollY;
9527                final Rect r = ai.mTmpInvalRect;
9528                r.set(dirty.left - scrollX, dirty.top - scrollY,
9529                        dirty.right - scrollX, dirty.bottom - scrollY);
9530                mParent.invalidateChild(this, r);
9531            }
9532        }
9533    }
9534
9535    /**
9536     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9537     * The coordinates of the dirty rect are relative to the view.
9538     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9539     * will be called at some point in the future. This must be called from
9540     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9541     * @param l the left position of the dirty region
9542     * @param t the top position of the dirty region
9543     * @param r the right position of the dirty region
9544     * @param b the bottom position of the dirty region
9545     */
9546    public void invalidate(int l, int t, int r, int b) {
9547        if (ViewDebug.TRACE_HIERARCHY) {
9548            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9549        }
9550
9551        if (skipInvalidate()) {
9552            return;
9553        }
9554        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9555                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9556                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9557            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9558            mPrivateFlags |= INVALIDATED;
9559            mPrivateFlags |= DIRTY;
9560            final ViewParent p = mParent;
9561            final AttachInfo ai = mAttachInfo;
9562            //noinspection PointlessBooleanExpression,ConstantConditions
9563            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9564                if (p != null && ai != null && ai.mHardwareAccelerated) {
9565                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9566                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9567                    p.invalidateChild(this, null);
9568                    return;
9569                }
9570            }
9571            if (p != null && ai != null && l < r && t < b) {
9572                final int scrollX = mScrollX;
9573                final int scrollY = mScrollY;
9574                final Rect tmpr = ai.mTmpInvalRect;
9575                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9576                p.invalidateChild(this, tmpr);
9577            }
9578        }
9579    }
9580
9581    /**
9582     * Invalidate the whole view. If the view is visible,
9583     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9584     * the future. This must be called from a UI thread. To call from a non-UI thread,
9585     * call {@link #postInvalidate()}.
9586     */
9587    public void invalidate() {
9588        invalidate(true);
9589    }
9590
9591    /**
9592     * This is where the invalidate() work actually happens. A full invalidate()
9593     * causes the drawing cache to be invalidated, but this function can be called with
9594     * invalidateCache set to false to skip that invalidation step for cases that do not
9595     * need it (for example, a component that remains at the same dimensions with the same
9596     * content).
9597     *
9598     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9599     * well. This is usually true for a full invalidate, but may be set to false if the
9600     * View's contents or dimensions have not changed.
9601     */
9602    void invalidate(boolean invalidateCache) {
9603        if (ViewDebug.TRACE_HIERARCHY) {
9604            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9605        }
9606
9607        if (skipInvalidate()) {
9608            return;
9609        }
9610        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9611                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9612                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9613            mLastIsOpaque = isOpaque();
9614            mPrivateFlags &= ~DRAWN;
9615            mPrivateFlags |= DIRTY;
9616            if (invalidateCache) {
9617                mPrivateFlags |= INVALIDATED;
9618                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9619            }
9620            final AttachInfo ai = mAttachInfo;
9621            final ViewParent p = mParent;
9622            //noinspection PointlessBooleanExpression,ConstantConditions
9623            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9624                if (p != null && ai != null && ai.mHardwareAccelerated) {
9625                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9626                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9627                    p.invalidateChild(this, null);
9628                    return;
9629                }
9630            }
9631
9632            if (p != null && ai != null) {
9633                final Rect r = ai.mTmpInvalRect;
9634                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9635                // Don't call invalidate -- we don't want to internally scroll
9636                // our own bounds
9637                p.invalidateChild(this, r);
9638            }
9639        }
9640    }
9641
9642    /**
9643     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9644     * set any flags or handle all of the cases handled by the default invalidation methods.
9645     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9646     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9647     * walk up the hierarchy, transforming the dirty rect as necessary.
9648     *
9649     * The method also handles normal invalidation logic if display list properties are not
9650     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9651     * backup approach, to handle these cases used in the various property-setting methods.
9652     *
9653     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9654     * are not being used in this view
9655     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9656     * list properties are not being used in this view
9657     */
9658    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9659        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9660            if (invalidateParent) {
9661                invalidateParentCaches();
9662            }
9663            if (forceRedraw) {
9664                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9665            }
9666            invalidate(false);
9667        } else {
9668            final AttachInfo ai = mAttachInfo;
9669            final ViewParent p = mParent;
9670            if (p != null && ai != null) {
9671                final Rect r = ai.mTmpInvalRect;
9672                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9673                if (mParent instanceof ViewGroup) {
9674                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9675                } else {
9676                    mParent.invalidateChild(this, r);
9677                }
9678            }
9679        }
9680    }
9681
9682    /**
9683     * Utility method to transform a given Rect by the current matrix of this view.
9684     */
9685    void transformRect(final Rect rect) {
9686        if (!getMatrix().isIdentity()) {
9687            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9688            boundingRect.set(rect);
9689            getMatrix().mapRect(boundingRect);
9690            rect.set((int) (boundingRect.left - 0.5f),
9691                    (int) (boundingRect.top - 0.5f),
9692                    (int) (boundingRect.right + 0.5f),
9693                    (int) (boundingRect.bottom + 0.5f));
9694        }
9695    }
9696
9697    /**
9698     * Used to indicate that the parent of this view should clear its caches. This functionality
9699     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9700     * which is necessary when various parent-managed properties of the view change, such as
9701     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9702     * clears the parent caches and does not causes an invalidate event.
9703     *
9704     * @hide
9705     */
9706    protected void invalidateParentCaches() {
9707        if (mParent instanceof View) {
9708            ((View) mParent).mPrivateFlags |= INVALIDATED;
9709        }
9710    }
9711
9712    /**
9713     * Used to indicate that the parent of this view should be invalidated. This functionality
9714     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9715     * which is necessary when various parent-managed properties of the view change, such as
9716     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9717     * an invalidation event to the parent.
9718     *
9719     * @hide
9720     */
9721    protected void invalidateParentIfNeeded() {
9722        if (isHardwareAccelerated() && mParent instanceof View) {
9723            ((View) mParent).invalidate(true);
9724        }
9725    }
9726
9727    /**
9728     * Indicates whether this View is opaque. An opaque View guarantees that it will
9729     * draw all the pixels overlapping its bounds using a fully opaque color.
9730     *
9731     * Subclasses of View should override this method whenever possible to indicate
9732     * whether an instance is opaque. Opaque Views are treated in a special way by
9733     * the View hierarchy, possibly allowing it to perform optimizations during
9734     * invalidate/draw passes.
9735     *
9736     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9737     */
9738    @ViewDebug.ExportedProperty(category = "drawing")
9739    public boolean isOpaque() {
9740        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9741                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9742                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9743    }
9744
9745    /**
9746     * @hide
9747     */
9748    protected void computeOpaqueFlags() {
9749        // Opaque if:
9750        //   - Has a background
9751        //   - Background is opaque
9752        //   - Doesn't have scrollbars or scrollbars are inside overlay
9753
9754        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
9755            mPrivateFlags |= OPAQUE_BACKGROUND;
9756        } else {
9757            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9758        }
9759
9760        final int flags = mViewFlags;
9761        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9762                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9763            mPrivateFlags |= OPAQUE_SCROLLBARS;
9764        } else {
9765            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9766        }
9767    }
9768
9769    /**
9770     * @hide
9771     */
9772    protected boolean hasOpaqueScrollbars() {
9773        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9774    }
9775
9776    /**
9777     * @return A handler associated with the thread running the View. This
9778     * handler can be used to pump events in the UI events queue.
9779     */
9780    public Handler getHandler() {
9781        if (mAttachInfo != null) {
9782            return mAttachInfo.mHandler;
9783        }
9784        return null;
9785    }
9786
9787    /**
9788     * Gets the view root associated with the View.
9789     * @return The view root, or null if none.
9790     * @hide
9791     */
9792    public ViewRootImpl getViewRootImpl() {
9793        if (mAttachInfo != null) {
9794            return mAttachInfo.mViewRootImpl;
9795        }
9796        return null;
9797    }
9798
9799    /**
9800     * <p>Causes the Runnable to be added to the message queue.
9801     * The runnable will be run on the user interface thread.</p>
9802     *
9803     * <p>This method can be invoked from outside of the UI thread
9804     * only when this View is attached to a window.</p>
9805     *
9806     * @param action The Runnable that will be executed.
9807     *
9808     * @return Returns true if the Runnable was successfully placed in to the
9809     *         message queue.  Returns false on failure, usually because the
9810     *         looper processing the message queue is exiting.
9811     *
9812     * @see #postDelayed
9813     * @see #removeCallbacks
9814     */
9815    public boolean post(Runnable action) {
9816        final AttachInfo attachInfo = mAttachInfo;
9817        if (attachInfo != null) {
9818            return attachInfo.mHandler.post(action);
9819        }
9820        // Assume that post will succeed later
9821        ViewRootImpl.getRunQueue().post(action);
9822        return true;
9823    }
9824
9825    /**
9826     * <p>Causes the Runnable to be added to the message queue, to be run
9827     * after the specified amount of time elapses.
9828     * The runnable will be run on the user interface thread.</p>
9829     *
9830     * <p>This method can be invoked from outside of the UI thread
9831     * only when this View is attached to a window.</p>
9832     *
9833     * @param action The Runnable that will be executed.
9834     * @param delayMillis The delay (in milliseconds) until the Runnable
9835     *        will be executed.
9836     *
9837     * @return true if the Runnable was successfully placed in to the
9838     *         message queue.  Returns false on failure, usually because the
9839     *         looper processing the message queue is exiting.  Note that a
9840     *         result of true does not mean the Runnable will be processed --
9841     *         if the looper is quit before the delivery time of the message
9842     *         occurs then the message will be dropped.
9843     *
9844     * @see #post
9845     * @see #removeCallbacks
9846     */
9847    public boolean postDelayed(Runnable action, long delayMillis) {
9848        final AttachInfo attachInfo = mAttachInfo;
9849        if (attachInfo != null) {
9850            return attachInfo.mHandler.postDelayed(action, delayMillis);
9851        }
9852        // Assume that post will succeed later
9853        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9854        return true;
9855    }
9856
9857    /**
9858     * <p>Causes the Runnable to execute on the next animation time step.
9859     * The runnable will be run on the user interface thread.</p>
9860     *
9861     * <p>This method can be invoked from outside of the UI thread
9862     * only when this View is attached to a window.</p>
9863     *
9864     * @param action The Runnable that will be executed.
9865     *
9866     * @see #postOnAnimationDelayed
9867     * @see #removeCallbacks
9868     */
9869    public void postOnAnimation(Runnable action) {
9870        final AttachInfo attachInfo = mAttachInfo;
9871        if (attachInfo != null) {
9872            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9873                    Choreographer.CALLBACK_ANIMATION, action, null);
9874        } else {
9875            // Assume that post will succeed later
9876            ViewRootImpl.getRunQueue().post(action);
9877        }
9878    }
9879
9880    /**
9881     * <p>Causes the Runnable to execute on the next animation time step,
9882     * after the specified amount of time elapses.
9883     * The runnable will be run on the user interface thread.</p>
9884     *
9885     * <p>This method can be invoked from outside of the UI thread
9886     * only when this View is attached to a window.</p>
9887     *
9888     * @param action The Runnable that will be executed.
9889     * @param delayMillis The delay (in milliseconds) until the Runnable
9890     *        will be executed.
9891     *
9892     * @see #postOnAnimation
9893     * @see #removeCallbacks
9894     */
9895    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9896        final AttachInfo attachInfo = mAttachInfo;
9897        if (attachInfo != null) {
9898            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9899                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9900        } else {
9901            // Assume that post will succeed later
9902            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9903        }
9904    }
9905
9906    /**
9907     * <p>Removes the specified Runnable from the message queue.</p>
9908     *
9909     * <p>This method can be invoked from outside of the UI thread
9910     * only when this View is attached to a window.</p>
9911     *
9912     * @param action The Runnable to remove from the message handling queue
9913     *
9914     * @return true if this view could ask the Handler to remove the Runnable,
9915     *         false otherwise. When the returned value is true, the Runnable
9916     *         may or may not have been actually removed from the message queue
9917     *         (for instance, if the Runnable was not in the queue already.)
9918     *
9919     * @see #post
9920     * @see #postDelayed
9921     * @see #postOnAnimation
9922     * @see #postOnAnimationDelayed
9923     */
9924    public boolean removeCallbacks(Runnable action) {
9925        if (action != null) {
9926            final AttachInfo attachInfo = mAttachInfo;
9927            if (attachInfo != null) {
9928                attachInfo.mHandler.removeCallbacks(action);
9929                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9930                        Choreographer.CALLBACK_ANIMATION, action, null);
9931            } else {
9932                // Assume that post will succeed later
9933                ViewRootImpl.getRunQueue().removeCallbacks(action);
9934            }
9935        }
9936        return true;
9937    }
9938
9939    /**
9940     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9941     * Use this to invalidate the View from a non-UI thread.</p>
9942     *
9943     * <p>This method can be invoked from outside of the UI thread
9944     * only when this View is attached to a window.</p>
9945     *
9946     * @see #invalidate()
9947     * @see #postInvalidateDelayed(long)
9948     */
9949    public void postInvalidate() {
9950        postInvalidateDelayed(0);
9951    }
9952
9953    /**
9954     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9955     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9956     *
9957     * <p>This method can be invoked from outside of the UI thread
9958     * only when this View is attached to a window.</p>
9959     *
9960     * @param left The left coordinate of the rectangle to invalidate.
9961     * @param top The top coordinate of the rectangle to invalidate.
9962     * @param right The right coordinate of the rectangle to invalidate.
9963     * @param bottom The bottom coordinate of the rectangle to invalidate.
9964     *
9965     * @see #invalidate(int, int, int, int)
9966     * @see #invalidate(Rect)
9967     * @see #postInvalidateDelayed(long, int, int, int, int)
9968     */
9969    public void postInvalidate(int left, int top, int right, int bottom) {
9970        postInvalidateDelayed(0, left, top, right, bottom);
9971    }
9972
9973    /**
9974     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9975     * loop. Waits for the specified amount of time.</p>
9976     *
9977     * <p>This method can be invoked from outside of the UI thread
9978     * only when this View is attached to a window.</p>
9979     *
9980     * @param delayMilliseconds the duration in milliseconds to delay the
9981     *         invalidation by
9982     *
9983     * @see #invalidate()
9984     * @see #postInvalidate()
9985     */
9986    public void postInvalidateDelayed(long delayMilliseconds) {
9987        // We try only with the AttachInfo because there's no point in invalidating
9988        // if we are not attached to our window
9989        final AttachInfo attachInfo = mAttachInfo;
9990        if (attachInfo != null) {
9991            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9992        }
9993    }
9994
9995    /**
9996     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9997     * through the event loop. Waits for the specified amount of time.</p>
9998     *
9999     * <p>This method can be invoked from outside of the UI thread
10000     * only when this View is attached to a window.</p>
10001     *
10002     * @param delayMilliseconds the duration in milliseconds to delay the
10003     *         invalidation by
10004     * @param left The left coordinate of the rectangle to invalidate.
10005     * @param top The top coordinate of the rectangle to invalidate.
10006     * @param right The right coordinate of the rectangle to invalidate.
10007     * @param bottom The bottom coordinate of the rectangle to invalidate.
10008     *
10009     * @see #invalidate(int, int, int, int)
10010     * @see #invalidate(Rect)
10011     * @see #postInvalidate(int, int, int, int)
10012     */
10013    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10014            int right, int bottom) {
10015
10016        // We try only with the AttachInfo because there's no point in invalidating
10017        // if we are not attached to our window
10018        final AttachInfo attachInfo = mAttachInfo;
10019        if (attachInfo != null) {
10020            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10021            info.target = this;
10022            info.left = left;
10023            info.top = top;
10024            info.right = right;
10025            info.bottom = bottom;
10026
10027            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10028        }
10029    }
10030
10031    /**
10032     * <p>Cause an invalidate to happen on the next animation time step, typically the
10033     * next display frame.</p>
10034     *
10035     * <p>This method can be invoked from outside of the UI thread
10036     * only when this View is attached to a window.</p>
10037     *
10038     * @see #invalidate()
10039     */
10040    public void postInvalidateOnAnimation() {
10041        // We try only with the AttachInfo because there's no point in invalidating
10042        // if we are not attached to our window
10043        final AttachInfo attachInfo = mAttachInfo;
10044        if (attachInfo != null) {
10045            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10046        }
10047    }
10048
10049    /**
10050     * <p>Cause an invalidate of the specified area to happen on the next animation
10051     * time step, typically the next display frame.</p>
10052     *
10053     * <p>This method can be invoked from outside of the UI thread
10054     * only when this View is attached to a window.</p>
10055     *
10056     * @param left The left coordinate of the rectangle to invalidate.
10057     * @param top The top coordinate of the rectangle to invalidate.
10058     * @param right The right coordinate of the rectangle to invalidate.
10059     * @param bottom The bottom coordinate of the rectangle to invalidate.
10060     *
10061     * @see #invalidate(int, int, int, int)
10062     * @see #invalidate(Rect)
10063     */
10064    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10065        // We try only with the AttachInfo because there's no point in invalidating
10066        // if we are not attached to our window
10067        final AttachInfo attachInfo = mAttachInfo;
10068        if (attachInfo != null) {
10069            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10070            info.target = this;
10071            info.left = left;
10072            info.top = top;
10073            info.right = right;
10074            info.bottom = bottom;
10075
10076            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10077        }
10078    }
10079
10080    /**
10081     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10082     * This event is sent at most once every
10083     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10084     */
10085    private void postSendViewScrolledAccessibilityEventCallback() {
10086        if (mSendViewScrolledAccessibilityEvent == null) {
10087            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10088        }
10089        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10090            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10091            postDelayed(mSendViewScrolledAccessibilityEvent,
10092                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10093        }
10094    }
10095
10096    /**
10097     * Called by a parent to request that a child update its values for mScrollX
10098     * and mScrollY if necessary. This will typically be done if the child is
10099     * animating a scroll using a {@link android.widget.Scroller Scroller}
10100     * object.
10101     */
10102    public void computeScroll() {
10103    }
10104
10105    /**
10106     * <p>Indicate whether the horizontal edges are faded when the view is
10107     * scrolled horizontally.</p>
10108     *
10109     * @return true if the horizontal edges should are faded on scroll, false
10110     *         otherwise
10111     *
10112     * @see #setHorizontalFadingEdgeEnabled(boolean)
10113     *
10114     * @attr ref android.R.styleable#View_requiresFadingEdge
10115     */
10116    public boolean isHorizontalFadingEdgeEnabled() {
10117        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10118    }
10119
10120    /**
10121     * <p>Define whether the horizontal edges should be faded when this view
10122     * is scrolled horizontally.</p>
10123     *
10124     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10125     *                                    be faded when the view is scrolled
10126     *                                    horizontally
10127     *
10128     * @see #isHorizontalFadingEdgeEnabled()
10129     *
10130     * @attr ref android.R.styleable#View_requiresFadingEdge
10131     */
10132    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10133        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10134            if (horizontalFadingEdgeEnabled) {
10135                initScrollCache();
10136            }
10137
10138            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10139        }
10140    }
10141
10142    /**
10143     * <p>Indicate whether the vertical edges are faded when the view is
10144     * scrolled horizontally.</p>
10145     *
10146     * @return true if the vertical edges should are faded on scroll, false
10147     *         otherwise
10148     *
10149     * @see #setVerticalFadingEdgeEnabled(boolean)
10150     *
10151     * @attr ref android.R.styleable#View_requiresFadingEdge
10152     */
10153    public boolean isVerticalFadingEdgeEnabled() {
10154        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10155    }
10156
10157    /**
10158     * <p>Define whether the vertical edges should be faded when this view
10159     * is scrolled vertically.</p>
10160     *
10161     * @param verticalFadingEdgeEnabled true if the vertical edges should
10162     *                                  be faded when the view is scrolled
10163     *                                  vertically
10164     *
10165     * @see #isVerticalFadingEdgeEnabled()
10166     *
10167     * @attr ref android.R.styleable#View_requiresFadingEdge
10168     */
10169    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10170        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10171            if (verticalFadingEdgeEnabled) {
10172                initScrollCache();
10173            }
10174
10175            mViewFlags ^= FADING_EDGE_VERTICAL;
10176        }
10177    }
10178
10179    /**
10180     * Returns the strength, or intensity, of the top faded edge. The strength is
10181     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10182     * returns 0.0 or 1.0 but no value in between.
10183     *
10184     * Subclasses should override this method to provide a smoother fade transition
10185     * when scrolling occurs.
10186     *
10187     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10188     */
10189    protected float getTopFadingEdgeStrength() {
10190        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10191    }
10192
10193    /**
10194     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10195     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10196     * returns 0.0 or 1.0 but no value in between.
10197     *
10198     * Subclasses should override this method to provide a smoother fade transition
10199     * when scrolling occurs.
10200     *
10201     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10202     */
10203    protected float getBottomFadingEdgeStrength() {
10204        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10205                computeVerticalScrollRange() ? 1.0f : 0.0f;
10206    }
10207
10208    /**
10209     * Returns the strength, or intensity, of the left faded edge. The strength is
10210     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10211     * returns 0.0 or 1.0 but no value in between.
10212     *
10213     * Subclasses should override this method to provide a smoother fade transition
10214     * when scrolling occurs.
10215     *
10216     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10217     */
10218    protected float getLeftFadingEdgeStrength() {
10219        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10220    }
10221
10222    /**
10223     * Returns the strength, or intensity, of the right faded edge. The strength is
10224     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10225     * returns 0.0 or 1.0 but no value in between.
10226     *
10227     * Subclasses should override this method to provide a smoother fade transition
10228     * when scrolling occurs.
10229     *
10230     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10231     */
10232    protected float getRightFadingEdgeStrength() {
10233        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10234                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10235    }
10236
10237    /**
10238     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10239     * scrollbar is not drawn by default.</p>
10240     *
10241     * @return true if the horizontal scrollbar should be painted, false
10242     *         otherwise
10243     *
10244     * @see #setHorizontalScrollBarEnabled(boolean)
10245     */
10246    public boolean isHorizontalScrollBarEnabled() {
10247        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10248    }
10249
10250    /**
10251     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10252     * scrollbar is not drawn by default.</p>
10253     *
10254     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10255     *                                   be painted
10256     *
10257     * @see #isHorizontalScrollBarEnabled()
10258     */
10259    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10260        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10261            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10262            computeOpaqueFlags();
10263            resolvePadding();
10264        }
10265    }
10266
10267    /**
10268     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10269     * scrollbar is not drawn by default.</p>
10270     *
10271     * @return true if the vertical scrollbar should be painted, false
10272     *         otherwise
10273     *
10274     * @see #setVerticalScrollBarEnabled(boolean)
10275     */
10276    public boolean isVerticalScrollBarEnabled() {
10277        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10278    }
10279
10280    /**
10281     * <p>Define whether the vertical scrollbar should be drawn or not. The
10282     * scrollbar is not drawn by default.</p>
10283     *
10284     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10285     *                                 be painted
10286     *
10287     * @see #isVerticalScrollBarEnabled()
10288     */
10289    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10290        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10291            mViewFlags ^= SCROLLBARS_VERTICAL;
10292            computeOpaqueFlags();
10293            resolvePadding();
10294        }
10295    }
10296
10297    /**
10298     * @hide
10299     */
10300    protected void recomputePadding() {
10301        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10302    }
10303
10304    /**
10305     * Define whether scrollbars will fade when the view is not scrolling.
10306     *
10307     * @param fadeScrollbars wheter to enable fading
10308     *
10309     * @attr ref android.R.styleable#View_fadeScrollbars
10310     */
10311    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10312        initScrollCache();
10313        final ScrollabilityCache scrollabilityCache = mScrollCache;
10314        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10315        if (fadeScrollbars) {
10316            scrollabilityCache.state = ScrollabilityCache.OFF;
10317        } else {
10318            scrollabilityCache.state = ScrollabilityCache.ON;
10319        }
10320    }
10321
10322    /**
10323     *
10324     * Returns true if scrollbars will fade when this view is not scrolling
10325     *
10326     * @return true if scrollbar fading is enabled
10327     *
10328     * @attr ref android.R.styleable#View_fadeScrollbars
10329     */
10330    public boolean isScrollbarFadingEnabled() {
10331        return mScrollCache != null && mScrollCache.fadeScrollBars;
10332    }
10333
10334    /**
10335     *
10336     * Returns the delay before scrollbars fade.
10337     *
10338     * @return the delay before scrollbars fade
10339     *
10340     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10341     */
10342    public int getScrollBarDefaultDelayBeforeFade() {
10343        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10344                mScrollCache.scrollBarDefaultDelayBeforeFade;
10345    }
10346
10347    /**
10348     * Define the delay before scrollbars fade.
10349     *
10350     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10351     *
10352     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10353     */
10354    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10355        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10356    }
10357
10358    /**
10359     *
10360     * Returns the scrollbar fade duration.
10361     *
10362     * @return the scrollbar fade duration
10363     *
10364     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10365     */
10366    public int getScrollBarFadeDuration() {
10367        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10368                mScrollCache.scrollBarFadeDuration;
10369    }
10370
10371    /**
10372     * Define the scrollbar fade duration.
10373     *
10374     * @param scrollBarFadeDuration - the scrollbar fade duration
10375     *
10376     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10377     */
10378    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10379        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10380    }
10381
10382    /**
10383     *
10384     * Returns the scrollbar size.
10385     *
10386     * @return the scrollbar size
10387     *
10388     * @attr ref android.R.styleable#View_scrollbarSize
10389     */
10390    public int getScrollBarSize() {
10391        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10392                mScrollCache.scrollBarSize;
10393    }
10394
10395    /**
10396     * Define the scrollbar size.
10397     *
10398     * @param scrollBarSize - the scrollbar size
10399     *
10400     * @attr ref android.R.styleable#View_scrollbarSize
10401     */
10402    public void setScrollBarSize(int scrollBarSize) {
10403        getScrollCache().scrollBarSize = scrollBarSize;
10404    }
10405
10406    /**
10407     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10408     * inset. When inset, they add to the padding of the view. And the scrollbars
10409     * can be drawn inside the padding area or on the edge of the view. For example,
10410     * if a view has a background drawable and you want to draw the scrollbars
10411     * inside the padding specified by the drawable, you can use
10412     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10413     * appear at the edge of the view, ignoring the padding, then you can use
10414     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10415     * @param style the style of the scrollbars. Should be one of
10416     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10417     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10418     * @see #SCROLLBARS_INSIDE_OVERLAY
10419     * @see #SCROLLBARS_INSIDE_INSET
10420     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10421     * @see #SCROLLBARS_OUTSIDE_INSET
10422     *
10423     * @attr ref android.R.styleable#View_scrollbarStyle
10424     */
10425    public void setScrollBarStyle(int style) {
10426        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10427            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10428            computeOpaqueFlags();
10429            resolvePadding();
10430        }
10431    }
10432
10433    /**
10434     * <p>Returns the current scrollbar style.</p>
10435     * @return the current scrollbar style
10436     * @see #SCROLLBARS_INSIDE_OVERLAY
10437     * @see #SCROLLBARS_INSIDE_INSET
10438     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10439     * @see #SCROLLBARS_OUTSIDE_INSET
10440     *
10441     * @attr ref android.R.styleable#View_scrollbarStyle
10442     */
10443    @ViewDebug.ExportedProperty(mapping = {
10444            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10445            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10446            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10447            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10448    })
10449    public int getScrollBarStyle() {
10450        return mViewFlags & SCROLLBARS_STYLE_MASK;
10451    }
10452
10453    /**
10454     * <p>Compute the horizontal range that the horizontal scrollbar
10455     * represents.</p>
10456     *
10457     * <p>The range is expressed in arbitrary units that must be the same as the
10458     * units used by {@link #computeHorizontalScrollExtent()} and
10459     * {@link #computeHorizontalScrollOffset()}.</p>
10460     *
10461     * <p>The default range is the drawing width of this view.</p>
10462     *
10463     * @return the total horizontal range represented by the horizontal
10464     *         scrollbar
10465     *
10466     * @see #computeHorizontalScrollExtent()
10467     * @see #computeHorizontalScrollOffset()
10468     * @see android.widget.ScrollBarDrawable
10469     */
10470    protected int computeHorizontalScrollRange() {
10471        return getWidth();
10472    }
10473
10474    /**
10475     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10476     * within the horizontal range. This value is used to compute the position
10477     * of the thumb within the scrollbar's track.</p>
10478     *
10479     * <p>The range is expressed in arbitrary units that must be the same as the
10480     * units used by {@link #computeHorizontalScrollRange()} and
10481     * {@link #computeHorizontalScrollExtent()}.</p>
10482     *
10483     * <p>The default offset is the scroll offset of this view.</p>
10484     *
10485     * @return the horizontal offset of the scrollbar's thumb
10486     *
10487     * @see #computeHorizontalScrollRange()
10488     * @see #computeHorizontalScrollExtent()
10489     * @see android.widget.ScrollBarDrawable
10490     */
10491    protected int computeHorizontalScrollOffset() {
10492        return mScrollX;
10493    }
10494
10495    /**
10496     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10497     * within the horizontal range. This value is used to compute the length
10498     * of the thumb within the scrollbar's track.</p>
10499     *
10500     * <p>The range is expressed in arbitrary units that must be the same as the
10501     * units used by {@link #computeHorizontalScrollRange()} and
10502     * {@link #computeHorizontalScrollOffset()}.</p>
10503     *
10504     * <p>The default extent is the drawing width of this view.</p>
10505     *
10506     * @return the horizontal extent of the scrollbar's thumb
10507     *
10508     * @see #computeHorizontalScrollRange()
10509     * @see #computeHorizontalScrollOffset()
10510     * @see android.widget.ScrollBarDrawable
10511     */
10512    protected int computeHorizontalScrollExtent() {
10513        return getWidth();
10514    }
10515
10516    /**
10517     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10518     *
10519     * <p>The range is expressed in arbitrary units that must be the same as the
10520     * units used by {@link #computeVerticalScrollExtent()} and
10521     * {@link #computeVerticalScrollOffset()}.</p>
10522     *
10523     * @return the total vertical range represented by the vertical scrollbar
10524     *
10525     * <p>The default range is the drawing height of this view.</p>
10526     *
10527     * @see #computeVerticalScrollExtent()
10528     * @see #computeVerticalScrollOffset()
10529     * @see android.widget.ScrollBarDrawable
10530     */
10531    protected int computeVerticalScrollRange() {
10532        return getHeight();
10533    }
10534
10535    /**
10536     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10537     * within the horizontal range. This value is used to compute the position
10538     * of the thumb within the scrollbar's track.</p>
10539     *
10540     * <p>The range is expressed in arbitrary units that must be the same as the
10541     * units used by {@link #computeVerticalScrollRange()} and
10542     * {@link #computeVerticalScrollExtent()}.</p>
10543     *
10544     * <p>The default offset is the scroll offset of this view.</p>
10545     *
10546     * @return the vertical offset of the scrollbar's thumb
10547     *
10548     * @see #computeVerticalScrollRange()
10549     * @see #computeVerticalScrollExtent()
10550     * @see android.widget.ScrollBarDrawable
10551     */
10552    protected int computeVerticalScrollOffset() {
10553        return mScrollY;
10554    }
10555
10556    /**
10557     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10558     * within the vertical range. This value is used to compute the length
10559     * of the thumb within the scrollbar's track.</p>
10560     *
10561     * <p>The range is expressed in arbitrary units that must be the same as the
10562     * units used by {@link #computeVerticalScrollRange()} and
10563     * {@link #computeVerticalScrollOffset()}.</p>
10564     *
10565     * <p>The default extent is the drawing height of this view.</p>
10566     *
10567     * @return the vertical extent of the scrollbar's thumb
10568     *
10569     * @see #computeVerticalScrollRange()
10570     * @see #computeVerticalScrollOffset()
10571     * @see android.widget.ScrollBarDrawable
10572     */
10573    protected int computeVerticalScrollExtent() {
10574        return getHeight();
10575    }
10576
10577    /**
10578     * Check if this view can be scrolled horizontally in a certain direction.
10579     *
10580     * @param direction Negative to check scrolling left, positive to check scrolling right.
10581     * @return true if this view can be scrolled in the specified direction, false otherwise.
10582     */
10583    public boolean canScrollHorizontally(int direction) {
10584        final int offset = computeHorizontalScrollOffset();
10585        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10586        if (range == 0) return false;
10587        if (direction < 0) {
10588            return offset > 0;
10589        } else {
10590            return offset < range - 1;
10591        }
10592    }
10593
10594    /**
10595     * Check if this view can be scrolled vertically in a certain direction.
10596     *
10597     * @param direction Negative to check scrolling up, positive to check scrolling down.
10598     * @return true if this view can be scrolled in the specified direction, false otherwise.
10599     */
10600    public boolean canScrollVertically(int direction) {
10601        final int offset = computeVerticalScrollOffset();
10602        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10603        if (range == 0) return false;
10604        if (direction < 0) {
10605            return offset > 0;
10606        } else {
10607            return offset < range - 1;
10608        }
10609    }
10610
10611    /**
10612     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10613     * scrollbars are painted only if they have been awakened first.</p>
10614     *
10615     * @param canvas the canvas on which to draw the scrollbars
10616     *
10617     * @see #awakenScrollBars(int)
10618     */
10619    protected final void onDrawScrollBars(Canvas canvas) {
10620        // scrollbars are drawn only when the animation is running
10621        final ScrollabilityCache cache = mScrollCache;
10622        if (cache != null) {
10623
10624            int state = cache.state;
10625
10626            if (state == ScrollabilityCache.OFF) {
10627                return;
10628            }
10629
10630            boolean invalidate = false;
10631
10632            if (state == ScrollabilityCache.FADING) {
10633                // We're fading -- get our fade interpolation
10634                if (cache.interpolatorValues == null) {
10635                    cache.interpolatorValues = new float[1];
10636                }
10637
10638                float[] values = cache.interpolatorValues;
10639
10640                // Stops the animation if we're done
10641                if (cache.scrollBarInterpolator.timeToValues(values) ==
10642                        Interpolator.Result.FREEZE_END) {
10643                    cache.state = ScrollabilityCache.OFF;
10644                } else {
10645                    cache.scrollBar.setAlpha(Math.round(values[0]));
10646                }
10647
10648                // This will make the scroll bars inval themselves after
10649                // drawing. We only want this when we're fading so that
10650                // we prevent excessive redraws
10651                invalidate = true;
10652            } else {
10653                // We're just on -- but we may have been fading before so
10654                // reset alpha
10655                cache.scrollBar.setAlpha(255);
10656            }
10657
10658
10659            final int viewFlags = mViewFlags;
10660
10661            final boolean drawHorizontalScrollBar =
10662                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10663            final boolean drawVerticalScrollBar =
10664                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10665                && !isVerticalScrollBarHidden();
10666
10667            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10668                final int width = mRight - mLeft;
10669                final int height = mBottom - mTop;
10670
10671                final ScrollBarDrawable scrollBar = cache.scrollBar;
10672
10673                final int scrollX = mScrollX;
10674                final int scrollY = mScrollY;
10675                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10676
10677                int left, top, right, bottom;
10678
10679                if (drawHorizontalScrollBar) {
10680                    int size = scrollBar.getSize(false);
10681                    if (size <= 0) {
10682                        size = cache.scrollBarSize;
10683                    }
10684
10685                    scrollBar.setParameters(computeHorizontalScrollRange(),
10686                                            computeHorizontalScrollOffset(),
10687                                            computeHorizontalScrollExtent(), false);
10688                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10689                            getVerticalScrollbarWidth() : 0;
10690                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10691                    left = scrollX + (mPaddingLeft & inside);
10692                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10693                    bottom = top + size;
10694                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10695                    if (invalidate) {
10696                        invalidate(left, top, right, bottom);
10697                    }
10698                }
10699
10700                if (drawVerticalScrollBar) {
10701                    int size = scrollBar.getSize(true);
10702                    if (size <= 0) {
10703                        size = cache.scrollBarSize;
10704                    }
10705
10706                    scrollBar.setParameters(computeVerticalScrollRange(),
10707                                            computeVerticalScrollOffset(),
10708                                            computeVerticalScrollExtent(), true);
10709                    switch (mVerticalScrollbarPosition) {
10710                        default:
10711                        case SCROLLBAR_POSITION_DEFAULT:
10712                        case SCROLLBAR_POSITION_RIGHT:
10713                            left = scrollX + width - size - (mUserPaddingRight & inside);
10714                            break;
10715                        case SCROLLBAR_POSITION_LEFT:
10716                            left = scrollX + (mUserPaddingLeft & inside);
10717                            break;
10718                    }
10719                    top = scrollY + (mPaddingTop & inside);
10720                    right = left + size;
10721                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10722                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10723                    if (invalidate) {
10724                        invalidate(left, top, right, bottom);
10725                    }
10726                }
10727            }
10728        }
10729    }
10730
10731    /**
10732     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10733     * FastScroller is visible.
10734     * @return whether to temporarily hide the vertical scrollbar
10735     * @hide
10736     */
10737    protected boolean isVerticalScrollBarHidden() {
10738        return false;
10739    }
10740
10741    /**
10742     * <p>Draw the horizontal scrollbar if
10743     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
10744     *
10745     * @param canvas the canvas on which to draw the scrollbar
10746     * @param scrollBar the scrollbar's drawable
10747     *
10748     * @see #isHorizontalScrollBarEnabled()
10749     * @see #computeHorizontalScrollRange()
10750     * @see #computeHorizontalScrollExtent()
10751     * @see #computeHorizontalScrollOffset()
10752     * @see android.widget.ScrollBarDrawable
10753     * @hide
10754     */
10755    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
10756            int l, int t, int r, int b) {
10757        scrollBar.setBounds(l, t, r, b);
10758        scrollBar.draw(canvas);
10759    }
10760
10761    /**
10762     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
10763     * returns true.</p>
10764     *
10765     * @param canvas the canvas on which to draw the scrollbar
10766     * @param scrollBar the scrollbar's drawable
10767     *
10768     * @see #isVerticalScrollBarEnabled()
10769     * @see #computeVerticalScrollRange()
10770     * @see #computeVerticalScrollExtent()
10771     * @see #computeVerticalScrollOffset()
10772     * @see android.widget.ScrollBarDrawable
10773     * @hide
10774     */
10775    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
10776            int l, int t, int r, int b) {
10777        scrollBar.setBounds(l, t, r, b);
10778        scrollBar.draw(canvas);
10779    }
10780
10781    /**
10782     * Implement this to do your drawing.
10783     *
10784     * @param canvas the canvas on which the background will be drawn
10785     */
10786    protected void onDraw(Canvas canvas) {
10787    }
10788
10789    /*
10790     * Caller is responsible for calling requestLayout if necessary.
10791     * (This allows addViewInLayout to not request a new layout.)
10792     */
10793    void assignParent(ViewParent parent) {
10794        if (mParent == null) {
10795            mParent = parent;
10796        } else if (parent == null) {
10797            mParent = null;
10798        } else {
10799            throw new RuntimeException("view " + this + " being added, but"
10800                    + " it already has a parent");
10801        }
10802    }
10803
10804    /**
10805     * This is called when the view is attached to a window.  At this point it
10806     * has a Surface and will start drawing.  Note that this function is
10807     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
10808     * however it may be called any time before the first onDraw -- including
10809     * before or after {@link #onMeasure(int, int)}.
10810     *
10811     * @see #onDetachedFromWindow()
10812     */
10813    protected void onAttachedToWindow() {
10814        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
10815            mParent.requestTransparentRegion(this);
10816        }
10817        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
10818            initialAwakenScrollBars();
10819            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
10820        }
10821        jumpDrawablesToCurrentState();
10822        // Order is important here: LayoutDirection MUST be resolved before Padding
10823        // and TextDirection
10824        resolveLayoutDirection();
10825        resolvePadding();
10826        resolveTextDirection();
10827        resolveTextAlignment();
10828        clearAccessibilityFocus();
10829        if (isFocused()) {
10830            InputMethodManager imm = InputMethodManager.peekInstance();
10831            imm.focusIn(this);
10832        }
10833    }
10834
10835    /**
10836     * @see #onScreenStateChanged(int)
10837     */
10838    void dispatchScreenStateChanged(int screenState) {
10839        onScreenStateChanged(screenState);
10840    }
10841
10842    /**
10843     * This method is called whenever the state of the screen this view is
10844     * attached to changes. A state change will usually occurs when the screen
10845     * turns on or off (whether it happens automatically or the user does it
10846     * manually.)
10847     *
10848     * @param screenState The new state of the screen. Can be either
10849     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10850     */
10851    public void onScreenStateChanged(int screenState) {
10852    }
10853
10854    /**
10855     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10856     */
10857    private boolean hasRtlSupport() {
10858        return mContext.getApplicationInfo().hasRtlSupport();
10859    }
10860
10861    /**
10862     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10863     * that the parent directionality can and will be resolved before its children.
10864     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10865     */
10866    public void resolveLayoutDirection() {
10867        // Clear any previous layout direction resolution
10868        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10869
10870        if (hasRtlSupport()) {
10871            // Set resolved depending on layout direction
10872            switch (getLayoutDirection()) {
10873                case LAYOUT_DIRECTION_INHERIT:
10874                    // If this is root view, no need to look at parent's layout dir.
10875                    if (canResolveLayoutDirection()) {
10876                        ViewGroup viewGroup = ((ViewGroup) mParent);
10877
10878                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10879                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10880                        }
10881                    } else {
10882                        // Nothing to do, LTR by default
10883                    }
10884                    break;
10885                case LAYOUT_DIRECTION_RTL:
10886                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10887                    break;
10888                case LAYOUT_DIRECTION_LOCALE:
10889                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10890                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10891                    }
10892                    break;
10893                default:
10894                    // Nothing to do, LTR by default
10895            }
10896        }
10897
10898        // Set to resolved
10899        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10900        onResolvedLayoutDirectionChanged();
10901        // Resolve padding
10902        resolvePadding();
10903    }
10904
10905    /**
10906     * Called when layout direction has been resolved.
10907     *
10908     * The default implementation does nothing.
10909     */
10910    public void onResolvedLayoutDirectionChanged() {
10911    }
10912
10913    /**
10914     * Resolve padding depending on layout direction.
10915     */
10916    public void resolvePadding() {
10917        // If the user specified the absolute padding (either with android:padding or
10918        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10919        // use the default padding or the padding from the background drawable
10920        // (stored at this point in mPadding*)
10921        int resolvedLayoutDirection = getResolvedLayoutDirection();
10922        switch (resolvedLayoutDirection) {
10923            case LAYOUT_DIRECTION_RTL:
10924                // Start user padding override Right user padding. Otherwise, if Right user
10925                // padding is not defined, use the default Right padding. If Right user padding
10926                // is defined, just use it.
10927                if (mUserPaddingStart >= 0) {
10928                    mUserPaddingRight = mUserPaddingStart;
10929                } else if (mUserPaddingRight < 0) {
10930                    mUserPaddingRight = mPaddingRight;
10931                }
10932                if (mUserPaddingEnd >= 0) {
10933                    mUserPaddingLeft = mUserPaddingEnd;
10934                } else if (mUserPaddingLeft < 0) {
10935                    mUserPaddingLeft = mPaddingLeft;
10936                }
10937                break;
10938            case LAYOUT_DIRECTION_LTR:
10939            default:
10940                // Start user padding override Left user padding. Otherwise, if Left user
10941                // padding is not defined, use the default left padding. If Left user padding
10942                // is defined, just use it.
10943                if (mUserPaddingStart >= 0) {
10944                    mUserPaddingLeft = mUserPaddingStart;
10945                } else if (mUserPaddingLeft < 0) {
10946                    mUserPaddingLeft = mPaddingLeft;
10947                }
10948                if (mUserPaddingEnd >= 0) {
10949                    mUserPaddingRight = mUserPaddingEnd;
10950                } else if (mUserPaddingRight < 0) {
10951                    mUserPaddingRight = mPaddingRight;
10952                }
10953        }
10954
10955        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
10956
10957        if(isPaddingRelative()) {
10958            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
10959        } else {
10960            recomputePadding();
10961        }
10962        onPaddingChanged(resolvedLayoutDirection);
10963    }
10964
10965    /**
10966     * Resolve padding depending on the layout direction. Subclasses that care about
10967     * padding resolution should override this method. The default implementation does
10968     * nothing.
10969     *
10970     * @param layoutDirection the direction of the layout
10971     *
10972     * @see {@link #LAYOUT_DIRECTION_LTR}
10973     * @see {@link #LAYOUT_DIRECTION_RTL}
10974     */
10975    public void onPaddingChanged(int layoutDirection) {
10976    }
10977
10978    /**
10979     * Check if layout direction resolution can be done.
10980     *
10981     * @return true if layout direction resolution can be done otherwise return false.
10982     */
10983    public boolean canResolveLayoutDirection() {
10984        switch (getLayoutDirection()) {
10985            case LAYOUT_DIRECTION_INHERIT:
10986                return (mParent != null) && (mParent instanceof ViewGroup);
10987            default:
10988                return true;
10989        }
10990    }
10991
10992    /**
10993     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
10994     * when reset is done.
10995     */
10996    public void resetResolvedLayoutDirection() {
10997        // Reset the current resolved bits
10998        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10999        onResolvedLayoutDirectionReset();
11000        // Reset also the text direction
11001        resetResolvedTextDirection();
11002    }
11003
11004    /**
11005     * Called during reset of resolved layout direction.
11006     *
11007     * Subclasses need to override this method to clear cached information that depends on the
11008     * resolved layout direction, or to inform child views that inherit their layout direction.
11009     *
11010     * The default implementation does nothing.
11011     */
11012    public void onResolvedLayoutDirectionReset() {
11013    }
11014
11015    /**
11016     * Check if a Locale uses an RTL script.
11017     *
11018     * @param locale Locale to check
11019     * @return true if the Locale uses an RTL script.
11020     */
11021    protected static boolean isLayoutDirectionRtl(Locale locale) {
11022        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11023    }
11024
11025    /**
11026     * This is called when the view is detached from a window.  At this point it
11027     * no longer has a surface for drawing.
11028     *
11029     * @see #onAttachedToWindow()
11030     */
11031    protected void onDetachedFromWindow() {
11032        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11033
11034        removeUnsetPressCallback();
11035        removeLongPressCallback();
11036        removePerformClickCallback();
11037        removeSendViewScrolledAccessibilityEventCallback();
11038
11039        destroyDrawingCache();
11040
11041        destroyLayer(false);
11042
11043        if (mAttachInfo != null) {
11044            if (mDisplayList != null) {
11045                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
11046            }
11047            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11048        } else {
11049            if (mDisplayList != null) {
11050                // Should never happen
11051                mDisplayList.invalidate();
11052            }
11053        }
11054
11055        mCurrentAnimation = null;
11056
11057        resetResolvedLayoutDirection();
11058        resetResolvedTextAlignment();
11059        resetAccessibilityStateChanged();
11060        clearAccessibilityFocus();
11061    }
11062
11063    /**
11064     * @return The number of times this view has been attached to a window
11065     */
11066    protected int getWindowAttachCount() {
11067        return mWindowAttachCount;
11068    }
11069
11070    /**
11071     * Retrieve a unique token identifying the window this view is attached to.
11072     * @return Return the window's token for use in
11073     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11074     */
11075    public IBinder getWindowToken() {
11076        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11077    }
11078
11079    /**
11080     * Retrieve a unique token identifying the top-level "real" window of
11081     * the window that this view is attached to.  That is, this is like
11082     * {@link #getWindowToken}, except if the window this view in is a panel
11083     * window (attached to another containing window), then the token of
11084     * the containing window is returned instead.
11085     *
11086     * @return Returns the associated window token, either
11087     * {@link #getWindowToken()} or the containing window's token.
11088     */
11089    public IBinder getApplicationWindowToken() {
11090        AttachInfo ai = mAttachInfo;
11091        if (ai != null) {
11092            IBinder appWindowToken = ai.mPanelParentWindowToken;
11093            if (appWindowToken == null) {
11094                appWindowToken = ai.mWindowToken;
11095            }
11096            return appWindowToken;
11097        }
11098        return null;
11099    }
11100
11101    /**
11102     * Retrieve private session object this view hierarchy is using to
11103     * communicate with the window manager.
11104     * @return the session object to communicate with the window manager
11105     */
11106    /*package*/ IWindowSession getWindowSession() {
11107        return mAttachInfo != null ? mAttachInfo.mSession : null;
11108    }
11109
11110    /**
11111     * @param info the {@link android.view.View.AttachInfo} to associated with
11112     *        this view
11113     */
11114    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11115        //System.out.println("Attached! " + this);
11116        mAttachInfo = info;
11117        mWindowAttachCount++;
11118        // We will need to evaluate the drawable state at least once.
11119        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11120        if (mFloatingTreeObserver != null) {
11121            info.mTreeObserver.merge(mFloatingTreeObserver);
11122            mFloatingTreeObserver = null;
11123        }
11124        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11125            mAttachInfo.mScrollContainers.add(this);
11126            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11127        }
11128        performCollectViewAttributes(mAttachInfo, visibility);
11129        onAttachedToWindow();
11130
11131        ListenerInfo li = mListenerInfo;
11132        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11133                li != null ? li.mOnAttachStateChangeListeners : null;
11134        if (listeners != null && listeners.size() > 0) {
11135            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11136            // perform the dispatching. The iterator is a safe guard against listeners that
11137            // could mutate the list by calling the various add/remove methods. This prevents
11138            // the array from being modified while we iterate it.
11139            for (OnAttachStateChangeListener listener : listeners) {
11140                listener.onViewAttachedToWindow(this);
11141            }
11142        }
11143
11144        int vis = info.mWindowVisibility;
11145        if (vis != GONE) {
11146            onWindowVisibilityChanged(vis);
11147        }
11148        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11149            // If nobody has evaluated the drawable state yet, then do it now.
11150            refreshDrawableState();
11151        }
11152    }
11153
11154    void dispatchDetachedFromWindow() {
11155        AttachInfo info = mAttachInfo;
11156        if (info != null) {
11157            int vis = info.mWindowVisibility;
11158            if (vis != GONE) {
11159                onWindowVisibilityChanged(GONE);
11160            }
11161        }
11162
11163        onDetachedFromWindow();
11164
11165        ListenerInfo li = mListenerInfo;
11166        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11167                li != null ? li.mOnAttachStateChangeListeners : null;
11168        if (listeners != null && listeners.size() > 0) {
11169            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11170            // perform the dispatching. The iterator is a safe guard against listeners that
11171            // could mutate the list by calling the various add/remove methods. This prevents
11172            // the array from being modified while we iterate it.
11173            for (OnAttachStateChangeListener listener : listeners) {
11174                listener.onViewDetachedFromWindow(this);
11175            }
11176        }
11177
11178        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11179            mAttachInfo.mScrollContainers.remove(this);
11180            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11181        }
11182
11183        mAttachInfo = null;
11184    }
11185
11186    /**
11187     * Store this view hierarchy's frozen state into the given container.
11188     *
11189     * @param container The SparseArray in which to save the view's state.
11190     *
11191     * @see #restoreHierarchyState(android.util.SparseArray)
11192     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11193     * @see #onSaveInstanceState()
11194     */
11195    public void saveHierarchyState(SparseArray<Parcelable> container) {
11196        dispatchSaveInstanceState(container);
11197    }
11198
11199    /**
11200     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11201     * this view and its children. May be overridden to modify how freezing happens to a
11202     * view's children; for example, some views may want to not store state for their children.
11203     *
11204     * @param container The SparseArray in which to save the view's state.
11205     *
11206     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11207     * @see #saveHierarchyState(android.util.SparseArray)
11208     * @see #onSaveInstanceState()
11209     */
11210    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11211        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11212            mPrivateFlags &= ~SAVE_STATE_CALLED;
11213            Parcelable state = onSaveInstanceState();
11214            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11215                throw new IllegalStateException(
11216                        "Derived class did not call super.onSaveInstanceState()");
11217            }
11218            if (state != null) {
11219                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11220                // + ": " + state);
11221                container.put(mID, state);
11222            }
11223        }
11224    }
11225
11226    /**
11227     * Hook allowing a view to generate a representation of its internal state
11228     * that can later be used to create a new instance with that same state.
11229     * This state should only contain information that is not persistent or can
11230     * not be reconstructed later. For example, you will never store your
11231     * current position on screen because that will be computed again when a
11232     * new instance of the view is placed in its view hierarchy.
11233     * <p>
11234     * Some examples of things you may store here: the current cursor position
11235     * in a text view (but usually not the text itself since that is stored in a
11236     * content provider or other persistent storage), the currently selected
11237     * item in a list view.
11238     *
11239     * @return Returns a Parcelable object containing the view's current dynamic
11240     *         state, or null if there is nothing interesting to save. The
11241     *         default implementation returns null.
11242     * @see #onRestoreInstanceState(android.os.Parcelable)
11243     * @see #saveHierarchyState(android.util.SparseArray)
11244     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11245     * @see #setSaveEnabled(boolean)
11246     */
11247    protected Parcelable onSaveInstanceState() {
11248        mPrivateFlags |= SAVE_STATE_CALLED;
11249        return BaseSavedState.EMPTY_STATE;
11250    }
11251
11252    /**
11253     * Restore this view hierarchy's frozen state from the given container.
11254     *
11255     * @param container The SparseArray which holds previously frozen states.
11256     *
11257     * @see #saveHierarchyState(android.util.SparseArray)
11258     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11259     * @see #onRestoreInstanceState(android.os.Parcelable)
11260     */
11261    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11262        dispatchRestoreInstanceState(container);
11263    }
11264
11265    /**
11266     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11267     * state for this view and its children. May be overridden to modify how restoring
11268     * happens to a view's children; for example, some views may want to not store state
11269     * for their children.
11270     *
11271     * @param container The SparseArray which holds previously saved state.
11272     *
11273     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11274     * @see #restoreHierarchyState(android.util.SparseArray)
11275     * @see #onRestoreInstanceState(android.os.Parcelable)
11276     */
11277    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11278        if (mID != NO_ID) {
11279            Parcelable state = container.get(mID);
11280            if (state != null) {
11281                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11282                // + ": " + state);
11283                mPrivateFlags &= ~SAVE_STATE_CALLED;
11284                onRestoreInstanceState(state);
11285                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11286                    throw new IllegalStateException(
11287                            "Derived class did not call super.onRestoreInstanceState()");
11288                }
11289            }
11290        }
11291    }
11292
11293    /**
11294     * Hook allowing a view to re-apply a representation of its internal state that had previously
11295     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11296     * null state.
11297     *
11298     * @param state The frozen state that had previously been returned by
11299     *        {@link #onSaveInstanceState}.
11300     *
11301     * @see #onSaveInstanceState()
11302     * @see #restoreHierarchyState(android.util.SparseArray)
11303     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11304     */
11305    protected void onRestoreInstanceState(Parcelable state) {
11306        mPrivateFlags |= SAVE_STATE_CALLED;
11307        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11308            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11309                    + "received " + state.getClass().toString() + " instead. This usually happens "
11310                    + "when two views of different type have the same id in the same hierarchy. "
11311                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11312                    + "other views do not use the same id.");
11313        }
11314    }
11315
11316    /**
11317     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11318     *
11319     * @return the drawing start time in milliseconds
11320     */
11321    public long getDrawingTime() {
11322        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11323    }
11324
11325    /**
11326     * <p>Enables or disables the duplication of the parent's state into this view. When
11327     * duplication is enabled, this view gets its drawable state from its parent rather
11328     * than from its own internal properties.</p>
11329     *
11330     * <p>Note: in the current implementation, setting this property to true after the
11331     * view was added to a ViewGroup might have no effect at all. This property should
11332     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11333     *
11334     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11335     * property is enabled, an exception will be thrown.</p>
11336     *
11337     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11338     * parent, these states should not be affected by this method.</p>
11339     *
11340     * @param enabled True to enable duplication of the parent's drawable state, false
11341     *                to disable it.
11342     *
11343     * @see #getDrawableState()
11344     * @see #isDuplicateParentStateEnabled()
11345     */
11346    public void setDuplicateParentStateEnabled(boolean enabled) {
11347        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11348    }
11349
11350    /**
11351     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11352     *
11353     * @return True if this view's drawable state is duplicated from the parent,
11354     *         false otherwise
11355     *
11356     * @see #getDrawableState()
11357     * @see #setDuplicateParentStateEnabled(boolean)
11358     */
11359    public boolean isDuplicateParentStateEnabled() {
11360        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11361    }
11362
11363    /**
11364     * <p>Specifies the type of layer backing this view. The layer can be
11365     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11366     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11367     *
11368     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11369     * instance that controls how the layer is composed on screen. The following
11370     * properties of the paint are taken into account when composing the layer:</p>
11371     * <ul>
11372     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11373     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11374     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11375     * </ul>
11376     *
11377     * <p>If this view has an alpha value set to < 1.0 by calling
11378     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11379     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11380     * equivalent to setting a hardware layer on this view and providing a paint with
11381     * the desired alpha value.<p>
11382     *
11383     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11384     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11385     * for more information on when and how to use layers.</p>
11386     *
11387     * @param layerType The ype of layer to use with this view, must be one of
11388     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11389     *        {@link #LAYER_TYPE_HARDWARE}
11390     * @param paint The paint used to compose the layer. This argument is optional
11391     *        and can be null. It is ignored when the layer type is
11392     *        {@link #LAYER_TYPE_NONE}
11393     *
11394     * @see #getLayerType()
11395     * @see #LAYER_TYPE_NONE
11396     * @see #LAYER_TYPE_SOFTWARE
11397     * @see #LAYER_TYPE_HARDWARE
11398     * @see #setAlpha(float)
11399     *
11400     * @attr ref android.R.styleable#View_layerType
11401     */
11402    public void setLayerType(int layerType, Paint paint) {
11403        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11404            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11405                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11406        }
11407
11408        if (layerType == mLayerType) {
11409            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11410                mLayerPaint = paint == null ? new Paint() : paint;
11411                invalidateParentCaches();
11412                invalidate(true);
11413            }
11414            return;
11415        }
11416
11417        // Destroy any previous software drawing cache if needed
11418        switch (mLayerType) {
11419            case LAYER_TYPE_HARDWARE:
11420                destroyLayer(false);
11421                // fall through - non-accelerated views may use software layer mechanism instead
11422            case LAYER_TYPE_SOFTWARE:
11423                destroyDrawingCache();
11424                break;
11425            default:
11426                break;
11427        }
11428
11429        mLayerType = layerType;
11430        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11431        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11432        mLocalDirtyRect = layerDisabled ? null : new Rect();
11433
11434        invalidateParentCaches();
11435        invalidate(true);
11436    }
11437
11438    /**
11439     * Indicates whether this view has a static layer. A view with layer type
11440     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11441     * dynamic.
11442     */
11443    boolean hasStaticLayer() {
11444        return true;
11445    }
11446
11447    /**
11448     * Indicates what type of layer is currently associated with this view. By default
11449     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11450     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11451     * for more information on the different types of layers.
11452     *
11453     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11454     *         {@link #LAYER_TYPE_HARDWARE}
11455     *
11456     * @see #setLayerType(int, android.graphics.Paint)
11457     * @see #buildLayer()
11458     * @see #LAYER_TYPE_NONE
11459     * @see #LAYER_TYPE_SOFTWARE
11460     * @see #LAYER_TYPE_HARDWARE
11461     */
11462    public int getLayerType() {
11463        return mLayerType;
11464    }
11465
11466    /**
11467     * Forces this view's layer to be created and this view to be rendered
11468     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11469     * invoking this method will have no effect.
11470     *
11471     * This method can for instance be used to render a view into its layer before
11472     * starting an animation. If this view is complex, rendering into the layer
11473     * before starting the animation will avoid skipping frames.
11474     *
11475     * @throws IllegalStateException If this view is not attached to a window
11476     *
11477     * @see #setLayerType(int, android.graphics.Paint)
11478     */
11479    public void buildLayer() {
11480        if (mLayerType == LAYER_TYPE_NONE) return;
11481
11482        if (mAttachInfo == null) {
11483            throw new IllegalStateException("This view must be attached to a window first");
11484        }
11485
11486        switch (mLayerType) {
11487            case LAYER_TYPE_HARDWARE:
11488                if (mAttachInfo.mHardwareRenderer != null &&
11489                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11490                        mAttachInfo.mHardwareRenderer.validate()) {
11491                    getHardwareLayer();
11492                }
11493                break;
11494            case LAYER_TYPE_SOFTWARE:
11495                buildDrawingCache(true);
11496                break;
11497        }
11498    }
11499
11500    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11501    void flushLayer() {
11502        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11503            mHardwareLayer.flush();
11504        }
11505    }
11506
11507    /**
11508     * <p>Returns a hardware layer that can be used to draw this view again
11509     * without executing its draw method.</p>
11510     *
11511     * @return A HardwareLayer ready to render, or null if an error occurred.
11512     */
11513    HardwareLayer getHardwareLayer() {
11514        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11515                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11516            return null;
11517        }
11518
11519        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11520
11521        final int width = mRight - mLeft;
11522        final int height = mBottom - mTop;
11523
11524        if (width == 0 || height == 0) {
11525            return null;
11526        }
11527
11528        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11529            if (mHardwareLayer == null) {
11530                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11531                        width, height, isOpaque());
11532                mLocalDirtyRect.set(0, 0, width, height);
11533            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11534                mHardwareLayer.resize(width, height);
11535                mLocalDirtyRect.set(0, 0, width, height);
11536            }
11537
11538            // The layer is not valid if the underlying GPU resources cannot be allocated
11539            if (!mHardwareLayer.isValid()) {
11540                return null;
11541            }
11542
11543            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11544            mLocalDirtyRect.setEmpty();
11545        }
11546
11547        return mHardwareLayer;
11548    }
11549
11550    /**
11551     * Destroys this View's hardware layer if possible.
11552     *
11553     * @return True if the layer was destroyed, false otherwise.
11554     *
11555     * @see #setLayerType(int, android.graphics.Paint)
11556     * @see #LAYER_TYPE_HARDWARE
11557     */
11558    boolean destroyLayer(boolean valid) {
11559        if (mHardwareLayer != null) {
11560            AttachInfo info = mAttachInfo;
11561            if (info != null && info.mHardwareRenderer != null &&
11562                    info.mHardwareRenderer.isEnabled() &&
11563                    (valid || info.mHardwareRenderer.validate())) {
11564                mHardwareLayer.destroy();
11565                mHardwareLayer = null;
11566
11567                invalidate(true);
11568                invalidateParentCaches();
11569            }
11570            return true;
11571        }
11572        return false;
11573    }
11574
11575    /**
11576     * Destroys all hardware rendering resources. This method is invoked
11577     * when the system needs to reclaim resources. Upon execution of this
11578     * method, you should free any OpenGL resources created by the view.
11579     *
11580     * Note: you <strong>must</strong> call
11581     * <code>super.destroyHardwareResources()</code> when overriding
11582     * this method.
11583     *
11584     * @hide
11585     */
11586    protected void destroyHardwareResources() {
11587        destroyLayer(true);
11588    }
11589
11590    /**
11591     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11592     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11593     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11594     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11595     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11596     * null.</p>
11597     *
11598     * <p>Enabling the drawing cache is similar to
11599     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11600     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11601     * drawing cache has no effect on rendering because the system uses a different mechanism
11602     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11603     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11604     * for information on how to enable software and hardware layers.</p>
11605     *
11606     * <p>This API can be used to manually generate
11607     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11608     * {@link #getDrawingCache()}.</p>
11609     *
11610     * @param enabled true to enable the drawing cache, false otherwise
11611     *
11612     * @see #isDrawingCacheEnabled()
11613     * @see #getDrawingCache()
11614     * @see #buildDrawingCache()
11615     * @see #setLayerType(int, android.graphics.Paint)
11616     */
11617    public void setDrawingCacheEnabled(boolean enabled) {
11618        mCachingFailed = false;
11619        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11620    }
11621
11622    /**
11623     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11624     *
11625     * @return true if the drawing cache is enabled
11626     *
11627     * @see #setDrawingCacheEnabled(boolean)
11628     * @see #getDrawingCache()
11629     */
11630    @ViewDebug.ExportedProperty(category = "drawing")
11631    public boolean isDrawingCacheEnabled() {
11632        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11633    }
11634
11635    /**
11636     * Debugging utility which recursively outputs the dirty state of a view and its
11637     * descendants.
11638     *
11639     * @hide
11640     */
11641    @SuppressWarnings({"UnusedDeclaration"})
11642    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11643        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11644                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11645                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11646                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11647        if (clear) {
11648            mPrivateFlags &= clearMask;
11649        }
11650        if (this instanceof ViewGroup) {
11651            ViewGroup parent = (ViewGroup) this;
11652            final int count = parent.getChildCount();
11653            for (int i = 0; i < count; i++) {
11654                final View child = parent.getChildAt(i);
11655                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11656            }
11657        }
11658    }
11659
11660    /**
11661     * This method is used by ViewGroup to cause its children to restore or recreate their
11662     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11663     * to recreate its own display list, which would happen if it went through the normal
11664     * draw/dispatchDraw mechanisms.
11665     *
11666     * @hide
11667     */
11668    protected void dispatchGetDisplayList() {}
11669
11670    /**
11671     * A view that is not attached or hardware accelerated cannot create a display list.
11672     * This method checks these conditions and returns the appropriate result.
11673     *
11674     * @return true if view has the ability to create a display list, false otherwise.
11675     *
11676     * @hide
11677     */
11678    public boolean canHaveDisplayList() {
11679        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11680    }
11681
11682    /**
11683     * @return The HardwareRenderer associated with that view or null if hardware rendering
11684     * is not supported or this this has not been attached to a window.
11685     *
11686     * @hide
11687     */
11688    public HardwareRenderer getHardwareRenderer() {
11689        if (mAttachInfo != null) {
11690            return mAttachInfo.mHardwareRenderer;
11691        }
11692        return null;
11693    }
11694
11695    /**
11696     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11697     * Otherwise, the same display list will be returned (after having been rendered into
11698     * along the way, depending on the invalidation state of the view).
11699     *
11700     * @param displayList The previous version of this displayList, could be null.
11701     * @param isLayer Whether the requester of the display list is a layer. If so,
11702     * the view will avoid creating a layer inside the resulting display list.
11703     * @return A new or reused DisplayList object.
11704     */
11705    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11706        if (!canHaveDisplayList()) {
11707            return null;
11708        }
11709
11710        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11711                displayList == null || !displayList.isValid() ||
11712                (!isLayer && mRecreateDisplayList))) {
11713            // Don't need to recreate the display list, just need to tell our
11714            // children to restore/recreate theirs
11715            if (displayList != null && displayList.isValid() &&
11716                    !isLayer && !mRecreateDisplayList) {
11717                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11718                mPrivateFlags &= ~DIRTY_MASK;
11719                dispatchGetDisplayList();
11720
11721                return displayList;
11722            }
11723
11724            if (!isLayer) {
11725                // If we got here, we're recreating it. Mark it as such to ensure that
11726                // we copy in child display lists into ours in drawChild()
11727                mRecreateDisplayList = true;
11728            }
11729            if (displayList == null) {
11730                final String name = getClass().getSimpleName();
11731                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
11732                // If we're creating a new display list, make sure our parent gets invalidated
11733                // since they will need to recreate their display list to account for this
11734                // new child display list.
11735                invalidateParentCaches();
11736            }
11737
11738            boolean caching = false;
11739            final HardwareCanvas canvas = displayList.start();
11740            int restoreCount = 0;
11741            int width = mRight - mLeft;
11742            int height = mBottom - mTop;
11743
11744            try {
11745                canvas.setViewport(width, height);
11746                // The dirty rect should always be null for a display list
11747                canvas.onPreDraw(null);
11748                int layerType = (
11749                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
11750                        getLayerType() : LAYER_TYPE_NONE;
11751                if (!isLayer && layerType != LAYER_TYPE_NONE) {
11752                    if (layerType == LAYER_TYPE_HARDWARE) {
11753                        final HardwareLayer layer = getHardwareLayer();
11754                        if (layer != null && layer.isValid()) {
11755                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
11756                        } else {
11757                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
11758                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
11759                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11760                        }
11761                        caching = true;
11762                    } else {
11763                        buildDrawingCache(true);
11764                        Bitmap cache = getDrawingCache(true);
11765                        if (cache != null) {
11766                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
11767                            caching = true;
11768                        }
11769                    }
11770                } else {
11771
11772                    computeScroll();
11773
11774                    canvas.translate(-mScrollX, -mScrollY);
11775                    if (!isLayer) {
11776                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11777                        mPrivateFlags &= ~DIRTY_MASK;
11778                    }
11779
11780                    // Fast path for layouts with no backgrounds
11781                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11782                        dispatchDraw(canvas);
11783                    } else {
11784                        draw(canvas);
11785                    }
11786                }
11787            } finally {
11788                canvas.onPostDraw();
11789
11790                displayList.end();
11791                displayList.setCaching(caching);
11792                if (isLayer) {
11793                    displayList.setLeftTopRightBottom(0, 0, width, height);
11794                } else {
11795                    setDisplayListProperties(displayList);
11796                }
11797            }
11798        } else if (!isLayer) {
11799            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11800            mPrivateFlags &= ~DIRTY_MASK;
11801        }
11802
11803        return displayList;
11804    }
11805
11806    /**
11807     * Get the DisplayList for the HardwareLayer
11808     *
11809     * @param layer The HardwareLayer whose DisplayList we want
11810     * @return A DisplayList fopr the specified HardwareLayer
11811     */
11812    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
11813        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
11814        layer.setDisplayList(displayList);
11815        return displayList;
11816    }
11817
11818
11819    /**
11820     * <p>Returns a display list that can be used to draw this view again
11821     * without executing its draw method.</p>
11822     *
11823     * @return A DisplayList ready to replay, or null if caching is not enabled.
11824     *
11825     * @hide
11826     */
11827    public DisplayList getDisplayList() {
11828        mDisplayList = getDisplayList(mDisplayList, false);
11829        return mDisplayList;
11830    }
11831
11832    /**
11833     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11834     *
11835     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11836     *
11837     * @see #getDrawingCache(boolean)
11838     */
11839    public Bitmap getDrawingCache() {
11840        return getDrawingCache(false);
11841    }
11842
11843    /**
11844     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11845     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11846     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11847     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11848     * request the drawing cache by calling this method and draw it on screen if the
11849     * returned bitmap is not null.</p>
11850     *
11851     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11852     * this method will create a bitmap of the same size as this view. Because this bitmap
11853     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11854     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11855     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11856     * size than the view. This implies that your application must be able to handle this
11857     * size.</p>
11858     *
11859     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11860     *        the current density of the screen when the application is in compatibility
11861     *        mode.
11862     *
11863     * @return A bitmap representing this view or null if cache is disabled.
11864     *
11865     * @see #setDrawingCacheEnabled(boolean)
11866     * @see #isDrawingCacheEnabled()
11867     * @see #buildDrawingCache(boolean)
11868     * @see #destroyDrawingCache()
11869     */
11870    public Bitmap getDrawingCache(boolean autoScale) {
11871        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11872            return null;
11873        }
11874        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11875            buildDrawingCache(autoScale);
11876        }
11877        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11878    }
11879
11880    /**
11881     * <p>Frees the resources used by the drawing cache. If you call
11882     * {@link #buildDrawingCache()} manually without calling
11883     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11884     * should cleanup the cache with this method afterwards.</p>
11885     *
11886     * @see #setDrawingCacheEnabled(boolean)
11887     * @see #buildDrawingCache()
11888     * @see #getDrawingCache()
11889     */
11890    public void destroyDrawingCache() {
11891        if (mDrawingCache != null) {
11892            mDrawingCache.recycle();
11893            mDrawingCache = null;
11894        }
11895        if (mUnscaledDrawingCache != null) {
11896            mUnscaledDrawingCache.recycle();
11897            mUnscaledDrawingCache = null;
11898        }
11899    }
11900
11901    /**
11902     * Setting a solid background color for the drawing cache's bitmaps will improve
11903     * performance and memory usage. Note, though that this should only be used if this
11904     * view will always be drawn on top of a solid color.
11905     *
11906     * @param color The background color to use for the drawing cache's bitmap
11907     *
11908     * @see #setDrawingCacheEnabled(boolean)
11909     * @see #buildDrawingCache()
11910     * @see #getDrawingCache()
11911     */
11912    public void setDrawingCacheBackgroundColor(int color) {
11913        if (color != mDrawingCacheBackgroundColor) {
11914            mDrawingCacheBackgroundColor = color;
11915            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11916        }
11917    }
11918
11919    /**
11920     * @see #setDrawingCacheBackgroundColor(int)
11921     *
11922     * @return The background color to used for the drawing cache's bitmap
11923     */
11924    public int getDrawingCacheBackgroundColor() {
11925        return mDrawingCacheBackgroundColor;
11926    }
11927
11928    /**
11929     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11930     *
11931     * @see #buildDrawingCache(boolean)
11932     */
11933    public void buildDrawingCache() {
11934        buildDrawingCache(false);
11935    }
11936
11937    /**
11938     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
11939     *
11940     * <p>If you call {@link #buildDrawingCache()} manually without calling
11941     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11942     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
11943     *
11944     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11945     * this method will create a bitmap of the same size as this view. Because this bitmap
11946     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11947     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11948     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11949     * size than the view. This implies that your application must be able to handle this
11950     * size.</p>
11951     *
11952     * <p>You should avoid calling this method when hardware acceleration is enabled. If
11953     * you do not need the drawing cache bitmap, calling this method will increase memory
11954     * usage and cause the view to be rendered in software once, thus negatively impacting
11955     * performance.</p>
11956     *
11957     * @see #getDrawingCache()
11958     * @see #destroyDrawingCache()
11959     */
11960    public void buildDrawingCache(boolean autoScale) {
11961        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
11962                mDrawingCache == null : mUnscaledDrawingCache == null)) {
11963            mCachingFailed = false;
11964
11965            if (ViewDebug.TRACE_HIERARCHY) {
11966                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
11967            }
11968
11969            int width = mRight - mLeft;
11970            int height = mBottom - mTop;
11971
11972            final AttachInfo attachInfo = mAttachInfo;
11973            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
11974
11975            if (autoScale && scalingRequired) {
11976                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
11977                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
11978            }
11979
11980            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
11981            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
11982            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
11983
11984            if (width <= 0 || height <= 0 ||
11985                     // Projected bitmap size in bytes
11986                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
11987                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
11988                destroyDrawingCache();
11989                mCachingFailed = true;
11990                return;
11991            }
11992
11993            boolean clear = true;
11994            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
11995
11996            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
11997                Bitmap.Config quality;
11998                if (!opaque) {
11999                    // Never pick ARGB_4444 because it looks awful
12000                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12001                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12002                        case DRAWING_CACHE_QUALITY_AUTO:
12003                            quality = Bitmap.Config.ARGB_8888;
12004                            break;
12005                        case DRAWING_CACHE_QUALITY_LOW:
12006                            quality = Bitmap.Config.ARGB_8888;
12007                            break;
12008                        case DRAWING_CACHE_QUALITY_HIGH:
12009                            quality = Bitmap.Config.ARGB_8888;
12010                            break;
12011                        default:
12012                            quality = Bitmap.Config.ARGB_8888;
12013                            break;
12014                    }
12015                } else {
12016                    // Optimization for translucent windows
12017                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12018                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12019                }
12020
12021                // Try to cleanup memory
12022                if (bitmap != null) bitmap.recycle();
12023
12024                try {
12025                    bitmap = Bitmap.createBitmap(width, height, quality);
12026                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12027                    if (autoScale) {
12028                        mDrawingCache = bitmap;
12029                    } else {
12030                        mUnscaledDrawingCache = bitmap;
12031                    }
12032                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12033                } catch (OutOfMemoryError e) {
12034                    // If there is not enough memory to create the bitmap cache, just
12035                    // ignore the issue as bitmap caches are not required to draw the
12036                    // view hierarchy
12037                    if (autoScale) {
12038                        mDrawingCache = null;
12039                    } else {
12040                        mUnscaledDrawingCache = null;
12041                    }
12042                    mCachingFailed = true;
12043                    return;
12044                }
12045
12046                clear = drawingCacheBackgroundColor != 0;
12047            }
12048
12049            Canvas canvas;
12050            if (attachInfo != null) {
12051                canvas = attachInfo.mCanvas;
12052                if (canvas == null) {
12053                    canvas = new Canvas();
12054                }
12055                canvas.setBitmap(bitmap);
12056                // Temporarily clobber the cached Canvas in case one of our children
12057                // is also using a drawing cache. Without this, the children would
12058                // steal the canvas by attaching their own bitmap to it and bad, bad
12059                // thing would happen (invisible views, corrupted drawings, etc.)
12060                attachInfo.mCanvas = null;
12061            } else {
12062                // This case should hopefully never or seldom happen
12063                canvas = new Canvas(bitmap);
12064            }
12065
12066            if (clear) {
12067                bitmap.eraseColor(drawingCacheBackgroundColor);
12068            }
12069
12070            computeScroll();
12071            final int restoreCount = canvas.save();
12072
12073            if (autoScale && scalingRequired) {
12074                final float scale = attachInfo.mApplicationScale;
12075                canvas.scale(scale, scale);
12076            }
12077
12078            canvas.translate(-mScrollX, -mScrollY);
12079
12080            mPrivateFlags |= DRAWN;
12081            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12082                    mLayerType != LAYER_TYPE_NONE) {
12083                mPrivateFlags |= DRAWING_CACHE_VALID;
12084            }
12085
12086            // Fast path for layouts with no backgrounds
12087            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12088                if (ViewDebug.TRACE_HIERARCHY) {
12089                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12090                }
12091                mPrivateFlags &= ~DIRTY_MASK;
12092                dispatchDraw(canvas);
12093            } else {
12094                draw(canvas);
12095            }
12096
12097            canvas.restoreToCount(restoreCount);
12098            canvas.setBitmap(null);
12099
12100            if (attachInfo != null) {
12101                // Restore the cached Canvas for our siblings
12102                attachInfo.mCanvas = canvas;
12103            }
12104        }
12105    }
12106
12107    /**
12108     * Create a snapshot of the view into a bitmap.  We should probably make
12109     * some form of this public, but should think about the API.
12110     */
12111    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12112        int width = mRight - mLeft;
12113        int height = mBottom - mTop;
12114
12115        final AttachInfo attachInfo = mAttachInfo;
12116        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12117        width = (int) ((width * scale) + 0.5f);
12118        height = (int) ((height * scale) + 0.5f);
12119
12120        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12121        if (bitmap == null) {
12122            throw new OutOfMemoryError();
12123        }
12124
12125        Resources resources = getResources();
12126        if (resources != null) {
12127            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12128        }
12129
12130        Canvas canvas;
12131        if (attachInfo != null) {
12132            canvas = attachInfo.mCanvas;
12133            if (canvas == null) {
12134                canvas = new Canvas();
12135            }
12136            canvas.setBitmap(bitmap);
12137            // Temporarily clobber the cached Canvas in case one of our children
12138            // is also using a drawing cache. Without this, the children would
12139            // steal the canvas by attaching their own bitmap to it and bad, bad
12140            // things would happen (invisible views, corrupted drawings, etc.)
12141            attachInfo.mCanvas = null;
12142        } else {
12143            // This case should hopefully never or seldom happen
12144            canvas = new Canvas(bitmap);
12145        }
12146
12147        if ((backgroundColor & 0xff000000) != 0) {
12148            bitmap.eraseColor(backgroundColor);
12149        }
12150
12151        computeScroll();
12152        final int restoreCount = canvas.save();
12153        canvas.scale(scale, scale);
12154        canvas.translate(-mScrollX, -mScrollY);
12155
12156        // Temporarily remove the dirty mask
12157        int flags = mPrivateFlags;
12158        mPrivateFlags &= ~DIRTY_MASK;
12159
12160        // Fast path for layouts with no backgrounds
12161        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12162            dispatchDraw(canvas);
12163        } else {
12164            draw(canvas);
12165        }
12166
12167        mPrivateFlags = flags;
12168
12169        canvas.restoreToCount(restoreCount);
12170        canvas.setBitmap(null);
12171
12172        if (attachInfo != null) {
12173            // Restore the cached Canvas for our siblings
12174            attachInfo.mCanvas = canvas;
12175        }
12176
12177        return bitmap;
12178    }
12179
12180    /**
12181     * Indicates whether this View is currently in edit mode. A View is usually
12182     * in edit mode when displayed within a developer tool. For instance, if
12183     * this View is being drawn by a visual user interface builder, this method
12184     * should return true.
12185     *
12186     * Subclasses should check the return value of this method to provide
12187     * different behaviors if their normal behavior might interfere with the
12188     * host environment. For instance: the class spawns a thread in its
12189     * constructor, the drawing code relies on device-specific features, etc.
12190     *
12191     * This method is usually checked in the drawing code of custom widgets.
12192     *
12193     * @return True if this View is in edit mode, false otherwise.
12194     */
12195    public boolean isInEditMode() {
12196        return false;
12197    }
12198
12199    /**
12200     * If the View draws content inside its padding and enables fading edges,
12201     * it needs to support padding offsets. Padding offsets are added to the
12202     * fading edges to extend the length of the fade so that it covers pixels
12203     * drawn inside the padding.
12204     *
12205     * Subclasses of this class should override this method if they need
12206     * to draw content inside the padding.
12207     *
12208     * @return True if padding offset must be applied, false otherwise.
12209     *
12210     * @see #getLeftPaddingOffset()
12211     * @see #getRightPaddingOffset()
12212     * @see #getTopPaddingOffset()
12213     * @see #getBottomPaddingOffset()
12214     *
12215     * @since CURRENT
12216     */
12217    protected boolean isPaddingOffsetRequired() {
12218        return false;
12219    }
12220
12221    /**
12222     * Amount by which to extend the left fading region. Called only when
12223     * {@link #isPaddingOffsetRequired()} returns true.
12224     *
12225     * @return The left padding offset in pixels.
12226     *
12227     * @see #isPaddingOffsetRequired()
12228     *
12229     * @since CURRENT
12230     */
12231    protected int getLeftPaddingOffset() {
12232        return 0;
12233    }
12234
12235    /**
12236     * Amount by which to extend the right fading region. Called only when
12237     * {@link #isPaddingOffsetRequired()} returns true.
12238     *
12239     * @return The right padding offset in pixels.
12240     *
12241     * @see #isPaddingOffsetRequired()
12242     *
12243     * @since CURRENT
12244     */
12245    protected int getRightPaddingOffset() {
12246        return 0;
12247    }
12248
12249    /**
12250     * Amount by which to extend the top fading region. Called only when
12251     * {@link #isPaddingOffsetRequired()} returns true.
12252     *
12253     * @return The top padding offset in pixels.
12254     *
12255     * @see #isPaddingOffsetRequired()
12256     *
12257     * @since CURRENT
12258     */
12259    protected int getTopPaddingOffset() {
12260        return 0;
12261    }
12262
12263    /**
12264     * Amount by which to extend the bottom fading region. Called only when
12265     * {@link #isPaddingOffsetRequired()} returns true.
12266     *
12267     * @return The bottom padding offset in pixels.
12268     *
12269     * @see #isPaddingOffsetRequired()
12270     *
12271     * @since CURRENT
12272     */
12273    protected int getBottomPaddingOffset() {
12274        return 0;
12275    }
12276
12277    /**
12278     * @hide
12279     * @param offsetRequired
12280     */
12281    protected int getFadeTop(boolean offsetRequired) {
12282        int top = mPaddingTop;
12283        if (offsetRequired) top += getTopPaddingOffset();
12284        return top;
12285    }
12286
12287    /**
12288     * @hide
12289     * @param offsetRequired
12290     */
12291    protected int getFadeHeight(boolean offsetRequired) {
12292        int padding = mPaddingTop;
12293        if (offsetRequired) padding += getTopPaddingOffset();
12294        return mBottom - mTop - mPaddingBottom - padding;
12295    }
12296
12297    /**
12298     * <p>Indicates whether this view is attached to a hardware accelerated
12299     * window or not.</p>
12300     *
12301     * <p>Even if this method returns true, it does not mean that every call
12302     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12303     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12304     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12305     * window is hardware accelerated,
12306     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12307     * return false, and this method will return true.</p>
12308     *
12309     * @return True if the view is attached to a window and the window is
12310     *         hardware accelerated; false in any other case.
12311     */
12312    public boolean isHardwareAccelerated() {
12313        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12314    }
12315
12316    /**
12317     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12318     * case of an active Animation being run on the view.
12319     */
12320    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12321            Animation a, boolean scalingRequired) {
12322        Transformation invalidationTransform;
12323        final int flags = parent.mGroupFlags;
12324        final boolean initialized = a.isInitialized();
12325        if (!initialized) {
12326            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12327            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12328            onAnimationStart();
12329        }
12330
12331        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12332        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12333            if (parent.mInvalidationTransformation == null) {
12334                parent.mInvalidationTransformation = new Transformation();
12335            }
12336            invalidationTransform = parent.mInvalidationTransformation;
12337            a.getTransformation(drawingTime, invalidationTransform, 1f);
12338        } else {
12339            invalidationTransform = parent.mChildTransformation;
12340        }
12341        if (more) {
12342            if (!a.willChangeBounds()) {
12343                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12344                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12345                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12346                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12347                    // The child need to draw an animation, potentially offscreen, so
12348                    // make sure we do not cancel invalidate requests
12349                    parent.mPrivateFlags |= DRAW_ANIMATION;
12350                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12351                }
12352            } else {
12353                if (parent.mInvalidateRegion == null) {
12354                    parent.mInvalidateRegion = new RectF();
12355                }
12356                final RectF region = parent.mInvalidateRegion;
12357                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12358                        invalidationTransform);
12359
12360                // The child need to draw an animation, potentially offscreen, so
12361                // make sure we do not cancel invalidate requests
12362                parent.mPrivateFlags |= DRAW_ANIMATION;
12363
12364                final int left = mLeft + (int) region.left;
12365                final int top = mTop + (int) region.top;
12366                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12367                        top + (int) (region.height() + .5f));
12368            }
12369        }
12370        return more;
12371    }
12372
12373    void setDisplayListProperties() {
12374        setDisplayListProperties(mDisplayList);
12375    }
12376
12377    /**
12378     * This method is called by getDisplayList() when a display list is created or re-rendered.
12379     * It sets or resets the current value of all properties on that display list (resetting is
12380     * necessary when a display list is being re-created, because we need to make sure that
12381     * previously-set transform values
12382     */
12383    void setDisplayListProperties(DisplayList displayList) {
12384        if (displayList != null) {
12385            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12386            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12387            if (mParent instanceof ViewGroup) {
12388                displayList.setClipChildren(
12389                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12390            }
12391            float alpha = 1;
12392            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12393                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12394                ViewGroup parentVG = (ViewGroup) mParent;
12395                final boolean hasTransform =
12396                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12397                if (hasTransform) {
12398                    Transformation transform = parentVG.mChildTransformation;
12399                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12400                    if (transformType != Transformation.TYPE_IDENTITY) {
12401                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12402                            alpha = transform.getAlpha();
12403                        }
12404                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12405                            displayList.setStaticMatrix(transform.getMatrix());
12406                        }
12407                    }
12408                }
12409            }
12410            if (mTransformationInfo != null) {
12411                alpha *= mTransformationInfo.mAlpha;
12412                if (alpha < 1) {
12413                    final int multipliedAlpha = (int) (255 * alpha);
12414                    if (onSetAlpha(multipliedAlpha)) {
12415                        alpha = 1;
12416                    }
12417                }
12418                displayList.setTransformationInfo(alpha,
12419                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12420                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12421                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12422                        mTransformationInfo.mScaleY);
12423                if (mTransformationInfo.mCamera == null) {
12424                    mTransformationInfo.mCamera = new Camera();
12425                    mTransformationInfo.matrix3D = new Matrix();
12426                }
12427                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12428                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12429                    displayList.setPivotX(getPivotX());
12430                    displayList.setPivotY(getPivotY());
12431                }
12432            } else if (alpha < 1) {
12433                displayList.setAlpha(alpha);
12434            }
12435        }
12436    }
12437
12438    /**
12439     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12440     * This draw() method is an implementation detail and is not intended to be overridden or
12441     * to be called from anywhere else other than ViewGroup.drawChild().
12442     */
12443    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12444        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12445        boolean more = false;
12446        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12447        final int flags = parent.mGroupFlags;
12448
12449        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12450            parent.mChildTransformation.clear();
12451            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12452        }
12453
12454        Transformation transformToApply = null;
12455        boolean concatMatrix = false;
12456
12457        boolean scalingRequired = false;
12458        boolean caching;
12459        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12460
12461        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12462        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12463                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12464            caching = true;
12465            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12466            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12467        } else {
12468            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12469        }
12470
12471        final Animation a = getAnimation();
12472        if (a != null) {
12473            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12474            concatMatrix = a.willChangeTransformationMatrix();
12475            transformToApply = parent.mChildTransformation;
12476        } else if (!useDisplayListProperties &&
12477                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12478            final boolean hasTransform =
12479                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12480            if (hasTransform) {
12481                final int transformType = parent.mChildTransformation.getTransformationType();
12482                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12483                        parent.mChildTransformation : null;
12484                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12485            }
12486        }
12487
12488        concatMatrix |= !childHasIdentityMatrix;
12489
12490        // Sets the flag as early as possible to allow draw() implementations
12491        // to call invalidate() successfully when doing animations
12492        mPrivateFlags |= DRAWN;
12493
12494        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12495                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12496            return more;
12497        }
12498
12499        if (hardwareAccelerated) {
12500            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12501            // retain the flag's value temporarily in the mRecreateDisplayList flag
12502            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12503            mPrivateFlags &= ~INVALIDATED;
12504        }
12505
12506        computeScroll();
12507
12508        final int sx = mScrollX;
12509        final int sy = mScrollY;
12510
12511        DisplayList displayList = null;
12512        Bitmap cache = null;
12513        boolean hasDisplayList = false;
12514        if (caching) {
12515            if (!hardwareAccelerated) {
12516                if (layerType != LAYER_TYPE_NONE) {
12517                    layerType = LAYER_TYPE_SOFTWARE;
12518                    buildDrawingCache(true);
12519                }
12520                cache = getDrawingCache(true);
12521            } else {
12522                switch (layerType) {
12523                    case LAYER_TYPE_SOFTWARE:
12524                        if (useDisplayListProperties) {
12525                            hasDisplayList = canHaveDisplayList();
12526                        } else {
12527                            buildDrawingCache(true);
12528                            cache = getDrawingCache(true);
12529                        }
12530                        break;
12531                    case LAYER_TYPE_HARDWARE:
12532                        if (useDisplayListProperties) {
12533                            hasDisplayList = canHaveDisplayList();
12534                        }
12535                        break;
12536                    case LAYER_TYPE_NONE:
12537                        // Delay getting the display list until animation-driven alpha values are
12538                        // set up and possibly passed on to the view
12539                        hasDisplayList = canHaveDisplayList();
12540                        break;
12541                }
12542            }
12543        }
12544        useDisplayListProperties &= hasDisplayList;
12545        if (useDisplayListProperties) {
12546            displayList = getDisplayList();
12547            if (!displayList.isValid()) {
12548                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12549                // to getDisplayList(), the display list will be marked invalid and we should not
12550                // try to use it again.
12551                displayList = null;
12552                hasDisplayList = false;
12553                useDisplayListProperties = false;
12554            }
12555        }
12556
12557        final boolean hasNoCache = cache == null || hasDisplayList;
12558        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12559                layerType != LAYER_TYPE_HARDWARE;
12560
12561        int restoreTo = -1;
12562        if (!useDisplayListProperties || transformToApply != null) {
12563            restoreTo = canvas.save();
12564        }
12565        if (offsetForScroll) {
12566            canvas.translate(mLeft - sx, mTop - sy);
12567        } else {
12568            if (!useDisplayListProperties) {
12569                canvas.translate(mLeft, mTop);
12570            }
12571            if (scalingRequired) {
12572                if (useDisplayListProperties) {
12573                    // TODO: Might not need this if we put everything inside the DL
12574                    restoreTo = canvas.save();
12575                }
12576                // mAttachInfo cannot be null, otherwise scalingRequired == false
12577                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12578                canvas.scale(scale, scale);
12579            }
12580        }
12581
12582        float alpha = useDisplayListProperties ? 1 : getAlpha();
12583        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12584            if (transformToApply != null || !childHasIdentityMatrix) {
12585                int transX = 0;
12586                int transY = 0;
12587
12588                if (offsetForScroll) {
12589                    transX = -sx;
12590                    transY = -sy;
12591                }
12592
12593                if (transformToApply != null) {
12594                    if (concatMatrix) {
12595                        if (useDisplayListProperties) {
12596                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12597                        } else {
12598                            // Undo the scroll translation, apply the transformation matrix,
12599                            // then redo the scroll translate to get the correct result.
12600                            canvas.translate(-transX, -transY);
12601                            canvas.concat(transformToApply.getMatrix());
12602                            canvas.translate(transX, transY);
12603                        }
12604                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12605                    }
12606
12607                    float transformAlpha = transformToApply.getAlpha();
12608                    if (transformAlpha < 1) {
12609                        alpha *= transformToApply.getAlpha();
12610                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12611                    }
12612                }
12613
12614                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12615                    canvas.translate(-transX, -transY);
12616                    canvas.concat(getMatrix());
12617                    canvas.translate(transX, transY);
12618                }
12619            }
12620
12621            if (alpha < 1) {
12622                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12623                if (hasNoCache) {
12624                    final int multipliedAlpha = (int) (255 * alpha);
12625                    if (!onSetAlpha(multipliedAlpha)) {
12626                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12627                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12628                                layerType != LAYER_TYPE_NONE) {
12629                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12630                        }
12631                        if (useDisplayListProperties) {
12632                            displayList.setAlpha(alpha * getAlpha());
12633                        } else  if (layerType == LAYER_TYPE_NONE) {
12634                            final int scrollX = hasDisplayList ? 0 : sx;
12635                            final int scrollY = hasDisplayList ? 0 : sy;
12636                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12637                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12638                        }
12639                    } else {
12640                        // Alpha is handled by the child directly, clobber the layer's alpha
12641                        mPrivateFlags |= ALPHA_SET;
12642                    }
12643                }
12644            }
12645        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12646            onSetAlpha(255);
12647            mPrivateFlags &= ~ALPHA_SET;
12648        }
12649
12650        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12651                !useDisplayListProperties) {
12652            if (offsetForScroll) {
12653                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12654            } else {
12655                if (!scalingRequired || cache == null) {
12656                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12657                } else {
12658                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12659                }
12660            }
12661        }
12662
12663        if (!useDisplayListProperties && hasDisplayList) {
12664            displayList = getDisplayList();
12665            if (!displayList.isValid()) {
12666                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12667                // to getDisplayList(), the display list will be marked invalid and we should not
12668                // try to use it again.
12669                displayList = null;
12670                hasDisplayList = false;
12671            }
12672        }
12673
12674        if (hasNoCache) {
12675            boolean layerRendered = false;
12676            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12677                final HardwareLayer layer = getHardwareLayer();
12678                if (layer != null && layer.isValid()) {
12679                    mLayerPaint.setAlpha((int) (alpha * 255));
12680                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12681                    layerRendered = true;
12682                } else {
12683                    final int scrollX = hasDisplayList ? 0 : sx;
12684                    final int scrollY = hasDisplayList ? 0 : sy;
12685                    canvas.saveLayer(scrollX, scrollY,
12686                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12687                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12688                }
12689            }
12690
12691            if (!layerRendered) {
12692                if (!hasDisplayList) {
12693                    // Fast path for layouts with no backgrounds
12694                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12695                        if (ViewDebug.TRACE_HIERARCHY) {
12696                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12697                        }
12698                        mPrivateFlags &= ~DIRTY_MASK;
12699                        dispatchDraw(canvas);
12700                    } else {
12701                        draw(canvas);
12702                    }
12703                } else {
12704                    mPrivateFlags &= ~DIRTY_MASK;
12705                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12706                }
12707            }
12708        } else if (cache != null) {
12709            mPrivateFlags &= ~DIRTY_MASK;
12710            Paint cachePaint;
12711
12712            if (layerType == LAYER_TYPE_NONE) {
12713                cachePaint = parent.mCachePaint;
12714                if (cachePaint == null) {
12715                    cachePaint = new Paint();
12716                    cachePaint.setDither(false);
12717                    parent.mCachePaint = cachePaint;
12718                }
12719                if (alpha < 1) {
12720                    cachePaint.setAlpha((int) (alpha * 255));
12721                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12722                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12723                    cachePaint.setAlpha(255);
12724                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12725                }
12726            } else {
12727                cachePaint = mLayerPaint;
12728                cachePaint.setAlpha((int) (alpha * 255));
12729            }
12730            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12731        }
12732
12733        if (restoreTo >= 0) {
12734            canvas.restoreToCount(restoreTo);
12735        }
12736
12737        if (a != null && !more) {
12738            if (!hardwareAccelerated && !a.getFillAfter()) {
12739                onSetAlpha(255);
12740            }
12741            parent.finishAnimatingView(this, a);
12742        }
12743
12744        if (more && hardwareAccelerated) {
12745            // invalidation is the trigger to recreate display lists, so if we're using
12746            // display lists to render, force an invalidate to allow the animation to
12747            // continue drawing another frame
12748            parent.invalidate(true);
12749            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12750                // alpha animations should cause the child to recreate its display list
12751                invalidate(true);
12752            }
12753        }
12754
12755        mRecreateDisplayList = false;
12756
12757        return more;
12758    }
12759
12760    /**
12761     * Manually render this view (and all of its children) to the given Canvas.
12762     * The view must have already done a full layout before this function is
12763     * called.  When implementing a view, implement
12764     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
12765     * If you do need to override this method, call the superclass version.
12766     *
12767     * @param canvas The Canvas to which the View is rendered.
12768     */
12769    public void draw(Canvas canvas) {
12770        if (ViewDebug.TRACE_HIERARCHY) {
12771            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12772        }
12773
12774        final int privateFlags = mPrivateFlags;
12775        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
12776                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
12777        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
12778
12779        /*
12780         * Draw traversal performs several drawing steps which must be executed
12781         * in the appropriate order:
12782         *
12783         *      1. Draw the background
12784         *      2. If necessary, save the canvas' layers to prepare for fading
12785         *      3. Draw view's content
12786         *      4. Draw children
12787         *      5. If necessary, draw the fading edges and restore layers
12788         *      6. Draw decorations (scrollbars for instance)
12789         */
12790
12791        // Step 1, draw the background, if needed
12792        int saveCount;
12793
12794        if (!dirtyOpaque) {
12795            final Drawable background = mBackground;
12796            if (background != null) {
12797                final int scrollX = mScrollX;
12798                final int scrollY = mScrollY;
12799
12800                if (mBackgroundSizeChanged) {
12801                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
12802                    mBackgroundSizeChanged = false;
12803                }
12804
12805                if ((scrollX | scrollY) == 0) {
12806                    background.draw(canvas);
12807                } else {
12808                    canvas.translate(scrollX, scrollY);
12809                    background.draw(canvas);
12810                    canvas.translate(-scrollX, -scrollY);
12811                }
12812            }
12813        }
12814
12815        // skip step 2 & 5 if possible (common case)
12816        final int viewFlags = mViewFlags;
12817        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
12818        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
12819        if (!verticalEdges && !horizontalEdges) {
12820            // Step 3, draw the content
12821            if (!dirtyOpaque) onDraw(canvas);
12822
12823            // Step 4, draw the children
12824            dispatchDraw(canvas);
12825
12826            // Step 6, draw decorations (scrollbars)
12827            onDrawScrollBars(canvas);
12828
12829            // we're done...
12830            return;
12831        }
12832
12833        /*
12834         * Here we do the full fledged routine...
12835         * (this is an uncommon case where speed matters less,
12836         * this is why we repeat some of the tests that have been
12837         * done above)
12838         */
12839
12840        boolean drawTop = false;
12841        boolean drawBottom = false;
12842        boolean drawLeft = false;
12843        boolean drawRight = false;
12844
12845        float topFadeStrength = 0.0f;
12846        float bottomFadeStrength = 0.0f;
12847        float leftFadeStrength = 0.0f;
12848        float rightFadeStrength = 0.0f;
12849
12850        // Step 2, save the canvas' layers
12851        int paddingLeft = mPaddingLeft;
12852
12853        final boolean offsetRequired = isPaddingOffsetRequired();
12854        if (offsetRequired) {
12855            paddingLeft += getLeftPaddingOffset();
12856        }
12857
12858        int left = mScrollX + paddingLeft;
12859        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12860        int top = mScrollY + getFadeTop(offsetRequired);
12861        int bottom = top + getFadeHeight(offsetRequired);
12862
12863        if (offsetRequired) {
12864            right += getRightPaddingOffset();
12865            bottom += getBottomPaddingOffset();
12866        }
12867
12868        final ScrollabilityCache scrollabilityCache = mScrollCache;
12869        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12870        int length = (int) fadeHeight;
12871
12872        // clip the fade length if top and bottom fades overlap
12873        // overlapping fades produce odd-looking artifacts
12874        if (verticalEdges && (top + length > bottom - length)) {
12875            length = (bottom - top) / 2;
12876        }
12877
12878        // also clip horizontal fades if necessary
12879        if (horizontalEdges && (left + length > right - length)) {
12880            length = (right - left) / 2;
12881        }
12882
12883        if (verticalEdges) {
12884            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12885            drawTop = topFadeStrength * fadeHeight > 1.0f;
12886            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12887            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12888        }
12889
12890        if (horizontalEdges) {
12891            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12892            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12893            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12894            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12895        }
12896
12897        saveCount = canvas.getSaveCount();
12898
12899        int solidColor = getSolidColor();
12900        if (solidColor == 0) {
12901            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12902
12903            if (drawTop) {
12904                canvas.saveLayer(left, top, right, top + length, null, flags);
12905            }
12906
12907            if (drawBottom) {
12908                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12909            }
12910
12911            if (drawLeft) {
12912                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12913            }
12914
12915            if (drawRight) {
12916                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12917            }
12918        } else {
12919            scrollabilityCache.setFadeColor(solidColor);
12920        }
12921
12922        // Step 3, draw the content
12923        if (!dirtyOpaque) onDraw(canvas);
12924
12925        // Step 4, draw the children
12926        dispatchDraw(canvas);
12927
12928        // Step 5, draw the fade effect and restore layers
12929        final Paint p = scrollabilityCache.paint;
12930        final Matrix matrix = scrollabilityCache.matrix;
12931        final Shader fade = scrollabilityCache.shader;
12932
12933        if (drawTop) {
12934            matrix.setScale(1, fadeHeight * topFadeStrength);
12935            matrix.postTranslate(left, top);
12936            fade.setLocalMatrix(matrix);
12937            canvas.drawRect(left, top, right, top + length, p);
12938        }
12939
12940        if (drawBottom) {
12941            matrix.setScale(1, fadeHeight * bottomFadeStrength);
12942            matrix.postRotate(180);
12943            matrix.postTranslate(left, bottom);
12944            fade.setLocalMatrix(matrix);
12945            canvas.drawRect(left, bottom - length, right, bottom, p);
12946        }
12947
12948        if (drawLeft) {
12949            matrix.setScale(1, fadeHeight * leftFadeStrength);
12950            matrix.postRotate(-90);
12951            matrix.postTranslate(left, top);
12952            fade.setLocalMatrix(matrix);
12953            canvas.drawRect(left, top, left + length, bottom, p);
12954        }
12955
12956        if (drawRight) {
12957            matrix.setScale(1, fadeHeight * rightFadeStrength);
12958            matrix.postRotate(90);
12959            matrix.postTranslate(right, top);
12960            fade.setLocalMatrix(matrix);
12961            canvas.drawRect(right - length, top, right, bottom, p);
12962        }
12963
12964        canvas.restoreToCount(saveCount);
12965
12966        // Step 6, draw decorations (scrollbars)
12967        onDrawScrollBars(canvas);
12968    }
12969
12970    /**
12971     * Override this if your view is known to always be drawn on top of a solid color background,
12972     * and needs to draw fading edges. Returning a non-zero color enables the view system to
12973     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
12974     * should be set to 0xFF.
12975     *
12976     * @see #setVerticalFadingEdgeEnabled(boolean)
12977     * @see #setHorizontalFadingEdgeEnabled(boolean)
12978     *
12979     * @return The known solid color background for this view, or 0 if the color may vary
12980     */
12981    @ViewDebug.ExportedProperty(category = "drawing")
12982    public int getSolidColor() {
12983        return 0;
12984    }
12985
12986    /**
12987     * Build a human readable string representation of the specified view flags.
12988     *
12989     * @param flags the view flags to convert to a string
12990     * @return a String representing the supplied flags
12991     */
12992    private static String printFlags(int flags) {
12993        String output = "";
12994        int numFlags = 0;
12995        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
12996            output += "TAKES_FOCUS";
12997            numFlags++;
12998        }
12999
13000        switch (flags & VISIBILITY_MASK) {
13001        case INVISIBLE:
13002            if (numFlags > 0) {
13003                output += " ";
13004            }
13005            output += "INVISIBLE";
13006            // USELESS HERE numFlags++;
13007            break;
13008        case GONE:
13009            if (numFlags > 0) {
13010                output += " ";
13011            }
13012            output += "GONE";
13013            // USELESS HERE numFlags++;
13014            break;
13015        default:
13016            break;
13017        }
13018        return output;
13019    }
13020
13021    /**
13022     * Build a human readable string representation of the specified private
13023     * view flags.
13024     *
13025     * @param privateFlags the private view flags to convert to a string
13026     * @return a String representing the supplied flags
13027     */
13028    private static String printPrivateFlags(int privateFlags) {
13029        String output = "";
13030        int numFlags = 0;
13031
13032        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13033            output += "WANTS_FOCUS";
13034            numFlags++;
13035        }
13036
13037        if ((privateFlags & FOCUSED) == FOCUSED) {
13038            if (numFlags > 0) {
13039                output += " ";
13040            }
13041            output += "FOCUSED";
13042            numFlags++;
13043        }
13044
13045        if ((privateFlags & SELECTED) == SELECTED) {
13046            if (numFlags > 0) {
13047                output += " ";
13048            }
13049            output += "SELECTED";
13050            numFlags++;
13051        }
13052
13053        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13054            if (numFlags > 0) {
13055                output += " ";
13056            }
13057            output += "IS_ROOT_NAMESPACE";
13058            numFlags++;
13059        }
13060
13061        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13062            if (numFlags > 0) {
13063                output += " ";
13064            }
13065            output += "HAS_BOUNDS";
13066            numFlags++;
13067        }
13068
13069        if ((privateFlags & DRAWN) == DRAWN) {
13070            if (numFlags > 0) {
13071                output += " ";
13072            }
13073            output += "DRAWN";
13074            // USELESS HERE numFlags++;
13075        }
13076        return output;
13077    }
13078
13079    /**
13080     * <p>Indicates whether or not this view's layout will be requested during
13081     * the next hierarchy layout pass.</p>
13082     *
13083     * @return true if the layout will be forced during next layout pass
13084     */
13085    public boolean isLayoutRequested() {
13086        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13087    }
13088
13089    /**
13090     * Assign a size and position to a view and all of its
13091     * descendants
13092     *
13093     * <p>This is the second phase of the layout mechanism.
13094     * (The first is measuring). In this phase, each parent calls
13095     * layout on all of its children to position them.
13096     * This is typically done using the child measurements
13097     * that were stored in the measure pass().</p>
13098     *
13099     * <p>Derived classes should not override this method.
13100     * Derived classes with children should override
13101     * onLayout. In that method, they should
13102     * call layout on each of their children.</p>
13103     *
13104     * @param l Left position, relative to parent
13105     * @param t Top position, relative to parent
13106     * @param r Right position, relative to parent
13107     * @param b Bottom position, relative to parent
13108     */
13109    @SuppressWarnings({"unchecked"})
13110    public void layout(int l, int t, int r, int b) {
13111        int oldL = mLeft;
13112        int oldT = mTop;
13113        int oldB = mBottom;
13114        int oldR = mRight;
13115        boolean changed = setFrame(l, t, r, b);
13116        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13117            if (ViewDebug.TRACE_HIERARCHY) {
13118                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13119            }
13120
13121            onLayout(changed, l, t, r, b);
13122            mPrivateFlags &= ~LAYOUT_REQUIRED;
13123
13124            ListenerInfo li = mListenerInfo;
13125            if (li != null && li.mOnLayoutChangeListeners != null) {
13126                ArrayList<OnLayoutChangeListener> listenersCopy =
13127                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13128                int numListeners = listenersCopy.size();
13129                for (int i = 0; i < numListeners; ++i) {
13130                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13131                }
13132            }
13133        }
13134        mPrivateFlags &= ~FORCE_LAYOUT;
13135    }
13136
13137    /**
13138     * Called from layout when this view should
13139     * assign a size and position to each of its children.
13140     *
13141     * Derived classes with children should override
13142     * this method and call layout on each of
13143     * their children.
13144     * @param changed This is a new size or position for this view
13145     * @param left Left position, relative to parent
13146     * @param top Top position, relative to parent
13147     * @param right Right position, relative to parent
13148     * @param bottom Bottom position, relative to parent
13149     */
13150    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13151    }
13152
13153    /**
13154     * Assign a size and position to this view.
13155     *
13156     * This is called from layout.
13157     *
13158     * @param left Left position, relative to parent
13159     * @param top Top position, relative to parent
13160     * @param right Right position, relative to parent
13161     * @param bottom Bottom position, relative to parent
13162     * @return true if the new size and position are different than the
13163     *         previous ones
13164     * {@hide}
13165     */
13166    protected boolean setFrame(int left, int top, int right, int bottom) {
13167        boolean changed = false;
13168
13169        if (DBG) {
13170            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13171                    + right + "," + bottom + ")");
13172        }
13173
13174        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13175            changed = true;
13176
13177            // Remember our drawn bit
13178            int drawn = mPrivateFlags & DRAWN;
13179
13180            int oldWidth = mRight - mLeft;
13181            int oldHeight = mBottom - mTop;
13182            int newWidth = right - left;
13183            int newHeight = bottom - top;
13184            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13185
13186            // Invalidate our old position
13187            invalidate(sizeChanged);
13188
13189            mLeft = left;
13190            mTop = top;
13191            mRight = right;
13192            mBottom = bottom;
13193            if (mDisplayList != null) {
13194                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13195            }
13196
13197            mPrivateFlags |= HAS_BOUNDS;
13198
13199
13200            if (sizeChanged) {
13201                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13202                    // A change in dimension means an auto-centered pivot point changes, too
13203                    if (mTransformationInfo != null) {
13204                        mTransformationInfo.mMatrixDirty = true;
13205                    }
13206                }
13207                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13208            }
13209
13210            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13211                // If we are visible, force the DRAWN bit to on so that
13212                // this invalidate will go through (at least to our parent).
13213                // This is because someone may have invalidated this view
13214                // before this call to setFrame came in, thereby clearing
13215                // the DRAWN bit.
13216                mPrivateFlags |= DRAWN;
13217                invalidate(sizeChanged);
13218                // parent display list may need to be recreated based on a change in the bounds
13219                // of any child
13220                invalidateParentCaches();
13221            }
13222
13223            // Reset drawn bit to original value (invalidate turns it off)
13224            mPrivateFlags |= drawn;
13225
13226            mBackgroundSizeChanged = true;
13227        }
13228        return changed;
13229    }
13230
13231    /**
13232     * Finalize inflating a view from XML.  This is called as the last phase
13233     * of inflation, after all child views have been added.
13234     *
13235     * <p>Even if the subclass overrides onFinishInflate, they should always be
13236     * sure to call the super method, so that we get called.
13237     */
13238    protected void onFinishInflate() {
13239    }
13240
13241    /**
13242     * Returns the resources associated with this view.
13243     *
13244     * @return Resources object.
13245     */
13246    public Resources getResources() {
13247        return mResources;
13248    }
13249
13250    /**
13251     * Invalidates the specified Drawable.
13252     *
13253     * @param drawable the drawable to invalidate
13254     */
13255    public void invalidateDrawable(Drawable drawable) {
13256        if (verifyDrawable(drawable)) {
13257            final Rect dirty = drawable.getBounds();
13258            final int scrollX = mScrollX;
13259            final int scrollY = mScrollY;
13260
13261            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13262                    dirty.right + scrollX, dirty.bottom + scrollY);
13263        }
13264    }
13265
13266    /**
13267     * Schedules an action on a drawable to occur at a specified time.
13268     *
13269     * @param who the recipient of the action
13270     * @param what the action to run on the drawable
13271     * @param when the time at which the action must occur. Uses the
13272     *        {@link SystemClock#uptimeMillis} timebase.
13273     */
13274    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13275        if (verifyDrawable(who) && what != null) {
13276            final long delay = when - SystemClock.uptimeMillis();
13277            if (mAttachInfo != null) {
13278                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13279                        Choreographer.CALLBACK_ANIMATION, what, who,
13280                        Choreographer.subtractFrameDelay(delay));
13281            } else {
13282                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13283            }
13284        }
13285    }
13286
13287    /**
13288     * Cancels a scheduled action on a drawable.
13289     *
13290     * @param who the recipient of the action
13291     * @param what the action to cancel
13292     */
13293    public void unscheduleDrawable(Drawable who, Runnable what) {
13294        if (verifyDrawable(who) && what != null) {
13295            if (mAttachInfo != null) {
13296                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13297                        Choreographer.CALLBACK_ANIMATION, what, who);
13298            } else {
13299                ViewRootImpl.getRunQueue().removeCallbacks(what);
13300            }
13301        }
13302    }
13303
13304    /**
13305     * Unschedule any events associated with the given Drawable.  This can be
13306     * used when selecting a new Drawable into a view, so that the previous
13307     * one is completely unscheduled.
13308     *
13309     * @param who The Drawable to unschedule.
13310     *
13311     * @see #drawableStateChanged
13312     */
13313    public void unscheduleDrawable(Drawable who) {
13314        if (mAttachInfo != null && who != null) {
13315            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13316                    Choreographer.CALLBACK_ANIMATION, null, who);
13317        }
13318    }
13319
13320    /**
13321    * Return the layout direction of a given Drawable.
13322    *
13323    * @param who the Drawable to query
13324    */
13325    public int getResolvedLayoutDirection(Drawable who) {
13326        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13327    }
13328
13329    /**
13330     * If your view subclass is displaying its own Drawable objects, it should
13331     * override this function and return true for any Drawable it is
13332     * displaying.  This allows animations for those drawables to be
13333     * scheduled.
13334     *
13335     * <p>Be sure to call through to the super class when overriding this
13336     * function.
13337     *
13338     * @param who The Drawable to verify.  Return true if it is one you are
13339     *            displaying, else return the result of calling through to the
13340     *            super class.
13341     *
13342     * @return boolean If true than the Drawable is being displayed in the
13343     *         view; else false and it is not allowed to animate.
13344     *
13345     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13346     * @see #drawableStateChanged()
13347     */
13348    protected boolean verifyDrawable(Drawable who) {
13349        return who == mBackground;
13350    }
13351
13352    /**
13353     * This function is called whenever the state of the view changes in such
13354     * a way that it impacts the state of drawables being shown.
13355     *
13356     * <p>Be sure to call through to the superclass when overriding this
13357     * function.
13358     *
13359     * @see Drawable#setState(int[])
13360     */
13361    protected void drawableStateChanged() {
13362        Drawable d = mBackground;
13363        if (d != null && d.isStateful()) {
13364            d.setState(getDrawableState());
13365        }
13366    }
13367
13368    /**
13369     * Call this to force a view to update its drawable state. This will cause
13370     * drawableStateChanged to be called on this view. Views that are interested
13371     * in the new state should call getDrawableState.
13372     *
13373     * @see #drawableStateChanged
13374     * @see #getDrawableState
13375     */
13376    public void refreshDrawableState() {
13377        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13378        drawableStateChanged();
13379
13380        ViewParent parent = mParent;
13381        if (parent != null) {
13382            parent.childDrawableStateChanged(this);
13383        }
13384    }
13385
13386    /**
13387     * Return an array of resource IDs of the drawable states representing the
13388     * current state of the view.
13389     *
13390     * @return The current drawable state
13391     *
13392     * @see Drawable#setState(int[])
13393     * @see #drawableStateChanged()
13394     * @see #onCreateDrawableState(int)
13395     */
13396    public final int[] getDrawableState() {
13397        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13398            return mDrawableState;
13399        } else {
13400            mDrawableState = onCreateDrawableState(0);
13401            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13402            return mDrawableState;
13403        }
13404    }
13405
13406    /**
13407     * Generate the new {@link android.graphics.drawable.Drawable} state for
13408     * this view. This is called by the view
13409     * system when the cached Drawable state is determined to be invalid.  To
13410     * retrieve the current state, you should use {@link #getDrawableState}.
13411     *
13412     * @param extraSpace if non-zero, this is the number of extra entries you
13413     * would like in the returned array in which you can place your own
13414     * states.
13415     *
13416     * @return Returns an array holding the current {@link Drawable} state of
13417     * the view.
13418     *
13419     * @see #mergeDrawableStates(int[], int[])
13420     */
13421    protected int[] onCreateDrawableState(int extraSpace) {
13422        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13423                mParent instanceof View) {
13424            return ((View) mParent).onCreateDrawableState(extraSpace);
13425        }
13426
13427        int[] drawableState;
13428
13429        int privateFlags = mPrivateFlags;
13430
13431        int viewStateIndex = 0;
13432        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13433        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13434        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13435        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13436        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13437        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13438        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13439                HardwareRenderer.isAvailable()) {
13440            // This is set if HW acceleration is requested, even if the current
13441            // process doesn't allow it.  This is just to allow app preview
13442            // windows to better match their app.
13443            viewStateIndex |= VIEW_STATE_ACCELERATED;
13444        }
13445        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13446
13447        final int privateFlags2 = mPrivateFlags2;
13448        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13449        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13450
13451        drawableState = VIEW_STATE_SETS[viewStateIndex];
13452
13453        //noinspection ConstantIfStatement
13454        if (false) {
13455            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13456            Log.i("View", toString()
13457                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13458                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13459                    + " fo=" + hasFocus()
13460                    + " sl=" + ((privateFlags & SELECTED) != 0)
13461                    + " wf=" + hasWindowFocus()
13462                    + ": " + Arrays.toString(drawableState));
13463        }
13464
13465        if (extraSpace == 0) {
13466            return drawableState;
13467        }
13468
13469        final int[] fullState;
13470        if (drawableState != null) {
13471            fullState = new int[drawableState.length + extraSpace];
13472            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13473        } else {
13474            fullState = new int[extraSpace];
13475        }
13476
13477        return fullState;
13478    }
13479
13480    /**
13481     * Merge your own state values in <var>additionalState</var> into the base
13482     * state values <var>baseState</var> that were returned by
13483     * {@link #onCreateDrawableState(int)}.
13484     *
13485     * @param baseState The base state values returned by
13486     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13487     * own additional state values.
13488     *
13489     * @param additionalState The additional state values you would like
13490     * added to <var>baseState</var>; this array is not modified.
13491     *
13492     * @return As a convenience, the <var>baseState</var> array you originally
13493     * passed into the function is returned.
13494     *
13495     * @see #onCreateDrawableState(int)
13496     */
13497    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13498        final int N = baseState.length;
13499        int i = N - 1;
13500        while (i >= 0 && baseState[i] == 0) {
13501            i--;
13502        }
13503        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13504        return baseState;
13505    }
13506
13507    /**
13508     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13509     * on all Drawable objects associated with this view.
13510     */
13511    public void jumpDrawablesToCurrentState() {
13512        if (mBackground != null) {
13513            mBackground.jumpToCurrentState();
13514        }
13515    }
13516
13517    /**
13518     * Sets the background color for this view.
13519     * @param color the color of the background
13520     */
13521    @RemotableViewMethod
13522    public void setBackgroundColor(int color) {
13523        if (mBackground instanceof ColorDrawable) {
13524            ((ColorDrawable) mBackground).setColor(color);
13525        } else {
13526            setBackground(new ColorDrawable(color));
13527        }
13528    }
13529
13530    /**
13531     * Set the background to a given resource. The resource should refer to
13532     * a Drawable object or 0 to remove the background.
13533     * @param resid The identifier of the resource.
13534     *
13535     * @attr ref android.R.styleable#View_background
13536     */
13537    @RemotableViewMethod
13538    public void setBackgroundResource(int resid) {
13539        if (resid != 0 && resid == mBackgroundResource) {
13540            return;
13541        }
13542
13543        Drawable d= null;
13544        if (resid != 0) {
13545            d = mResources.getDrawable(resid);
13546        }
13547        setBackground(d);
13548
13549        mBackgroundResource = resid;
13550    }
13551
13552    /**
13553     * Set the background to a given Drawable, or remove the background. If the
13554     * background has padding, this View's padding is set to the background's
13555     * padding. However, when a background is removed, this View's padding isn't
13556     * touched. If setting the padding is desired, please use
13557     * {@link #setPadding(int, int, int, int)}.
13558     *
13559     * @param background The Drawable to use as the background, or null to remove the
13560     *        background
13561     */
13562    public void setBackground(Drawable background) {
13563        //noinspection deprecation
13564        setBackgroundDrawable(background);
13565    }
13566
13567    /**
13568     * @deprecated use {@link #setBackground(Drawable)} instead
13569     */
13570    @Deprecated
13571    public void setBackgroundDrawable(Drawable background) {
13572        if (background == mBackground) {
13573            return;
13574        }
13575
13576        boolean requestLayout = false;
13577
13578        mBackgroundResource = 0;
13579
13580        /*
13581         * Regardless of whether we're setting a new background or not, we want
13582         * to clear the previous drawable.
13583         */
13584        if (mBackground != null) {
13585            mBackground.setCallback(null);
13586            unscheduleDrawable(mBackground);
13587        }
13588
13589        if (background != null) {
13590            Rect padding = sThreadLocal.get();
13591            if (padding == null) {
13592                padding = new Rect();
13593                sThreadLocal.set(padding);
13594            }
13595            if (background.getPadding(padding)) {
13596                switch (background.getResolvedLayoutDirectionSelf()) {
13597                    case LAYOUT_DIRECTION_RTL:
13598                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13599                        break;
13600                    case LAYOUT_DIRECTION_LTR:
13601                    default:
13602                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13603                }
13604            }
13605
13606            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13607            // if it has a different minimum size, we should layout again
13608            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13609                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13610                requestLayout = true;
13611            }
13612
13613            background.setCallback(this);
13614            if (background.isStateful()) {
13615                background.setState(getDrawableState());
13616            }
13617            background.setVisible(getVisibility() == VISIBLE, false);
13618            mBackground = background;
13619
13620            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13621                mPrivateFlags &= ~SKIP_DRAW;
13622                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13623                requestLayout = true;
13624            }
13625        } else {
13626            /* Remove the background */
13627            mBackground = null;
13628
13629            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13630                /*
13631                 * This view ONLY drew the background before and we're removing
13632                 * the background, so now it won't draw anything
13633                 * (hence we SKIP_DRAW)
13634                 */
13635                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13636                mPrivateFlags |= SKIP_DRAW;
13637            }
13638
13639            /*
13640             * When the background is set, we try to apply its padding to this
13641             * View. When the background is removed, we don't touch this View's
13642             * padding. This is noted in the Javadocs. Hence, we don't need to
13643             * requestLayout(), the invalidate() below is sufficient.
13644             */
13645
13646            // The old background's minimum size could have affected this
13647            // View's layout, so let's requestLayout
13648            requestLayout = true;
13649        }
13650
13651        computeOpaqueFlags();
13652
13653        if (requestLayout) {
13654            requestLayout();
13655        }
13656
13657        mBackgroundSizeChanged = true;
13658        invalidate(true);
13659    }
13660
13661    /**
13662     * Gets the background drawable
13663     *
13664     * @return The drawable used as the background for this view, if any.
13665     *
13666     * @see #setBackground(Drawable)
13667     *
13668     * @attr ref android.R.styleable#View_background
13669     */
13670    public Drawable getBackground() {
13671        return mBackground;
13672    }
13673
13674    /**
13675     * Sets the padding. The view may add on the space required to display
13676     * the scrollbars, depending on the style and visibility of the scrollbars.
13677     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13678     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13679     * from the values set in this call.
13680     *
13681     * @attr ref android.R.styleable#View_padding
13682     * @attr ref android.R.styleable#View_paddingBottom
13683     * @attr ref android.R.styleable#View_paddingLeft
13684     * @attr ref android.R.styleable#View_paddingRight
13685     * @attr ref android.R.styleable#View_paddingTop
13686     * @param left the left padding in pixels
13687     * @param top the top padding in pixels
13688     * @param right the right padding in pixels
13689     * @param bottom the bottom padding in pixels
13690     */
13691    public void setPadding(int left, int top, int right, int bottom) {
13692        mUserPaddingStart = -1;
13693        mUserPaddingEnd = -1;
13694        mUserPaddingRelative = false;
13695
13696        internalSetPadding(left, top, right, bottom);
13697    }
13698
13699    private void internalSetPadding(int left, int top, int right, int bottom) {
13700        mUserPaddingLeft = left;
13701        mUserPaddingRight = right;
13702        mUserPaddingBottom = bottom;
13703
13704        final int viewFlags = mViewFlags;
13705        boolean changed = false;
13706
13707        // Common case is there are no scroll bars.
13708        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13709            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13710                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13711                        ? 0 : getVerticalScrollbarWidth();
13712                switch (mVerticalScrollbarPosition) {
13713                    case SCROLLBAR_POSITION_DEFAULT:
13714                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13715                            left += offset;
13716                        } else {
13717                            right += offset;
13718                        }
13719                        break;
13720                    case SCROLLBAR_POSITION_RIGHT:
13721                        right += offset;
13722                        break;
13723                    case SCROLLBAR_POSITION_LEFT:
13724                        left += offset;
13725                        break;
13726                }
13727            }
13728            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13729                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13730                        ? 0 : getHorizontalScrollbarHeight();
13731            }
13732        }
13733
13734        if (mPaddingLeft != left) {
13735            changed = true;
13736            mPaddingLeft = left;
13737        }
13738        if (mPaddingTop != top) {
13739            changed = true;
13740            mPaddingTop = top;
13741        }
13742        if (mPaddingRight != right) {
13743            changed = true;
13744            mPaddingRight = right;
13745        }
13746        if (mPaddingBottom != bottom) {
13747            changed = true;
13748            mPaddingBottom = bottom;
13749        }
13750
13751        if (changed) {
13752            requestLayout();
13753        }
13754    }
13755
13756    /**
13757     * Sets the relative padding. The view may add on the space required to display
13758     * the scrollbars, depending on the style and visibility of the scrollbars.
13759     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
13760     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
13761     * from the values set in this call.
13762     *
13763     * @attr ref android.R.styleable#View_padding
13764     * @attr ref android.R.styleable#View_paddingBottom
13765     * @attr ref android.R.styleable#View_paddingStart
13766     * @attr ref android.R.styleable#View_paddingEnd
13767     * @attr ref android.R.styleable#View_paddingTop
13768     * @param start the start padding in pixels
13769     * @param top the top padding in pixels
13770     * @param end the end padding in pixels
13771     * @param bottom the bottom padding in pixels
13772     */
13773    public void setPaddingRelative(int start, int top, int end, int bottom) {
13774        mUserPaddingStart = start;
13775        mUserPaddingEnd = end;
13776        mUserPaddingRelative = true;
13777
13778        switch(getResolvedLayoutDirection()) {
13779            case LAYOUT_DIRECTION_RTL:
13780                internalSetPadding(end, top, start, bottom);
13781                break;
13782            case LAYOUT_DIRECTION_LTR:
13783            default:
13784                internalSetPadding(start, top, end, bottom);
13785        }
13786    }
13787
13788    /**
13789     * Returns the top padding of this view.
13790     *
13791     * @return the top padding in pixels
13792     */
13793    public int getPaddingTop() {
13794        return mPaddingTop;
13795    }
13796
13797    /**
13798     * Returns the bottom padding of this view. If there are inset and enabled
13799     * scrollbars, this value may include the space required to display the
13800     * scrollbars as well.
13801     *
13802     * @return the bottom padding in pixels
13803     */
13804    public int getPaddingBottom() {
13805        return mPaddingBottom;
13806    }
13807
13808    /**
13809     * Returns the left padding of this view. If there are inset and enabled
13810     * scrollbars, this value may include the space required to display the
13811     * scrollbars as well.
13812     *
13813     * @return the left padding in pixels
13814     */
13815    public int getPaddingLeft() {
13816        return mPaddingLeft;
13817    }
13818
13819    /**
13820     * Returns the start padding of this view depending on its resolved layout direction.
13821     * If there are inset and enabled scrollbars, this value may include the space
13822     * required to display the scrollbars as well.
13823     *
13824     * @return the start padding in pixels
13825     */
13826    public int getPaddingStart() {
13827        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13828                mPaddingRight : mPaddingLeft;
13829    }
13830
13831    /**
13832     * Returns the right padding of this view. If there are inset and enabled
13833     * scrollbars, this value may include the space required to display the
13834     * scrollbars as well.
13835     *
13836     * @return the right padding in pixels
13837     */
13838    public int getPaddingRight() {
13839        return mPaddingRight;
13840    }
13841
13842    /**
13843     * Returns the end padding of this view depending on its resolved layout direction.
13844     * If there are inset and enabled scrollbars, this value may include the space
13845     * required to display the scrollbars as well.
13846     *
13847     * @return the end padding in pixels
13848     */
13849    public int getPaddingEnd() {
13850        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13851                mPaddingLeft : mPaddingRight;
13852    }
13853
13854    /**
13855     * Return if the padding as been set thru relative values
13856     * {@link #setPaddingRelative(int, int, int, int)} or thru
13857     * @attr ref android.R.styleable#View_paddingStart or
13858     * @attr ref android.R.styleable#View_paddingEnd
13859     *
13860     * @return true if the padding is relative or false if it is not.
13861     */
13862    public boolean isPaddingRelative() {
13863        return mUserPaddingRelative;
13864    }
13865
13866    /**
13867     * @hide
13868     */
13869    public Insets getLayoutInsets() {
13870        if (mLayoutInsets == null) {
13871            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
13872        }
13873        return mLayoutInsets;
13874    }
13875
13876    /**
13877     * @hide
13878     */
13879    public void setLayoutInsets(Insets layoutInsets) {
13880        mLayoutInsets = layoutInsets;
13881    }
13882
13883    /**
13884     * Changes the selection state of this view. A view can be selected or not.
13885     * Note that selection is not the same as focus. Views are typically
13886     * selected in the context of an AdapterView like ListView or GridView;
13887     * the selected view is the view that is highlighted.
13888     *
13889     * @param selected true if the view must be selected, false otherwise
13890     */
13891    public void setSelected(boolean selected) {
13892        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13893            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13894            if (!selected) resetPressedState();
13895            invalidate(true);
13896            refreshDrawableState();
13897            dispatchSetSelected(selected);
13898            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13899                notifyAccessibilityStateChanged();
13900            }
13901        }
13902    }
13903
13904    /**
13905     * Dispatch setSelected to all of this View's children.
13906     *
13907     * @see #setSelected(boolean)
13908     *
13909     * @param selected The new selected state
13910     */
13911    protected void dispatchSetSelected(boolean selected) {
13912    }
13913
13914    /**
13915     * Indicates the selection state of this view.
13916     *
13917     * @return true if the view is selected, false otherwise
13918     */
13919    @ViewDebug.ExportedProperty
13920    public boolean isSelected() {
13921        return (mPrivateFlags & SELECTED) != 0;
13922    }
13923
13924    /**
13925     * Changes the activated state of this view. A view can be activated or not.
13926     * Note that activation is not the same as selection.  Selection is
13927     * a transient property, representing the view (hierarchy) the user is
13928     * currently interacting with.  Activation is a longer-term state that the
13929     * user can move views in and out of.  For example, in a list view with
13930     * single or multiple selection enabled, the views in the current selection
13931     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13932     * here.)  The activated state is propagated down to children of the view it
13933     * is set on.
13934     *
13935     * @param activated true if the view must be activated, false otherwise
13936     */
13937    public void setActivated(boolean activated) {
13938        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13939            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13940            invalidate(true);
13941            refreshDrawableState();
13942            dispatchSetActivated(activated);
13943        }
13944    }
13945
13946    /**
13947     * Dispatch setActivated to all of this View's children.
13948     *
13949     * @see #setActivated(boolean)
13950     *
13951     * @param activated The new activated state
13952     */
13953    protected void dispatchSetActivated(boolean activated) {
13954    }
13955
13956    /**
13957     * Indicates the activation state of this view.
13958     *
13959     * @return true if the view is activated, false otherwise
13960     */
13961    @ViewDebug.ExportedProperty
13962    public boolean isActivated() {
13963        return (mPrivateFlags & ACTIVATED) != 0;
13964    }
13965
13966    /**
13967     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
13968     * observer can be used to get notifications when global events, like
13969     * layout, happen.
13970     *
13971     * The returned ViewTreeObserver observer is not guaranteed to remain
13972     * valid for the lifetime of this View. If the caller of this method keeps
13973     * a long-lived reference to ViewTreeObserver, it should always check for
13974     * the return value of {@link ViewTreeObserver#isAlive()}.
13975     *
13976     * @return The ViewTreeObserver for this view's hierarchy.
13977     */
13978    public ViewTreeObserver getViewTreeObserver() {
13979        if (mAttachInfo != null) {
13980            return mAttachInfo.mTreeObserver;
13981        }
13982        if (mFloatingTreeObserver == null) {
13983            mFloatingTreeObserver = new ViewTreeObserver();
13984        }
13985        return mFloatingTreeObserver;
13986    }
13987
13988    /**
13989     * <p>Finds the topmost view in the current view hierarchy.</p>
13990     *
13991     * @return the topmost view containing this view
13992     */
13993    public View getRootView() {
13994        if (mAttachInfo != null) {
13995            final View v = mAttachInfo.mRootView;
13996            if (v != null) {
13997                return v;
13998            }
13999        }
14000
14001        View parent = this;
14002
14003        while (parent.mParent != null && parent.mParent instanceof View) {
14004            parent = (View) parent.mParent;
14005        }
14006
14007        return parent;
14008    }
14009
14010    /**
14011     * <p>Computes the coordinates of this view on the screen. The argument
14012     * must be an array of two integers. After the method returns, the array
14013     * contains the x and y location in that order.</p>
14014     *
14015     * @param location an array of two integers in which to hold the coordinates
14016     */
14017    public void getLocationOnScreen(int[] location) {
14018        getLocationInWindow(location);
14019
14020        final AttachInfo info = mAttachInfo;
14021        if (info != null) {
14022            location[0] += info.mWindowLeft;
14023            location[1] += info.mWindowTop;
14024        }
14025    }
14026
14027    /**
14028     * <p>Computes the coordinates of this view in its window. The argument
14029     * must be an array of two integers. After the method returns, the array
14030     * contains the x and y location in that order.</p>
14031     *
14032     * @param location an array of two integers in which to hold the coordinates
14033     */
14034    public void getLocationInWindow(int[] location) {
14035        if (location == null || location.length < 2) {
14036            throw new IllegalArgumentException("location must be an array of two integers");
14037        }
14038
14039        if (mAttachInfo == null) {
14040            // When the view is not attached to a window, this method does not make sense
14041            location[0] = location[1] = 0;
14042            return;
14043        }
14044
14045        float[] position = mAttachInfo.mTmpTransformLocation;
14046        position[0] = position[1] = 0.0f;
14047
14048        if (!hasIdentityMatrix()) {
14049            getMatrix().mapPoints(position);
14050        }
14051
14052        position[0] += mLeft;
14053        position[1] += mTop;
14054
14055        ViewParent viewParent = mParent;
14056        while (viewParent instanceof View) {
14057            final View view = (View) viewParent;
14058
14059            position[0] -= view.mScrollX;
14060            position[1] -= view.mScrollY;
14061
14062            if (!view.hasIdentityMatrix()) {
14063                view.getMatrix().mapPoints(position);
14064            }
14065
14066            position[0] += view.mLeft;
14067            position[1] += view.mTop;
14068
14069            viewParent = view.mParent;
14070         }
14071
14072        if (viewParent instanceof ViewRootImpl) {
14073            // *cough*
14074            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14075            position[1] -= vr.mCurScrollY;
14076        }
14077
14078        location[0] = (int) (position[0] + 0.5f);
14079        location[1] = (int) (position[1] + 0.5f);
14080    }
14081
14082    /**
14083     * {@hide}
14084     * @param id the id of the view to be found
14085     * @return the view of the specified id, null if cannot be found
14086     */
14087    protected View findViewTraversal(int id) {
14088        if (id == mID) {
14089            return this;
14090        }
14091        return null;
14092    }
14093
14094    /**
14095     * {@hide}
14096     * @param tag the tag of the view to be found
14097     * @return the view of specified tag, null if cannot be found
14098     */
14099    protected View findViewWithTagTraversal(Object tag) {
14100        if (tag != null && tag.equals(mTag)) {
14101            return this;
14102        }
14103        return null;
14104    }
14105
14106    /**
14107     * {@hide}
14108     * @param predicate The predicate to evaluate.
14109     * @param childToSkip If not null, ignores this child during the recursive traversal.
14110     * @return The first view that matches the predicate or null.
14111     */
14112    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14113        if (predicate.apply(this)) {
14114            return this;
14115        }
14116        return null;
14117    }
14118
14119    /**
14120     * Look for a child view with the given id.  If this view has the given
14121     * id, return this view.
14122     *
14123     * @param id The id to search for.
14124     * @return The view that has the given id in the hierarchy or null
14125     */
14126    public final View findViewById(int id) {
14127        if (id < 0) {
14128            return null;
14129        }
14130        return findViewTraversal(id);
14131    }
14132
14133    /**
14134     * Finds a view by its unuque and stable accessibility id.
14135     *
14136     * @param accessibilityId The searched accessibility id.
14137     * @return The found view.
14138     */
14139    final View findViewByAccessibilityId(int accessibilityId) {
14140        if (accessibilityId < 0) {
14141            return null;
14142        }
14143        return findViewByAccessibilityIdTraversal(accessibilityId);
14144    }
14145
14146    /**
14147     * Performs the traversal to find a view by its unuque and stable accessibility id.
14148     *
14149     * <strong>Note:</strong>This method does not stop at the root namespace
14150     * boundary since the user can touch the screen at an arbitrary location
14151     * potentially crossing the root namespace bounday which will send an
14152     * accessibility event to accessibility services and they should be able
14153     * to obtain the event source. Also accessibility ids are guaranteed to be
14154     * unique in the window.
14155     *
14156     * @param accessibilityId The accessibility id.
14157     * @return The found view.
14158     */
14159    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14160        if (getAccessibilityViewId() == accessibilityId) {
14161            return this;
14162        }
14163        return null;
14164    }
14165
14166    /**
14167     * Look for a child view with the given tag.  If this view has the given
14168     * tag, return this view.
14169     *
14170     * @param tag The tag to search for, using "tag.equals(getTag())".
14171     * @return The View that has the given tag in the hierarchy or null
14172     */
14173    public final View findViewWithTag(Object tag) {
14174        if (tag == null) {
14175            return null;
14176        }
14177        return findViewWithTagTraversal(tag);
14178    }
14179
14180    /**
14181     * {@hide}
14182     * Look for a child view that matches the specified predicate.
14183     * If this view matches the predicate, return this view.
14184     *
14185     * @param predicate The predicate to evaluate.
14186     * @return The first view that matches the predicate or null.
14187     */
14188    public final View findViewByPredicate(Predicate<View> predicate) {
14189        return findViewByPredicateTraversal(predicate, null);
14190    }
14191
14192    /**
14193     * {@hide}
14194     * Look for a child view that matches the specified predicate,
14195     * starting with the specified view and its descendents and then
14196     * recusively searching the ancestors and siblings of that view
14197     * until this view is reached.
14198     *
14199     * This method is useful in cases where the predicate does not match
14200     * a single unique view (perhaps multiple views use the same id)
14201     * and we are trying to find the view that is "closest" in scope to the
14202     * starting view.
14203     *
14204     * @param start The view to start from.
14205     * @param predicate The predicate to evaluate.
14206     * @return The first view that matches the predicate or null.
14207     */
14208    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14209        View childToSkip = null;
14210        for (;;) {
14211            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14212            if (view != null || start == this) {
14213                return view;
14214            }
14215
14216            ViewParent parent = start.getParent();
14217            if (parent == null || !(parent instanceof View)) {
14218                return null;
14219            }
14220
14221            childToSkip = start;
14222            start = (View) parent;
14223        }
14224    }
14225
14226    /**
14227     * Sets the identifier for this view. The identifier does not have to be
14228     * unique in this view's hierarchy. The identifier should be a positive
14229     * number.
14230     *
14231     * @see #NO_ID
14232     * @see #getId()
14233     * @see #findViewById(int)
14234     *
14235     * @param id a number used to identify the view
14236     *
14237     * @attr ref android.R.styleable#View_id
14238     */
14239    public void setId(int id) {
14240        mID = id;
14241    }
14242
14243    /**
14244     * {@hide}
14245     *
14246     * @param isRoot true if the view belongs to the root namespace, false
14247     *        otherwise
14248     */
14249    public void setIsRootNamespace(boolean isRoot) {
14250        if (isRoot) {
14251            mPrivateFlags |= IS_ROOT_NAMESPACE;
14252        } else {
14253            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14254        }
14255    }
14256
14257    /**
14258     * {@hide}
14259     *
14260     * @return true if the view belongs to the root namespace, false otherwise
14261     */
14262    public boolean isRootNamespace() {
14263        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14264    }
14265
14266    /**
14267     * Returns this view's identifier.
14268     *
14269     * @return a positive integer used to identify the view or {@link #NO_ID}
14270     *         if the view has no ID
14271     *
14272     * @see #setId(int)
14273     * @see #findViewById(int)
14274     * @attr ref android.R.styleable#View_id
14275     */
14276    @ViewDebug.CapturedViewProperty
14277    public int getId() {
14278        return mID;
14279    }
14280
14281    /**
14282     * Returns this view's tag.
14283     *
14284     * @return the Object stored in this view as a tag
14285     *
14286     * @see #setTag(Object)
14287     * @see #getTag(int)
14288     */
14289    @ViewDebug.ExportedProperty
14290    public Object getTag() {
14291        return mTag;
14292    }
14293
14294    /**
14295     * Sets the tag associated with this view. A tag can be used to mark
14296     * a view in its hierarchy and does not have to be unique within the
14297     * hierarchy. Tags can also be used to store data within a view without
14298     * resorting to another data structure.
14299     *
14300     * @param tag an Object to tag the view with
14301     *
14302     * @see #getTag()
14303     * @see #setTag(int, Object)
14304     */
14305    public void setTag(final Object tag) {
14306        mTag = tag;
14307    }
14308
14309    /**
14310     * Returns the tag associated with this view and the specified key.
14311     *
14312     * @param key The key identifying the tag
14313     *
14314     * @return the Object stored in this view as a tag
14315     *
14316     * @see #setTag(int, Object)
14317     * @see #getTag()
14318     */
14319    public Object getTag(int key) {
14320        if (mKeyedTags != null) return mKeyedTags.get(key);
14321        return null;
14322    }
14323
14324    /**
14325     * Sets a tag associated with this view and a key. A tag can be used
14326     * to mark a view in its hierarchy and does not have to be unique within
14327     * the hierarchy. Tags can also be used to store data within a view
14328     * without resorting to another data structure.
14329     *
14330     * The specified key should be an id declared in the resources of the
14331     * application to ensure it is unique (see the <a
14332     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14333     * Keys identified as belonging to
14334     * the Android framework or not associated with any package will cause
14335     * an {@link IllegalArgumentException} to be thrown.
14336     *
14337     * @param key The key identifying the tag
14338     * @param tag An Object to tag the view with
14339     *
14340     * @throws IllegalArgumentException If they specified key is not valid
14341     *
14342     * @see #setTag(Object)
14343     * @see #getTag(int)
14344     */
14345    public void setTag(int key, final Object tag) {
14346        // If the package id is 0x00 or 0x01, it's either an undefined package
14347        // or a framework id
14348        if ((key >>> 24) < 2) {
14349            throw new IllegalArgumentException("The key must be an application-specific "
14350                    + "resource id.");
14351        }
14352
14353        setKeyedTag(key, tag);
14354    }
14355
14356    /**
14357     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14358     * framework id.
14359     *
14360     * @hide
14361     */
14362    public void setTagInternal(int key, Object tag) {
14363        if ((key >>> 24) != 0x1) {
14364            throw new IllegalArgumentException("The key must be a framework-specific "
14365                    + "resource id.");
14366        }
14367
14368        setKeyedTag(key, tag);
14369    }
14370
14371    private void setKeyedTag(int key, Object tag) {
14372        if (mKeyedTags == null) {
14373            mKeyedTags = new SparseArray<Object>();
14374        }
14375
14376        mKeyedTags.put(key, tag);
14377    }
14378
14379    /**
14380     * @param consistency The type of consistency. See ViewDebug for more information.
14381     *
14382     * @hide
14383     */
14384    protected boolean dispatchConsistencyCheck(int consistency) {
14385        return onConsistencyCheck(consistency);
14386    }
14387
14388    /**
14389     * Method that subclasses should implement to check their consistency. The type of
14390     * consistency check is indicated by the bit field passed as a parameter.
14391     *
14392     * @param consistency The type of consistency. See ViewDebug for more information.
14393     *
14394     * @throws IllegalStateException if the view is in an inconsistent state.
14395     *
14396     * @hide
14397     */
14398    protected boolean onConsistencyCheck(int consistency) {
14399        boolean result = true;
14400
14401        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14402        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14403
14404        if (checkLayout) {
14405            if (getParent() == null) {
14406                result = false;
14407                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14408                        "View " + this + " does not have a parent.");
14409            }
14410
14411            if (mAttachInfo == null) {
14412                result = false;
14413                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14414                        "View " + this + " is not attached to a window.");
14415            }
14416        }
14417
14418        if (checkDrawing) {
14419            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14420            // from their draw() method
14421
14422            if ((mPrivateFlags & DRAWN) != DRAWN &&
14423                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14424                result = false;
14425                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14426                        "View " + this + " was invalidated but its drawing cache is valid.");
14427            }
14428        }
14429
14430        return result;
14431    }
14432
14433    /**
14434     * Prints information about this view in the log output, with the tag
14435     * {@link #VIEW_LOG_TAG}.
14436     *
14437     * @hide
14438     */
14439    public void debug() {
14440        debug(0);
14441    }
14442
14443    /**
14444     * Prints information about this view in the log output, with the tag
14445     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14446     * indentation defined by the <code>depth</code>.
14447     *
14448     * @param depth the indentation level
14449     *
14450     * @hide
14451     */
14452    protected void debug(int depth) {
14453        String output = debugIndent(depth - 1);
14454
14455        output += "+ " + this;
14456        int id = getId();
14457        if (id != -1) {
14458            output += " (id=" + id + ")";
14459        }
14460        Object tag = getTag();
14461        if (tag != null) {
14462            output += " (tag=" + tag + ")";
14463        }
14464        Log.d(VIEW_LOG_TAG, output);
14465
14466        if ((mPrivateFlags & FOCUSED) != 0) {
14467            output = debugIndent(depth) + " FOCUSED";
14468            Log.d(VIEW_LOG_TAG, output);
14469        }
14470
14471        output = debugIndent(depth);
14472        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14473                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14474                + "} ";
14475        Log.d(VIEW_LOG_TAG, output);
14476
14477        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14478                || mPaddingBottom != 0) {
14479            output = debugIndent(depth);
14480            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14481                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14482            Log.d(VIEW_LOG_TAG, output);
14483        }
14484
14485        output = debugIndent(depth);
14486        output += "mMeasureWidth=" + mMeasuredWidth +
14487                " mMeasureHeight=" + mMeasuredHeight;
14488        Log.d(VIEW_LOG_TAG, output);
14489
14490        output = debugIndent(depth);
14491        if (mLayoutParams == null) {
14492            output += "BAD! no layout params";
14493        } else {
14494            output = mLayoutParams.debug(output);
14495        }
14496        Log.d(VIEW_LOG_TAG, output);
14497
14498        output = debugIndent(depth);
14499        output += "flags={";
14500        output += View.printFlags(mViewFlags);
14501        output += "}";
14502        Log.d(VIEW_LOG_TAG, output);
14503
14504        output = debugIndent(depth);
14505        output += "privateFlags={";
14506        output += View.printPrivateFlags(mPrivateFlags);
14507        output += "}";
14508        Log.d(VIEW_LOG_TAG, output);
14509    }
14510
14511    /**
14512     * Creates a string of whitespaces used for indentation.
14513     *
14514     * @param depth the indentation level
14515     * @return a String containing (depth * 2 + 3) * 2 white spaces
14516     *
14517     * @hide
14518     */
14519    protected static String debugIndent(int depth) {
14520        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14521        for (int i = 0; i < (depth * 2) + 3; i++) {
14522            spaces.append(' ').append(' ');
14523        }
14524        return spaces.toString();
14525    }
14526
14527    /**
14528     * <p>Return the offset of the widget's text baseline from the widget's top
14529     * boundary. If this widget does not support baseline alignment, this
14530     * method returns -1. </p>
14531     *
14532     * @return the offset of the baseline within the widget's bounds or -1
14533     *         if baseline alignment is not supported
14534     */
14535    @ViewDebug.ExportedProperty(category = "layout")
14536    public int getBaseline() {
14537        return -1;
14538    }
14539
14540    /**
14541     * Call this when something has changed which has invalidated the
14542     * layout of this view. This will schedule a layout pass of the view
14543     * tree.
14544     */
14545    public void requestLayout() {
14546        if (ViewDebug.TRACE_HIERARCHY) {
14547            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14548        }
14549
14550        mPrivateFlags |= FORCE_LAYOUT;
14551        mPrivateFlags |= INVALIDATED;
14552
14553        if (mLayoutParams != null) {
14554            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14555        }
14556
14557        if (mParent != null && !mParent.isLayoutRequested()) {
14558            mParent.requestLayout();
14559        }
14560    }
14561
14562    /**
14563     * Forces this view to be laid out during the next layout pass.
14564     * This method does not call requestLayout() or forceLayout()
14565     * on the parent.
14566     */
14567    public void forceLayout() {
14568        mPrivateFlags |= FORCE_LAYOUT;
14569        mPrivateFlags |= INVALIDATED;
14570    }
14571
14572    /**
14573     * <p>
14574     * This is called to find out how big a view should be. The parent
14575     * supplies constraint information in the width and height parameters.
14576     * </p>
14577     *
14578     * <p>
14579     * The actual measurement work of a view is performed in
14580     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14581     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14582     * </p>
14583     *
14584     *
14585     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14586     *        parent
14587     * @param heightMeasureSpec Vertical space requirements as imposed by the
14588     *        parent
14589     *
14590     * @see #onMeasure(int, int)
14591     */
14592    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14593        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14594                widthMeasureSpec != mOldWidthMeasureSpec ||
14595                heightMeasureSpec != mOldHeightMeasureSpec) {
14596
14597            // first clears the measured dimension flag
14598            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14599
14600            if (ViewDebug.TRACE_HIERARCHY) {
14601                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14602            }
14603
14604            // measure ourselves, this should set the measured dimension flag back
14605            onMeasure(widthMeasureSpec, heightMeasureSpec);
14606
14607            // flag not set, setMeasuredDimension() was not invoked, we raise
14608            // an exception to warn the developer
14609            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14610                throw new IllegalStateException("onMeasure() did not set the"
14611                        + " measured dimension by calling"
14612                        + " setMeasuredDimension()");
14613            }
14614
14615            mPrivateFlags |= LAYOUT_REQUIRED;
14616        }
14617
14618        mOldWidthMeasureSpec = widthMeasureSpec;
14619        mOldHeightMeasureSpec = heightMeasureSpec;
14620    }
14621
14622    /**
14623     * <p>
14624     * Measure the view and its content to determine the measured width and the
14625     * measured height. This method is invoked by {@link #measure(int, int)} and
14626     * should be overriden by subclasses to provide accurate and efficient
14627     * measurement of their contents.
14628     * </p>
14629     *
14630     * <p>
14631     * <strong>CONTRACT:</strong> When overriding this method, you
14632     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14633     * measured width and height of this view. Failure to do so will trigger an
14634     * <code>IllegalStateException</code>, thrown by
14635     * {@link #measure(int, int)}. Calling the superclass'
14636     * {@link #onMeasure(int, int)} is a valid use.
14637     * </p>
14638     *
14639     * <p>
14640     * The base class implementation of measure defaults to the background size,
14641     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14642     * override {@link #onMeasure(int, int)} to provide better measurements of
14643     * their content.
14644     * </p>
14645     *
14646     * <p>
14647     * If this method is overridden, it is the subclass's responsibility to make
14648     * sure the measured height and width are at least the view's minimum height
14649     * and width ({@link #getSuggestedMinimumHeight()} and
14650     * {@link #getSuggestedMinimumWidth()}).
14651     * </p>
14652     *
14653     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14654     *                         The requirements are encoded with
14655     *                         {@link android.view.View.MeasureSpec}.
14656     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14657     *                         The requirements are encoded with
14658     *                         {@link android.view.View.MeasureSpec}.
14659     *
14660     * @see #getMeasuredWidth()
14661     * @see #getMeasuredHeight()
14662     * @see #setMeasuredDimension(int, int)
14663     * @see #getSuggestedMinimumHeight()
14664     * @see #getSuggestedMinimumWidth()
14665     * @see android.view.View.MeasureSpec#getMode(int)
14666     * @see android.view.View.MeasureSpec#getSize(int)
14667     */
14668    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14669        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14670                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14671    }
14672
14673    /**
14674     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14675     * measured width and measured height. Failing to do so will trigger an
14676     * exception at measurement time.</p>
14677     *
14678     * @param measuredWidth The measured width of this view.  May be a complex
14679     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14680     * {@link #MEASURED_STATE_TOO_SMALL}.
14681     * @param measuredHeight The measured height of this view.  May be a complex
14682     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14683     * {@link #MEASURED_STATE_TOO_SMALL}.
14684     */
14685    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14686        mMeasuredWidth = measuredWidth;
14687        mMeasuredHeight = measuredHeight;
14688
14689        mPrivateFlags |= MEASURED_DIMENSION_SET;
14690    }
14691
14692    /**
14693     * Merge two states as returned by {@link #getMeasuredState()}.
14694     * @param curState The current state as returned from a view or the result
14695     * of combining multiple views.
14696     * @param newState The new view state to combine.
14697     * @return Returns a new integer reflecting the combination of the two
14698     * states.
14699     */
14700    public static int combineMeasuredStates(int curState, int newState) {
14701        return curState | newState;
14702    }
14703
14704    /**
14705     * Version of {@link #resolveSizeAndState(int, int, int)}
14706     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14707     */
14708    public static int resolveSize(int size, int measureSpec) {
14709        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14710    }
14711
14712    /**
14713     * Utility to reconcile a desired size and state, with constraints imposed
14714     * by a MeasureSpec.  Will take the desired size, unless a different size
14715     * is imposed by the constraints.  The returned value is a compound integer,
14716     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14717     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14718     * size is smaller than the size the view wants to be.
14719     *
14720     * @param size How big the view wants to be
14721     * @param measureSpec Constraints imposed by the parent
14722     * @return Size information bit mask as defined by
14723     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14724     */
14725    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14726        int result = size;
14727        int specMode = MeasureSpec.getMode(measureSpec);
14728        int specSize =  MeasureSpec.getSize(measureSpec);
14729        switch (specMode) {
14730        case MeasureSpec.UNSPECIFIED:
14731            result = size;
14732            break;
14733        case MeasureSpec.AT_MOST:
14734            if (specSize < size) {
14735                result = specSize | MEASURED_STATE_TOO_SMALL;
14736            } else {
14737                result = size;
14738            }
14739            break;
14740        case MeasureSpec.EXACTLY:
14741            result = specSize;
14742            break;
14743        }
14744        return result | (childMeasuredState&MEASURED_STATE_MASK);
14745    }
14746
14747    /**
14748     * Utility to return a default size. Uses the supplied size if the
14749     * MeasureSpec imposed no constraints. Will get larger if allowed
14750     * by the MeasureSpec.
14751     *
14752     * @param size Default size for this view
14753     * @param measureSpec Constraints imposed by the parent
14754     * @return The size this view should be.
14755     */
14756    public static int getDefaultSize(int size, int measureSpec) {
14757        int result = size;
14758        int specMode = MeasureSpec.getMode(measureSpec);
14759        int specSize = MeasureSpec.getSize(measureSpec);
14760
14761        switch (specMode) {
14762        case MeasureSpec.UNSPECIFIED:
14763            result = size;
14764            break;
14765        case MeasureSpec.AT_MOST:
14766        case MeasureSpec.EXACTLY:
14767            result = specSize;
14768            break;
14769        }
14770        return result;
14771    }
14772
14773    /**
14774     * Returns the suggested minimum height that the view should use. This
14775     * returns the maximum of the view's minimum height
14776     * and the background's minimum height
14777     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
14778     * <p>
14779     * When being used in {@link #onMeasure(int, int)}, the caller should still
14780     * ensure the returned height is within the requirements of the parent.
14781     *
14782     * @return The suggested minimum height of the view.
14783     */
14784    protected int getSuggestedMinimumHeight() {
14785        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
14786
14787    }
14788
14789    /**
14790     * Returns the suggested minimum width that the view should use. This
14791     * returns the maximum of the view's minimum width)
14792     * and the background's minimum width
14793     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
14794     * <p>
14795     * When being used in {@link #onMeasure(int, int)}, the caller should still
14796     * ensure the returned width is within the requirements of the parent.
14797     *
14798     * @return The suggested minimum width of the view.
14799     */
14800    protected int getSuggestedMinimumWidth() {
14801        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14802    }
14803
14804    /**
14805     * Returns the minimum height of the view.
14806     *
14807     * @return the minimum height the view will try to be.
14808     *
14809     * @see #setMinimumHeight(int)
14810     *
14811     * @attr ref android.R.styleable#View_minHeight
14812     */
14813    public int getMinimumHeight() {
14814        return mMinHeight;
14815    }
14816
14817    /**
14818     * Sets the minimum height of the view. It is not guaranteed the view will
14819     * be able to achieve this minimum height (for example, if its parent layout
14820     * constrains it with less available height).
14821     *
14822     * @param minHeight The minimum height the view will try to be.
14823     *
14824     * @see #getMinimumHeight()
14825     *
14826     * @attr ref android.R.styleable#View_minHeight
14827     */
14828    public void setMinimumHeight(int minHeight) {
14829        mMinHeight = minHeight;
14830        requestLayout();
14831    }
14832
14833    /**
14834     * Returns the minimum width of the view.
14835     *
14836     * @return the minimum width the view will try to be.
14837     *
14838     * @see #setMinimumWidth(int)
14839     *
14840     * @attr ref android.R.styleable#View_minWidth
14841     */
14842    public int getMinimumWidth() {
14843        return mMinWidth;
14844    }
14845
14846    /**
14847     * Sets the minimum width of the view. It is not guaranteed the view will
14848     * be able to achieve this minimum width (for example, if its parent layout
14849     * constrains it with less available width).
14850     *
14851     * @param minWidth The minimum width the view will try to be.
14852     *
14853     * @see #getMinimumWidth()
14854     *
14855     * @attr ref android.R.styleable#View_minWidth
14856     */
14857    public void setMinimumWidth(int minWidth) {
14858        mMinWidth = minWidth;
14859        requestLayout();
14860
14861    }
14862
14863    /**
14864     * Get the animation currently associated with this view.
14865     *
14866     * @return The animation that is currently playing or
14867     *         scheduled to play for this view.
14868     */
14869    public Animation getAnimation() {
14870        return mCurrentAnimation;
14871    }
14872
14873    /**
14874     * Start the specified animation now.
14875     *
14876     * @param animation the animation to start now
14877     */
14878    public void startAnimation(Animation animation) {
14879        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
14880        setAnimation(animation);
14881        invalidateParentCaches();
14882        invalidate(true);
14883    }
14884
14885    /**
14886     * Cancels any animations for this view.
14887     */
14888    public void clearAnimation() {
14889        if (mCurrentAnimation != null) {
14890            mCurrentAnimation.detach();
14891        }
14892        mCurrentAnimation = null;
14893        invalidateParentIfNeeded();
14894    }
14895
14896    /**
14897     * Sets the next animation to play for this view.
14898     * If you want the animation to play immediately, use
14899     * startAnimation. This method provides allows fine-grained
14900     * control over the start time and invalidation, but you
14901     * must make sure that 1) the animation has a start time set, and
14902     * 2) the view will be invalidated when the animation is supposed to
14903     * start.
14904     *
14905     * @param animation The next animation, or null.
14906     */
14907    public void setAnimation(Animation animation) {
14908        mCurrentAnimation = animation;
14909
14910        if (animation != null) {
14911            // If the screen is off assume the animation start time is now instead of
14912            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
14913            // would cause the animation to start when the screen turns back on
14914            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
14915                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
14916                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
14917            }
14918            animation.reset();
14919        }
14920    }
14921
14922    /**
14923     * Invoked by a parent ViewGroup to notify the start of the animation
14924     * currently associated with this view. If you override this method,
14925     * always call super.onAnimationStart();
14926     *
14927     * @see #setAnimation(android.view.animation.Animation)
14928     * @see #getAnimation()
14929     */
14930    protected void onAnimationStart() {
14931        mPrivateFlags |= ANIMATION_STARTED;
14932    }
14933
14934    /**
14935     * Invoked by a parent ViewGroup to notify the end of the animation
14936     * currently associated with this view. If you override this method,
14937     * always call super.onAnimationEnd();
14938     *
14939     * @see #setAnimation(android.view.animation.Animation)
14940     * @see #getAnimation()
14941     */
14942    protected void onAnimationEnd() {
14943        mPrivateFlags &= ~ANIMATION_STARTED;
14944    }
14945
14946    /**
14947     * Invoked if there is a Transform that involves alpha. Subclass that can
14948     * draw themselves with the specified alpha should return true, and then
14949     * respect that alpha when their onDraw() is called. If this returns false
14950     * then the view may be redirected to draw into an offscreen buffer to
14951     * fulfill the request, which will look fine, but may be slower than if the
14952     * subclass handles it internally. The default implementation returns false.
14953     *
14954     * @param alpha The alpha (0..255) to apply to the view's drawing
14955     * @return true if the view can draw with the specified alpha.
14956     */
14957    protected boolean onSetAlpha(int alpha) {
14958        return false;
14959    }
14960
14961    /**
14962     * This is used by the RootView to perform an optimization when
14963     * the view hierarchy contains one or several SurfaceView.
14964     * SurfaceView is always considered transparent, but its children are not,
14965     * therefore all View objects remove themselves from the global transparent
14966     * region (passed as a parameter to this function).
14967     *
14968     * @param region The transparent region for this ViewAncestor (window).
14969     *
14970     * @return Returns true if the effective visibility of the view at this
14971     * point is opaque, regardless of the transparent region; returns false
14972     * if it is possible for underlying windows to be seen behind the view.
14973     *
14974     * {@hide}
14975     */
14976    public boolean gatherTransparentRegion(Region region) {
14977        final AttachInfo attachInfo = mAttachInfo;
14978        if (region != null && attachInfo != null) {
14979            final int pflags = mPrivateFlags;
14980            if ((pflags & SKIP_DRAW) == 0) {
14981                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
14982                // remove it from the transparent region.
14983                final int[] location = attachInfo.mTransparentLocation;
14984                getLocationInWindow(location);
14985                region.op(location[0], location[1], location[0] + mRight - mLeft,
14986                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
14987            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
14988                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
14989                // exists, so we remove the background drawable's non-transparent
14990                // parts from this transparent region.
14991                applyDrawableToTransparentRegion(mBackground, region);
14992            }
14993        }
14994        return true;
14995    }
14996
14997    /**
14998     * Play a sound effect for this view.
14999     *
15000     * <p>The framework will play sound effects for some built in actions, such as
15001     * clicking, but you may wish to play these effects in your widget,
15002     * for instance, for internal navigation.
15003     *
15004     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15005     * {@link #isSoundEffectsEnabled()} is true.
15006     *
15007     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15008     */
15009    public void playSoundEffect(int soundConstant) {
15010        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15011            return;
15012        }
15013        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15014    }
15015
15016    /**
15017     * BZZZTT!!1!
15018     *
15019     * <p>Provide haptic feedback to the user for this view.
15020     *
15021     * <p>The framework will provide haptic feedback for some built in actions,
15022     * such as long presses, but you may wish to provide feedback for your
15023     * own widget.
15024     *
15025     * <p>The feedback will only be performed if
15026     * {@link #isHapticFeedbackEnabled()} is true.
15027     *
15028     * @param feedbackConstant One of the constants defined in
15029     * {@link HapticFeedbackConstants}
15030     */
15031    public boolean performHapticFeedback(int feedbackConstant) {
15032        return performHapticFeedback(feedbackConstant, 0);
15033    }
15034
15035    /**
15036     * BZZZTT!!1!
15037     *
15038     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15039     *
15040     * @param feedbackConstant One of the constants defined in
15041     * {@link HapticFeedbackConstants}
15042     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15043     */
15044    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15045        if (mAttachInfo == null) {
15046            return false;
15047        }
15048        //noinspection SimplifiableIfStatement
15049        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15050                && !isHapticFeedbackEnabled()) {
15051            return false;
15052        }
15053        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15054                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15055    }
15056
15057    /**
15058     * Request that the visibility of the status bar or other screen/window
15059     * decorations be changed.
15060     *
15061     * <p>This method is used to put the over device UI into temporary modes
15062     * where the user's attention is focused more on the application content,
15063     * by dimming or hiding surrounding system affordances.  This is typically
15064     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15065     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15066     * to be placed behind the action bar (and with these flags other system
15067     * affordances) so that smooth transitions between hiding and showing them
15068     * can be done.
15069     *
15070     * <p>Two representative examples of the use of system UI visibility is
15071     * implementing a content browsing application (like a magazine reader)
15072     * and a video playing application.
15073     *
15074     * <p>The first code shows a typical implementation of a View in a content
15075     * browsing application.  In this implementation, the application goes
15076     * into a content-oriented mode by hiding the status bar and action bar,
15077     * and putting the navigation elements into lights out mode.  The user can
15078     * then interact with content while in this mode.  Such an application should
15079     * provide an easy way for the user to toggle out of the mode (such as to
15080     * check information in the status bar or access notifications).  In the
15081     * implementation here, this is done simply by tapping on the content.
15082     *
15083     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15084     *      content}
15085     *
15086     * <p>This second code sample shows a typical implementation of a View
15087     * in a video playing application.  In this situation, while the video is
15088     * playing the application would like to go into a complete full-screen mode,
15089     * to use as much of the display as possible for the video.  When in this state
15090     * the user can not interact with the application; the system intercepts
15091     * touching on the screen to pop the UI out of full screen mode.
15092     *
15093     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15094     *      content}
15095     *
15096     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15097     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15098     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15099     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15100     */
15101    public void setSystemUiVisibility(int visibility) {
15102        if (visibility != mSystemUiVisibility) {
15103            mSystemUiVisibility = visibility;
15104            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15105                mParent.recomputeViewAttributes(this);
15106            }
15107        }
15108    }
15109
15110    /**
15111     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15112     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15113     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15114     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15115     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15116     */
15117    public int getSystemUiVisibility() {
15118        return mSystemUiVisibility;
15119    }
15120
15121    /**
15122     * Returns the current system UI visibility that is currently set for
15123     * the entire window.  This is the combination of the
15124     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15125     * views in the window.
15126     */
15127    public int getWindowSystemUiVisibility() {
15128        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15129    }
15130
15131    /**
15132     * Override to find out when the window's requested system UI visibility
15133     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15134     * This is different from the callbacks recieved through
15135     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15136     * in that this is only telling you about the local request of the window,
15137     * not the actual values applied by the system.
15138     */
15139    public void onWindowSystemUiVisibilityChanged(int visible) {
15140    }
15141
15142    /**
15143     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15144     * the view hierarchy.
15145     */
15146    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15147        onWindowSystemUiVisibilityChanged(visible);
15148    }
15149
15150    /**
15151     * Set a listener to receive callbacks when the visibility of the system bar changes.
15152     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15153     */
15154    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15155        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15156        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15157            mParent.recomputeViewAttributes(this);
15158        }
15159    }
15160
15161    /**
15162     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15163     * the view hierarchy.
15164     */
15165    public void dispatchSystemUiVisibilityChanged(int visibility) {
15166        ListenerInfo li = mListenerInfo;
15167        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15168            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15169                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15170        }
15171    }
15172
15173    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15174        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15175        if (val != mSystemUiVisibility) {
15176            setSystemUiVisibility(val);
15177        }
15178    }
15179
15180    /**
15181     * Creates an image that the system displays during the drag and drop
15182     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15183     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15184     * appearance as the given View. The default also positions the center of the drag shadow
15185     * directly under the touch point. If no View is provided (the constructor with no parameters
15186     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15187     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15188     * default is an invisible drag shadow.
15189     * <p>
15190     * You are not required to use the View you provide to the constructor as the basis of the
15191     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15192     * anything you want as the drag shadow.
15193     * </p>
15194     * <p>
15195     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15196     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15197     *  size and position of the drag shadow. It uses this data to construct a
15198     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15199     *  so that your application can draw the shadow image in the Canvas.
15200     * </p>
15201     *
15202     * <div class="special reference">
15203     * <h3>Developer Guides</h3>
15204     * <p>For a guide to implementing drag and drop features, read the
15205     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15206     * </div>
15207     */
15208    public static class DragShadowBuilder {
15209        private final WeakReference<View> mView;
15210
15211        /**
15212         * Constructs a shadow image builder based on a View. By default, the resulting drag
15213         * shadow will have the same appearance and dimensions as the View, with the touch point
15214         * over the center of the View.
15215         * @param view A View. Any View in scope can be used.
15216         */
15217        public DragShadowBuilder(View view) {
15218            mView = new WeakReference<View>(view);
15219        }
15220
15221        /**
15222         * Construct a shadow builder object with no associated View.  This
15223         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15224         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15225         * to supply the drag shadow's dimensions and appearance without
15226         * reference to any View object. If they are not overridden, then the result is an
15227         * invisible drag shadow.
15228         */
15229        public DragShadowBuilder() {
15230            mView = new WeakReference<View>(null);
15231        }
15232
15233        /**
15234         * Returns the View object that had been passed to the
15235         * {@link #View.DragShadowBuilder(View)}
15236         * constructor.  If that View parameter was {@code null} or if the
15237         * {@link #View.DragShadowBuilder()}
15238         * constructor was used to instantiate the builder object, this method will return
15239         * null.
15240         *
15241         * @return The View object associate with this builder object.
15242         */
15243        @SuppressWarnings({"JavadocReference"})
15244        final public View getView() {
15245            return mView.get();
15246        }
15247
15248        /**
15249         * Provides the metrics for the shadow image. These include the dimensions of
15250         * the shadow image, and the point within that shadow that should
15251         * be centered under the touch location while dragging.
15252         * <p>
15253         * The default implementation sets the dimensions of the shadow to be the
15254         * same as the dimensions of the View itself and centers the shadow under
15255         * the touch point.
15256         * </p>
15257         *
15258         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15259         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15260         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15261         * image.
15262         *
15263         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15264         * shadow image that should be underneath the touch point during the drag and drop
15265         * operation. Your application must set {@link android.graphics.Point#x} to the
15266         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15267         */
15268        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15269            final View view = mView.get();
15270            if (view != null) {
15271                shadowSize.set(view.getWidth(), view.getHeight());
15272                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15273            } else {
15274                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15275            }
15276        }
15277
15278        /**
15279         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15280         * based on the dimensions it received from the
15281         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15282         *
15283         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15284         */
15285        public void onDrawShadow(Canvas canvas) {
15286            final View view = mView.get();
15287            if (view != null) {
15288                view.draw(canvas);
15289            } else {
15290                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15291            }
15292        }
15293    }
15294
15295    /**
15296     * Starts a drag and drop operation. When your application calls this method, it passes a
15297     * {@link android.view.View.DragShadowBuilder} object to the system. The
15298     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15299     * to get metrics for the drag shadow, and then calls the object's
15300     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15301     * <p>
15302     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15303     *  drag events to all the View objects in your application that are currently visible. It does
15304     *  this either by calling the View object's drag listener (an implementation of
15305     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15306     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15307     *  Both are passed a {@link android.view.DragEvent} object that has a
15308     *  {@link android.view.DragEvent#getAction()} value of
15309     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15310     * </p>
15311     * <p>
15312     * Your application can invoke startDrag() on any attached View object. The View object does not
15313     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15314     * be related to the View the user selected for dragging.
15315     * </p>
15316     * @param data A {@link android.content.ClipData} object pointing to the data to be
15317     * transferred by the drag and drop operation.
15318     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15319     * drag shadow.
15320     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15321     * drop operation. This Object is put into every DragEvent object sent by the system during the
15322     * current drag.
15323     * <p>
15324     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15325     * to the target Views. For example, it can contain flags that differentiate between a
15326     * a copy operation and a move operation.
15327     * </p>
15328     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15329     * so the parameter should be set to 0.
15330     * @return {@code true} if the method completes successfully, or
15331     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15332     * do a drag, and so no drag operation is in progress.
15333     */
15334    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15335            Object myLocalState, int flags) {
15336        if (ViewDebug.DEBUG_DRAG) {
15337            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15338        }
15339        boolean okay = false;
15340
15341        Point shadowSize = new Point();
15342        Point shadowTouchPoint = new Point();
15343        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15344
15345        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15346                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15347            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15348        }
15349
15350        if (ViewDebug.DEBUG_DRAG) {
15351            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15352                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15353        }
15354        Surface surface = new Surface();
15355        try {
15356            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15357                    flags, shadowSize.x, shadowSize.y, surface);
15358            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15359                    + " surface=" + surface);
15360            if (token != null) {
15361                Canvas canvas = surface.lockCanvas(null);
15362                try {
15363                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15364                    shadowBuilder.onDrawShadow(canvas);
15365                } finally {
15366                    surface.unlockCanvasAndPost(canvas);
15367                }
15368
15369                final ViewRootImpl root = getViewRootImpl();
15370
15371                // Cache the local state object for delivery with DragEvents
15372                root.setLocalDragState(myLocalState);
15373
15374                // repurpose 'shadowSize' for the last touch point
15375                root.getLastTouchPoint(shadowSize);
15376
15377                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15378                        shadowSize.x, shadowSize.y,
15379                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15380                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15381
15382                // Off and running!  Release our local surface instance; the drag
15383                // shadow surface is now managed by the system process.
15384                surface.release();
15385            }
15386        } catch (Exception e) {
15387            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15388            surface.destroy();
15389        }
15390
15391        return okay;
15392    }
15393
15394    /**
15395     * Handles drag events sent by the system following a call to
15396     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15397     *<p>
15398     * When the system calls this method, it passes a
15399     * {@link android.view.DragEvent} object. A call to
15400     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15401     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15402     * operation.
15403     * @param event The {@link android.view.DragEvent} sent by the system.
15404     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15405     * in DragEvent, indicating the type of drag event represented by this object.
15406     * @return {@code true} if the method was successful, otherwise {@code false}.
15407     * <p>
15408     *  The method should return {@code true} in response to an action type of
15409     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15410     *  operation.
15411     * </p>
15412     * <p>
15413     *  The method should also return {@code true} in response to an action type of
15414     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15415     *  {@code false} if it didn't.
15416     * </p>
15417     */
15418    public boolean onDragEvent(DragEvent event) {
15419        return false;
15420    }
15421
15422    /**
15423     * Detects if this View is enabled and has a drag event listener.
15424     * If both are true, then it calls the drag event listener with the
15425     * {@link android.view.DragEvent} it received. If the drag event listener returns
15426     * {@code true}, then dispatchDragEvent() returns {@code true}.
15427     * <p>
15428     * For all other cases, the method calls the
15429     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15430     * method and returns its result.
15431     * </p>
15432     * <p>
15433     * This ensures that a drag event is always consumed, even if the View does not have a drag
15434     * event listener. However, if the View has a listener and the listener returns true, then
15435     * onDragEvent() is not called.
15436     * </p>
15437     */
15438    public boolean dispatchDragEvent(DragEvent event) {
15439        //noinspection SimplifiableIfStatement
15440        ListenerInfo li = mListenerInfo;
15441        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15442                && li.mOnDragListener.onDrag(this, event)) {
15443            return true;
15444        }
15445        return onDragEvent(event);
15446    }
15447
15448    boolean canAcceptDrag() {
15449        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15450    }
15451
15452    /**
15453     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15454     * it is ever exposed at all.
15455     * @hide
15456     */
15457    public void onCloseSystemDialogs(String reason) {
15458    }
15459
15460    /**
15461     * Given a Drawable whose bounds have been set to draw into this view,
15462     * update a Region being computed for
15463     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15464     * that any non-transparent parts of the Drawable are removed from the
15465     * given transparent region.
15466     *
15467     * @param dr The Drawable whose transparency is to be applied to the region.
15468     * @param region A Region holding the current transparency information,
15469     * where any parts of the region that are set are considered to be
15470     * transparent.  On return, this region will be modified to have the
15471     * transparency information reduced by the corresponding parts of the
15472     * Drawable that are not transparent.
15473     * {@hide}
15474     */
15475    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15476        if (DBG) {
15477            Log.i("View", "Getting transparent region for: " + this);
15478        }
15479        final Region r = dr.getTransparentRegion();
15480        final Rect db = dr.getBounds();
15481        final AttachInfo attachInfo = mAttachInfo;
15482        if (r != null && attachInfo != null) {
15483            final int w = getRight()-getLeft();
15484            final int h = getBottom()-getTop();
15485            if (db.left > 0) {
15486                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15487                r.op(0, 0, db.left, h, Region.Op.UNION);
15488            }
15489            if (db.right < w) {
15490                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15491                r.op(db.right, 0, w, h, Region.Op.UNION);
15492            }
15493            if (db.top > 0) {
15494                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15495                r.op(0, 0, w, db.top, Region.Op.UNION);
15496            }
15497            if (db.bottom < h) {
15498                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15499                r.op(0, db.bottom, w, h, Region.Op.UNION);
15500            }
15501            final int[] location = attachInfo.mTransparentLocation;
15502            getLocationInWindow(location);
15503            r.translate(location[0], location[1]);
15504            region.op(r, Region.Op.INTERSECT);
15505        } else {
15506            region.op(db, Region.Op.DIFFERENCE);
15507        }
15508    }
15509
15510    private void checkForLongClick(int delayOffset) {
15511        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15512            mHasPerformedLongPress = false;
15513
15514            if (mPendingCheckForLongPress == null) {
15515                mPendingCheckForLongPress = new CheckForLongPress();
15516            }
15517            mPendingCheckForLongPress.rememberWindowAttachCount();
15518            postDelayed(mPendingCheckForLongPress,
15519                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15520        }
15521    }
15522
15523    /**
15524     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15525     * LayoutInflater} class, which provides a full range of options for view inflation.
15526     *
15527     * @param context The Context object for your activity or application.
15528     * @param resource The resource ID to inflate
15529     * @param root A view group that will be the parent.  Used to properly inflate the
15530     * layout_* parameters.
15531     * @see LayoutInflater
15532     */
15533    public static View inflate(Context context, int resource, ViewGroup root) {
15534        LayoutInflater factory = LayoutInflater.from(context);
15535        return factory.inflate(resource, root);
15536    }
15537
15538    /**
15539     * Scroll the view with standard behavior for scrolling beyond the normal
15540     * content boundaries. Views that call this method should override
15541     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15542     * results of an over-scroll operation.
15543     *
15544     * Views can use this method to handle any touch or fling-based scrolling.
15545     *
15546     * @param deltaX Change in X in pixels
15547     * @param deltaY Change in Y in pixels
15548     * @param scrollX Current X scroll value in pixels before applying deltaX
15549     * @param scrollY Current Y scroll value in pixels before applying deltaY
15550     * @param scrollRangeX Maximum content scroll range along the X axis
15551     * @param scrollRangeY Maximum content scroll range along the Y axis
15552     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15553     *          along the X axis.
15554     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15555     *          along the Y axis.
15556     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15557     * @return true if scrolling was clamped to an over-scroll boundary along either
15558     *          axis, false otherwise.
15559     */
15560    @SuppressWarnings({"UnusedParameters"})
15561    protected boolean overScrollBy(int deltaX, int deltaY,
15562            int scrollX, int scrollY,
15563            int scrollRangeX, int scrollRangeY,
15564            int maxOverScrollX, int maxOverScrollY,
15565            boolean isTouchEvent) {
15566        final int overScrollMode = mOverScrollMode;
15567        final boolean canScrollHorizontal =
15568                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15569        final boolean canScrollVertical =
15570                computeVerticalScrollRange() > computeVerticalScrollExtent();
15571        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15572                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15573        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15574                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15575
15576        int newScrollX = scrollX + deltaX;
15577        if (!overScrollHorizontal) {
15578            maxOverScrollX = 0;
15579        }
15580
15581        int newScrollY = scrollY + deltaY;
15582        if (!overScrollVertical) {
15583            maxOverScrollY = 0;
15584        }
15585
15586        // Clamp values if at the limits and record
15587        final int left = -maxOverScrollX;
15588        final int right = maxOverScrollX + scrollRangeX;
15589        final int top = -maxOverScrollY;
15590        final int bottom = maxOverScrollY + scrollRangeY;
15591
15592        boolean clampedX = false;
15593        if (newScrollX > right) {
15594            newScrollX = right;
15595            clampedX = true;
15596        } else if (newScrollX < left) {
15597            newScrollX = left;
15598            clampedX = true;
15599        }
15600
15601        boolean clampedY = false;
15602        if (newScrollY > bottom) {
15603            newScrollY = bottom;
15604            clampedY = true;
15605        } else if (newScrollY < top) {
15606            newScrollY = top;
15607            clampedY = true;
15608        }
15609
15610        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15611
15612        return clampedX || clampedY;
15613    }
15614
15615    /**
15616     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15617     * respond to the results of an over-scroll operation.
15618     *
15619     * @param scrollX New X scroll value in pixels
15620     * @param scrollY New Y scroll value in pixels
15621     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15622     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15623     */
15624    protected void onOverScrolled(int scrollX, int scrollY,
15625            boolean clampedX, boolean clampedY) {
15626        // Intentionally empty.
15627    }
15628
15629    /**
15630     * Returns the over-scroll mode for this view. The result will be
15631     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15632     * (allow over-scrolling only if the view content is larger than the container),
15633     * or {@link #OVER_SCROLL_NEVER}.
15634     *
15635     * @return This view's over-scroll mode.
15636     */
15637    public int getOverScrollMode() {
15638        return mOverScrollMode;
15639    }
15640
15641    /**
15642     * Set the over-scroll mode for this view. Valid over-scroll modes are
15643     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15644     * (allow over-scrolling only if the view content is larger than the container),
15645     * or {@link #OVER_SCROLL_NEVER}.
15646     *
15647     * Setting the over-scroll mode of a view will have an effect only if the
15648     * view is capable of scrolling.
15649     *
15650     * @param overScrollMode The new over-scroll mode for this view.
15651     */
15652    public void setOverScrollMode(int overScrollMode) {
15653        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15654                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15655                overScrollMode != OVER_SCROLL_NEVER) {
15656            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15657        }
15658        mOverScrollMode = overScrollMode;
15659    }
15660
15661    /**
15662     * Gets a scale factor that determines the distance the view should scroll
15663     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15664     * @return The vertical scroll scale factor.
15665     * @hide
15666     */
15667    protected float getVerticalScrollFactor() {
15668        if (mVerticalScrollFactor == 0) {
15669            TypedValue outValue = new TypedValue();
15670            if (!mContext.getTheme().resolveAttribute(
15671                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15672                throw new IllegalStateException(
15673                        "Expected theme to define listPreferredItemHeight.");
15674            }
15675            mVerticalScrollFactor = outValue.getDimension(
15676                    mContext.getResources().getDisplayMetrics());
15677        }
15678        return mVerticalScrollFactor;
15679    }
15680
15681    /**
15682     * Gets a scale factor that determines the distance the view should scroll
15683     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15684     * @return The horizontal scroll scale factor.
15685     * @hide
15686     */
15687    protected float getHorizontalScrollFactor() {
15688        // TODO: Should use something else.
15689        return getVerticalScrollFactor();
15690    }
15691
15692    /**
15693     * Return the value specifying the text direction or policy that was set with
15694     * {@link #setTextDirection(int)}.
15695     *
15696     * @return the defined text direction. It can be one of:
15697     *
15698     * {@link #TEXT_DIRECTION_INHERIT},
15699     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15700     * {@link #TEXT_DIRECTION_ANY_RTL},
15701     * {@link #TEXT_DIRECTION_LTR},
15702     * {@link #TEXT_DIRECTION_RTL},
15703     * {@link #TEXT_DIRECTION_LOCALE}
15704     */
15705    @ViewDebug.ExportedProperty(category = "text", mapping = {
15706            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15707            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15708            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15709            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15710            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15711            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15712    })
15713    public int getTextDirection() {
15714        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15715    }
15716
15717    /**
15718     * Set the text direction.
15719     *
15720     * @param textDirection the direction to set. Should be one of:
15721     *
15722     * {@link #TEXT_DIRECTION_INHERIT},
15723     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15724     * {@link #TEXT_DIRECTION_ANY_RTL},
15725     * {@link #TEXT_DIRECTION_LTR},
15726     * {@link #TEXT_DIRECTION_RTL},
15727     * {@link #TEXT_DIRECTION_LOCALE}
15728     */
15729    public void setTextDirection(int textDirection) {
15730        if (getTextDirection() != textDirection) {
15731            // Reset the current text direction and the resolved one
15732            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
15733            resetResolvedTextDirection();
15734            // Set the new text direction
15735            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
15736            // Refresh
15737            requestLayout();
15738            invalidate(true);
15739        }
15740    }
15741
15742    /**
15743     * Return the resolved text direction.
15744     *
15745     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
15746     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
15747     * up the parent chain of the view. if there is no parent, then it will return the default
15748     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
15749     *
15750     * @return the resolved text direction. Returns one of:
15751     *
15752     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15753     * {@link #TEXT_DIRECTION_ANY_RTL},
15754     * {@link #TEXT_DIRECTION_LTR},
15755     * {@link #TEXT_DIRECTION_RTL},
15756     * {@link #TEXT_DIRECTION_LOCALE}
15757     */
15758    public int getResolvedTextDirection() {
15759        // The text direction will be resolved only if needed
15760        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
15761            resolveTextDirection();
15762        }
15763        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
15764    }
15765
15766    /**
15767     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
15768     * resolution is done.
15769     */
15770    public void resolveTextDirection() {
15771        // Reset any previous text direction resolution
15772        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15773
15774        if (hasRtlSupport()) {
15775            // Set resolved text direction flag depending on text direction flag
15776            final int textDirection = getTextDirection();
15777            switch(textDirection) {
15778                case TEXT_DIRECTION_INHERIT:
15779                    if (canResolveTextDirection()) {
15780                        ViewGroup viewGroup = ((ViewGroup) mParent);
15781
15782                        // Set current resolved direction to the same value as the parent's one
15783                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
15784                        switch (parentResolvedDirection) {
15785                            case TEXT_DIRECTION_FIRST_STRONG:
15786                            case TEXT_DIRECTION_ANY_RTL:
15787                            case TEXT_DIRECTION_LTR:
15788                            case TEXT_DIRECTION_RTL:
15789                            case TEXT_DIRECTION_LOCALE:
15790                                mPrivateFlags2 |=
15791                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15792                                break;
15793                            default:
15794                                // Default resolved direction is "first strong" heuristic
15795                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15796                        }
15797                    } else {
15798                        // We cannot do the resolution if there is no parent, so use the default one
15799                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15800                    }
15801                    break;
15802                case TEXT_DIRECTION_FIRST_STRONG:
15803                case TEXT_DIRECTION_ANY_RTL:
15804                case TEXT_DIRECTION_LTR:
15805                case TEXT_DIRECTION_RTL:
15806                case TEXT_DIRECTION_LOCALE:
15807                    // Resolved direction is the same as text direction
15808                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15809                    break;
15810                default:
15811                    // Default resolved direction is "first strong" heuristic
15812                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15813            }
15814        } else {
15815            // Default resolved direction is "first strong" heuristic
15816            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15817        }
15818
15819        // Set to resolved
15820        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
15821        onResolvedTextDirectionChanged();
15822    }
15823
15824    /**
15825     * Called when text direction has been resolved. Subclasses that care about text direction
15826     * resolution should override this method.
15827     *
15828     * The default implementation does nothing.
15829     */
15830    public void onResolvedTextDirectionChanged() {
15831    }
15832
15833    /**
15834     * Check if text direction resolution can be done.
15835     *
15836     * @return true if text direction resolution can be done otherwise return false.
15837     */
15838    public boolean canResolveTextDirection() {
15839        switch (getTextDirection()) {
15840            case TEXT_DIRECTION_INHERIT:
15841                return (mParent != null) && (mParent instanceof ViewGroup);
15842            default:
15843                return true;
15844        }
15845    }
15846
15847    /**
15848     * Reset resolved text direction. Text direction can be resolved with a call to
15849     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
15850     * reset is done.
15851     */
15852    public void resetResolvedTextDirection() {
15853        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15854        onResolvedTextDirectionReset();
15855    }
15856
15857    /**
15858     * Called when text direction is reset. Subclasses that care about text direction reset should
15859     * override this method and do a reset of the text direction of their children. The default
15860     * implementation does nothing.
15861     */
15862    public void onResolvedTextDirectionReset() {
15863    }
15864
15865    /**
15866     * Return the value specifying the text alignment or policy that was set with
15867     * {@link #setTextAlignment(int)}.
15868     *
15869     * @return the defined text alignment. It can be one of:
15870     *
15871     * {@link #TEXT_ALIGNMENT_INHERIT},
15872     * {@link #TEXT_ALIGNMENT_GRAVITY},
15873     * {@link #TEXT_ALIGNMENT_CENTER},
15874     * {@link #TEXT_ALIGNMENT_TEXT_START},
15875     * {@link #TEXT_ALIGNMENT_TEXT_END},
15876     * {@link #TEXT_ALIGNMENT_VIEW_START},
15877     * {@link #TEXT_ALIGNMENT_VIEW_END}
15878     */
15879    @ViewDebug.ExportedProperty(category = "text", mapping = {
15880            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15881            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15882            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15883            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15884            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15885            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15886            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15887    })
15888    public int getTextAlignment() {
15889        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
15890    }
15891
15892    /**
15893     * Set the text alignment.
15894     *
15895     * @param textAlignment The text alignment to set. Should be one of
15896     *
15897     * {@link #TEXT_ALIGNMENT_INHERIT},
15898     * {@link #TEXT_ALIGNMENT_GRAVITY},
15899     * {@link #TEXT_ALIGNMENT_CENTER},
15900     * {@link #TEXT_ALIGNMENT_TEXT_START},
15901     * {@link #TEXT_ALIGNMENT_TEXT_END},
15902     * {@link #TEXT_ALIGNMENT_VIEW_START},
15903     * {@link #TEXT_ALIGNMENT_VIEW_END}
15904     *
15905     * @attr ref android.R.styleable#View_textAlignment
15906     */
15907    public void setTextAlignment(int textAlignment) {
15908        if (textAlignment != getTextAlignment()) {
15909            // Reset the current and resolved text alignment
15910            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
15911            resetResolvedTextAlignment();
15912            // Set the new text alignment
15913            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
15914            // Refresh
15915            requestLayout();
15916            invalidate(true);
15917        }
15918    }
15919
15920    /**
15921     * Return the resolved text alignment.
15922     *
15923     * The resolved text alignment. This needs resolution if the value is
15924     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
15925     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
15926     *
15927     * @return the resolved text alignment. Returns one of:
15928     *
15929     * {@link #TEXT_ALIGNMENT_GRAVITY},
15930     * {@link #TEXT_ALIGNMENT_CENTER},
15931     * {@link #TEXT_ALIGNMENT_TEXT_START},
15932     * {@link #TEXT_ALIGNMENT_TEXT_END},
15933     * {@link #TEXT_ALIGNMENT_VIEW_START},
15934     * {@link #TEXT_ALIGNMENT_VIEW_END}
15935     */
15936    @ViewDebug.ExportedProperty(category = "text", mapping = {
15937            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15938            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15939            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15940            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15941            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15942            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15943            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15944    })
15945    public int getResolvedTextAlignment() {
15946        // If text alignment is not resolved, then resolve it
15947        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
15948            resolveTextAlignment();
15949        }
15950        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
15951    }
15952
15953    /**
15954     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
15955     * resolution is done.
15956     */
15957    public void resolveTextAlignment() {
15958        // Reset any previous text alignment resolution
15959        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
15960
15961        if (hasRtlSupport()) {
15962            // Set resolved text alignment flag depending on text alignment flag
15963            final int textAlignment = getTextAlignment();
15964            switch (textAlignment) {
15965                case TEXT_ALIGNMENT_INHERIT:
15966                    // Check if we can resolve the text alignment
15967                    if (canResolveLayoutDirection() && mParent instanceof View) {
15968                        View view = (View) mParent;
15969
15970                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
15971                        switch (parentResolvedTextAlignment) {
15972                            case TEXT_ALIGNMENT_GRAVITY:
15973                            case TEXT_ALIGNMENT_TEXT_START:
15974                            case TEXT_ALIGNMENT_TEXT_END:
15975                            case TEXT_ALIGNMENT_CENTER:
15976                            case TEXT_ALIGNMENT_VIEW_START:
15977                            case TEXT_ALIGNMENT_VIEW_END:
15978                                // Resolved text alignment is the same as the parent resolved
15979                                // text alignment
15980                                mPrivateFlags2 |=
15981                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
15982                                break;
15983                            default:
15984                                // Use default resolved text alignment
15985                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15986                        }
15987                    }
15988                    else {
15989                        // We cannot do the resolution if there is no parent so use the default
15990                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15991                    }
15992                    break;
15993                case TEXT_ALIGNMENT_GRAVITY:
15994                case TEXT_ALIGNMENT_TEXT_START:
15995                case TEXT_ALIGNMENT_TEXT_END:
15996                case TEXT_ALIGNMENT_CENTER:
15997                case TEXT_ALIGNMENT_VIEW_START:
15998                case TEXT_ALIGNMENT_VIEW_END:
15999                    // Resolved text alignment is the same as text alignment
16000                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16001                    break;
16002                default:
16003                    // Use default resolved text alignment
16004                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16005            }
16006        } else {
16007            // Use default resolved text alignment
16008            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16009        }
16010
16011        // Set the resolved
16012        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16013        onResolvedTextAlignmentChanged();
16014    }
16015
16016    /**
16017     * Check if text alignment resolution can be done.
16018     *
16019     * @return true if text alignment resolution can be done otherwise return false.
16020     */
16021    public boolean canResolveTextAlignment() {
16022        switch (getTextAlignment()) {
16023            case TEXT_DIRECTION_INHERIT:
16024                return (mParent != null);
16025            default:
16026                return true;
16027        }
16028    }
16029
16030    /**
16031     * Called when text alignment has been resolved. Subclasses that care about text alignment
16032     * resolution should override this method.
16033     *
16034     * The default implementation does nothing.
16035     */
16036    public void onResolvedTextAlignmentChanged() {
16037    }
16038
16039    /**
16040     * Reset resolved text alignment. Text alignment can be resolved with a call to
16041     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16042     * reset is done.
16043     */
16044    public void resetResolvedTextAlignment() {
16045        // Reset any previous text alignment resolution
16046        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16047        onResolvedTextAlignmentReset();
16048    }
16049
16050    /**
16051     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16052     * override this method and do a reset of the text alignment of their children. The default
16053     * implementation does nothing.
16054     */
16055    public void onResolvedTextAlignmentReset() {
16056    }
16057
16058    //
16059    // Properties
16060    //
16061    /**
16062     * A Property wrapper around the <code>alpha</code> functionality handled by the
16063     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16064     */
16065    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16066        @Override
16067        public void setValue(View object, float value) {
16068            object.setAlpha(value);
16069        }
16070
16071        @Override
16072        public Float get(View object) {
16073            return object.getAlpha();
16074        }
16075    };
16076
16077    /**
16078     * A Property wrapper around the <code>translationX</code> functionality handled by the
16079     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16080     */
16081    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16082        @Override
16083        public void setValue(View object, float value) {
16084            object.setTranslationX(value);
16085        }
16086
16087                @Override
16088        public Float get(View object) {
16089            return object.getTranslationX();
16090        }
16091    };
16092
16093    /**
16094     * A Property wrapper around the <code>translationY</code> functionality handled by the
16095     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16096     */
16097    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16098        @Override
16099        public void setValue(View object, float value) {
16100            object.setTranslationY(value);
16101        }
16102
16103        @Override
16104        public Float get(View object) {
16105            return object.getTranslationY();
16106        }
16107    };
16108
16109    /**
16110     * A Property wrapper around the <code>x</code> functionality handled by the
16111     * {@link View#setX(float)} and {@link View#getX()} methods.
16112     */
16113    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16114        @Override
16115        public void setValue(View object, float value) {
16116            object.setX(value);
16117        }
16118
16119        @Override
16120        public Float get(View object) {
16121            return object.getX();
16122        }
16123    };
16124
16125    /**
16126     * A Property wrapper around the <code>y</code> functionality handled by the
16127     * {@link View#setY(float)} and {@link View#getY()} methods.
16128     */
16129    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16130        @Override
16131        public void setValue(View object, float value) {
16132            object.setY(value);
16133        }
16134
16135        @Override
16136        public Float get(View object) {
16137            return object.getY();
16138        }
16139    };
16140
16141    /**
16142     * A Property wrapper around the <code>rotation</code> functionality handled by the
16143     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16144     */
16145    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16146        @Override
16147        public void setValue(View object, float value) {
16148            object.setRotation(value);
16149        }
16150
16151        @Override
16152        public Float get(View object) {
16153            return object.getRotation();
16154        }
16155    };
16156
16157    /**
16158     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16159     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16160     */
16161    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16162        @Override
16163        public void setValue(View object, float value) {
16164            object.setRotationX(value);
16165        }
16166
16167        @Override
16168        public Float get(View object) {
16169            return object.getRotationX();
16170        }
16171    };
16172
16173    /**
16174     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16175     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16176     */
16177    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16178        @Override
16179        public void setValue(View object, float value) {
16180            object.setRotationY(value);
16181        }
16182
16183        @Override
16184        public Float get(View object) {
16185            return object.getRotationY();
16186        }
16187    };
16188
16189    /**
16190     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16191     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16192     */
16193    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16194        @Override
16195        public void setValue(View object, float value) {
16196            object.setScaleX(value);
16197        }
16198
16199        @Override
16200        public Float get(View object) {
16201            return object.getScaleX();
16202        }
16203    };
16204
16205    /**
16206     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16207     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16208     */
16209    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16210        @Override
16211        public void setValue(View object, float value) {
16212            object.setScaleY(value);
16213        }
16214
16215        @Override
16216        public Float get(View object) {
16217            return object.getScaleY();
16218        }
16219    };
16220
16221    /**
16222     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16223     * Each MeasureSpec represents a requirement for either the width or the height.
16224     * A MeasureSpec is comprised of a size and a mode. There are three possible
16225     * modes:
16226     * <dl>
16227     * <dt>UNSPECIFIED</dt>
16228     * <dd>
16229     * The parent has not imposed any constraint on the child. It can be whatever size
16230     * it wants.
16231     * </dd>
16232     *
16233     * <dt>EXACTLY</dt>
16234     * <dd>
16235     * The parent has determined an exact size for the child. The child is going to be
16236     * given those bounds regardless of how big it wants to be.
16237     * </dd>
16238     *
16239     * <dt>AT_MOST</dt>
16240     * <dd>
16241     * The child can be as large as it wants up to the specified size.
16242     * </dd>
16243     * </dl>
16244     *
16245     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16246     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16247     */
16248    public static class MeasureSpec {
16249        private static final int MODE_SHIFT = 30;
16250        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16251
16252        /**
16253         * Measure specification mode: The parent has not imposed any constraint
16254         * on the child. It can be whatever size it wants.
16255         */
16256        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16257
16258        /**
16259         * Measure specification mode: The parent has determined an exact size
16260         * for the child. The child is going to be given those bounds regardless
16261         * of how big it wants to be.
16262         */
16263        public static final int EXACTLY     = 1 << MODE_SHIFT;
16264
16265        /**
16266         * Measure specification mode: The child can be as large as it wants up
16267         * to the specified size.
16268         */
16269        public static final int AT_MOST     = 2 << MODE_SHIFT;
16270
16271        /**
16272         * Creates a measure specification based on the supplied size and mode.
16273         *
16274         * The mode must always be one of the following:
16275         * <ul>
16276         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16277         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16278         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16279         * </ul>
16280         *
16281         * @param size the size of the measure specification
16282         * @param mode the mode of the measure specification
16283         * @return the measure specification based on size and mode
16284         */
16285        public static int makeMeasureSpec(int size, int mode) {
16286            return size + mode;
16287        }
16288
16289        /**
16290         * Extracts the mode from the supplied measure specification.
16291         *
16292         * @param measureSpec the measure specification to extract the mode from
16293         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16294         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16295         *         {@link android.view.View.MeasureSpec#EXACTLY}
16296         */
16297        public static int getMode(int measureSpec) {
16298            return (measureSpec & MODE_MASK);
16299        }
16300
16301        /**
16302         * Extracts the size from the supplied measure specification.
16303         *
16304         * @param measureSpec the measure specification to extract the size from
16305         * @return the size in pixels defined in the supplied measure specification
16306         */
16307        public static int getSize(int measureSpec) {
16308            return (measureSpec & ~MODE_MASK);
16309        }
16310
16311        /**
16312         * Returns a String representation of the specified measure
16313         * specification.
16314         *
16315         * @param measureSpec the measure specification to convert to a String
16316         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16317         */
16318        public static String toString(int measureSpec) {
16319            int mode = getMode(measureSpec);
16320            int size = getSize(measureSpec);
16321
16322            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16323
16324            if (mode == UNSPECIFIED)
16325                sb.append("UNSPECIFIED ");
16326            else if (mode == EXACTLY)
16327                sb.append("EXACTLY ");
16328            else if (mode == AT_MOST)
16329                sb.append("AT_MOST ");
16330            else
16331                sb.append(mode).append(" ");
16332
16333            sb.append(size);
16334            return sb.toString();
16335        }
16336    }
16337
16338    class CheckForLongPress implements Runnable {
16339
16340        private int mOriginalWindowAttachCount;
16341
16342        public void run() {
16343            if (isPressed() && (mParent != null)
16344                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16345                if (performLongClick()) {
16346                    mHasPerformedLongPress = true;
16347                }
16348            }
16349        }
16350
16351        public void rememberWindowAttachCount() {
16352            mOriginalWindowAttachCount = mWindowAttachCount;
16353        }
16354    }
16355
16356    private final class CheckForTap implements Runnable {
16357        public void run() {
16358            mPrivateFlags &= ~PREPRESSED;
16359            setPressed(true);
16360            checkForLongClick(ViewConfiguration.getTapTimeout());
16361        }
16362    }
16363
16364    private final class PerformClick implements Runnable {
16365        public void run() {
16366            performClick();
16367        }
16368    }
16369
16370    /** @hide */
16371    public void hackTurnOffWindowResizeAnim(boolean off) {
16372        mAttachInfo.mTurnOffWindowResizeAnim = off;
16373    }
16374
16375    /**
16376     * This method returns a ViewPropertyAnimator object, which can be used to animate
16377     * specific properties on this View.
16378     *
16379     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16380     */
16381    public ViewPropertyAnimator animate() {
16382        if (mAnimator == null) {
16383            mAnimator = new ViewPropertyAnimator(this);
16384        }
16385        return mAnimator;
16386    }
16387
16388    /**
16389     * Interface definition for a callback to be invoked when a key event is
16390     * dispatched to this view. The callback will be invoked before the key
16391     * event is given to the view.
16392     */
16393    public interface OnKeyListener {
16394        /**
16395         * Called when a key is dispatched to a view. This allows listeners to
16396         * get a chance to respond before the target view.
16397         *
16398         * @param v The view the key has been dispatched to.
16399         * @param keyCode The code for the physical key that was pressed
16400         * @param event The KeyEvent object containing full information about
16401         *        the event.
16402         * @return True if the listener has consumed the event, false otherwise.
16403         */
16404        boolean onKey(View v, int keyCode, KeyEvent event);
16405    }
16406
16407    /**
16408     * Interface definition for a callback to be invoked when a touch event is
16409     * dispatched to this view. The callback will be invoked before the touch
16410     * event is given to the view.
16411     */
16412    public interface OnTouchListener {
16413        /**
16414         * Called when a touch event is dispatched to a view. This allows listeners to
16415         * get a chance to respond before the target view.
16416         *
16417         * @param v The view the touch event has been dispatched to.
16418         * @param event The MotionEvent object containing full information about
16419         *        the event.
16420         * @return True if the listener has consumed the event, false otherwise.
16421         */
16422        boolean onTouch(View v, MotionEvent event);
16423    }
16424
16425    /**
16426     * Interface definition for a callback to be invoked when a hover event is
16427     * dispatched to this view. The callback will be invoked before the hover
16428     * event is given to the view.
16429     */
16430    public interface OnHoverListener {
16431        /**
16432         * Called when a hover event is dispatched to a view. This allows listeners to
16433         * get a chance to respond before the target view.
16434         *
16435         * @param v The view the hover event has been dispatched to.
16436         * @param event The MotionEvent object containing full information about
16437         *        the event.
16438         * @return True if the listener has consumed the event, false otherwise.
16439         */
16440        boolean onHover(View v, MotionEvent event);
16441    }
16442
16443    /**
16444     * Interface definition for a callback to be invoked when a generic motion event is
16445     * dispatched to this view. The callback will be invoked before the generic motion
16446     * event is given to the view.
16447     */
16448    public interface OnGenericMotionListener {
16449        /**
16450         * Called when a generic motion event is dispatched to a view. This allows listeners to
16451         * get a chance to respond before the target view.
16452         *
16453         * @param v The view the generic motion event has been dispatched to.
16454         * @param event The MotionEvent object containing full information about
16455         *        the event.
16456         * @return True if the listener has consumed the event, false otherwise.
16457         */
16458        boolean onGenericMotion(View v, MotionEvent event);
16459    }
16460
16461    /**
16462     * Interface definition for a callback to be invoked when a view has been clicked and held.
16463     */
16464    public interface OnLongClickListener {
16465        /**
16466         * Called when a view has been clicked and held.
16467         *
16468         * @param v The view that was clicked and held.
16469         *
16470         * @return true if the callback consumed the long click, false otherwise.
16471         */
16472        boolean onLongClick(View v);
16473    }
16474
16475    /**
16476     * Interface definition for a callback to be invoked when a drag is being dispatched
16477     * to this view.  The callback will be invoked before the hosting view's own
16478     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16479     * onDrag(event) behavior, it should return 'false' from this callback.
16480     *
16481     * <div class="special reference">
16482     * <h3>Developer Guides</h3>
16483     * <p>For a guide to implementing drag and drop features, read the
16484     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16485     * </div>
16486     */
16487    public interface OnDragListener {
16488        /**
16489         * Called when a drag event is dispatched to a view. This allows listeners
16490         * to get a chance to override base View behavior.
16491         *
16492         * @param v The View that received the drag event.
16493         * @param event The {@link android.view.DragEvent} object for the drag event.
16494         * @return {@code true} if the drag event was handled successfully, or {@code false}
16495         * if the drag event was not handled. Note that {@code false} will trigger the View
16496         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16497         */
16498        boolean onDrag(View v, DragEvent event);
16499    }
16500
16501    /**
16502     * Interface definition for a callback to be invoked when the focus state of
16503     * a view changed.
16504     */
16505    public interface OnFocusChangeListener {
16506        /**
16507         * Called when the focus state of a view has changed.
16508         *
16509         * @param v The view whose state has changed.
16510         * @param hasFocus The new focus state of v.
16511         */
16512        void onFocusChange(View v, boolean hasFocus);
16513    }
16514
16515    /**
16516     * Interface definition for a callback to be invoked when a view is clicked.
16517     */
16518    public interface OnClickListener {
16519        /**
16520         * Called when a view has been clicked.
16521         *
16522         * @param v The view that was clicked.
16523         */
16524        void onClick(View v);
16525    }
16526
16527    /**
16528     * Interface definition for a callback to be invoked when the context menu
16529     * for this view is being built.
16530     */
16531    public interface OnCreateContextMenuListener {
16532        /**
16533         * Called when the context menu for this view is being built. It is not
16534         * safe to hold onto the menu after this method returns.
16535         *
16536         * @param menu The context menu that is being built
16537         * @param v The view for which the context menu is being built
16538         * @param menuInfo Extra information about the item for which the
16539         *            context menu should be shown. This information will vary
16540         *            depending on the class of v.
16541         */
16542        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16543    }
16544
16545    /**
16546     * Interface definition for a callback to be invoked when the status bar changes
16547     * visibility.  This reports <strong>global</strong> changes to the system UI
16548     * state, not just what the application is requesting.
16549     *
16550     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16551     */
16552    public interface OnSystemUiVisibilityChangeListener {
16553        /**
16554         * Called when the status bar changes visibility because of a call to
16555         * {@link View#setSystemUiVisibility(int)}.
16556         *
16557         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16558         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16559         * <strong>global</strong> state of the UI visibility flags, not what your
16560         * app is currently applying.
16561         */
16562        public void onSystemUiVisibilityChange(int visibility);
16563    }
16564
16565    /**
16566     * Interface definition for a callback to be invoked when this view is attached
16567     * or detached from its window.
16568     */
16569    public interface OnAttachStateChangeListener {
16570        /**
16571         * Called when the view is attached to a window.
16572         * @param v The view that was attached
16573         */
16574        public void onViewAttachedToWindow(View v);
16575        /**
16576         * Called when the view is detached from a window.
16577         * @param v The view that was detached
16578         */
16579        public void onViewDetachedFromWindow(View v);
16580    }
16581
16582    private final class UnsetPressedState implements Runnable {
16583        public void run() {
16584            setPressed(false);
16585        }
16586    }
16587
16588    /**
16589     * Base class for derived classes that want to save and restore their own
16590     * state in {@link android.view.View#onSaveInstanceState()}.
16591     */
16592    public static class BaseSavedState extends AbsSavedState {
16593        /**
16594         * Constructor used when reading from a parcel. Reads the state of the superclass.
16595         *
16596         * @param source
16597         */
16598        public BaseSavedState(Parcel source) {
16599            super(source);
16600        }
16601
16602        /**
16603         * Constructor called by derived classes when creating their SavedState objects
16604         *
16605         * @param superState The state of the superclass of this view
16606         */
16607        public BaseSavedState(Parcelable superState) {
16608            super(superState);
16609        }
16610
16611        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16612                new Parcelable.Creator<BaseSavedState>() {
16613            public BaseSavedState createFromParcel(Parcel in) {
16614                return new BaseSavedState(in);
16615            }
16616
16617            public BaseSavedState[] newArray(int size) {
16618                return new BaseSavedState[size];
16619            }
16620        };
16621    }
16622
16623    /**
16624     * A set of information given to a view when it is attached to its parent
16625     * window.
16626     */
16627    static class AttachInfo {
16628        interface Callbacks {
16629            void playSoundEffect(int effectId);
16630            boolean performHapticFeedback(int effectId, boolean always);
16631        }
16632
16633        /**
16634         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16635         * to a Handler. This class contains the target (View) to invalidate and
16636         * the coordinates of the dirty rectangle.
16637         *
16638         * For performance purposes, this class also implements a pool of up to
16639         * POOL_LIMIT objects that get reused. This reduces memory allocations
16640         * whenever possible.
16641         */
16642        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16643            private static final int POOL_LIMIT = 10;
16644            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16645                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16646                        public InvalidateInfo newInstance() {
16647                            return new InvalidateInfo();
16648                        }
16649
16650                        public void onAcquired(InvalidateInfo element) {
16651                        }
16652
16653                        public void onReleased(InvalidateInfo element) {
16654                            element.target = null;
16655                        }
16656                    }, POOL_LIMIT)
16657            );
16658
16659            private InvalidateInfo mNext;
16660            private boolean mIsPooled;
16661
16662            View target;
16663
16664            int left;
16665            int top;
16666            int right;
16667            int bottom;
16668
16669            public void setNextPoolable(InvalidateInfo element) {
16670                mNext = element;
16671            }
16672
16673            public InvalidateInfo getNextPoolable() {
16674                return mNext;
16675            }
16676
16677            static InvalidateInfo acquire() {
16678                return sPool.acquire();
16679            }
16680
16681            void release() {
16682                sPool.release(this);
16683            }
16684
16685            public boolean isPooled() {
16686                return mIsPooled;
16687            }
16688
16689            public void setPooled(boolean isPooled) {
16690                mIsPooled = isPooled;
16691            }
16692        }
16693
16694        final IWindowSession mSession;
16695
16696        final IWindow mWindow;
16697
16698        final IBinder mWindowToken;
16699
16700        final Callbacks mRootCallbacks;
16701
16702        HardwareCanvas mHardwareCanvas;
16703
16704        /**
16705         * The top view of the hierarchy.
16706         */
16707        View mRootView;
16708
16709        IBinder mPanelParentWindowToken;
16710        Surface mSurface;
16711
16712        boolean mHardwareAccelerated;
16713        boolean mHardwareAccelerationRequested;
16714        HardwareRenderer mHardwareRenderer;
16715
16716        boolean mScreenOn;
16717
16718        /**
16719         * Scale factor used by the compatibility mode
16720         */
16721        float mApplicationScale;
16722
16723        /**
16724         * Indicates whether the application is in compatibility mode
16725         */
16726        boolean mScalingRequired;
16727
16728        /**
16729         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
16730         */
16731        boolean mTurnOffWindowResizeAnim;
16732
16733        /**
16734         * Left position of this view's window
16735         */
16736        int mWindowLeft;
16737
16738        /**
16739         * Top position of this view's window
16740         */
16741        int mWindowTop;
16742
16743        /**
16744         * Indicates whether views need to use 32-bit drawing caches
16745         */
16746        boolean mUse32BitDrawingCache;
16747
16748        /**
16749         * For windows that are full-screen but using insets to layout inside
16750         * of the screen decorations, these are the current insets for the
16751         * content of the window.
16752         */
16753        final Rect mContentInsets = new Rect();
16754
16755        /**
16756         * For windows that are full-screen but using insets to layout inside
16757         * of the screen decorations, these are the current insets for the
16758         * actual visible parts of the window.
16759         */
16760        final Rect mVisibleInsets = new Rect();
16761
16762        /**
16763         * The internal insets given by this window.  This value is
16764         * supplied by the client (through
16765         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
16766         * be given to the window manager when changed to be used in laying
16767         * out windows behind it.
16768         */
16769        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
16770                = new ViewTreeObserver.InternalInsetsInfo();
16771
16772        /**
16773         * All views in the window's hierarchy that serve as scroll containers,
16774         * used to determine if the window can be resized or must be panned
16775         * to adjust for a soft input area.
16776         */
16777        final ArrayList<View> mScrollContainers = new ArrayList<View>();
16778
16779        final KeyEvent.DispatcherState mKeyDispatchState
16780                = new KeyEvent.DispatcherState();
16781
16782        /**
16783         * Indicates whether the view's window currently has the focus.
16784         */
16785        boolean mHasWindowFocus;
16786
16787        /**
16788         * The current visibility of the window.
16789         */
16790        int mWindowVisibility;
16791
16792        /**
16793         * Indicates the time at which drawing started to occur.
16794         */
16795        long mDrawingTime;
16796
16797        /**
16798         * Indicates whether or not ignoring the DIRTY_MASK flags.
16799         */
16800        boolean mIgnoreDirtyState;
16801
16802        /**
16803         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
16804         * to avoid clearing that flag prematurely.
16805         */
16806        boolean mSetIgnoreDirtyState = false;
16807
16808        /**
16809         * Indicates whether the view's window is currently in touch mode.
16810         */
16811        boolean mInTouchMode;
16812
16813        /**
16814         * Indicates that ViewAncestor should trigger a global layout change
16815         * the next time it performs a traversal
16816         */
16817        boolean mRecomputeGlobalAttributes;
16818
16819        /**
16820         * Always report new attributes at next traversal.
16821         */
16822        boolean mForceReportNewAttributes;
16823
16824        /**
16825         * Set during a traveral if any views want to keep the screen on.
16826         */
16827        boolean mKeepScreenOn;
16828
16829        /**
16830         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
16831         */
16832        int mSystemUiVisibility;
16833
16834        /**
16835         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
16836         * attached.
16837         */
16838        boolean mHasSystemUiListeners;
16839
16840        /**
16841         * Set if the visibility of any views has changed.
16842         */
16843        boolean mViewVisibilityChanged;
16844
16845        /**
16846         * Set to true if a view has been scrolled.
16847         */
16848        boolean mViewScrollChanged;
16849
16850        /**
16851         * Global to the view hierarchy used as a temporary for dealing with
16852         * x/y points in the transparent region computations.
16853         */
16854        final int[] mTransparentLocation = new int[2];
16855
16856        /**
16857         * Global to the view hierarchy used as a temporary for dealing with
16858         * x/y points in the ViewGroup.invalidateChild implementation.
16859         */
16860        final int[] mInvalidateChildLocation = new int[2];
16861
16862
16863        /**
16864         * Global to the view hierarchy used as a temporary for dealing with
16865         * x/y location when view is transformed.
16866         */
16867        final float[] mTmpTransformLocation = new float[2];
16868
16869        /**
16870         * The view tree observer used to dispatch global events like
16871         * layout, pre-draw, touch mode change, etc.
16872         */
16873        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
16874
16875        /**
16876         * A Canvas used by the view hierarchy to perform bitmap caching.
16877         */
16878        Canvas mCanvas;
16879
16880        /**
16881         * The view root impl.
16882         */
16883        final ViewRootImpl mViewRootImpl;
16884
16885        /**
16886         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
16887         * handler can be used to pump events in the UI events queue.
16888         */
16889        final Handler mHandler;
16890
16891        /**
16892         * Temporary for use in computing invalidate rectangles while
16893         * calling up the hierarchy.
16894         */
16895        final Rect mTmpInvalRect = new Rect();
16896
16897        /**
16898         * Temporary for use in computing hit areas with transformed views
16899         */
16900        final RectF mTmpTransformRect = new RectF();
16901
16902        /**
16903         * Temporary list for use in collecting focusable descendents of a view.
16904         */
16905        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
16906
16907        /**
16908         * The id of the window for accessibility purposes.
16909         */
16910        int mAccessibilityWindowId = View.NO_ID;
16911
16912        /**
16913         * Whether to ingore not exposed for accessibility Views when
16914         * reporting the view tree to accessibility services.
16915         */
16916        boolean mIncludeNotImportantViews;
16917
16918        /**
16919         * The drawable for highlighting accessibility focus.
16920         */
16921        Drawable mAccessibilityFocusDrawable;
16922
16923        /**
16924         * Show where the margins, bounds and layout bounds are for each view.
16925         */
16926        final boolean mDebugLayout = SystemProperties.getBoolean("debug.layout", false);
16927
16928        /**
16929         * Creates a new set of attachment information with the specified
16930         * events handler and thread.
16931         *
16932         * @param handler the events handler the view must use
16933         */
16934        AttachInfo(IWindowSession session, IWindow window,
16935                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
16936            mSession = session;
16937            mWindow = window;
16938            mWindowToken = window.asBinder();
16939            mViewRootImpl = viewRootImpl;
16940            mHandler = handler;
16941            mRootCallbacks = effectPlayer;
16942        }
16943    }
16944
16945    /**
16946     * <p>ScrollabilityCache holds various fields used by a View when scrolling
16947     * is supported. This avoids keeping too many unused fields in most
16948     * instances of View.</p>
16949     */
16950    private static class ScrollabilityCache implements Runnable {
16951
16952        /**
16953         * Scrollbars are not visible
16954         */
16955        public static final int OFF = 0;
16956
16957        /**
16958         * Scrollbars are visible
16959         */
16960        public static final int ON = 1;
16961
16962        /**
16963         * Scrollbars are fading away
16964         */
16965        public static final int FADING = 2;
16966
16967        public boolean fadeScrollBars;
16968
16969        public int fadingEdgeLength;
16970        public int scrollBarDefaultDelayBeforeFade;
16971        public int scrollBarFadeDuration;
16972
16973        public int scrollBarSize;
16974        public ScrollBarDrawable scrollBar;
16975        public float[] interpolatorValues;
16976        public View host;
16977
16978        public final Paint paint;
16979        public final Matrix matrix;
16980        public Shader shader;
16981
16982        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
16983
16984        private static final float[] OPAQUE = { 255 };
16985        private static final float[] TRANSPARENT = { 0.0f };
16986
16987        /**
16988         * When fading should start. This time moves into the future every time
16989         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
16990         */
16991        public long fadeStartTime;
16992
16993
16994        /**
16995         * The current state of the scrollbars: ON, OFF, or FADING
16996         */
16997        public int state = OFF;
16998
16999        private int mLastColor;
17000
17001        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17002            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17003            scrollBarSize = configuration.getScaledScrollBarSize();
17004            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17005            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17006
17007            paint = new Paint();
17008            matrix = new Matrix();
17009            // use use a height of 1, and then wack the matrix each time we
17010            // actually use it.
17011            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17012
17013            paint.setShader(shader);
17014            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17015            this.host = host;
17016        }
17017
17018        public void setFadeColor(int color) {
17019            if (color != 0 && color != mLastColor) {
17020                mLastColor = color;
17021                color |= 0xFF000000;
17022
17023                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17024                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17025
17026                paint.setShader(shader);
17027                // Restore the default transfer mode (src_over)
17028                paint.setXfermode(null);
17029            }
17030        }
17031
17032        public void run() {
17033            long now = AnimationUtils.currentAnimationTimeMillis();
17034            if (now >= fadeStartTime) {
17035
17036                // the animation fades the scrollbars out by changing
17037                // the opacity (alpha) from fully opaque to fully
17038                // transparent
17039                int nextFrame = (int) now;
17040                int framesCount = 0;
17041
17042                Interpolator interpolator = scrollBarInterpolator;
17043
17044                // Start opaque
17045                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17046
17047                // End transparent
17048                nextFrame += scrollBarFadeDuration;
17049                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17050
17051                state = FADING;
17052
17053                // Kick off the fade animation
17054                host.invalidate(true);
17055            }
17056        }
17057    }
17058
17059    /**
17060     * Resuable callback for sending
17061     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17062     */
17063    private class SendViewScrolledAccessibilityEvent implements Runnable {
17064        public volatile boolean mIsPending;
17065
17066        public void run() {
17067            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17068            mIsPending = false;
17069        }
17070    }
17071
17072    /**
17073     * <p>
17074     * This class represents a delegate that can be registered in a {@link View}
17075     * to enhance accessibility support via composition rather via inheritance.
17076     * It is specifically targeted to widget developers that extend basic View
17077     * classes i.e. classes in package android.view, that would like their
17078     * applications to be backwards compatible.
17079     * </p>
17080     * <div class="special reference">
17081     * <h3>Developer Guides</h3>
17082     * <p>For more information about making applications accessible, read the
17083     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17084     * developer guide.</p>
17085     * </div>
17086     * <p>
17087     * A scenario in which a developer would like to use an accessibility delegate
17088     * is overriding a method introduced in a later API version then the minimal API
17089     * version supported by the application. For example, the method
17090     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17091     * in API version 4 when the accessibility APIs were first introduced. If a
17092     * developer would like his application to run on API version 4 devices (assuming
17093     * all other APIs used by the application are version 4 or lower) and take advantage
17094     * of this method, instead of overriding the method which would break the application's
17095     * backwards compatibility, he can override the corresponding method in this
17096     * delegate and register the delegate in the target View if the API version of
17097     * the system is high enough i.e. the API version is same or higher to the API
17098     * version that introduced
17099     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17100     * </p>
17101     * <p>
17102     * Here is an example implementation:
17103     * </p>
17104     * <code><pre><p>
17105     * if (Build.VERSION.SDK_INT >= 14) {
17106     *     // If the API version is equal of higher than the version in
17107     *     // which onInitializeAccessibilityNodeInfo was introduced we
17108     *     // register a delegate with a customized implementation.
17109     *     View view = findViewById(R.id.view_id);
17110     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17111     *         public void onInitializeAccessibilityNodeInfo(View host,
17112     *                 AccessibilityNodeInfo info) {
17113     *             // Let the default implementation populate the info.
17114     *             super.onInitializeAccessibilityNodeInfo(host, info);
17115     *             // Set some other information.
17116     *             info.setEnabled(host.isEnabled());
17117     *         }
17118     *     });
17119     * }
17120     * </code></pre></p>
17121     * <p>
17122     * This delegate contains methods that correspond to the accessibility methods
17123     * in View. If a delegate has been specified the implementation in View hands
17124     * off handling to the corresponding method in this delegate. The default
17125     * implementation the delegate methods behaves exactly as the corresponding
17126     * method in View for the case of no accessibility delegate been set. Hence,
17127     * to customize the behavior of a View method, clients can override only the
17128     * corresponding delegate method without altering the behavior of the rest
17129     * accessibility related methods of the host view.
17130     * </p>
17131     */
17132    public static class AccessibilityDelegate {
17133
17134        /**
17135         * Sends an accessibility event of the given type. If accessibility is not
17136         * enabled this method has no effect.
17137         * <p>
17138         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17139         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17140         * been set.
17141         * </p>
17142         *
17143         * @param host The View hosting the delegate.
17144         * @param eventType The type of the event to send.
17145         *
17146         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17147         */
17148        public void sendAccessibilityEvent(View host, int eventType) {
17149            host.sendAccessibilityEventInternal(eventType);
17150        }
17151
17152        /**
17153         * Sends an accessibility event. This method behaves exactly as
17154         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17155         * empty {@link AccessibilityEvent} and does not perform a check whether
17156         * accessibility is enabled.
17157         * <p>
17158         * The default implementation behaves as
17159         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17160         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17161         * the case of no accessibility delegate been set.
17162         * </p>
17163         *
17164         * @param host The View hosting the delegate.
17165         * @param event The event to send.
17166         *
17167         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17168         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17169         */
17170        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17171            host.sendAccessibilityEventUncheckedInternal(event);
17172        }
17173
17174        /**
17175         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17176         * to its children for adding their text content to the event.
17177         * <p>
17178         * The default implementation behaves as
17179         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17180         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17181         * the case of no accessibility delegate been set.
17182         * </p>
17183         *
17184         * @param host The View hosting the delegate.
17185         * @param event The event.
17186         * @return True if the event population was completed.
17187         *
17188         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17189         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17190         */
17191        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17192            return host.dispatchPopulateAccessibilityEventInternal(event);
17193        }
17194
17195        /**
17196         * Gives a chance to the host View to populate the accessibility event with its
17197         * text content.
17198         * <p>
17199         * The default implementation behaves as
17200         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17201         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17202         * the case of no accessibility delegate been set.
17203         * </p>
17204         *
17205         * @param host The View hosting the delegate.
17206         * @param event The accessibility event which to populate.
17207         *
17208         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17209         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17210         */
17211        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17212            host.onPopulateAccessibilityEventInternal(event);
17213        }
17214
17215        /**
17216         * Initializes an {@link AccessibilityEvent} with information about the
17217         * the host View which is the event source.
17218         * <p>
17219         * The default implementation behaves as
17220         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17221         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17222         * the case of no accessibility delegate been set.
17223         * </p>
17224         *
17225         * @param host The View hosting the delegate.
17226         * @param event The event to initialize.
17227         *
17228         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17229         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17230         */
17231        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17232            host.onInitializeAccessibilityEventInternal(event);
17233        }
17234
17235        /**
17236         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17237         * <p>
17238         * The default implementation behaves as
17239         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17240         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17241         * the case of no accessibility delegate been set.
17242         * </p>
17243         *
17244         * @param host The View hosting the delegate.
17245         * @param info The instance to initialize.
17246         *
17247         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17248         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17249         */
17250        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17251            host.onInitializeAccessibilityNodeInfoInternal(info);
17252        }
17253
17254        /**
17255         * Called when a child of the host View has requested sending an
17256         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17257         * to augment the event.
17258         * <p>
17259         * The default implementation behaves as
17260         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17261         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17262         * the case of no accessibility delegate been set.
17263         * </p>
17264         *
17265         * @param host The View hosting the delegate.
17266         * @param child The child which requests sending the event.
17267         * @param event The event to be sent.
17268         * @return True if the event should be sent
17269         *
17270         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17271         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17272         */
17273        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17274                AccessibilityEvent event) {
17275            return host.onRequestSendAccessibilityEventInternal(child, event);
17276        }
17277
17278        /**
17279         * Gets the provider for managing a virtual view hierarchy rooted at this View
17280         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17281         * that explore the window content.
17282         * <p>
17283         * The default implementation behaves as
17284         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17285         * the case of no accessibility delegate been set.
17286         * </p>
17287         *
17288         * @return The provider.
17289         *
17290         * @see AccessibilityNodeProvider
17291         */
17292        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17293            return null;
17294        }
17295    }
17296}
17297