View.java revision 6d3d5057b445069e73fd06adbc11fa412e7c48c3
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.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.text.TextUtils;
49import android.util.AttributeSet;
50import android.util.FloatProperty;
51import android.util.LocaleUtil;
52import android.util.Log;
53import android.util.Pool;
54import android.util.Poolable;
55import android.util.PoolableManager;
56import android.util.Pools;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.accessibility.AccessibilityNodeProvider;
66import android.view.animation.Animation;
67import android.view.animation.AnimationUtils;
68import android.view.animation.Transformation;
69import android.view.inputmethod.EditorInfo;
70import android.view.inputmethod.InputConnection;
71import android.view.inputmethod.InputMethodManager;
72import android.widget.ScrollBarDrawable;
73
74import static android.os.Build.VERSION_CODES.*;
75
76import com.android.internal.R;
77import com.android.internal.util.Predicate;
78import com.android.internal.view.menu.MenuBuilder;
79
80import java.lang.ref.WeakReference;
81import java.lang.reflect.InvocationTargetException;
82import java.lang.reflect.Method;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Locale;
86import java.util.concurrent.CopyOnWriteArrayList;
87
88/**
89 * <p>
90 * This class represents the basic building block for user interface components. A View
91 * occupies a rectangular area on the screen and is responsible for drawing and
92 * event handling. View is the base class for <em>widgets</em>, which are
93 * used to create interactive UI components (buttons, text fields, etc.). The
94 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
95 * are invisible containers that hold other Views (or other ViewGroups) and define
96 * their layout properties.
97 * </p>
98 *
99 * <div class="special reference">
100 * <h3>Developer Guides</h3>
101 * <p>For information about using this class to develop your application's user interface,
102 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
103 * </div>
104 *
105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
130 * Other view subclasses offer more specialized listeners. For example, a Button
131 * exposes a listener to notify clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility(int)}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 *     <thead>
153 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 *     </thead>
155 *
156 *     <tbody>
157 *     <tr>
158 *         <td rowspan="2">Creation</td>
159 *         <td>Constructors</td>
160 *         <td>There is a form of the constructor that are called when the view
161 *         is created from code and a form that is called when the view is
162 *         inflated from a layout file. The second form should parse and apply
163 *         any attributes defined in the layout file.
164 *         </td>
165 *     </tr>
166 *     <tr>
167 *         <td><code>{@link #onFinishInflate()}</code></td>
168 *         <td>Called after a view and all of its children has been inflated
169 *         from XML.</td>
170 *     </tr>
171 *
172 *     <tr>
173 *         <td rowspan="3">Layout</td>
174 *         <td><code>{@link #onMeasure(int, int)}</code></td>
175 *         <td>Called to determine the size requirements for this view and all
176 *         of its children.
177 *         </td>
178 *     </tr>
179 *     <tr>
180 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
181 *         <td>Called when this view should assign a size and position to all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
187 *         <td>Called when the size of this view has changed.
188 *         </td>
189 *     </tr>
190 *
191 *     <tr>
192 *         <td>Drawing</td>
193 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
194 *         <td>Called when the view should render its content.
195 *         </td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="4">Event processing</td>
200 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
201 *         <td>Called when a new key event occurs.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
206 *         <td>Called when a key up event occurs.
207 *         </td>
208 *     </tr>
209 *     <tr>
210 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
211 *         <td>Called when a trackball motion event occurs.
212 *         </td>
213 *     </tr>
214 *     <tr>
215 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
216 *         <td>Called when a touch screen motion event occurs.
217 *         </td>
218 *     </tr>
219 *
220 *     <tr>
221 *         <td rowspan="2">Focus</td>
222 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
223 *         <td>Called when the view gains or loses focus.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
229 *         <td>Called when the window containing the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td rowspan="3">Attaching</td>
235 *         <td><code>{@link #onAttachedToWindow()}</code></td>
236 *         <td>Called when the view is attached to a window.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td><code>{@link #onDetachedFromWindow}</code></td>
242 *         <td>Called when the view is detached from its window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
248 *         <td>Called when the visibility of the window containing the view
249 *         has changed.
250 *         </td>
251 *     </tr>
252 *     </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
265 * &lt;Button
266 *     android:id="@+id/my_button"
267 *     android:layout_width="wrap_content"
268 *     android:layout_height="wrap_content"
269 *     android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 *      Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} method and queried by calling
341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
343 * </p>
344 *
345 * <p>
346 * Even though a view can define a padding, it does not provide any support for
347 * margins. However, view groups provide such a support. Refer to
348 * {@link android.view.ViewGroup} and
349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
350 * </p>
351 *
352 * <a name="Layout"></a>
353 * <h3>Layout</h3>
354 * <p>
355 * Layout is a two pass process: a measure pass and a layout pass. The measuring
356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
357 * of the view tree. Each view pushes dimension specifications down the tree
358 * during the recursion. At the end of the measure pass, every view has stored
359 * its measurements. The second pass happens in
360 * {@link #layout(int,int,int,int)} and is also top-down. During
361 * this pass each parent is responsible for positioning all of its children
362 * using the sizes computed in the measure pass.
363 * </p>
364 *
365 * <p>
366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
367 * {@link #getMeasuredHeight()} values must be set, along with those for all of
368 * that view's descendants. A view's measured width and measured height values
369 * must respect the constraints imposed by the view's parents. This guarantees
370 * that at the end of the measure pass, all parents accept all of their
371 * children's measurements. A parent view may call measure() more than once on
372 * its children. For example, the parent may measure each child once with
373 * unspecified dimensions to find out how big they want to be, then call
374 * measure() on them again with actual numbers if the sum of all the children's
375 * unconstrained sizes is too big or too small.
376 * </p>
377 *
378 * <p>
379 * The measure pass uses two classes to communicate dimensions. The
380 * {@link MeasureSpec} class is used by views to tell their parents how they
381 * want to be measured and positioned. The base LayoutParams class just
382 * describes how big the view wants to be for both width and height. For each
383 * dimension, it can specify one of:
384 * <ul>
385 * <li> an exact number
386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
387 * (minus padding)
388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
389 * enclose its content (plus padding).
390 * </ul>
391 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
393 * an X and Y value.
394 * </p>
395 *
396 * <p>
397 * MeasureSpecs are used to push requirements down the tree from parent to
398 * child. A MeasureSpec can be in one of three modes:
399 * <ul>
400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
401 * of a child view. For example, a LinearLayout may call measure() on its child
402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
403 * tall the child view wants to be given a width of 240 pixels.
404 * <li>EXACTLY: This is used by the parent to impose an exact size on the
405 * child. The child must use this size, and guarantee that all of its
406 * descendants will fit within this size.
407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
408 * child. The child must gurantee that it and all of its descendants will fit
409 * within this size.
410 * </ul>
411 * </p>
412 *
413 * <p>
414 * To intiate a layout, call {@link #requestLayout}. This method is typically
415 * called by a view on itself when it believes that is can no longer fit within
416 * its current bounds.
417 * </p>
418 *
419 * <a name="Drawing"></a>
420 * <h3>Drawing</h3>
421 * <p>
422 * Drawing is handled by walking the tree and rendering each view that
423 * intersects the invalid region. Because the tree is traversed in-order,
424 * this means that parents will draw before (i.e., behind) their children, with
425 * siblings drawn in the order they appear in the tree.
426 * If you set a background drawable for a View, then the View will draw it for you
427 * before calling back to its <code>onDraw()</code> method.
428 * </p>
429 *
430 * <p>
431 * Note that the framework will not draw views that are not in the invalid region.
432 * </p>
433 *
434 * <p>
435 * To force a view to draw, call {@link #invalidate()}.
436 * </p>
437 *
438 * <a name="EventHandlingThreading"></a>
439 * <h3>Event Handling and Threading</h3>
440 * <p>
441 * The basic cycle of a view is as follows:
442 * <ol>
443 * <li>An event comes in and is dispatched to the appropriate view. The view
444 * handles the event and notifies any listeners.</li>
445 * <li>If in the course of processing the event, the view's bounds may need
446 * to be changed, the view will call {@link #requestLayout()}.</li>
447 * <li>Similarly, if in the course of processing the event the view's appearance
448 * may need to be changed, the view will call {@link #invalidate()}.</li>
449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
450 * the framework will take care of measuring, laying out, and drawing the tree
451 * as appropriate.</li>
452 * </ol>
453 * </p>
454 *
455 * <p><em>Note: The entire view tree is single threaded. You must always be on
456 * the UI thread when calling any method on any view.</em>
457 * If you are doing work on other threads and want to update the state of a view
458 * from that thread, you should use a {@link Handler}.
459 * </p>
460 *
461 * <a name="FocusHandling"></a>
462 * <h3>Focus Handling</h3>
463 * <p>
464 * The framework will handle routine focus movement in response to user input.
465 * This includes changing the focus as views are removed or hidden, or as new
466 * views become available. Views indicate their willingness to take focus
467 * through the {@link #isFocusable} method. To change whether a view can take
468 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
470 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
471 * </p>
472 * <p>
473 * Focus movement is based on an algorithm which finds the nearest neighbor in a
474 * given direction. In rare cases, the default algorithm may not match the
475 * intended behavior of the developer. In these situations, you can provide
476 * explicit overrides by using these XML attributes in the layout file:
477 * <pre>
478 * nextFocusDown
479 * nextFocusLeft
480 * nextFocusRight
481 * nextFocusUp
482 * </pre>
483 * </p>
484 *
485 *
486 * <p>
487 * To get a particular view to take focus, call {@link #requestFocus()}.
488 * </p>
489 *
490 * <a name="TouchMode"></a>
491 * <h3>Touch Mode</h3>
492 * <p>
493 * When a user is navigating a user interface via directional keys such as a D-pad, it is
494 * necessary to give focus to actionable items such as buttons so the user can see
495 * what will take input.  If the device has touch capabilities, however, and the user
496 * begins interacting with the interface by touching it, it is no longer necessary to
497 * always highlight, or give focus to, a particular view.  This motivates a mode
498 * for interaction named 'touch mode'.
499 * </p>
500 * <p>
501 * For a touch capable device, once the user touches the screen, the device
502 * will enter touch mode.  From this point onward, only views for which
503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
504 * Other views that are touchable, like buttons, will not take focus when touched; they will
505 * only fire the on click listeners.
506 * </p>
507 * <p>
508 * Any time a user hits a directional key, such as a D-pad direction, the view device will
509 * exit touch mode, and find a view to take focus, so that the user may resume interacting
510 * with the user interface without touching the screen again.
511 * </p>
512 * <p>
513 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
514 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
515 * </p>
516 *
517 * <a name="Scrolling"></a>
518 * <h3>Scrolling</h3>
519 * <p>
520 * The framework provides basic support for views that wish to internally
521 * scroll their content. This includes keeping track of the X and Y scroll
522 * offset as well as mechanisms for drawing scrollbars. See
523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
524 * {@link #awakenScrollBars()} for more details.
525 * </p>
526 *
527 * <a name="Tags"></a>
528 * <h3>Tags</h3>
529 * <p>
530 * Unlike IDs, tags are not used to identify views. Tags are essentially an
531 * extra piece of information that can be associated with a view. They are most
532 * often used as a convenience to store data related to views in the views
533 * themselves rather than by putting them in a separate structure.
534 * </p>
535 *
536 * <a name="Animation"></a>
537 * <h3>Animation</h3>
538 * <p>
539 * You can attach an {@link Animation} object to a view using
540 * {@link #setAnimation(Animation)} or
541 * {@link #startAnimation(Animation)}. The animation can alter the scale,
542 * rotation, translation and alpha of a view over time. If the animation is
543 * attached to a view that has children, the animation will affect the entire
544 * subtree rooted by that node. When an animation is started, the framework will
545 * take care of redrawing the appropriate views until the animation completes.
546 * </p>
547 * <p>
548 * Starting with Android 3.0, the preferred way of animating views is to use the
549 * {@link android.animation} package APIs.
550 * </p>
551 *
552 * <a name="Security"></a>
553 * <h3>Security</h3>
554 * <p>
555 * Sometimes it is essential that an application be able to verify that an action
556 * is being performed with the full knowledge and consent of the user, such as
557 * granting a permission request, making a purchase or clicking on an advertisement.
558 * Unfortunately, a malicious application could try to spoof the user into
559 * performing these actions, unaware, by concealing the intended purpose of the view.
560 * As a remedy, the framework offers a touch filtering mechanism that can be used to
561 * improve the security of views that provide access to sensitive functionality.
562 * </p><p>
563 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
564 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
565 * will discard touches that are received whenever the view's window is obscured by
566 * another visible window.  As a result, the view will not receive touches whenever a
567 * toast, dialog or other window appears above the view's window.
568 * </p><p>
569 * For more fine-grained control over security, consider overriding the
570 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
571 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
572 * </p>
573 *
574 * @attr ref android.R.styleable#View_alpha
575 * @attr ref android.R.styleable#View_background
576 * @attr ref android.R.styleable#View_clickable
577 * @attr ref android.R.styleable#View_contentDescription
578 * @attr ref android.R.styleable#View_drawingCacheQuality
579 * @attr ref android.R.styleable#View_duplicateParentState
580 * @attr ref android.R.styleable#View_id
581 * @attr ref android.R.styleable#View_requiresFadingEdge
582 * @attr ref android.R.styleable#View_fadingEdgeLength
583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
584 * @attr ref android.R.styleable#View_fitsSystemWindows
585 * @attr ref android.R.styleable#View_isScrollContainer
586 * @attr ref android.R.styleable#View_focusable
587 * @attr ref android.R.styleable#View_focusableInTouchMode
588 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
589 * @attr ref android.R.styleable#View_keepScreenOn
590 * @attr ref android.R.styleable#View_layerType
591 * @attr ref android.R.styleable#View_longClickable
592 * @attr ref android.R.styleable#View_minHeight
593 * @attr ref android.R.styleable#View_minWidth
594 * @attr ref android.R.styleable#View_nextFocusDown
595 * @attr ref android.R.styleable#View_nextFocusLeft
596 * @attr ref android.R.styleable#View_nextFocusRight
597 * @attr ref android.R.styleable#View_nextFocusUp
598 * @attr ref android.R.styleable#View_onClick
599 * @attr ref android.R.styleable#View_padding
600 * @attr ref android.R.styleable#View_paddingBottom
601 * @attr ref android.R.styleable#View_paddingLeft
602 * @attr ref android.R.styleable#View_paddingRight
603 * @attr ref android.R.styleable#View_paddingTop
604 * @attr ref android.R.styleable#View_saveEnabled
605 * @attr ref android.R.styleable#View_rotation
606 * @attr ref android.R.styleable#View_rotationX
607 * @attr ref android.R.styleable#View_rotationY
608 * @attr ref android.R.styleable#View_scaleX
609 * @attr ref android.R.styleable#View_scaleY
610 * @attr ref android.R.styleable#View_scrollX
611 * @attr ref android.R.styleable#View_scrollY
612 * @attr ref android.R.styleable#View_scrollbarSize
613 * @attr ref android.R.styleable#View_scrollbarStyle
614 * @attr ref android.R.styleable#View_scrollbars
615 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
616 * @attr ref android.R.styleable#View_scrollbarFadeDuration
617 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
618 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbVertical
620 * @attr ref android.R.styleable#View_scrollbarTrackVertical
621 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
623 * @attr ref android.R.styleable#View_soundEffectsEnabled
624 * @attr ref android.R.styleable#View_tag
625 * @attr ref android.R.styleable#View_transformPivotX
626 * @attr ref android.R.styleable#View_transformPivotY
627 * @attr ref android.R.styleable#View_translationX
628 * @attr ref android.R.styleable#View_translationY
629 * @attr ref android.R.styleable#View_visibility
630 *
631 * @see android.view.ViewGroup
632 */
633public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
634        AccessibilityEventSource {
635    private static final boolean DBG = false;
636
637    /**
638     * The logging tag used by this class with android.util.Log.
639     */
640    protected static final String VIEW_LOG_TAG = "View";
641
642    /**
643     * Used to mark a View that has no ID.
644     */
645    public static final int NO_ID = -1;
646
647    /**
648     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649     * calling setFlags.
650     */
651    private static final int NOT_FOCUSABLE = 0x00000000;
652
653    /**
654     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655     * setFlags.
656     */
657    private static final int FOCUSABLE = 0x00000001;
658
659    /**
660     * Mask for use with setFlags indicating bits used for focus.
661     */
662    private static final int FOCUSABLE_MASK = 0x00000001;
663
664    /**
665     * This view will adjust its padding to fit sytem windows (e.g. status bar)
666     */
667    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669    /**
670     * This view is visible.
671     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
672     * android:visibility}.
673     */
674    public static final int VISIBLE = 0x00000000;
675
676    /**
677     * This view is invisible, but it still takes up space for layout purposes.
678     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
679     * android:visibility}.
680     */
681    public static final int INVISIBLE = 0x00000004;
682
683    /**
684     * This view is invisible, and it doesn't take any space for layout
685     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
686     * android:visibility}.
687     */
688    public static final int GONE = 0x00000008;
689
690    /**
691     * Mask for use with setFlags indicating bits used for visibility.
692     * {@hide}
693     */
694    static final int VISIBILITY_MASK = 0x0000000C;
695
696    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
697
698    /**
699     * This view is enabled. Intrepretation varies by subclass.
700     * Use with ENABLED_MASK when calling setFlags.
701     * {@hide}
702     */
703    static final int ENABLED = 0x00000000;
704
705    /**
706     * This view is disabled. Intrepretation varies by subclass.
707     * Use with ENABLED_MASK when calling setFlags.
708     * {@hide}
709     */
710    static final int DISABLED = 0x00000020;
711
712   /**
713    * Mask for use with setFlags indicating bits used for indicating whether
714    * this view is enabled
715    * {@hide}
716    */
717    static final int ENABLED_MASK = 0x00000020;
718
719    /**
720     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
721     * called and further optimizations will be performed. It is okay to have
722     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
723     * {@hide}
724     */
725    static final int WILL_NOT_DRAW = 0x00000080;
726
727    /**
728     * Mask for use with setFlags indicating bits used for indicating whether
729     * this view is will draw
730     * {@hide}
731     */
732    static final int DRAW_MASK = 0x00000080;
733
734    /**
735     * <p>This view doesn't show scrollbars.</p>
736     * {@hide}
737     */
738    static final int SCROLLBARS_NONE = 0x00000000;
739
740    /**
741     * <p>This view shows horizontal scrollbars.</p>
742     * {@hide}
743     */
744    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
745
746    /**
747     * <p>This view shows vertical scrollbars.</p>
748     * {@hide}
749     */
750    static final int SCROLLBARS_VERTICAL = 0x00000200;
751
752    /**
753     * <p>Mask for use with setFlags indicating bits used for indicating which
754     * scrollbars are enabled.</p>
755     * {@hide}
756     */
757    static final int SCROLLBARS_MASK = 0x00000300;
758
759    /**
760     * Indicates that the view should filter touches when its window is obscured.
761     * Refer to the class comments for more information about this security feature.
762     * {@hide}
763     */
764    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
765
766    // note flag value 0x00000800 is now available for next flags...
767
768    /**
769     * <p>This view doesn't show fading edges.</p>
770     * {@hide}
771     */
772    static final int FADING_EDGE_NONE = 0x00000000;
773
774    /**
775     * <p>This view shows horizontal fading edges.</p>
776     * {@hide}
777     */
778    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
779
780    /**
781     * <p>This view shows vertical fading edges.</p>
782     * {@hide}
783     */
784    static final int FADING_EDGE_VERTICAL = 0x00002000;
785
786    /**
787     * <p>Mask for use with setFlags indicating bits used for indicating which
788     * fading edges are enabled.</p>
789     * {@hide}
790     */
791    static final int FADING_EDGE_MASK = 0x00003000;
792
793    /**
794     * <p>Indicates this view can be clicked. When clickable, a View reacts
795     * to clicks by notifying the OnClickListener.<p>
796     * {@hide}
797     */
798    static final int CLICKABLE = 0x00004000;
799
800    /**
801     * <p>Indicates this view is caching its drawing into a bitmap.</p>
802     * {@hide}
803     */
804    static final int DRAWING_CACHE_ENABLED = 0x00008000;
805
806    /**
807     * <p>Indicates that no icicle should be saved for this view.<p>
808     * {@hide}
809     */
810    static final int SAVE_DISABLED = 0x000010000;
811
812    /**
813     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
814     * property.</p>
815     * {@hide}
816     */
817    static final int SAVE_DISABLED_MASK = 0x000010000;
818
819    /**
820     * <p>Indicates that no drawing cache should ever be created for this view.<p>
821     * {@hide}
822     */
823    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
824
825    /**
826     * <p>Indicates this view can take / keep focus when int touch mode.</p>
827     * {@hide}
828     */
829    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
830
831    /**
832     * <p>Enables low quality mode for the drawing cache.</p>
833     */
834    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
835
836    /**
837     * <p>Enables high quality mode for the drawing cache.</p>
838     */
839    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
840
841    /**
842     * <p>Enables automatic quality mode for the drawing cache.</p>
843     */
844    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
845
846    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
847            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
848    };
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for the cache
852     * quality property.</p>
853     * {@hide}
854     */
855    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
856
857    /**
858     * <p>
859     * Indicates this view can be long clicked. When long clickable, a View
860     * reacts to long clicks by notifying the OnLongClickListener or showing a
861     * context menu.
862     * </p>
863     * {@hide}
864     */
865    static final int LONG_CLICKABLE = 0x00200000;
866
867    /**
868     * <p>Indicates that this view gets its drawable states from its direct parent
869     * and ignores its original internal states.</p>
870     *
871     * @hide
872     */
873    static final int DUPLICATE_PARENT_STATE = 0x00400000;
874
875    /**
876     * The scrollbar style to display the scrollbars inside the content area,
877     * without increasing the padding. The scrollbars will be overlaid with
878     * translucency on the view's content.
879     */
880    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
881
882    /**
883     * The scrollbar style to display the scrollbars inside the padded area,
884     * increasing the padding of the view. The scrollbars will not overlap the
885     * content area of the view.
886     */
887    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
888
889    /**
890     * The scrollbar style to display the scrollbars at the edge of the view,
891     * without increasing the padding. The scrollbars will be overlaid with
892     * translucency.
893     */
894    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
895
896    /**
897     * The scrollbar style to display the scrollbars at the edge of the view,
898     * increasing the padding of the view. The scrollbars will only overlap the
899     * background, if any.
900     */
901    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
902
903    /**
904     * Mask to check if the scrollbar style is overlay or inset.
905     * {@hide}
906     */
907    static final int SCROLLBARS_INSET_MASK = 0x01000000;
908
909    /**
910     * Mask to check if the scrollbar style is inside or outside.
911     * {@hide}
912     */
913    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
914
915    /**
916     * Mask for scrollbar style.
917     * {@hide}
918     */
919    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
920
921    /**
922     * View flag indicating that the screen should remain on while the
923     * window containing this view is visible to the user.  This effectively
924     * takes care of automatically setting the WindowManager's
925     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
926     */
927    public static final int KEEP_SCREEN_ON = 0x04000000;
928
929    /**
930     * View flag indicating whether this view should have sound effects enabled
931     * for events such as clicking and touching.
932     */
933    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
934
935    /**
936     * View flag indicating whether this view should have haptic feedback
937     * enabled for events such as long presses.
938     */
939    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
940
941    /**
942     * <p>Indicates that the view hierarchy should stop saving state when
943     * it reaches this view.  If state saving is initiated immediately at
944     * the view, it will be allowed.
945     * {@hide}
946     */
947    static final int PARENT_SAVE_DISABLED = 0x20000000;
948
949    /**
950     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
951     * {@hide}
952     */
953    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
954
955    /**
956     * Horizontal direction of this view is from Left to Right.
957     * Use with {@link #setLayoutDirection}.
958     * {@hide}
959     */
960    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
961
962    /**
963     * Horizontal direction of this view is from Right to Left.
964     * Use with {@link #setLayoutDirection}.
965     * {@hide}
966     */
967    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
968
969    /**
970     * Horizontal direction of this view is inherited from its parent.
971     * Use with {@link #setLayoutDirection}.
972     * {@hide}
973     */
974    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
975
976    /**
977     * Horizontal direction of this view is from deduced from the default language
978     * script for the locale. Use with {@link #setLayoutDirection}.
979     * {@hide}
980     */
981    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
982
983    /**
984     * Mask for use with setFlags indicating bits used for horizontalDirection.
985     * {@hide}
986     */
987    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
988
989    /*
990     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
991     * flag value.
992     * {@hide}
993     */
994    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
995        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
996
997    /**
998     * Default horizontalDirection.
999     * {@hide}
1000     */
1001    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1002
1003    /**
1004     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1005     * should add all focusable Views regardless if they are focusable in touch mode.
1006     */
1007    public static final int FOCUSABLES_ALL = 0x00000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add only Views focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1014
1015    /**
1016     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1017     * item.
1018     */
1019    public static final int FOCUS_BACKWARD = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1023     * item.
1024     */
1025    public static final int FOCUS_FORWARD = 0x00000002;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the left.
1029     */
1030    public static final int FOCUS_LEFT = 0x00000011;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus up.
1034     */
1035    public static final int FOCUS_UP = 0x00000021;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus to the right.
1039     */
1040    public static final int FOCUS_RIGHT = 0x00000042;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus down.
1044     */
1045    public static final int FOCUS_DOWN = 0x00000082;
1046
1047    /**
1048     * Bits of {@link #getMeasuredWidthAndState()} and
1049     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1050     */
1051    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1056     */
1057    public static final int MEASURED_STATE_MASK = 0xff000000;
1058
1059    /**
1060     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1061     * for functions that combine both width and height into a single int,
1062     * such as {@link #getMeasuredState()} and the childState argument of
1063     * {@link #resolveSizeAndState(int, int, int)}.
1064     */
1065    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1066
1067    /**
1068     * Bit of {@link #getMeasuredWidthAndState()} and
1069     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1070     * is smaller that the space the view would like to have.
1071     */
1072    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1073
1074    /**
1075     * Base View state sets
1076     */
1077    // Singles
1078    /**
1079     * Indicates the view has no states set. States are used with
1080     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1081     * view depending on its state.
1082     *
1083     * @see android.graphics.drawable.Drawable
1084     * @see #getDrawableState()
1085     */
1086    protected static final int[] EMPTY_STATE_SET;
1087    /**
1088     * Indicates the view is enabled. States are used with
1089     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1090     * view depending on its state.
1091     *
1092     * @see android.graphics.drawable.Drawable
1093     * @see #getDrawableState()
1094     */
1095    protected static final int[] ENABLED_STATE_SET;
1096    /**
1097     * Indicates the view is focused. States are used with
1098     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1099     * view depending on its state.
1100     *
1101     * @see android.graphics.drawable.Drawable
1102     * @see #getDrawableState()
1103     */
1104    protected static final int[] FOCUSED_STATE_SET;
1105    /**
1106     * Indicates the view is selected. States are used with
1107     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1108     * view depending on its state.
1109     *
1110     * @see android.graphics.drawable.Drawable
1111     * @see #getDrawableState()
1112     */
1113    protected static final int[] SELECTED_STATE_SET;
1114    /**
1115     * Indicates the view is pressed. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     * @hide
1122     */
1123    protected static final int[] PRESSED_STATE_SET;
1124    /**
1125     * Indicates the view's window has focus. States are used with
1126     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1127     * view depending on its state.
1128     *
1129     * @see android.graphics.drawable.Drawable
1130     * @see #getDrawableState()
1131     */
1132    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1133    // Doubles
1134    /**
1135     * Indicates the view is enabled and has the focus.
1136     *
1137     * @see #ENABLED_STATE_SET
1138     * @see #FOCUSED_STATE_SET
1139     */
1140    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1141    /**
1142     * Indicates the view is enabled and selected.
1143     *
1144     * @see #ENABLED_STATE_SET
1145     * @see #SELECTED_STATE_SET
1146     */
1147    protected static final int[] ENABLED_SELECTED_STATE_SET;
1148    /**
1149     * Indicates the view is enabled and that its window has focus.
1150     *
1151     * @see #ENABLED_STATE_SET
1152     * @see #WINDOW_FOCUSED_STATE_SET
1153     */
1154    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1155    /**
1156     * Indicates the view is focused and selected.
1157     *
1158     * @see #FOCUSED_STATE_SET
1159     * @see #SELECTED_STATE_SET
1160     */
1161    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1162    /**
1163     * Indicates the view has the focus and that its window has the focus.
1164     *
1165     * @see #FOCUSED_STATE_SET
1166     * @see #WINDOW_FOCUSED_STATE_SET
1167     */
1168    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1169    /**
1170     * Indicates the view is selected and that its window has the focus.
1171     *
1172     * @see #SELECTED_STATE_SET
1173     * @see #WINDOW_FOCUSED_STATE_SET
1174     */
1175    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1176    // Triples
1177    /**
1178     * Indicates the view is enabled, focused and selected.
1179     *
1180     * @see #ENABLED_STATE_SET
1181     * @see #FOCUSED_STATE_SET
1182     * @see #SELECTED_STATE_SET
1183     */
1184    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1185    /**
1186     * Indicates the view is enabled, focused and its window has the focus.
1187     *
1188     * @see #ENABLED_STATE_SET
1189     * @see #FOCUSED_STATE_SET
1190     * @see #WINDOW_FOCUSED_STATE_SET
1191     */
1192    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1193    /**
1194     * Indicates the view is enabled, selected and its window has the focus.
1195     *
1196     * @see #ENABLED_STATE_SET
1197     * @see #SELECTED_STATE_SET
1198     * @see #WINDOW_FOCUSED_STATE_SET
1199     */
1200    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is focused, selected and its window has the focus.
1203     *
1204     * @see #FOCUSED_STATE_SET
1205     * @see #SELECTED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is enabled, focused, selected and its window
1211     * has the focus.
1212     *
1213     * @see #ENABLED_STATE_SET
1214     * @see #FOCUSED_STATE_SET
1215     * @see #SELECTED_STATE_SET
1216     * @see #WINDOW_FOCUSED_STATE_SET
1217     */
1218    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1219    /**
1220     * Indicates the view is pressed and its window has the focus.
1221     *
1222     * @see #PRESSED_STATE_SET
1223     * @see #WINDOW_FOCUSED_STATE_SET
1224     */
1225    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1226    /**
1227     * Indicates the view is pressed and selected.
1228     *
1229     * @see #PRESSED_STATE_SET
1230     * @see #SELECTED_STATE_SET
1231     */
1232    protected static final int[] PRESSED_SELECTED_STATE_SET;
1233    /**
1234     * Indicates the view is pressed, selected and its window has the focus.
1235     *
1236     * @see #PRESSED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is pressed and focused.
1243     *
1244     * @see #PRESSED_STATE_SET
1245     * @see #FOCUSED_STATE_SET
1246     */
1247    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1248    /**
1249     * Indicates the view is pressed, focused and its window has the focus.
1250     *
1251     * @see #PRESSED_STATE_SET
1252     * @see #FOCUSED_STATE_SET
1253     * @see #WINDOW_FOCUSED_STATE_SET
1254     */
1255    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed, focused and selected.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #SELECTED_STATE_SET
1261     * @see #FOCUSED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, focused, selected and its window has the focus.
1266     *
1267     * @see #PRESSED_STATE_SET
1268     * @see #FOCUSED_STATE_SET
1269     * @see #SELECTED_STATE_SET
1270     * @see #WINDOW_FOCUSED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed and enabled.
1275     *
1276     * @see #PRESSED_STATE_SET
1277     * @see #ENABLED_STATE_SET
1278     */
1279    protected static final int[] PRESSED_ENABLED_STATE_SET;
1280    /**
1281     * Indicates the view is pressed, enabled and its window has the focus.
1282     *
1283     * @see #PRESSED_STATE_SET
1284     * @see #ENABLED_STATE_SET
1285     * @see #WINDOW_FOCUSED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, enabled and selected.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #ENABLED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, enabled, selected and its window has the
1298     * focus.
1299     *
1300     * @see #PRESSED_STATE_SET
1301     * @see #ENABLED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed, enabled and focused.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #ENABLED_STATE_SET
1311     * @see #FOCUSED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, enabled, focused and its window has the
1316     * focus.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #ENABLED_STATE_SET
1320     * @see #FOCUSED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled, focused and selected.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #SELECTED_STATE_SET
1330     * @see #FOCUSED_STATE_SET
1331     */
1332    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1333    /**
1334     * Indicates the view is pressed, enabled, focused, selected and its window
1335     * has the focus.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #ENABLED_STATE_SET
1339     * @see #SELECTED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     * @see #WINDOW_FOCUSED_STATE_SET
1342     */
1343    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1344
1345    /**
1346     * The order here is very important to {@link #getDrawableState()}
1347     */
1348    private static final int[][] VIEW_STATE_SETS;
1349
1350    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1351    static final int VIEW_STATE_SELECTED = 1 << 1;
1352    static final int VIEW_STATE_FOCUSED = 1 << 2;
1353    static final int VIEW_STATE_ENABLED = 1 << 3;
1354    static final int VIEW_STATE_PRESSED = 1 << 4;
1355    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1356    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1357    static final int VIEW_STATE_HOVERED = 1 << 7;
1358    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1359    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1360
1361    static final int[] VIEW_STATE_IDS = new int[] {
1362        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1363        R.attr.state_selected,          VIEW_STATE_SELECTED,
1364        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1365        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1366        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1367        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1368        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1369        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1370        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1371        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1372    };
1373
1374    static {
1375        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1376            throw new IllegalStateException(
1377                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1378        }
1379        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1380        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1381            int viewState = R.styleable.ViewDrawableStates[i];
1382            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1383                if (VIEW_STATE_IDS[j] == viewState) {
1384                    orderedIds[i * 2] = viewState;
1385                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1386                }
1387            }
1388        }
1389        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1390        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1391        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1392            int numBits = Integer.bitCount(i);
1393            int[] set = new int[numBits];
1394            int pos = 0;
1395            for (int j = 0; j < orderedIds.length; j += 2) {
1396                if ((i & orderedIds[j+1]) != 0) {
1397                    set[pos++] = orderedIds[j];
1398                }
1399            }
1400            VIEW_STATE_SETS[i] = set;
1401        }
1402
1403        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1404        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1405        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1406        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1408        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1409        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1411        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1413        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1415                | VIEW_STATE_FOCUSED];
1416        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1417        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1419        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1421        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1423                | VIEW_STATE_ENABLED];
1424        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1431                | VIEW_STATE_ENABLED];
1432        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1434                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1435
1436        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1437        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1439        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1441        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1443                | VIEW_STATE_PRESSED];
1444        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1451                | VIEW_STATE_PRESSED];
1452        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1454                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1455        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1462                | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1465                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1468                | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1472        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1474                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1475        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1477                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1478                | VIEW_STATE_PRESSED];
1479    }
1480
1481    /**
1482     * Accessibility event types that are dispatched for text population.
1483     */
1484    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1485            AccessibilityEvent.TYPE_VIEW_CLICKED
1486            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1487            | AccessibilityEvent.TYPE_VIEW_SELECTED
1488            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1489            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1490            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1491            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1492            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1493            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1494
1495    /**
1496     * Temporary Rect currently for use in setBackground().  This will probably
1497     * be extended in the future to hold our own class with more than just
1498     * a Rect. :)
1499     */
1500    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1501
1502    /**
1503     * Map used to store views' tags.
1504     */
1505    private SparseArray<Object> mKeyedTags;
1506
1507    /**
1508     * The next available accessiiblity id.
1509     */
1510    private static int sNextAccessibilityViewId;
1511
1512    /**
1513     * The animation currently associated with this view.
1514     * @hide
1515     */
1516    protected Animation mCurrentAnimation = null;
1517
1518    /**
1519     * Width as measured during measure pass.
1520     * {@hide}
1521     */
1522    @ViewDebug.ExportedProperty(category = "measurement")
1523    int mMeasuredWidth;
1524
1525    /**
1526     * Height as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredHeight;
1531
1532    /**
1533     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1534     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1535     * its display list. This flag, used only when hw accelerated, allows us to clear the
1536     * flag while retaining this information until it's needed (at getDisplayList() time and
1537     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1538     *
1539     * {@hide}
1540     */
1541    boolean mRecreateDisplayList = false;
1542
1543    /**
1544     * The view's identifier.
1545     * {@hide}
1546     *
1547     * @see #setId(int)
1548     * @see #getId()
1549     */
1550    @ViewDebug.ExportedProperty(resolveId = true)
1551    int mID = NO_ID;
1552
1553    /**
1554     * The stable ID of this view for accessibility purposes.
1555     */
1556    int mAccessibilityViewId = NO_ID;
1557
1558    /**
1559     * The view's tag.
1560     * {@hide}
1561     *
1562     * @see #setTag(Object)
1563     * @see #getTag()
1564     */
1565    protected Object mTag;
1566
1567    // for mPrivateFlags:
1568    /** {@hide} */
1569    static final int WANTS_FOCUS                    = 0x00000001;
1570    /** {@hide} */
1571    static final int FOCUSED                        = 0x00000002;
1572    /** {@hide} */
1573    static final int SELECTED                       = 0x00000004;
1574    /** {@hide} */
1575    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1576    /** {@hide} */
1577    static final int HAS_BOUNDS                     = 0x00000010;
1578    /** {@hide} */
1579    static final int DRAWN                          = 0x00000020;
1580    /**
1581     * When this flag is set, this view is running an animation on behalf of its
1582     * children and should therefore not cancel invalidate requests, even if they
1583     * lie outside of this view's bounds.
1584     *
1585     * {@hide}
1586     */
1587    static final int DRAW_ANIMATION                 = 0x00000040;
1588    /** {@hide} */
1589    static final int SKIP_DRAW                      = 0x00000080;
1590    /** {@hide} */
1591    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1592    /** {@hide} */
1593    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1594    /** {@hide} */
1595    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1596    /** {@hide} */
1597    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1598    /** {@hide} */
1599    static final int FORCE_LAYOUT                   = 0x00001000;
1600    /** {@hide} */
1601    static final int LAYOUT_REQUIRED                = 0x00002000;
1602
1603    private static final int PRESSED                = 0x00004000;
1604
1605    /** {@hide} */
1606    static final int DRAWING_CACHE_VALID            = 0x00008000;
1607    /**
1608     * Flag used to indicate that this view should be drawn once more (and only once
1609     * more) after its animation has completed.
1610     * {@hide}
1611     */
1612    static final int ANIMATION_STARTED              = 0x00010000;
1613
1614    private static final int SAVE_STATE_CALLED      = 0x00020000;
1615
1616    /**
1617     * Indicates that the View returned true when onSetAlpha() was called and that
1618     * the alpha must be restored.
1619     * {@hide}
1620     */
1621    static final int ALPHA_SET                      = 0x00040000;
1622
1623    /**
1624     * Set by {@link #setScrollContainer(boolean)}.
1625     */
1626    static final int SCROLL_CONTAINER               = 0x00080000;
1627
1628    /**
1629     * Set by {@link #setScrollContainer(boolean)}.
1630     */
1631    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1632
1633    /**
1634     * View flag indicating whether this view was invalidated (fully or partially.)
1635     *
1636     * @hide
1637     */
1638    static final int DIRTY                          = 0x00200000;
1639
1640    /**
1641     * View flag indicating whether this view was invalidated by an opaque
1642     * invalidate request.
1643     *
1644     * @hide
1645     */
1646    static final int DIRTY_OPAQUE                   = 0x00400000;
1647
1648    /**
1649     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1650     *
1651     * @hide
1652     */
1653    static final int DIRTY_MASK                     = 0x00600000;
1654
1655    /**
1656     * Indicates whether the background is opaque.
1657     *
1658     * @hide
1659     */
1660    static final int OPAQUE_BACKGROUND              = 0x00800000;
1661
1662    /**
1663     * Indicates whether the scrollbars are opaque.
1664     *
1665     * @hide
1666     */
1667    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1668
1669    /**
1670     * Indicates whether the view is opaque.
1671     *
1672     * @hide
1673     */
1674    static final int OPAQUE_MASK                    = 0x01800000;
1675
1676    /**
1677     * Indicates a prepressed state;
1678     * the short time between ACTION_DOWN and recognizing
1679     * a 'real' press. Prepressed is used to recognize quick taps
1680     * even when they are shorter than ViewConfiguration.getTapTimeout().
1681     *
1682     * @hide
1683     */
1684    private static final int PREPRESSED             = 0x02000000;
1685
1686    /**
1687     * Indicates whether the view is temporarily detached.
1688     *
1689     * @hide
1690     */
1691    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1692
1693    /**
1694     * Indicates that we should awaken scroll bars once attached
1695     *
1696     * @hide
1697     */
1698    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1699
1700    /**
1701     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1702     * @hide
1703     */
1704    private static final int HOVERED              = 0x10000000;
1705
1706    /**
1707     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1708     * for transform operations
1709     *
1710     * @hide
1711     */
1712    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1713
1714    /** {@hide} */
1715    static final int ACTIVATED                    = 0x40000000;
1716
1717    /**
1718     * Indicates that this view was specifically invalidated, not just dirtied because some
1719     * child view was invalidated. The flag is used to determine when we need to recreate
1720     * a view's display list (as opposed to just returning a reference to its existing
1721     * display list).
1722     *
1723     * @hide
1724     */
1725    static final int INVALIDATED                  = 0x80000000;
1726
1727    /* Masks for mPrivateFlags2 */
1728
1729    /**
1730     * Indicates that this view has reported that it can accept the current drag's content.
1731     * Cleared when the drag operation concludes.
1732     * @hide
1733     */
1734    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1735
1736    /**
1737     * Indicates that this view is currently directly under the drag location in a
1738     * drag-and-drop operation involving content that it can accept.  Cleared when
1739     * the drag exits the view, or when the drag operation concludes.
1740     * @hide
1741     */
1742    static final int DRAG_HOVERED                 = 0x00000002;
1743
1744    /**
1745     * Indicates whether the view layout direction has been resolved and drawn to the
1746     * right-to-left direction.
1747     *
1748     * @hide
1749     */
1750    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1751
1752    /**
1753     * Indicates whether the view layout direction has been resolved.
1754     *
1755     * @hide
1756     */
1757    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1758
1759
1760    /* End of masks for mPrivateFlags2 */
1761
1762    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1763
1764    /**
1765     * Always allow a user to over-scroll this view, provided it is a
1766     * view that can scroll.
1767     *
1768     * @see #getOverScrollMode()
1769     * @see #setOverScrollMode(int)
1770     */
1771    public static final int OVER_SCROLL_ALWAYS = 0;
1772
1773    /**
1774     * Allow a user to over-scroll this view only if the content is large
1775     * enough to meaningfully scroll, provided it is a view that can scroll.
1776     *
1777     * @see #getOverScrollMode()
1778     * @see #setOverScrollMode(int)
1779     */
1780    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1781
1782    /**
1783     * Never allow a user to over-scroll this view.
1784     *
1785     * @see #getOverScrollMode()
1786     * @see #setOverScrollMode(int)
1787     */
1788    public static final int OVER_SCROLL_NEVER = 2;
1789
1790    /**
1791     * View has requested the system UI (status bar) to be visible (the default).
1792     *
1793     * @see #setSystemUiVisibility(int)
1794     */
1795    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1796
1797    /**
1798     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1799     *
1800     * This is for use in games, book readers, video players, or any other "immersive" application
1801     * where the usual system chrome is deemed too distracting.
1802     *
1803     * In low profile mode, the status bar and/or navigation icons may dim.
1804     *
1805     * @see #setSystemUiVisibility(int)
1806     */
1807    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1808
1809    /**
1810     * View has requested that the system navigation be temporarily hidden.
1811     *
1812     * This is an even less obtrusive state than that called for by
1813     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1814     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1815     * those to disappear. This is useful (in conjunction with the
1816     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1817     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1818     * window flags) for displaying content using every last pixel on the display.
1819     *
1820     * There is a limitation: because navigation controls are so important, the least user
1821     * interaction will cause them to reappear immediately.
1822     *
1823     * @see #setSystemUiVisibility(int)
1824     */
1825    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1826
1827    /**
1828     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1829     */
1830    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1831
1832    /**
1833     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1834     */
1835    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1836
1837    /**
1838     * @hide
1839     *
1840     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1841     * out of the public fields to keep the undefined bits out of the developer's way.
1842     *
1843     * Flag to make the status bar not expandable.  Unless you also
1844     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1845     */
1846    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1847
1848    /**
1849     * @hide
1850     *
1851     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1852     * out of the public fields to keep the undefined bits out of the developer's way.
1853     *
1854     * Flag to hide notification icons and scrolling ticker text.
1855     */
1856    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1857
1858    /**
1859     * @hide
1860     *
1861     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1862     * out of the public fields to keep the undefined bits out of the developer's way.
1863     *
1864     * Flag to disable incoming notification alerts.  This will not block
1865     * icons, but it will block sound, vibrating and other visual or aural notifications.
1866     */
1867    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1868
1869    /**
1870     * @hide
1871     *
1872     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1873     * out of the public fields to keep the undefined bits out of the developer's way.
1874     *
1875     * Flag to hide only the scrolling ticker.  Note that
1876     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1877     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1878     */
1879    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1880
1881    /**
1882     * @hide
1883     *
1884     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1885     * out of the public fields to keep the undefined bits out of the developer's way.
1886     *
1887     * Flag to hide the center system info area.
1888     */
1889    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1890
1891    /**
1892     * @hide
1893     *
1894     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1895     * out of the public fields to keep the undefined bits out of the developer's way.
1896     *
1897     * Flag to hide only the home button.  Don't use this
1898     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1899     */
1900    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
1901
1902    /**
1903     * @hide
1904     *
1905     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1906     * out of the public fields to keep the undefined bits out of the developer's way.
1907     *
1908     * Flag to hide only the back button. Don't use this
1909     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1910     */
1911    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1912
1913    /**
1914     * @hide
1915     *
1916     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1917     * out of the public fields to keep the undefined bits out of the developer's way.
1918     *
1919     * Flag to hide only the clock.  You might use this if your activity has
1920     * its own clock making the status bar's clock redundant.
1921     */
1922    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1923
1924    /**
1925     * @hide
1926     *
1927     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1928     * out of the public fields to keep the undefined bits out of the developer's way.
1929     *
1930     * Flag to hide only the recent apps button. Don't use this
1931     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1932     */
1933    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
1934
1935    /**
1936     * @hide
1937     *
1938     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
1939     *
1940     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
1941     */
1942    @Deprecated
1943    public static final int STATUS_BAR_DISABLE_NAVIGATION =
1944            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
1945
1946    /**
1947     * @hide
1948     */
1949    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1950
1951    /**
1952     * These are the system UI flags that can be cleared by events outside
1953     * of an application.  Currently this is just the ability to tap on the
1954     * screen while hiding the navigation bar to have it return.
1955     * @hide
1956     */
1957    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1958            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1959
1960    /**
1961     * Find views that render the specified text.
1962     *
1963     * @see #findViewsWithText(ArrayList, CharSequence, int)
1964     */
1965    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1966
1967    /**
1968     * Find find views that contain the specified content description.
1969     *
1970     * @see #findViewsWithText(ArrayList, CharSequence, int)
1971     */
1972    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1973
1974    /**
1975     * Find views that contain {@link AccessibilityNodeProvider}. Such
1976     * a View is a root of virtual view hierarchy and may contain the searched
1977     * text. If this flag is set Views with providers are automatically
1978     * added and it is a responsibility of the client to call the APIs of
1979     * the provider to determine whether the virtual tree rooted at this View
1980     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
1981     * represeting the virtual views with this text.
1982     *
1983     * @see #findViewsWithText(ArrayList, CharSequence, int)
1984     *
1985     * @hide
1986     */
1987    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
1988
1989    /**
1990     * Controls the over-scroll mode for this view.
1991     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1992     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1993     * and {@link #OVER_SCROLL_NEVER}.
1994     */
1995    private int mOverScrollMode;
1996
1997    /**
1998     * The parent this view is attached to.
1999     * {@hide}
2000     *
2001     * @see #getParent()
2002     */
2003    protected ViewParent mParent;
2004
2005    /**
2006     * {@hide}
2007     */
2008    AttachInfo mAttachInfo;
2009
2010    /**
2011     * {@hide}
2012     */
2013    @ViewDebug.ExportedProperty(flagMapping = {
2014        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2015                name = "FORCE_LAYOUT"),
2016        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2017                name = "LAYOUT_REQUIRED"),
2018        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2019            name = "DRAWING_CACHE_INVALID", outputIf = false),
2020        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2021        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2022        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2023        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2024    })
2025    int mPrivateFlags;
2026    int mPrivateFlags2;
2027
2028    /**
2029     * This view's request for the visibility of the status bar.
2030     * @hide
2031     */
2032    @ViewDebug.ExportedProperty(flagMapping = {
2033        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2034                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2035                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2036        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2037                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2038                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2039        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2040                                equals = SYSTEM_UI_FLAG_VISIBLE,
2041                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2042    })
2043    int mSystemUiVisibility;
2044
2045    /**
2046     * Count of how many windows this view has been attached to.
2047     */
2048    int mWindowAttachCount;
2049
2050    /**
2051     * The layout parameters associated with this view and used by the parent
2052     * {@link android.view.ViewGroup} to determine how this view should be
2053     * laid out.
2054     * {@hide}
2055     */
2056    protected ViewGroup.LayoutParams mLayoutParams;
2057
2058    /**
2059     * The view flags hold various views states.
2060     * {@hide}
2061     */
2062    @ViewDebug.ExportedProperty
2063    int mViewFlags;
2064
2065    static class TransformationInfo {
2066        /**
2067         * The transform matrix for the View. This transform is calculated internally
2068         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2069         * is used by default. Do *not* use this variable directly; instead call
2070         * getMatrix(), which will automatically recalculate the matrix if necessary
2071         * to get the correct matrix based on the latest rotation and scale properties.
2072         */
2073        private final Matrix mMatrix = new Matrix();
2074
2075        /**
2076         * The transform matrix for the View. This transform is calculated internally
2077         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2078         * is used by default. Do *not* use this variable directly; instead call
2079         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2080         * to get the correct matrix based on the latest rotation and scale properties.
2081         */
2082        private Matrix mInverseMatrix;
2083
2084        /**
2085         * An internal variable that tracks whether we need to recalculate the
2086         * transform matrix, based on whether the rotation or scaleX/Y properties
2087         * have changed since the matrix was last calculated.
2088         */
2089        boolean mMatrixDirty = false;
2090
2091        /**
2092         * An internal variable that tracks whether we need to recalculate the
2093         * transform matrix, based on whether the rotation or scaleX/Y properties
2094         * have changed since the matrix was last calculated.
2095         */
2096        private boolean mInverseMatrixDirty = true;
2097
2098        /**
2099         * A variable that tracks whether we need to recalculate the
2100         * transform matrix, based on whether the rotation or scaleX/Y properties
2101         * have changed since the matrix was last calculated. This variable
2102         * is only valid after a call to updateMatrix() or to a function that
2103         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2104         */
2105        private boolean mMatrixIsIdentity = true;
2106
2107        /**
2108         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2109         */
2110        private Camera mCamera = null;
2111
2112        /**
2113         * This matrix is used when computing the matrix for 3D rotations.
2114         */
2115        private Matrix matrix3D = null;
2116
2117        /**
2118         * These prev values are used to recalculate a centered pivot point when necessary. The
2119         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2120         * set), so thes values are only used then as well.
2121         */
2122        private int mPrevWidth = -1;
2123        private int mPrevHeight = -1;
2124
2125        /**
2126         * The degrees rotation around the vertical axis through the pivot point.
2127         */
2128        @ViewDebug.ExportedProperty
2129        float mRotationY = 0f;
2130
2131        /**
2132         * The degrees rotation around the horizontal axis through the pivot point.
2133         */
2134        @ViewDebug.ExportedProperty
2135        float mRotationX = 0f;
2136
2137        /**
2138         * The degrees rotation around the pivot point.
2139         */
2140        @ViewDebug.ExportedProperty
2141        float mRotation = 0f;
2142
2143        /**
2144         * The amount of translation of the object away from its left property (post-layout).
2145         */
2146        @ViewDebug.ExportedProperty
2147        float mTranslationX = 0f;
2148
2149        /**
2150         * The amount of translation of the object away from its top property (post-layout).
2151         */
2152        @ViewDebug.ExportedProperty
2153        float mTranslationY = 0f;
2154
2155        /**
2156         * The amount of scale in the x direction around the pivot point. A
2157         * value of 1 means no scaling is applied.
2158         */
2159        @ViewDebug.ExportedProperty
2160        float mScaleX = 1f;
2161
2162        /**
2163         * The amount of scale in the y direction around the pivot point. A
2164         * value of 1 means no scaling is applied.
2165         */
2166        @ViewDebug.ExportedProperty
2167        float mScaleY = 1f;
2168
2169        /**
2170         * The x location of the point around which the view is rotated and scaled.
2171         */
2172        @ViewDebug.ExportedProperty
2173        float mPivotX = 0f;
2174
2175        /**
2176         * The y location of the point around which the view is rotated and scaled.
2177         */
2178        @ViewDebug.ExportedProperty
2179        float mPivotY = 0f;
2180
2181        /**
2182         * The opacity of the View. This is a value from 0 to 1, where 0 means
2183         * completely transparent and 1 means completely opaque.
2184         */
2185        @ViewDebug.ExportedProperty
2186        float mAlpha = 1f;
2187    }
2188
2189    TransformationInfo mTransformationInfo;
2190
2191    private boolean mLastIsOpaque;
2192
2193    /**
2194     * Convenience value to check for float values that are close enough to zero to be considered
2195     * zero.
2196     */
2197    private static final float NONZERO_EPSILON = .001f;
2198
2199    /**
2200     * The distance in pixels from the left edge of this view's parent
2201     * to the left edge of this view.
2202     * {@hide}
2203     */
2204    @ViewDebug.ExportedProperty(category = "layout")
2205    protected int mLeft;
2206    /**
2207     * The distance in pixels from the left edge of this view's parent
2208     * to the right edge of this view.
2209     * {@hide}
2210     */
2211    @ViewDebug.ExportedProperty(category = "layout")
2212    protected int mRight;
2213    /**
2214     * The distance in pixels from the top edge of this view's parent
2215     * to the top edge of this view.
2216     * {@hide}
2217     */
2218    @ViewDebug.ExportedProperty(category = "layout")
2219    protected int mTop;
2220    /**
2221     * The distance in pixels from the top edge of this view's parent
2222     * to the bottom edge of this view.
2223     * {@hide}
2224     */
2225    @ViewDebug.ExportedProperty(category = "layout")
2226    protected int mBottom;
2227
2228    /**
2229     * The offset, in pixels, by which the content of this view is scrolled
2230     * horizontally.
2231     * {@hide}
2232     */
2233    @ViewDebug.ExportedProperty(category = "scrolling")
2234    protected int mScrollX;
2235    /**
2236     * The offset, in pixels, by which the content of this view is scrolled
2237     * vertically.
2238     * {@hide}
2239     */
2240    @ViewDebug.ExportedProperty(category = "scrolling")
2241    protected int mScrollY;
2242
2243    /**
2244     * The left padding in pixels, that is the distance in pixels between the
2245     * left edge of this view and the left edge of its content.
2246     * {@hide}
2247     */
2248    @ViewDebug.ExportedProperty(category = "padding")
2249    protected int mPaddingLeft;
2250    /**
2251     * The right padding in pixels, that is the distance in pixels between the
2252     * right edge of this view and the right edge of its content.
2253     * {@hide}
2254     */
2255    @ViewDebug.ExportedProperty(category = "padding")
2256    protected int mPaddingRight;
2257    /**
2258     * The top padding in pixels, that is the distance in pixels between the
2259     * top edge of this view and the top edge of its content.
2260     * {@hide}
2261     */
2262    @ViewDebug.ExportedProperty(category = "padding")
2263    protected int mPaddingTop;
2264    /**
2265     * The bottom padding in pixels, that is the distance in pixels between the
2266     * bottom edge of this view and the bottom edge of its content.
2267     * {@hide}
2268     */
2269    @ViewDebug.ExportedProperty(category = "padding")
2270    protected int mPaddingBottom;
2271
2272    /**
2273     * Briefly describes the view and is primarily used for accessibility support.
2274     */
2275    private CharSequence mContentDescription;
2276
2277    /**
2278     * Cache the paddingRight set by the user to append to the scrollbar's size.
2279     *
2280     * @hide
2281     */
2282    @ViewDebug.ExportedProperty(category = "padding")
2283    protected int mUserPaddingRight;
2284
2285    /**
2286     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2287     *
2288     * @hide
2289     */
2290    @ViewDebug.ExportedProperty(category = "padding")
2291    protected int mUserPaddingBottom;
2292
2293    /**
2294     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2295     *
2296     * @hide
2297     */
2298    @ViewDebug.ExportedProperty(category = "padding")
2299    protected int mUserPaddingLeft;
2300
2301    /**
2302     * Cache if the user padding is relative.
2303     *
2304     */
2305    @ViewDebug.ExportedProperty(category = "padding")
2306    boolean mUserPaddingRelative;
2307
2308    /**
2309     * Cache the paddingStart set by the user to append to the scrollbar's size.
2310     *
2311     */
2312    @ViewDebug.ExportedProperty(category = "padding")
2313    int mUserPaddingStart;
2314
2315    /**
2316     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2317     *
2318     */
2319    @ViewDebug.ExportedProperty(category = "padding")
2320    int mUserPaddingEnd;
2321
2322    /**
2323     * @hide
2324     */
2325    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2326    /**
2327     * @hide
2328     */
2329    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2330
2331    private Drawable mBGDrawable;
2332
2333    private int mBackgroundResource;
2334    private boolean mBackgroundSizeChanged;
2335
2336    static class ListenerInfo {
2337        /**
2338         * Listener used to dispatch focus change events.
2339         * This field should be made private, so it is hidden from the SDK.
2340         * {@hide}
2341         */
2342        protected OnFocusChangeListener mOnFocusChangeListener;
2343
2344        /**
2345         * Listeners for layout change events.
2346         */
2347        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2348
2349        /**
2350         * Listeners for attach events.
2351         */
2352        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2353
2354        /**
2355         * Listener used to dispatch click events.
2356         * This field should be made private, so it is hidden from the SDK.
2357         * {@hide}
2358         */
2359        public OnClickListener mOnClickListener;
2360
2361        /**
2362         * Listener used to dispatch long click events.
2363         * This field should be made private, so it is hidden from the SDK.
2364         * {@hide}
2365         */
2366        protected OnLongClickListener mOnLongClickListener;
2367
2368        /**
2369         * Listener used to build the context menu.
2370         * This field should be made private, so it is hidden from the SDK.
2371         * {@hide}
2372         */
2373        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2374
2375        private OnKeyListener mOnKeyListener;
2376
2377        private OnTouchListener mOnTouchListener;
2378
2379        private OnHoverListener mOnHoverListener;
2380
2381        private OnGenericMotionListener mOnGenericMotionListener;
2382
2383        private OnDragListener mOnDragListener;
2384
2385        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2386    }
2387
2388    ListenerInfo mListenerInfo;
2389
2390    /**
2391     * The application environment this view lives in.
2392     * This field should be made private, so it is hidden from the SDK.
2393     * {@hide}
2394     */
2395    protected Context mContext;
2396
2397    private final Resources mResources;
2398
2399    private ScrollabilityCache mScrollCache;
2400
2401    private int[] mDrawableState = null;
2402
2403    /**
2404     * Set to true when drawing cache is enabled and cannot be created.
2405     *
2406     * @hide
2407     */
2408    public boolean mCachingFailed;
2409
2410    private Bitmap mDrawingCache;
2411    private Bitmap mUnscaledDrawingCache;
2412    private HardwareLayer mHardwareLayer;
2413    DisplayList mDisplayList;
2414
2415    /**
2416     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2417     * the user may specify which view to go to next.
2418     */
2419    private int mNextFocusLeftId = View.NO_ID;
2420
2421    /**
2422     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2423     * the user may specify which view to go to next.
2424     */
2425    private int mNextFocusRightId = View.NO_ID;
2426
2427    /**
2428     * When this view has focus and the next focus is {@link #FOCUS_UP},
2429     * the user may specify which view to go to next.
2430     */
2431    private int mNextFocusUpId = View.NO_ID;
2432
2433    /**
2434     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2435     * the user may specify which view to go to next.
2436     */
2437    private int mNextFocusDownId = View.NO_ID;
2438
2439    /**
2440     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2441     * the user may specify which view to go to next.
2442     */
2443    int mNextFocusForwardId = View.NO_ID;
2444
2445    private CheckForLongPress mPendingCheckForLongPress;
2446    private CheckForTap mPendingCheckForTap = null;
2447    private PerformClick mPerformClick;
2448    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2449
2450    private UnsetPressedState mUnsetPressedState;
2451
2452    /**
2453     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2454     * up event while a long press is invoked as soon as the long press duration is reached, so
2455     * a long press could be performed before the tap is checked, in which case the tap's action
2456     * should not be invoked.
2457     */
2458    private boolean mHasPerformedLongPress;
2459
2460    /**
2461     * The minimum height of the view. We'll try our best to have the height
2462     * of this view to at least this amount.
2463     */
2464    @ViewDebug.ExportedProperty(category = "measurement")
2465    private int mMinHeight;
2466
2467    /**
2468     * The minimum width of the view. We'll try our best to have the width
2469     * of this view to at least this amount.
2470     */
2471    @ViewDebug.ExportedProperty(category = "measurement")
2472    private int mMinWidth;
2473
2474    /**
2475     * The delegate to handle touch events that are physically in this view
2476     * but should be handled by another view.
2477     */
2478    private TouchDelegate mTouchDelegate = null;
2479
2480    /**
2481     * Solid color to use as a background when creating the drawing cache. Enables
2482     * the cache to use 16 bit bitmaps instead of 32 bit.
2483     */
2484    private int mDrawingCacheBackgroundColor = 0;
2485
2486    /**
2487     * Special tree observer used when mAttachInfo is null.
2488     */
2489    private ViewTreeObserver mFloatingTreeObserver;
2490
2491    /**
2492     * Cache the touch slop from the context that created the view.
2493     */
2494    private int mTouchSlop;
2495
2496    /**
2497     * Object that handles automatic animation of view properties.
2498     */
2499    private ViewPropertyAnimator mAnimator = null;
2500
2501    /**
2502     * Flag indicating that a drag can cross window boundaries.  When
2503     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2504     * with this flag set, all visible applications will be able to participate
2505     * in the drag operation and receive the dragged content.
2506     *
2507     * @hide
2508     */
2509    public static final int DRAG_FLAG_GLOBAL = 1;
2510
2511    /**
2512     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2513     */
2514    private float mVerticalScrollFactor;
2515
2516    /**
2517     * Position of the vertical scroll bar.
2518     */
2519    private int mVerticalScrollbarPosition;
2520
2521    /**
2522     * Position the scroll bar at the default position as determined by the system.
2523     */
2524    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2525
2526    /**
2527     * Position the scroll bar along the left edge.
2528     */
2529    public static final int SCROLLBAR_POSITION_LEFT = 1;
2530
2531    /**
2532     * Position the scroll bar along the right edge.
2533     */
2534    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2535
2536    /**
2537     * Indicates that the view does not have a layer.
2538     *
2539     * @see #getLayerType()
2540     * @see #setLayerType(int, android.graphics.Paint)
2541     * @see #LAYER_TYPE_SOFTWARE
2542     * @see #LAYER_TYPE_HARDWARE
2543     */
2544    public static final int LAYER_TYPE_NONE = 0;
2545
2546    /**
2547     * <p>Indicates that the view has a software layer. A software layer is backed
2548     * by a bitmap and causes the view to be rendered using Android's software
2549     * rendering pipeline, even if hardware acceleration is enabled.</p>
2550     *
2551     * <p>Software layers have various usages:</p>
2552     * <p>When the application is not using hardware acceleration, a software layer
2553     * is useful to apply a specific color filter and/or blending mode and/or
2554     * translucency to a view and all its children.</p>
2555     * <p>When the application is using hardware acceleration, a software layer
2556     * is useful to render drawing primitives not supported by the hardware
2557     * accelerated pipeline. It can also be used to cache a complex view tree
2558     * into a texture and reduce the complexity of drawing operations. For instance,
2559     * when animating a complex view tree with a translation, a software layer can
2560     * be used to render the view tree only once.</p>
2561     * <p>Software layers should be avoided when the affected view tree updates
2562     * often. Every update will require to re-render the software layer, which can
2563     * potentially be slow (particularly when hardware acceleration is turned on
2564     * since the layer will have to be uploaded into a hardware texture after every
2565     * update.)</p>
2566     *
2567     * @see #getLayerType()
2568     * @see #setLayerType(int, android.graphics.Paint)
2569     * @see #LAYER_TYPE_NONE
2570     * @see #LAYER_TYPE_HARDWARE
2571     */
2572    public static final int LAYER_TYPE_SOFTWARE = 1;
2573
2574    /**
2575     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2576     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2577     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2578     * rendering pipeline, but only if hardware acceleration is turned on for the
2579     * view hierarchy. When hardware acceleration is turned off, hardware layers
2580     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2581     *
2582     * <p>A hardware layer is useful to apply a specific color filter and/or
2583     * blending mode and/or translucency to a view and all its children.</p>
2584     * <p>A hardware layer can be used to cache a complex view tree into a
2585     * texture and reduce the complexity of drawing operations. For instance,
2586     * when animating a complex view tree with a translation, a hardware layer can
2587     * be used to render the view tree only once.</p>
2588     * <p>A hardware layer can also be used to increase the rendering quality when
2589     * rotation transformations are applied on a view. It can also be used to
2590     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2591     *
2592     * @see #getLayerType()
2593     * @see #setLayerType(int, android.graphics.Paint)
2594     * @see #LAYER_TYPE_NONE
2595     * @see #LAYER_TYPE_SOFTWARE
2596     */
2597    public static final int LAYER_TYPE_HARDWARE = 2;
2598
2599    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2600            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2601            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2602            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2603    })
2604    int mLayerType = LAYER_TYPE_NONE;
2605    Paint mLayerPaint;
2606    Rect mLocalDirtyRect;
2607
2608    /**
2609     * Set to true when the view is sending hover accessibility events because it
2610     * is the innermost hovered view.
2611     */
2612    private boolean mSendingHoverAccessibilityEvents;
2613
2614    /**
2615     * Delegate for injecting accessiblity functionality.
2616     */
2617    AccessibilityDelegate mAccessibilityDelegate;
2618
2619    /**
2620     * Text direction is inherited thru {@link ViewGroup}
2621     */
2622    public static final int TEXT_DIRECTION_INHERIT = 0;
2623
2624    /**
2625     * Text direction is using "first strong algorithm". The first strong directional character
2626     * determines the paragraph direction. If there is no strong directional character, the
2627     * paragraph direction is the view's resolved layout direction.
2628     *
2629     */
2630    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2631
2632    /**
2633     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2634     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2635     * If there are neither, the paragraph direction is the view's resolved layout direction.
2636     *
2637     */
2638    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2639
2640    /**
2641     * Text direction is forced to LTR.
2642     *
2643     */
2644    public static final int TEXT_DIRECTION_LTR = 3;
2645
2646    /**
2647     * Text direction is forced to RTL.
2648     *
2649     */
2650    public static final int TEXT_DIRECTION_RTL = 4;
2651
2652    /**
2653     * Text direction is coming from the system Locale.
2654     *
2655     */
2656    public static final int TEXT_DIRECTION_LOCALE = 5;
2657
2658    /**
2659     * Default text direction is inherited
2660     *
2661     */
2662    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2663
2664    /**
2665     * The text direction that has been defined by {@link #setTextDirection(int)}.
2666     *
2667     */
2668    @ViewDebug.ExportedProperty(category = "text", mapping = {
2669            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2670            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2671            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2672            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2673            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2674            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2675    })
2676    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2677
2678    /**
2679     * The resolved text direction.  This needs resolution if the value is
2680     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if it is
2681     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2682     * chain of the view.
2683     *
2684     */
2685    @ViewDebug.ExportedProperty(category = "text", mapping = {
2686            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2687            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2688            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2689            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2690            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2691            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2692    })
2693    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2694
2695    /**
2696     * Consistency verifier for debugging purposes.
2697     * @hide
2698     */
2699    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2700            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2701                    new InputEventConsistencyVerifier(this, 0) : null;
2702
2703    /**
2704     * Simple constructor to use when creating a view from code.
2705     *
2706     * @param context The Context the view is running in, through which it can
2707     *        access the current theme, resources, etc.
2708     */
2709    public View(Context context) {
2710        mContext = context;
2711        mResources = context != null ? context.getResources() : null;
2712        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2713        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2714        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2715        mUserPaddingStart = -1;
2716        mUserPaddingEnd = -1;
2717        mUserPaddingRelative = false;
2718    }
2719
2720    /**
2721     * Constructor that is called when inflating a view from XML. This is called
2722     * when a view is being constructed from an XML file, supplying attributes
2723     * that were specified in the XML file. This version uses a default style of
2724     * 0, so the only attribute values applied are those in the Context's Theme
2725     * and the given AttributeSet.
2726     *
2727     * <p>
2728     * The method onFinishInflate() will be called after all children have been
2729     * added.
2730     *
2731     * @param context The Context the view is running in, through which it can
2732     *        access the current theme, resources, etc.
2733     * @param attrs The attributes of the XML tag that is inflating the view.
2734     * @see #View(Context, AttributeSet, int)
2735     */
2736    public View(Context context, AttributeSet attrs) {
2737        this(context, attrs, 0);
2738    }
2739
2740    /**
2741     * Perform inflation from XML and apply a class-specific base style. This
2742     * constructor of View allows subclasses to use their own base style when
2743     * they are inflating. For example, a Button class's constructor would call
2744     * this version of the super class constructor and supply
2745     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2746     * the theme's button style to modify all of the base view attributes (in
2747     * particular its background) as well as the Button class's attributes.
2748     *
2749     * @param context The Context the view is running in, through which it can
2750     *        access the current theme, resources, etc.
2751     * @param attrs The attributes of the XML tag that is inflating the view.
2752     * @param defStyle The default style to apply to this view. If 0, no style
2753     *        will be applied (beyond what is included in the theme). This may
2754     *        either be an attribute resource, whose value will be retrieved
2755     *        from the current theme, or an explicit style resource.
2756     * @see #View(Context, AttributeSet)
2757     */
2758    public View(Context context, AttributeSet attrs, int defStyle) {
2759        this(context);
2760
2761        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2762                defStyle, 0);
2763
2764        Drawable background = null;
2765
2766        int leftPadding = -1;
2767        int topPadding = -1;
2768        int rightPadding = -1;
2769        int bottomPadding = -1;
2770        int startPadding = -1;
2771        int endPadding = -1;
2772
2773        int padding = -1;
2774
2775        int viewFlagValues = 0;
2776        int viewFlagMasks = 0;
2777
2778        boolean setScrollContainer = false;
2779
2780        int x = 0;
2781        int y = 0;
2782
2783        float tx = 0;
2784        float ty = 0;
2785        float rotation = 0;
2786        float rotationX = 0;
2787        float rotationY = 0;
2788        float sx = 1f;
2789        float sy = 1f;
2790        boolean transformSet = false;
2791
2792        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2793
2794        int overScrollMode = mOverScrollMode;
2795        final int N = a.getIndexCount();
2796        for (int i = 0; i < N; i++) {
2797            int attr = a.getIndex(i);
2798            switch (attr) {
2799                case com.android.internal.R.styleable.View_background:
2800                    background = a.getDrawable(attr);
2801                    break;
2802                case com.android.internal.R.styleable.View_padding:
2803                    padding = a.getDimensionPixelSize(attr, -1);
2804                    break;
2805                 case com.android.internal.R.styleable.View_paddingLeft:
2806                    leftPadding = a.getDimensionPixelSize(attr, -1);
2807                    break;
2808                case com.android.internal.R.styleable.View_paddingTop:
2809                    topPadding = a.getDimensionPixelSize(attr, -1);
2810                    break;
2811                case com.android.internal.R.styleable.View_paddingRight:
2812                    rightPadding = a.getDimensionPixelSize(attr, -1);
2813                    break;
2814                case com.android.internal.R.styleable.View_paddingBottom:
2815                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2816                    break;
2817                case com.android.internal.R.styleable.View_paddingStart:
2818                    startPadding = a.getDimensionPixelSize(attr, -1);
2819                    break;
2820                case com.android.internal.R.styleable.View_paddingEnd:
2821                    endPadding = a.getDimensionPixelSize(attr, -1);
2822                    break;
2823                case com.android.internal.R.styleable.View_scrollX:
2824                    x = a.getDimensionPixelOffset(attr, 0);
2825                    break;
2826                case com.android.internal.R.styleable.View_scrollY:
2827                    y = a.getDimensionPixelOffset(attr, 0);
2828                    break;
2829                case com.android.internal.R.styleable.View_alpha:
2830                    setAlpha(a.getFloat(attr, 1f));
2831                    break;
2832                case com.android.internal.R.styleable.View_transformPivotX:
2833                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2834                    break;
2835                case com.android.internal.R.styleable.View_transformPivotY:
2836                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2837                    break;
2838                case com.android.internal.R.styleable.View_translationX:
2839                    tx = a.getDimensionPixelOffset(attr, 0);
2840                    transformSet = true;
2841                    break;
2842                case com.android.internal.R.styleable.View_translationY:
2843                    ty = a.getDimensionPixelOffset(attr, 0);
2844                    transformSet = true;
2845                    break;
2846                case com.android.internal.R.styleable.View_rotation:
2847                    rotation = a.getFloat(attr, 0);
2848                    transformSet = true;
2849                    break;
2850                case com.android.internal.R.styleable.View_rotationX:
2851                    rotationX = a.getFloat(attr, 0);
2852                    transformSet = true;
2853                    break;
2854                case com.android.internal.R.styleable.View_rotationY:
2855                    rotationY = a.getFloat(attr, 0);
2856                    transformSet = true;
2857                    break;
2858                case com.android.internal.R.styleable.View_scaleX:
2859                    sx = a.getFloat(attr, 1f);
2860                    transformSet = true;
2861                    break;
2862                case com.android.internal.R.styleable.View_scaleY:
2863                    sy = a.getFloat(attr, 1f);
2864                    transformSet = true;
2865                    break;
2866                case com.android.internal.R.styleable.View_id:
2867                    mID = a.getResourceId(attr, NO_ID);
2868                    break;
2869                case com.android.internal.R.styleable.View_tag:
2870                    mTag = a.getText(attr);
2871                    break;
2872                case com.android.internal.R.styleable.View_fitsSystemWindows:
2873                    if (a.getBoolean(attr, false)) {
2874                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2875                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2876                    }
2877                    break;
2878                case com.android.internal.R.styleable.View_focusable:
2879                    if (a.getBoolean(attr, false)) {
2880                        viewFlagValues |= FOCUSABLE;
2881                        viewFlagMasks |= FOCUSABLE_MASK;
2882                    }
2883                    break;
2884                case com.android.internal.R.styleable.View_focusableInTouchMode:
2885                    if (a.getBoolean(attr, false)) {
2886                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2887                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2888                    }
2889                    break;
2890                case com.android.internal.R.styleable.View_clickable:
2891                    if (a.getBoolean(attr, false)) {
2892                        viewFlagValues |= CLICKABLE;
2893                        viewFlagMasks |= CLICKABLE;
2894                    }
2895                    break;
2896                case com.android.internal.R.styleable.View_longClickable:
2897                    if (a.getBoolean(attr, false)) {
2898                        viewFlagValues |= LONG_CLICKABLE;
2899                        viewFlagMasks |= LONG_CLICKABLE;
2900                    }
2901                    break;
2902                case com.android.internal.R.styleable.View_saveEnabled:
2903                    if (!a.getBoolean(attr, true)) {
2904                        viewFlagValues |= SAVE_DISABLED;
2905                        viewFlagMasks |= SAVE_DISABLED_MASK;
2906                    }
2907                    break;
2908                case com.android.internal.R.styleable.View_duplicateParentState:
2909                    if (a.getBoolean(attr, false)) {
2910                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2911                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2912                    }
2913                    break;
2914                case com.android.internal.R.styleable.View_visibility:
2915                    final int visibility = a.getInt(attr, 0);
2916                    if (visibility != 0) {
2917                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2918                        viewFlagMasks |= VISIBILITY_MASK;
2919                    }
2920                    break;
2921                case com.android.internal.R.styleable.View_layoutDirection:
2922                    // Clear any HORIZONTAL_DIRECTION flag already set
2923                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2924                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2925                    final int layoutDirection = a.getInt(attr, -1);
2926                    if (layoutDirection != -1) {
2927                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2928                    } else {
2929                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2930                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2931                    }
2932                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2933                    break;
2934                case com.android.internal.R.styleable.View_drawingCacheQuality:
2935                    final int cacheQuality = a.getInt(attr, 0);
2936                    if (cacheQuality != 0) {
2937                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2938                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2939                    }
2940                    break;
2941                case com.android.internal.R.styleable.View_contentDescription:
2942                    mContentDescription = a.getString(attr);
2943                    break;
2944                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2945                    if (!a.getBoolean(attr, true)) {
2946                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2947                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2948                    }
2949                    break;
2950                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2951                    if (!a.getBoolean(attr, true)) {
2952                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2953                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2954                    }
2955                    break;
2956                case R.styleable.View_scrollbars:
2957                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2958                    if (scrollbars != SCROLLBARS_NONE) {
2959                        viewFlagValues |= scrollbars;
2960                        viewFlagMasks |= SCROLLBARS_MASK;
2961                        initializeScrollbars(a);
2962                    }
2963                    break;
2964                //noinspection deprecation
2965                case R.styleable.View_fadingEdge:
2966                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2967                        // Ignore the attribute starting with ICS
2968                        break;
2969                    }
2970                    // With builds < ICS, fall through and apply fading edges
2971                case R.styleable.View_requiresFadingEdge:
2972                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2973                    if (fadingEdge != FADING_EDGE_NONE) {
2974                        viewFlagValues |= fadingEdge;
2975                        viewFlagMasks |= FADING_EDGE_MASK;
2976                        initializeFadingEdge(a);
2977                    }
2978                    break;
2979                case R.styleable.View_scrollbarStyle:
2980                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2981                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2982                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2983                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2984                    }
2985                    break;
2986                case R.styleable.View_isScrollContainer:
2987                    setScrollContainer = true;
2988                    if (a.getBoolean(attr, false)) {
2989                        setScrollContainer(true);
2990                    }
2991                    break;
2992                case com.android.internal.R.styleable.View_keepScreenOn:
2993                    if (a.getBoolean(attr, false)) {
2994                        viewFlagValues |= KEEP_SCREEN_ON;
2995                        viewFlagMasks |= KEEP_SCREEN_ON;
2996                    }
2997                    break;
2998                case R.styleable.View_filterTouchesWhenObscured:
2999                    if (a.getBoolean(attr, false)) {
3000                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3001                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3002                    }
3003                    break;
3004                case R.styleable.View_nextFocusLeft:
3005                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3006                    break;
3007                case R.styleable.View_nextFocusRight:
3008                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3009                    break;
3010                case R.styleable.View_nextFocusUp:
3011                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3012                    break;
3013                case R.styleable.View_nextFocusDown:
3014                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3015                    break;
3016                case R.styleable.View_nextFocusForward:
3017                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3018                    break;
3019                case R.styleable.View_minWidth:
3020                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3021                    break;
3022                case R.styleable.View_minHeight:
3023                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3024                    break;
3025                case R.styleable.View_onClick:
3026                    if (context.isRestricted()) {
3027                        throw new IllegalStateException("The android:onClick attribute cannot "
3028                                + "be used within a restricted context");
3029                    }
3030
3031                    final String handlerName = a.getString(attr);
3032                    if (handlerName != null) {
3033                        setOnClickListener(new OnClickListener() {
3034                            private Method mHandler;
3035
3036                            public void onClick(View v) {
3037                                if (mHandler == null) {
3038                                    try {
3039                                        mHandler = getContext().getClass().getMethod(handlerName,
3040                                                View.class);
3041                                    } catch (NoSuchMethodException e) {
3042                                        int id = getId();
3043                                        String idText = id == NO_ID ? "" : " with id '"
3044                                                + getContext().getResources().getResourceEntryName(
3045                                                    id) + "'";
3046                                        throw new IllegalStateException("Could not find a method " +
3047                                                handlerName + "(View) in the activity "
3048                                                + getContext().getClass() + " for onClick handler"
3049                                                + " on view " + View.this.getClass() + idText, e);
3050                                    }
3051                                }
3052
3053                                try {
3054                                    mHandler.invoke(getContext(), View.this);
3055                                } catch (IllegalAccessException e) {
3056                                    throw new IllegalStateException("Could not execute non "
3057                                            + "public method of the activity", e);
3058                                } catch (InvocationTargetException e) {
3059                                    throw new IllegalStateException("Could not execute "
3060                                            + "method of the activity", e);
3061                                }
3062                            }
3063                        });
3064                    }
3065                    break;
3066                case R.styleable.View_overScrollMode:
3067                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3068                    break;
3069                case R.styleable.View_verticalScrollbarPosition:
3070                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3071                    break;
3072                case R.styleable.View_layerType:
3073                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3074                    break;
3075                case R.styleable.View_textDirection:
3076                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3077                    break;
3078            }
3079        }
3080
3081        a.recycle();
3082
3083        setOverScrollMode(overScrollMode);
3084
3085        if (background != null) {
3086            setBackgroundDrawable(background);
3087        }
3088
3089        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3090
3091        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3092        // layout direction). Those cached values will be used later during padding resolution.
3093        mUserPaddingStart = startPadding;
3094        mUserPaddingEnd = endPadding;
3095
3096        if (padding >= 0) {
3097            leftPadding = padding;
3098            topPadding = padding;
3099            rightPadding = padding;
3100            bottomPadding = padding;
3101        }
3102
3103        // If the user specified the padding (either with android:padding or
3104        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3105        // use the default padding or the padding from the background drawable
3106        // (stored at this point in mPadding*)
3107        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3108                topPadding >= 0 ? topPadding : mPaddingTop,
3109                rightPadding >= 0 ? rightPadding : mPaddingRight,
3110                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3111
3112        if (viewFlagMasks != 0) {
3113            setFlags(viewFlagValues, viewFlagMasks);
3114        }
3115
3116        // Needs to be called after mViewFlags is set
3117        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3118            recomputePadding();
3119        }
3120
3121        if (x != 0 || y != 0) {
3122            scrollTo(x, y);
3123        }
3124
3125        if (transformSet) {
3126            setTranslationX(tx);
3127            setTranslationY(ty);
3128            setRotation(rotation);
3129            setRotationX(rotationX);
3130            setRotationY(rotationY);
3131            setScaleX(sx);
3132            setScaleY(sy);
3133        }
3134
3135        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3136            setScrollContainer(true);
3137        }
3138
3139        computeOpaqueFlags();
3140    }
3141
3142    /**
3143     * Non-public constructor for use in testing
3144     */
3145    View() {
3146        mResources = null;
3147    }
3148
3149    /**
3150     * <p>
3151     * Initializes the fading edges from a given set of styled attributes. This
3152     * method should be called by subclasses that need fading edges and when an
3153     * instance of these subclasses is created programmatically rather than
3154     * being inflated from XML. This method is automatically called when the XML
3155     * is inflated.
3156     * </p>
3157     *
3158     * @param a the styled attributes set to initialize the fading edges from
3159     */
3160    protected void initializeFadingEdge(TypedArray a) {
3161        initScrollCache();
3162
3163        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3164                R.styleable.View_fadingEdgeLength,
3165                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3166    }
3167
3168    /**
3169     * Returns the size of the vertical faded edges used to indicate that more
3170     * content in this view is visible.
3171     *
3172     * @return The size in pixels of the vertical faded edge or 0 if vertical
3173     *         faded edges are not enabled for this view.
3174     * @attr ref android.R.styleable#View_fadingEdgeLength
3175     */
3176    public int getVerticalFadingEdgeLength() {
3177        if (isVerticalFadingEdgeEnabled()) {
3178            ScrollabilityCache cache = mScrollCache;
3179            if (cache != null) {
3180                return cache.fadingEdgeLength;
3181            }
3182        }
3183        return 0;
3184    }
3185
3186    /**
3187     * Set the size of the faded edge used to indicate that more content in this
3188     * view is available.  Will not change whether the fading edge is enabled; use
3189     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3190     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3191     * for the vertical or horizontal fading edges.
3192     *
3193     * @param length The size in pixels of the faded edge used to indicate that more
3194     *        content in this view is visible.
3195     */
3196    public void setFadingEdgeLength(int length) {
3197        initScrollCache();
3198        mScrollCache.fadingEdgeLength = length;
3199    }
3200
3201    /**
3202     * Returns the size of the horizontal faded edges used to indicate that more
3203     * content in this view is visible.
3204     *
3205     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3206     *         faded edges are not enabled for this view.
3207     * @attr ref android.R.styleable#View_fadingEdgeLength
3208     */
3209    public int getHorizontalFadingEdgeLength() {
3210        if (isHorizontalFadingEdgeEnabled()) {
3211            ScrollabilityCache cache = mScrollCache;
3212            if (cache != null) {
3213                return cache.fadingEdgeLength;
3214            }
3215        }
3216        return 0;
3217    }
3218
3219    /**
3220     * Returns the width of the vertical scrollbar.
3221     *
3222     * @return The width in pixels of the vertical scrollbar or 0 if there
3223     *         is no vertical scrollbar.
3224     */
3225    public int getVerticalScrollbarWidth() {
3226        ScrollabilityCache cache = mScrollCache;
3227        if (cache != null) {
3228            ScrollBarDrawable scrollBar = cache.scrollBar;
3229            if (scrollBar != null) {
3230                int size = scrollBar.getSize(true);
3231                if (size <= 0) {
3232                    size = cache.scrollBarSize;
3233                }
3234                return size;
3235            }
3236            return 0;
3237        }
3238        return 0;
3239    }
3240
3241    /**
3242     * Returns the height of the horizontal scrollbar.
3243     *
3244     * @return The height in pixels of the horizontal scrollbar or 0 if
3245     *         there is no horizontal scrollbar.
3246     */
3247    protected int getHorizontalScrollbarHeight() {
3248        ScrollabilityCache cache = mScrollCache;
3249        if (cache != null) {
3250            ScrollBarDrawable scrollBar = cache.scrollBar;
3251            if (scrollBar != null) {
3252                int size = scrollBar.getSize(false);
3253                if (size <= 0) {
3254                    size = cache.scrollBarSize;
3255                }
3256                return size;
3257            }
3258            return 0;
3259        }
3260        return 0;
3261    }
3262
3263    /**
3264     * <p>
3265     * Initializes the scrollbars from a given set of styled attributes. This
3266     * method should be called by subclasses that need scrollbars and when an
3267     * instance of these subclasses is created programmatically rather than
3268     * being inflated from XML. This method is automatically called when the XML
3269     * is inflated.
3270     * </p>
3271     *
3272     * @param a the styled attributes set to initialize the scrollbars from
3273     */
3274    protected void initializeScrollbars(TypedArray a) {
3275        initScrollCache();
3276
3277        final ScrollabilityCache scrollabilityCache = mScrollCache;
3278
3279        if (scrollabilityCache.scrollBar == null) {
3280            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3281        }
3282
3283        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3284
3285        if (!fadeScrollbars) {
3286            scrollabilityCache.state = ScrollabilityCache.ON;
3287        }
3288        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3289
3290
3291        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3292                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3293                        .getScrollBarFadeDuration());
3294        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3295                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3296                ViewConfiguration.getScrollDefaultDelay());
3297
3298
3299        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3300                com.android.internal.R.styleable.View_scrollbarSize,
3301                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3302
3303        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3304        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3305
3306        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3307        if (thumb != null) {
3308            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3309        }
3310
3311        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3312                false);
3313        if (alwaysDraw) {
3314            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3315        }
3316
3317        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3318        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3319
3320        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3321        if (thumb != null) {
3322            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3323        }
3324
3325        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3326                false);
3327        if (alwaysDraw) {
3328            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3329        }
3330
3331        // Re-apply user/background padding so that scrollbar(s) get added
3332        resolvePadding();
3333    }
3334
3335    /**
3336     * <p>
3337     * Initalizes the scrollability cache if necessary.
3338     * </p>
3339     */
3340    private void initScrollCache() {
3341        if (mScrollCache == null) {
3342            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3343        }
3344    }
3345
3346    /**
3347     * Set the position of the vertical scroll bar. Should be one of
3348     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3349     * {@link #SCROLLBAR_POSITION_RIGHT}.
3350     *
3351     * @param position Where the vertical scroll bar should be positioned.
3352     */
3353    public void setVerticalScrollbarPosition(int position) {
3354        if (mVerticalScrollbarPosition != position) {
3355            mVerticalScrollbarPosition = position;
3356            computeOpaqueFlags();
3357            resolvePadding();
3358        }
3359    }
3360
3361    /**
3362     * @return The position where the vertical scroll bar will show, if applicable.
3363     * @see #setVerticalScrollbarPosition(int)
3364     */
3365    public int getVerticalScrollbarPosition() {
3366        return mVerticalScrollbarPosition;
3367    }
3368
3369    ListenerInfo getListenerInfo() {
3370        if (mListenerInfo != null) {
3371            return mListenerInfo;
3372        }
3373        mListenerInfo = new ListenerInfo();
3374        return mListenerInfo;
3375    }
3376
3377    /**
3378     * Register a callback to be invoked when focus of this view changed.
3379     *
3380     * @param l The callback that will run.
3381     */
3382    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3383        getListenerInfo().mOnFocusChangeListener = l;
3384    }
3385
3386    /**
3387     * Add a listener that will be called when the bounds of the view change due to
3388     * layout processing.
3389     *
3390     * @param listener The listener that will be called when layout bounds change.
3391     */
3392    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3393        ListenerInfo li = getListenerInfo();
3394        if (li.mOnLayoutChangeListeners == null) {
3395            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3396        }
3397        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3398            li.mOnLayoutChangeListeners.add(listener);
3399        }
3400    }
3401
3402    /**
3403     * Remove a listener for layout changes.
3404     *
3405     * @param listener The listener for layout bounds change.
3406     */
3407    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3408        ListenerInfo li = mListenerInfo;
3409        if (li == null || li.mOnLayoutChangeListeners == null) {
3410            return;
3411        }
3412        li.mOnLayoutChangeListeners.remove(listener);
3413    }
3414
3415    /**
3416     * Add a listener for attach state changes.
3417     *
3418     * This listener will be called whenever this view is attached or detached
3419     * from a window. Remove the listener using
3420     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3421     *
3422     * @param listener Listener to attach
3423     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3424     */
3425    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3426        ListenerInfo li = getListenerInfo();
3427        if (li.mOnAttachStateChangeListeners == null) {
3428            li.mOnAttachStateChangeListeners
3429                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3430        }
3431        li.mOnAttachStateChangeListeners.add(listener);
3432    }
3433
3434    /**
3435     * Remove a listener for attach state changes. The listener will receive no further
3436     * notification of window attach/detach events.
3437     *
3438     * @param listener Listener to remove
3439     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3440     */
3441    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3442        ListenerInfo li = mListenerInfo;
3443        if (li == null || li.mOnAttachStateChangeListeners == null) {
3444            return;
3445        }
3446        li.mOnAttachStateChangeListeners.remove(listener);
3447    }
3448
3449    /**
3450     * Returns the focus-change callback registered for this view.
3451     *
3452     * @return The callback, or null if one is not registered.
3453     */
3454    public OnFocusChangeListener getOnFocusChangeListener() {
3455        ListenerInfo li = mListenerInfo;
3456        return li != null ? li.mOnFocusChangeListener : null;
3457    }
3458
3459    /**
3460     * Register a callback to be invoked when this view is clicked. If this view is not
3461     * clickable, it becomes clickable.
3462     *
3463     * @param l The callback that will run
3464     *
3465     * @see #setClickable(boolean)
3466     */
3467    public void setOnClickListener(OnClickListener l) {
3468        if (!isClickable()) {
3469            setClickable(true);
3470        }
3471        getListenerInfo().mOnClickListener = l;
3472    }
3473
3474    /**
3475     * Return whether this view has an attached OnClickListener.  Returns
3476     * true if there is a listener, false if there is none.
3477     */
3478    public boolean hasOnClickListeners() {
3479        ListenerInfo li = mListenerInfo;
3480        return (li != null && li.mOnClickListener != null);
3481    }
3482
3483    /**
3484     * Register a callback to be invoked when this view is clicked and held. If this view is not
3485     * long clickable, it becomes long clickable.
3486     *
3487     * @param l The callback that will run
3488     *
3489     * @see #setLongClickable(boolean)
3490     */
3491    public void setOnLongClickListener(OnLongClickListener l) {
3492        if (!isLongClickable()) {
3493            setLongClickable(true);
3494        }
3495        getListenerInfo().mOnLongClickListener = l;
3496    }
3497
3498    /**
3499     * Register a callback to be invoked when the context menu for this view is
3500     * being built. If this view is not long clickable, it becomes long clickable.
3501     *
3502     * @param l The callback that will run
3503     *
3504     */
3505    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3506        if (!isLongClickable()) {
3507            setLongClickable(true);
3508        }
3509        getListenerInfo().mOnCreateContextMenuListener = l;
3510    }
3511
3512    /**
3513     * Call this view's OnClickListener, if it is defined.  Performs all normal
3514     * actions associated with clicking: reporting accessibility event, playing
3515     * a sound, etc.
3516     *
3517     * @return True there was an assigned OnClickListener that was called, false
3518     *         otherwise is returned.
3519     */
3520    public boolean performClick() {
3521        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3522
3523        ListenerInfo li = mListenerInfo;
3524        if (li != null && li.mOnClickListener != null) {
3525            playSoundEffect(SoundEffectConstants.CLICK);
3526            li.mOnClickListener.onClick(this);
3527            return true;
3528        }
3529
3530        return false;
3531    }
3532
3533    /**
3534     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3535     * this only calls the listener, and does not do any associated clicking
3536     * actions like reporting an accessibility event.
3537     *
3538     * @return True there was an assigned OnClickListener that was called, false
3539     *         otherwise is returned.
3540     */
3541    public boolean callOnClick() {
3542        ListenerInfo li = mListenerInfo;
3543        if (li != null && li.mOnClickListener != null) {
3544            li.mOnClickListener.onClick(this);
3545            return true;
3546        }
3547        return false;
3548    }
3549
3550    /**
3551     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3552     * OnLongClickListener did not consume the event.
3553     *
3554     * @return True if one of the above receivers consumed the event, false otherwise.
3555     */
3556    public boolean performLongClick() {
3557        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3558
3559        boolean handled = false;
3560        ListenerInfo li = mListenerInfo;
3561        if (li != null && li.mOnLongClickListener != null) {
3562            handled = li.mOnLongClickListener.onLongClick(View.this);
3563        }
3564        if (!handled) {
3565            handled = showContextMenu();
3566        }
3567        if (handled) {
3568            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3569        }
3570        return handled;
3571    }
3572
3573    /**
3574     * Performs button-related actions during a touch down event.
3575     *
3576     * @param event The event.
3577     * @return True if the down was consumed.
3578     *
3579     * @hide
3580     */
3581    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3582        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3583            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3584                return true;
3585            }
3586        }
3587        return false;
3588    }
3589
3590    /**
3591     * Bring up the context menu for this view.
3592     *
3593     * @return Whether a context menu was displayed.
3594     */
3595    public boolean showContextMenu() {
3596        return getParent().showContextMenuForChild(this);
3597    }
3598
3599    /**
3600     * Bring up the context menu for this view, referring to the item under the specified point.
3601     *
3602     * @param x The referenced x coordinate.
3603     * @param y The referenced y coordinate.
3604     * @param metaState The keyboard modifiers that were pressed.
3605     * @return Whether a context menu was displayed.
3606     *
3607     * @hide
3608     */
3609    public boolean showContextMenu(float x, float y, int metaState) {
3610        return showContextMenu();
3611    }
3612
3613    /**
3614     * Start an action mode.
3615     *
3616     * @param callback Callback that will control the lifecycle of the action mode
3617     * @return The new action mode if it is started, null otherwise
3618     *
3619     * @see ActionMode
3620     */
3621    public ActionMode startActionMode(ActionMode.Callback callback) {
3622        return getParent().startActionModeForChild(this, callback);
3623    }
3624
3625    /**
3626     * Register a callback to be invoked when a key is pressed in this view.
3627     * @param l the key listener to attach to this view
3628     */
3629    public void setOnKeyListener(OnKeyListener l) {
3630        getListenerInfo().mOnKeyListener = l;
3631    }
3632
3633    /**
3634     * Register a callback to be invoked when a touch event is sent to this view.
3635     * @param l the touch listener to attach to this view
3636     */
3637    public void setOnTouchListener(OnTouchListener l) {
3638        getListenerInfo().mOnTouchListener = l;
3639    }
3640
3641    /**
3642     * Register a callback to be invoked when a generic motion event is sent to this view.
3643     * @param l the generic motion listener to attach to this view
3644     */
3645    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3646        getListenerInfo().mOnGenericMotionListener = l;
3647    }
3648
3649    /**
3650     * Register a callback to be invoked when a hover event is sent to this view.
3651     * @param l the hover listener to attach to this view
3652     */
3653    public void setOnHoverListener(OnHoverListener l) {
3654        getListenerInfo().mOnHoverListener = l;
3655    }
3656
3657    /**
3658     * Register a drag event listener callback object for this View. The parameter is
3659     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3660     * View, the system calls the
3661     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3662     * @param l An implementation of {@link android.view.View.OnDragListener}.
3663     */
3664    public void setOnDragListener(OnDragListener l) {
3665        getListenerInfo().mOnDragListener = l;
3666    }
3667
3668    /**
3669     * Give this view focus. This will cause
3670     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3671     *
3672     * Note: this does not check whether this {@link View} should get focus, it just
3673     * gives it focus no matter what.  It should only be called internally by framework
3674     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3675     *
3676     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3677     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3678     *        focus moved when requestFocus() is called. It may not always
3679     *        apply, in which case use the default View.FOCUS_DOWN.
3680     * @param previouslyFocusedRect The rectangle of the view that had focus
3681     *        prior in this View's coordinate system.
3682     */
3683    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3684        if (DBG) {
3685            System.out.println(this + " requestFocus()");
3686        }
3687
3688        if ((mPrivateFlags & FOCUSED) == 0) {
3689            mPrivateFlags |= FOCUSED;
3690
3691            if (mParent != null) {
3692                mParent.requestChildFocus(this, this);
3693            }
3694
3695            onFocusChanged(true, direction, previouslyFocusedRect);
3696            refreshDrawableState();
3697        }
3698    }
3699
3700    /**
3701     * Request that a rectangle of this view be visible on the screen,
3702     * scrolling if necessary just enough.
3703     *
3704     * <p>A View should call this if it maintains some notion of which part
3705     * of its content is interesting.  For example, a text editing view
3706     * should call this when its cursor moves.
3707     *
3708     * @param rectangle The rectangle.
3709     * @return Whether any parent scrolled.
3710     */
3711    public boolean requestRectangleOnScreen(Rect rectangle) {
3712        return requestRectangleOnScreen(rectangle, false);
3713    }
3714
3715    /**
3716     * Request that a rectangle of this view be visible on the screen,
3717     * scrolling if necessary just enough.
3718     *
3719     * <p>A View should call this if it maintains some notion of which part
3720     * of its content is interesting.  For example, a text editing view
3721     * should call this when its cursor moves.
3722     *
3723     * <p>When <code>immediate</code> is set to true, scrolling will not be
3724     * animated.
3725     *
3726     * @param rectangle The rectangle.
3727     * @param immediate True to forbid animated scrolling, false otherwise
3728     * @return Whether any parent scrolled.
3729     */
3730    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3731        View child = this;
3732        ViewParent parent = mParent;
3733        boolean scrolled = false;
3734        while (parent != null) {
3735            scrolled |= parent.requestChildRectangleOnScreen(child,
3736                    rectangle, immediate);
3737
3738            // offset rect so next call has the rectangle in the
3739            // coordinate system of its direct child.
3740            rectangle.offset(child.getLeft(), child.getTop());
3741            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3742
3743            if (!(parent instanceof View)) {
3744                break;
3745            }
3746
3747            child = (View) parent;
3748            parent = child.getParent();
3749        }
3750        return scrolled;
3751    }
3752
3753    /**
3754     * Called when this view wants to give up focus. If focus is cleared
3755     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3756     * <p>
3757     * <strong>Note:</strong> When a View clears focus the framework is trying
3758     * to give focus to the first focusable View from the top. Hence, if this
3759     * View is the first from the top that can take focus, then its focus will
3760     * not be cleared nor will the focus change callback be invoked.
3761     * </p>
3762     */
3763    public void clearFocus() {
3764        if (DBG) {
3765            System.out.println(this + " clearFocus()");
3766        }
3767
3768        if ((mPrivateFlags & FOCUSED) != 0) {
3769            mPrivateFlags &= ~FOCUSED;
3770
3771            if (mParent != null) {
3772                mParent.clearChildFocus(this);
3773            }
3774
3775            onFocusChanged(false, 0, null);
3776            refreshDrawableState();
3777        }
3778    }
3779
3780    /**
3781     * Called to clear the focus of a view that is about to be removed.
3782     * Doesn't call clearChildFocus, which prevents this view from taking
3783     * focus again before it has been removed from the parent
3784     */
3785    void clearFocusForRemoval() {
3786        if ((mPrivateFlags & FOCUSED) != 0) {
3787            mPrivateFlags &= ~FOCUSED;
3788
3789            onFocusChanged(false, 0, null);
3790            refreshDrawableState();
3791
3792            // The view cleared focus and invoked the callbacks, so  now is the
3793            // time to give focus to the the first focusable from the top to
3794            // ensure that the gain focus is announced after clear focus.
3795            getRootView().requestFocus(FOCUS_FORWARD);
3796        }
3797    }
3798
3799    /**
3800     * Called internally by the view system when a new view is getting focus.
3801     * This is what clears the old focus.
3802     */
3803    void unFocus() {
3804        if (DBG) {
3805            System.out.println(this + " unFocus()");
3806        }
3807
3808        if ((mPrivateFlags & FOCUSED) != 0) {
3809            mPrivateFlags &= ~FOCUSED;
3810
3811            onFocusChanged(false, 0, null);
3812            refreshDrawableState();
3813        }
3814    }
3815
3816    /**
3817     * Returns true if this view has focus iteself, or is the ancestor of the
3818     * view that has focus.
3819     *
3820     * @return True if this view has or contains focus, false otherwise.
3821     */
3822    @ViewDebug.ExportedProperty(category = "focus")
3823    public boolean hasFocus() {
3824        return (mPrivateFlags & FOCUSED) != 0;
3825    }
3826
3827    /**
3828     * Returns true if this view is focusable or if it contains a reachable View
3829     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3830     * is a View whose parents do not block descendants focus.
3831     *
3832     * Only {@link #VISIBLE} views are considered focusable.
3833     *
3834     * @return True if the view is focusable or if the view contains a focusable
3835     *         View, false otherwise.
3836     *
3837     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3838     */
3839    public boolean hasFocusable() {
3840        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3841    }
3842
3843    /**
3844     * Called by the view system when the focus state of this view changes.
3845     * When the focus change event is caused by directional navigation, direction
3846     * and previouslyFocusedRect provide insight into where the focus is coming from.
3847     * When overriding, be sure to call up through to the super class so that
3848     * the standard focus handling will occur.
3849     *
3850     * @param gainFocus True if the View has focus; false otherwise.
3851     * @param direction The direction focus has moved when requestFocus()
3852     *                  is called to give this view focus. Values are
3853     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3854     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3855     *                  It may not always apply, in which case use the default.
3856     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3857     *        system, of the previously focused view.  If applicable, this will be
3858     *        passed in as finer grained information about where the focus is coming
3859     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3860     */
3861    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3862        if (gainFocus) {
3863            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3864        }
3865
3866        InputMethodManager imm = InputMethodManager.peekInstance();
3867        if (!gainFocus) {
3868            if (isPressed()) {
3869                setPressed(false);
3870            }
3871            if (imm != null && mAttachInfo != null
3872                    && mAttachInfo.mHasWindowFocus) {
3873                imm.focusOut(this);
3874            }
3875            onFocusLost();
3876        } else if (imm != null && mAttachInfo != null
3877                && mAttachInfo.mHasWindowFocus) {
3878            imm.focusIn(this);
3879        }
3880
3881        invalidate(true);
3882        ListenerInfo li = mListenerInfo;
3883        if (li != null && li.mOnFocusChangeListener != null) {
3884            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3885        }
3886
3887        if (mAttachInfo != null) {
3888            mAttachInfo.mKeyDispatchState.reset(this);
3889        }
3890    }
3891
3892    /**
3893     * Sends an accessibility event of the given type. If accessiiblity is
3894     * not enabled this method has no effect. The default implementation calls
3895     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3896     * to populate information about the event source (this View), then calls
3897     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3898     * populate the text content of the event source including its descendants,
3899     * and last calls
3900     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3901     * on its parent to resuest sending of the event to interested parties.
3902     * <p>
3903     * If an {@link AccessibilityDelegate} has been specified via calling
3904     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3905     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3906     * responsible for handling this call.
3907     * </p>
3908     *
3909     * @param eventType The type of the event to send, as defined by several types from
3910     * {@link android.view.accessibility.AccessibilityEvent}, such as
3911     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3912     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3913     *
3914     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3915     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3916     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3917     * @see AccessibilityDelegate
3918     */
3919    public void sendAccessibilityEvent(int eventType) {
3920        if (mAccessibilityDelegate != null) {
3921            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3922        } else {
3923            sendAccessibilityEventInternal(eventType);
3924        }
3925    }
3926
3927    /**
3928     * @see #sendAccessibilityEvent(int)
3929     *
3930     * Note: Called from the default {@link AccessibilityDelegate}.
3931     */
3932    void sendAccessibilityEventInternal(int eventType) {
3933        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3934            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3935        }
3936    }
3937
3938    /**
3939     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3940     * takes as an argument an empty {@link AccessibilityEvent} and does not
3941     * perform a check whether accessibility is enabled.
3942     * <p>
3943     * If an {@link AccessibilityDelegate} has been specified via calling
3944     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3945     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3946     * is responsible for handling this call.
3947     * </p>
3948     *
3949     * @param event The event to send.
3950     *
3951     * @see #sendAccessibilityEvent(int)
3952     */
3953    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3954        if (mAccessibilityDelegate != null) {
3955           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3956        } else {
3957            sendAccessibilityEventUncheckedInternal(event);
3958        }
3959    }
3960
3961    /**
3962     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3963     *
3964     * Note: Called from the default {@link AccessibilityDelegate}.
3965     */
3966    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3967        if (!isShown()) {
3968            return;
3969        }
3970        onInitializeAccessibilityEvent(event);
3971        // Only a subset of accessibility events populates text content.
3972        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
3973            dispatchPopulateAccessibilityEvent(event);
3974        }
3975        // In the beginning we called #isShown(), so we know that getParent() is not null.
3976        getParent().requestSendAccessibilityEvent(this, event);
3977    }
3978
3979    /**
3980     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3981     * to its children for adding their text content to the event. Note that the
3982     * event text is populated in a separate dispatch path since we add to the
3983     * event not only the text of the source but also the text of all its descendants.
3984     * A typical implementation will call
3985     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3986     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3987     * on each child. Override this method if custom population of the event text
3988     * content is required.
3989     * <p>
3990     * If an {@link AccessibilityDelegate} has been specified via calling
3991     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3992     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
3993     * is responsible for handling this call.
3994     * </p>
3995     * <p>
3996     * <em>Note:</em> Accessibility events of certain types are not dispatched for
3997     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
3998     * </p>
3999     *
4000     * @param event The event.
4001     *
4002     * @return True if the event population was completed.
4003     */
4004    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4005        if (mAccessibilityDelegate != null) {
4006            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4007        } else {
4008            return dispatchPopulateAccessibilityEventInternal(event);
4009        }
4010    }
4011
4012    /**
4013     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4014     *
4015     * Note: Called from the default {@link AccessibilityDelegate}.
4016     */
4017    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4018        onPopulateAccessibilityEvent(event);
4019        return false;
4020    }
4021
4022    /**
4023     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4024     * giving a chance to this View to populate the accessibility event with its
4025     * text content. While this method is free to modify event
4026     * attributes other than text content, doing so should normally be performed in
4027     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4028     * <p>
4029     * Example: Adding formatted date string to an accessibility event in addition
4030     *          to the text added by the super implementation:
4031     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4032     *     super.onPopulateAccessibilityEvent(event);
4033     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4034     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4035     *         mCurrentDate.getTimeInMillis(), flags);
4036     *     event.getText().add(selectedDateUtterance);
4037     * }</pre>
4038     * <p>
4039     * If an {@link AccessibilityDelegate} has been specified via calling
4040     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4041     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4042     * is responsible for handling this call.
4043     * </p>
4044     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4045     * information to the event, in case the default implementation has basic information to add.
4046     * </p>
4047     *
4048     * @param event The accessibility event which to populate.
4049     *
4050     * @see #sendAccessibilityEvent(int)
4051     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4052     */
4053    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4054        if (mAccessibilityDelegate != null) {
4055            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4056        } else {
4057            onPopulateAccessibilityEventInternal(event);
4058        }
4059    }
4060
4061    /**
4062     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4063     *
4064     * Note: Called from the default {@link AccessibilityDelegate}.
4065     */
4066    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4067
4068    }
4069
4070    /**
4071     * Initializes an {@link AccessibilityEvent} with information about
4072     * this View which is the event source. In other words, the source of
4073     * an accessibility event is the view whose state change triggered firing
4074     * the event.
4075     * <p>
4076     * Example: Setting the password property of an event in addition
4077     *          to properties set by the super implementation:
4078     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4079     *     super.onInitializeAccessibilityEvent(event);
4080     *     event.setPassword(true);
4081     * }</pre>
4082     * <p>
4083     * If an {@link AccessibilityDelegate} has been specified via calling
4084     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4085     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4086     * is responsible for handling this call.
4087     * </p>
4088     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4089     * information to the event, in case the default implementation has basic information to add.
4090     * </p>
4091     * @param event The event to initialize.
4092     *
4093     * @see #sendAccessibilityEvent(int)
4094     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4095     */
4096    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4097        if (mAccessibilityDelegate != null) {
4098            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4099        } else {
4100            onInitializeAccessibilityEventInternal(event);
4101        }
4102    }
4103
4104    /**
4105     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4106     *
4107     * Note: Called from the default {@link AccessibilityDelegate}.
4108     */
4109    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4110        event.setSource(this);
4111        event.setClassName(View.class.getName());
4112        event.setPackageName(getContext().getPackageName());
4113        event.setEnabled(isEnabled());
4114        event.setContentDescription(mContentDescription);
4115
4116        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4117            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4118            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4119                    FOCUSABLES_ALL);
4120            event.setItemCount(focusablesTempList.size());
4121            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4122            focusablesTempList.clear();
4123        }
4124    }
4125
4126    /**
4127     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4128     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4129     * This method is responsible for obtaining an accessibility node info from a
4130     * pool of reusable instances and calling
4131     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4132     * initialize the former.
4133     * <p>
4134     * Note: The client is responsible for recycling the obtained instance by calling
4135     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4136     * </p>
4137     *
4138     * @return A populated {@link AccessibilityNodeInfo}.
4139     *
4140     * @see AccessibilityNodeInfo
4141     */
4142    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4143        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4144        if (provider != null) {
4145            return provider.createAccessibilityNodeInfo(View.NO_ID);
4146        } else {
4147            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4148            onInitializeAccessibilityNodeInfo(info);
4149            return info;
4150        }
4151    }
4152
4153    /**
4154     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4155     * The base implementation sets:
4156     * <ul>
4157     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4158     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4159     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4160     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4161     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4162     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4163     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4164     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4165     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4166     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4167     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4168     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4169     * </ul>
4170     * <p>
4171     * Subclasses should override this method, call the super implementation,
4172     * and set additional attributes.
4173     * </p>
4174     * <p>
4175     * If an {@link AccessibilityDelegate} has been specified via calling
4176     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4177     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4178     * is responsible for handling this call.
4179     * </p>
4180     *
4181     * @param info The instance to initialize.
4182     */
4183    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4184        if (mAccessibilityDelegate != null) {
4185            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4186        } else {
4187            onInitializeAccessibilityNodeInfoInternal(info);
4188        }
4189    }
4190
4191    /**
4192     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4193     *
4194     * Note: Called from the default {@link AccessibilityDelegate}.
4195     */
4196    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4197        Rect bounds = mAttachInfo.mTmpInvalRect;
4198        getDrawingRect(bounds);
4199        info.setBoundsInParent(bounds);
4200
4201        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4202        getLocationOnScreen(locationOnScreen);
4203        bounds.offsetTo(0, 0);
4204        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4205        info.setBoundsInScreen(bounds);
4206
4207        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4208            ViewParent parent = getParent();
4209            if (parent instanceof View) {
4210                View parentView = (View) parent;
4211                info.setParent(parentView);
4212            }
4213        }
4214
4215        info.setPackageName(mContext.getPackageName());
4216        info.setClassName(View.class.getName());
4217        info.setContentDescription(getContentDescription());
4218
4219        info.setEnabled(isEnabled());
4220        info.setClickable(isClickable());
4221        info.setFocusable(isFocusable());
4222        info.setFocused(isFocused());
4223        info.setSelected(isSelected());
4224        info.setLongClickable(isLongClickable());
4225
4226        // TODO: These make sense only if we are in an AdapterView but all
4227        // views can be selected. Maybe from accessiiblity perspective
4228        // we should report as selectable view in an AdapterView.
4229        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4230        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4231
4232        if (isFocusable()) {
4233            if (isFocused()) {
4234                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4235            } else {
4236                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4237            }
4238        }
4239    }
4240
4241    /**
4242     * Sets a delegate for implementing accessibility support via compositon as
4243     * opposed to inheritance. The delegate's primary use is for implementing
4244     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4245     *
4246     * @param delegate The delegate instance.
4247     *
4248     * @see AccessibilityDelegate
4249     */
4250    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4251        mAccessibilityDelegate = delegate;
4252    }
4253
4254    /**
4255     * Gets the provider for managing a virtual view hierarchy rooted at this View
4256     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4257     * that explore the window content.
4258     * <p>
4259     * If this method returns an instance, this instance is responsible for managing
4260     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4261     * View including the one representing the View itself. Similarly the returned
4262     * instance is responsible for performing accessibility actions on any virtual
4263     * view or the root view itself.
4264     * </p>
4265     * <p>
4266     * If an {@link AccessibilityDelegate} has been specified via calling
4267     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4268     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4269     * is responsible for handling this call.
4270     * </p>
4271     *
4272     * @return The provider.
4273     *
4274     * @see AccessibilityNodeProvider
4275     */
4276    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4277        if (mAccessibilityDelegate != null) {
4278            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4279        } else {
4280            return null;
4281        }
4282    }
4283
4284    /**
4285     * Gets the unique identifier of this view on the screen for accessibility purposes.
4286     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4287     *
4288     * @return The view accessibility id.
4289     *
4290     * @hide
4291     */
4292    public int getAccessibilityViewId() {
4293        if (mAccessibilityViewId == NO_ID) {
4294            mAccessibilityViewId = sNextAccessibilityViewId++;
4295        }
4296        return mAccessibilityViewId;
4297    }
4298
4299    /**
4300     * Gets the unique identifier of the window in which this View reseides.
4301     *
4302     * @return The window accessibility id.
4303     *
4304     * @hide
4305     */
4306    public int getAccessibilityWindowId() {
4307        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4308    }
4309
4310    /**
4311     * Gets the {@link View} description. It briefly describes the view and is
4312     * primarily used for accessibility support. Set this property to enable
4313     * better accessibility support for your application. This is especially
4314     * true for views that do not have textual representation (For example,
4315     * ImageButton).
4316     *
4317     * @return The content descriptiopn.
4318     *
4319     * @attr ref android.R.styleable#View_contentDescription
4320     */
4321    public CharSequence getContentDescription() {
4322        return mContentDescription;
4323    }
4324
4325    /**
4326     * Sets the {@link View} description. It briefly describes the view and is
4327     * primarily used for accessibility support. Set this property to enable
4328     * better accessibility support for your application. This is especially
4329     * true for views that do not have textual representation (For example,
4330     * ImageButton).
4331     *
4332     * @param contentDescription The content description.
4333     *
4334     * @attr ref android.R.styleable#View_contentDescription
4335     */
4336    @RemotableViewMethod
4337    public void setContentDescription(CharSequence contentDescription) {
4338        mContentDescription = contentDescription;
4339    }
4340
4341    /**
4342     * Invoked whenever this view loses focus, either by losing window focus or by losing
4343     * focus within its window. This method can be used to clear any state tied to the
4344     * focus. For instance, if a button is held pressed with the trackball and the window
4345     * loses focus, this method can be used to cancel the press.
4346     *
4347     * Subclasses of View overriding this method should always call super.onFocusLost().
4348     *
4349     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4350     * @see #onWindowFocusChanged(boolean)
4351     *
4352     * @hide pending API council approval
4353     */
4354    protected void onFocusLost() {
4355        resetPressedState();
4356    }
4357
4358    private void resetPressedState() {
4359        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4360            return;
4361        }
4362
4363        if (isPressed()) {
4364            setPressed(false);
4365
4366            if (!mHasPerformedLongPress) {
4367                removeLongPressCallback();
4368            }
4369        }
4370    }
4371
4372    /**
4373     * Returns true if this view has focus
4374     *
4375     * @return True if this view has focus, false otherwise.
4376     */
4377    @ViewDebug.ExportedProperty(category = "focus")
4378    public boolean isFocused() {
4379        return (mPrivateFlags & FOCUSED) != 0;
4380    }
4381
4382    /**
4383     * Find the view in the hierarchy rooted at this view that currently has
4384     * focus.
4385     *
4386     * @return The view that currently has focus, or null if no focused view can
4387     *         be found.
4388     */
4389    public View findFocus() {
4390        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4391    }
4392
4393    /**
4394     * Change whether this view is one of the set of scrollable containers in
4395     * its window.  This will be used to determine whether the window can
4396     * resize or must pan when a soft input area is open -- scrollable
4397     * containers allow the window to use resize mode since the container
4398     * will appropriately shrink.
4399     */
4400    public void setScrollContainer(boolean isScrollContainer) {
4401        if (isScrollContainer) {
4402            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4403                mAttachInfo.mScrollContainers.add(this);
4404                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4405            }
4406            mPrivateFlags |= SCROLL_CONTAINER;
4407        } else {
4408            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4409                mAttachInfo.mScrollContainers.remove(this);
4410            }
4411            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4412        }
4413    }
4414
4415    /**
4416     * Returns the quality of the drawing cache.
4417     *
4418     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4419     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4420     *
4421     * @see #setDrawingCacheQuality(int)
4422     * @see #setDrawingCacheEnabled(boolean)
4423     * @see #isDrawingCacheEnabled()
4424     *
4425     * @attr ref android.R.styleable#View_drawingCacheQuality
4426     */
4427    public int getDrawingCacheQuality() {
4428        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4429    }
4430
4431    /**
4432     * Set the drawing cache quality of this view. This value is used only when the
4433     * drawing cache is enabled
4434     *
4435     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4436     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4437     *
4438     * @see #getDrawingCacheQuality()
4439     * @see #setDrawingCacheEnabled(boolean)
4440     * @see #isDrawingCacheEnabled()
4441     *
4442     * @attr ref android.R.styleable#View_drawingCacheQuality
4443     */
4444    public void setDrawingCacheQuality(int quality) {
4445        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4446    }
4447
4448    /**
4449     * Returns whether the screen should remain on, corresponding to the current
4450     * value of {@link #KEEP_SCREEN_ON}.
4451     *
4452     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4453     *
4454     * @see #setKeepScreenOn(boolean)
4455     *
4456     * @attr ref android.R.styleable#View_keepScreenOn
4457     */
4458    public boolean getKeepScreenOn() {
4459        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4460    }
4461
4462    /**
4463     * Controls whether the screen should remain on, modifying the
4464     * value of {@link #KEEP_SCREEN_ON}.
4465     *
4466     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4467     *
4468     * @see #getKeepScreenOn()
4469     *
4470     * @attr ref android.R.styleable#View_keepScreenOn
4471     */
4472    public void setKeepScreenOn(boolean keepScreenOn) {
4473        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4474    }
4475
4476    /**
4477     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4478     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4479     *
4480     * @attr ref android.R.styleable#View_nextFocusLeft
4481     */
4482    public int getNextFocusLeftId() {
4483        return mNextFocusLeftId;
4484    }
4485
4486    /**
4487     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4488     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4489     * decide automatically.
4490     *
4491     * @attr ref android.R.styleable#View_nextFocusLeft
4492     */
4493    public void setNextFocusLeftId(int nextFocusLeftId) {
4494        mNextFocusLeftId = nextFocusLeftId;
4495    }
4496
4497    /**
4498     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4499     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4500     *
4501     * @attr ref android.R.styleable#View_nextFocusRight
4502     */
4503    public int getNextFocusRightId() {
4504        return mNextFocusRightId;
4505    }
4506
4507    /**
4508     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4509     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4510     * decide automatically.
4511     *
4512     * @attr ref android.R.styleable#View_nextFocusRight
4513     */
4514    public void setNextFocusRightId(int nextFocusRightId) {
4515        mNextFocusRightId = nextFocusRightId;
4516    }
4517
4518    /**
4519     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4520     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4521     *
4522     * @attr ref android.R.styleable#View_nextFocusUp
4523     */
4524    public int getNextFocusUpId() {
4525        return mNextFocusUpId;
4526    }
4527
4528    /**
4529     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4530     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4531     * decide automatically.
4532     *
4533     * @attr ref android.R.styleable#View_nextFocusUp
4534     */
4535    public void setNextFocusUpId(int nextFocusUpId) {
4536        mNextFocusUpId = nextFocusUpId;
4537    }
4538
4539    /**
4540     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4541     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4542     *
4543     * @attr ref android.R.styleable#View_nextFocusDown
4544     */
4545    public int getNextFocusDownId() {
4546        return mNextFocusDownId;
4547    }
4548
4549    /**
4550     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4551     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4552     * decide automatically.
4553     *
4554     * @attr ref android.R.styleable#View_nextFocusDown
4555     */
4556    public void setNextFocusDownId(int nextFocusDownId) {
4557        mNextFocusDownId = nextFocusDownId;
4558    }
4559
4560    /**
4561     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4562     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4563     *
4564     * @attr ref android.R.styleable#View_nextFocusForward
4565     */
4566    public int getNextFocusForwardId() {
4567        return mNextFocusForwardId;
4568    }
4569
4570    /**
4571     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4572     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4573     * decide automatically.
4574     *
4575     * @attr ref android.R.styleable#View_nextFocusForward
4576     */
4577    public void setNextFocusForwardId(int nextFocusForwardId) {
4578        mNextFocusForwardId = nextFocusForwardId;
4579    }
4580
4581    /**
4582     * Returns the visibility of this view and all of its ancestors
4583     *
4584     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4585     */
4586    public boolean isShown() {
4587        View current = this;
4588        //noinspection ConstantConditions
4589        do {
4590            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4591                return false;
4592            }
4593            ViewParent parent = current.mParent;
4594            if (parent == null) {
4595                return false; // We are not attached to the view root
4596            }
4597            if (!(parent instanceof View)) {
4598                return true;
4599            }
4600            current = (View) parent;
4601        } while (current != null);
4602
4603        return false;
4604    }
4605
4606    /**
4607     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4608     * is set
4609     *
4610     * @param insets Insets for system windows
4611     *
4612     * @return True if this view applied the insets, false otherwise
4613     */
4614    protected boolean fitSystemWindows(Rect insets) {
4615        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4616            mPaddingLeft = insets.left;
4617            mPaddingTop = insets.top;
4618            mPaddingRight = insets.right;
4619            mPaddingBottom = insets.bottom;
4620            requestLayout();
4621            return true;
4622        }
4623        return false;
4624    }
4625
4626    /**
4627     * Set whether or not this view should account for system screen decorations
4628     * such as the status bar and inset its content. This allows this view to be
4629     * positioned in absolute screen coordinates and remain visible to the user.
4630     *
4631     * <p>This should only be used by top-level window decor views.
4632     *
4633     * @param fitSystemWindows true to inset content for system screen decorations, false for
4634     *                         default behavior.
4635     *
4636     * @attr ref android.R.styleable#View_fitsSystemWindows
4637     */
4638    public void setFitsSystemWindows(boolean fitSystemWindows) {
4639        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4640    }
4641
4642    /**
4643     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4644     * will account for system screen decorations such as the status bar and inset its
4645     * content. This allows the view to be positioned in absolute screen coordinates
4646     * and remain visible to the user.
4647     *
4648     * @return true if this view will adjust its content bounds for system screen decorations.
4649     *
4650     * @attr ref android.R.styleable#View_fitsSystemWindows
4651     */
4652    public boolean fitsSystemWindows() {
4653        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4654    }
4655
4656    /**
4657     * Returns the visibility status for this view.
4658     *
4659     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4660     * @attr ref android.R.styleable#View_visibility
4661     */
4662    @ViewDebug.ExportedProperty(mapping = {
4663        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4664        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4665        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4666    })
4667    public int getVisibility() {
4668        return mViewFlags & VISIBILITY_MASK;
4669    }
4670
4671    /**
4672     * Set the enabled state of this view.
4673     *
4674     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4675     * @attr ref android.R.styleable#View_visibility
4676     */
4677    @RemotableViewMethod
4678    public void setVisibility(int visibility) {
4679        setFlags(visibility, VISIBILITY_MASK);
4680        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4681    }
4682
4683    /**
4684     * Returns the enabled status for this view. The interpretation of the
4685     * enabled state varies by subclass.
4686     *
4687     * @return True if this view is enabled, false otherwise.
4688     */
4689    @ViewDebug.ExportedProperty
4690    public boolean isEnabled() {
4691        return (mViewFlags & ENABLED_MASK) == ENABLED;
4692    }
4693
4694    /**
4695     * Set the enabled state of this view. The interpretation of the enabled
4696     * state varies by subclass.
4697     *
4698     * @param enabled True if this view is enabled, false otherwise.
4699     */
4700    @RemotableViewMethod
4701    public void setEnabled(boolean enabled) {
4702        if (enabled == isEnabled()) return;
4703
4704        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4705
4706        /*
4707         * The View most likely has to change its appearance, so refresh
4708         * the drawable state.
4709         */
4710        refreshDrawableState();
4711
4712        // Invalidate too, since the default behavior for views is to be
4713        // be drawn at 50% alpha rather than to change the drawable.
4714        invalidate(true);
4715    }
4716
4717    /**
4718     * Set whether this view can receive the focus.
4719     *
4720     * Setting this to false will also ensure that this view is not focusable
4721     * in touch mode.
4722     *
4723     * @param focusable If true, this view can receive the focus.
4724     *
4725     * @see #setFocusableInTouchMode(boolean)
4726     * @attr ref android.R.styleable#View_focusable
4727     */
4728    public void setFocusable(boolean focusable) {
4729        if (!focusable) {
4730            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4731        }
4732        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4733    }
4734
4735    /**
4736     * Set whether this view can receive focus while in touch mode.
4737     *
4738     * Setting this to true will also ensure that this view is focusable.
4739     *
4740     * @param focusableInTouchMode If true, this view can receive the focus while
4741     *   in touch mode.
4742     *
4743     * @see #setFocusable(boolean)
4744     * @attr ref android.R.styleable#View_focusableInTouchMode
4745     */
4746    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4747        // Focusable in touch mode should always be set before the focusable flag
4748        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4749        // which, in touch mode, will not successfully request focus on this view
4750        // because the focusable in touch mode flag is not set
4751        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4752        if (focusableInTouchMode) {
4753            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4754        }
4755    }
4756
4757    /**
4758     * Set whether this view should have sound effects enabled for events such as
4759     * clicking and touching.
4760     *
4761     * <p>You may wish to disable sound effects for a view if you already play sounds,
4762     * for instance, a dial key that plays dtmf tones.
4763     *
4764     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4765     * @see #isSoundEffectsEnabled()
4766     * @see #playSoundEffect(int)
4767     * @attr ref android.R.styleable#View_soundEffectsEnabled
4768     */
4769    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4770        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4771    }
4772
4773    /**
4774     * @return whether this view should have sound effects enabled for events such as
4775     *     clicking and touching.
4776     *
4777     * @see #setSoundEffectsEnabled(boolean)
4778     * @see #playSoundEffect(int)
4779     * @attr ref android.R.styleable#View_soundEffectsEnabled
4780     */
4781    @ViewDebug.ExportedProperty
4782    public boolean isSoundEffectsEnabled() {
4783        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4784    }
4785
4786    /**
4787     * Set whether this view should have haptic feedback for events such as
4788     * long presses.
4789     *
4790     * <p>You may wish to disable haptic feedback if your view already controls
4791     * its own haptic feedback.
4792     *
4793     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4794     * @see #isHapticFeedbackEnabled()
4795     * @see #performHapticFeedback(int)
4796     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4797     */
4798    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4799        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4800    }
4801
4802    /**
4803     * @return whether this view should have haptic feedback enabled for events
4804     * long presses.
4805     *
4806     * @see #setHapticFeedbackEnabled(boolean)
4807     * @see #performHapticFeedback(int)
4808     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4809     */
4810    @ViewDebug.ExportedProperty
4811    public boolean isHapticFeedbackEnabled() {
4812        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4813    }
4814
4815    /**
4816     * Returns the layout direction for this view.
4817     *
4818     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4819     *   {@link #LAYOUT_DIRECTION_RTL},
4820     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4821     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4822     * @attr ref android.R.styleable#View_layoutDirection
4823     *
4824     * @hide
4825     */
4826    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4827        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4828        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4829        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4830        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4831    })
4832    public int getLayoutDirection() {
4833        return mViewFlags & LAYOUT_DIRECTION_MASK;
4834    }
4835
4836    /**
4837     * Set the layout direction for this view. This will propagate a reset of layout direction
4838     * resolution to the view's children and resolve layout direction for this view.
4839     *
4840     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4841     *   {@link #LAYOUT_DIRECTION_RTL},
4842     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4843     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4844     *
4845     * @attr ref android.R.styleable#View_layoutDirection
4846     *
4847     * @hide
4848     */
4849    @RemotableViewMethod
4850    public void setLayoutDirection(int layoutDirection) {
4851        if (getLayoutDirection() != layoutDirection) {
4852            resetResolvedLayoutDirection();
4853            // Setting the flag will also request a layout.
4854            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4855        }
4856    }
4857
4858    /**
4859     * Returns the resolved layout direction for this view.
4860     *
4861     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4862     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4863     *
4864     * @hide
4865     */
4866    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4867        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4868        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4869    })
4870    public int getResolvedLayoutDirection() {
4871        resolveLayoutDirectionIfNeeded();
4872        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4873                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4874    }
4875
4876    /**
4877     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4878     * layout attribute and/or the inherited value from the parent.</p>
4879     *
4880     * @return true if the layout is right-to-left.
4881     *
4882     * @hide
4883     */
4884    @ViewDebug.ExportedProperty(category = "layout")
4885    public boolean isLayoutRtl() {
4886        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4887    }
4888
4889    /**
4890     * If this view doesn't do any drawing on its own, set this flag to
4891     * allow further optimizations. By default, this flag is not set on
4892     * View, but could be set on some View subclasses such as ViewGroup.
4893     *
4894     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4895     * you should clear this flag.
4896     *
4897     * @param willNotDraw whether or not this View draw on its own
4898     */
4899    public void setWillNotDraw(boolean willNotDraw) {
4900        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4901    }
4902
4903    /**
4904     * Returns whether or not this View draws on its own.
4905     *
4906     * @return true if this view has nothing to draw, false otherwise
4907     */
4908    @ViewDebug.ExportedProperty(category = "drawing")
4909    public boolean willNotDraw() {
4910        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4911    }
4912
4913    /**
4914     * When a View's drawing cache is enabled, drawing is redirected to an
4915     * offscreen bitmap. Some views, like an ImageView, must be able to
4916     * bypass this mechanism if they already draw a single bitmap, to avoid
4917     * unnecessary usage of the memory.
4918     *
4919     * @param willNotCacheDrawing true if this view does not cache its
4920     *        drawing, false otherwise
4921     */
4922    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4923        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4924    }
4925
4926    /**
4927     * Returns whether or not this View can cache its drawing or not.
4928     *
4929     * @return true if this view does not cache its drawing, false otherwise
4930     */
4931    @ViewDebug.ExportedProperty(category = "drawing")
4932    public boolean willNotCacheDrawing() {
4933        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4934    }
4935
4936    /**
4937     * Indicates whether this view reacts to click events or not.
4938     *
4939     * @return true if the view is clickable, false otherwise
4940     *
4941     * @see #setClickable(boolean)
4942     * @attr ref android.R.styleable#View_clickable
4943     */
4944    @ViewDebug.ExportedProperty
4945    public boolean isClickable() {
4946        return (mViewFlags & CLICKABLE) == CLICKABLE;
4947    }
4948
4949    /**
4950     * Enables or disables click events for this view. When a view
4951     * is clickable it will change its state to "pressed" on every click.
4952     * Subclasses should set the view clickable to visually react to
4953     * user's clicks.
4954     *
4955     * @param clickable true to make the view clickable, false otherwise
4956     *
4957     * @see #isClickable()
4958     * @attr ref android.R.styleable#View_clickable
4959     */
4960    public void setClickable(boolean clickable) {
4961        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4962    }
4963
4964    /**
4965     * Indicates whether this view reacts to long click events or not.
4966     *
4967     * @return true if the view is long clickable, false otherwise
4968     *
4969     * @see #setLongClickable(boolean)
4970     * @attr ref android.R.styleable#View_longClickable
4971     */
4972    public boolean isLongClickable() {
4973        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4974    }
4975
4976    /**
4977     * Enables or disables long click events for this view. When a view is long
4978     * clickable it reacts to the user holding down the button for a longer
4979     * duration than a tap. This event can either launch the listener or a
4980     * context menu.
4981     *
4982     * @param longClickable true to make the view long clickable, false otherwise
4983     * @see #isLongClickable()
4984     * @attr ref android.R.styleable#View_longClickable
4985     */
4986    public void setLongClickable(boolean longClickable) {
4987        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4988    }
4989
4990    /**
4991     * Sets the pressed state for this view.
4992     *
4993     * @see #isClickable()
4994     * @see #setClickable(boolean)
4995     *
4996     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4997     *        the View's internal state from a previously set "pressed" state.
4998     */
4999    public void setPressed(boolean pressed) {
5000        if (pressed) {
5001            mPrivateFlags |= PRESSED;
5002        } else {
5003            mPrivateFlags &= ~PRESSED;
5004        }
5005        refreshDrawableState();
5006        dispatchSetPressed(pressed);
5007    }
5008
5009    /**
5010     * Dispatch setPressed to all of this View's children.
5011     *
5012     * @see #setPressed(boolean)
5013     *
5014     * @param pressed The new pressed state
5015     */
5016    protected void dispatchSetPressed(boolean pressed) {
5017    }
5018
5019    /**
5020     * Indicates whether the view is currently in pressed state. Unless
5021     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5022     * the pressed state.
5023     *
5024     * @see #setPressed(boolean)
5025     * @see #isClickable()
5026     * @see #setClickable(boolean)
5027     *
5028     * @return true if the view is currently pressed, false otherwise
5029     */
5030    public boolean isPressed() {
5031        return (mPrivateFlags & PRESSED) == PRESSED;
5032    }
5033
5034    /**
5035     * Indicates whether this view will save its state (that is,
5036     * whether its {@link #onSaveInstanceState} method will be called).
5037     *
5038     * @return Returns true if the view state saving is enabled, else false.
5039     *
5040     * @see #setSaveEnabled(boolean)
5041     * @attr ref android.R.styleable#View_saveEnabled
5042     */
5043    public boolean isSaveEnabled() {
5044        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5045    }
5046
5047    /**
5048     * Controls whether the saving of this view's state is
5049     * enabled (that is, whether its {@link #onSaveInstanceState} method
5050     * will be called).  Note that even if freezing is enabled, the
5051     * view still must have an id assigned to it (via {@link #setId(int)})
5052     * for its state to be saved.  This flag can only disable the
5053     * saving of this view; any child views may still have their state saved.
5054     *
5055     * @param enabled Set to false to <em>disable</em> state saving, or true
5056     * (the default) to allow it.
5057     *
5058     * @see #isSaveEnabled()
5059     * @see #setId(int)
5060     * @see #onSaveInstanceState()
5061     * @attr ref android.R.styleable#View_saveEnabled
5062     */
5063    public void setSaveEnabled(boolean enabled) {
5064        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5065    }
5066
5067    /**
5068     * Gets whether the framework should discard touches when the view's
5069     * window is obscured by another visible window.
5070     * Refer to the {@link View} security documentation for more details.
5071     *
5072     * @return True if touch filtering is enabled.
5073     *
5074     * @see #setFilterTouchesWhenObscured(boolean)
5075     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5076     */
5077    @ViewDebug.ExportedProperty
5078    public boolean getFilterTouchesWhenObscured() {
5079        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5080    }
5081
5082    /**
5083     * Sets whether the framework should discard touches when the view's
5084     * window is obscured by another visible window.
5085     * Refer to the {@link View} security documentation for more details.
5086     *
5087     * @param enabled True if touch filtering should be enabled.
5088     *
5089     * @see #getFilterTouchesWhenObscured
5090     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5091     */
5092    public void setFilterTouchesWhenObscured(boolean enabled) {
5093        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5094                FILTER_TOUCHES_WHEN_OBSCURED);
5095    }
5096
5097    /**
5098     * Indicates whether the entire hierarchy under this view will save its
5099     * state when a state saving traversal occurs from its parent.  The default
5100     * is true; if false, these views will not be saved unless
5101     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5102     *
5103     * @return Returns true if the view state saving from parent is enabled, else false.
5104     *
5105     * @see #setSaveFromParentEnabled(boolean)
5106     */
5107    public boolean isSaveFromParentEnabled() {
5108        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5109    }
5110
5111    /**
5112     * Controls whether the entire hierarchy under this view will save its
5113     * state when a state saving traversal occurs from its parent.  The default
5114     * is true; if false, these views will not be saved unless
5115     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5116     *
5117     * @param enabled Set to false to <em>disable</em> state saving, or true
5118     * (the default) to allow it.
5119     *
5120     * @see #isSaveFromParentEnabled()
5121     * @see #setId(int)
5122     * @see #onSaveInstanceState()
5123     */
5124    public void setSaveFromParentEnabled(boolean enabled) {
5125        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5126    }
5127
5128
5129    /**
5130     * Returns whether this View is able to take focus.
5131     *
5132     * @return True if this view can take focus, or false otherwise.
5133     * @attr ref android.R.styleable#View_focusable
5134     */
5135    @ViewDebug.ExportedProperty(category = "focus")
5136    public final boolean isFocusable() {
5137        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5138    }
5139
5140    /**
5141     * When a view is focusable, it may not want to take focus when in touch mode.
5142     * For example, a button would like focus when the user is navigating via a D-pad
5143     * so that the user can click on it, but once the user starts touching the screen,
5144     * the button shouldn't take focus
5145     * @return Whether the view is focusable in touch mode.
5146     * @attr ref android.R.styleable#View_focusableInTouchMode
5147     */
5148    @ViewDebug.ExportedProperty
5149    public final boolean isFocusableInTouchMode() {
5150        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5151    }
5152
5153    /**
5154     * Find the nearest view in the specified direction that can take focus.
5155     * This does not actually give focus to that view.
5156     *
5157     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5158     *
5159     * @return The nearest focusable in the specified direction, or null if none
5160     *         can be found.
5161     */
5162    public View focusSearch(int direction) {
5163        if (mParent != null) {
5164            return mParent.focusSearch(this, direction);
5165        } else {
5166            return null;
5167        }
5168    }
5169
5170    /**
5171     * This method is the last chance for the focused view and its ancestors to
5172     * respond to an arrow key. This is called when the focused view did not
5173     * consume the key internally, nor could the view system find a new view in
5174     * the requested direction to give focus to.
5175     *
5176     * @param focused The currently focused view.
5177     * @param direction The direction focus wants to move. One of FOCUS_UP,
5178     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5179     * @return True if the this view consumed this unhandled move.
5180     */
5181    public boolean dispatchUnhandledMove(View focused, int direction) {
5182        return false;
5183    }
5184
5185    /**
5186     * If a user manually specified the next view id for a particular direction,
5187     * use the root to look up the view.
5188     * @param root The root view of the hierarchy containing this view.
5189     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5190     * or FOCUS_BACKWARD.
5191     * @return The user specified next view, or null if there is none.
5192     */
5193    View findUserSetNextFocus(View root, int direction) {
5194        switch (direction) {
5195            case FOCUS_LEFT:
5196                if (mNextFocusLeftId == View.NO_ID) return null;
5197                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5198            case FOCUS_RIGHT:
5199                if (mNextFocusRightId == View.NO_ID) return null;
5200                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5201            case FOCUS_UP:
5202                if (mNextFocusUpId == View.NO_ID) return null;
5203                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5204            case FOCUS_DOWN:
5205                if (mNextFocusDownId == View.NO_ID) return null;
5206                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5207            case FOCUS_FORWARD:
5208                if (mNextFocusForwardId == View.NO_ID) return null;
5209                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5210            case FOCUS_BACKWARD: {
5211                final int id = mID;
5212                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5213                    @Override
5214                    public boolean apply(View t) {
5215                        return t.mNextFocusForwardId == id;
5216                    }
5217                });
5218            }
5219        }
5220        return null;
5221    }
5222
5223    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5224        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5225            @Override
5226            public boolean apply(View t) {
5227                return t.mID == childViewId;
5228            }
5229        });
5230
5231        if (result == null) {
5232            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5233                    + "by user for id " + childViewId);
5234        }
5235        return result;
5236    }
5237
5238    /**
5239     * Find and return all focusable views that are descendants of this view,
5240     * possibly including this view if it is focusable itself.
5241     *
5242     * @param direction The direction of the focus
5243     * @return A list of focusable views
5244     */
5245    public ArrayList<View> getFocusables(int direction) {
5246        ArrayList<View> result = new ArrayList<View>(24);
5247        addFocusables(result, direction);
5248        return result;
5249    }
5250
5251    /**
5252     * Add any focusable views that are descendants of this view (possibly
5253     * including this view if it is focusable itself) to views.  If we are in touch mode,
5254     * only add views that are also focusable in touch mode.
5255     *
5256     * @param views Focusable views found so far
5257     * @param direction The direction of the focus
5258     */
5259    public void addFocusables(ArrayList<View> views, int direction) {
5260        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5261    }
5262
5263    /**
5264     * Adds any focusable views that are descendants of this view (possibly
5265     * including this view if it is focusable itself) to views. This method
5266     * adds all focusable views regardless if we are in touch mode or
5267     * only views focusable in touch mode if we are in touch mode depending on
5268     * the focusable mode paramater.
5269     *
5270     * @param views Focusable views found so far or null if all we are interested is
5271     *        the number of focusables.
5272     * @param direction The direction of the focus.
5273     * @param focusableMode The type of focusables to be added.
5274     *
5275     * @see #FOCUSABLES_ALL
5276     * @see #FOCUSABLES_TOUCH_MODE
5277     */
5278    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5279        if (!isFocusable()) {
5280            return;
5281        }
5282
5283        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5284                isInTouchMode() && !isFocusableInTouchMode()) {
5285            return;
5286        }
5287
5288        if (views != null) {
5289            views.add(this);
5290        }
5291    }
5292
5293    /**
5294     * Finds the Views that contain given text. The containment is case insensitive.
5295     * The search is performed by either the text that the View renders or the content
5296     * description that describes the view for accessibility purposes and the view does
5297     * not render or both. Clients can specify how the search is to be performed via
5298     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5299     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5300     *
5301     * @param outViews The output list of matching Views.
5302     * @param searched The text to match against.
5303     *
5304     * @see #FIND_VIEWS_WITH_TEXT
5305     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5306     * @see #setContentDescription(CharSequence)
5307     */
5308    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5309        if (getAccessibilityNodeProvider() != null) {
5310            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5311                outViews.add(this);
5312            }
5313        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5314                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5315            String searchedLowerCase = searched.toString().toLowerCase();
5316            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5317            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5318                outViews.add(this);
5319            }
5320        }
5321    }
5322
5323    /**
5324     * Find and return all touchable views that are descendants of this view,
5325     * possibly including this view if it is touchable itself.
5326     *
5327     * @return A list of touchable views
5328     */
5329    public ArrayList<View> getTouchables() {
5330        ArrayList<View> result = new ArrayList<View>();
5331        addTouchables(result);
5332        return result;
5333    }
5334
5335    /**
5336     * Add any touchable views that are descendants of this view (possibly
5337     * including this view if it is touchable itself) to views.
5338     *
5339     * @param views Touchable views found so far
5340     */
5341    public void addTouchables(ArrayList<View> views) {
5342        final int viewFlags = mViewFlags;
5343
5344        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5345                && (viewFlags & ENABLED_MASK) == ENABLED) {
5346            views.add(this);
5347        }
5348    }
5349
5350    /**
5351     * Call this to try to give focus to a specific view or to one of its
5352     * descendants.
5353     *
5354     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5355     * false), or if it is focusable and it is not focusable in touch mode
5356     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5357     *
5358     * See also {@link #focusSearch(int)}, which is what you call to say that you
5359     * have focus, and you want your parent to look for the next one.
5360     *
5361     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5362     * {@link #FOCUS_DOWN} and <code>null</code>.
5363     *
5364     * @return Whether this view or one of its descendants actually took focus.
5365     */
5366    public final boolean requestFocus() {
5367        return requestFocus(View.FOCUS_DOWN);
5368    }
5369
5370
5371    /**
5372     * Call this to try to give focus to a specific view or to one of its
5373     * descendants and give it a hint about what direction focus is heading.
5374     *
5375     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5376     * false), or if it is focusable and it is not focusable in touch mode
5377     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5378     *
5379     * See also {@link #focusSearch(int)}, which is what you call to say that you
5380     * have focus, and you want your parent to look for the next one.
5381     *
5382     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5383     * <code>null</code> set for the previously focused rectangle.
5384     *
5385     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5386     * @return Whether this view or one of its descendants actually took focus.
5387     */
5388    public final boolean requestFocus(int direction) {
5389        return requestFocus(direction, null);
5390    }
5391
5392    /**
5393     * Call this to try to give focus to a specific view or to one of its descendants
5394     * and give it hints about the direction and a specific rectangle that the focus
5395     * is coming from.  The rectangle can help give larger views a finer grained hint
5396     * about where focus is coming from, and therefore, where to show selection, or
5397     * forward focus change internally.
5398     *
5399     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5400     * false), or if it is focusable and it is not focusable in touch mode
5401     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5402     *
5403     * A View will not take focus if it is not visible.
5404     *
5405     * A View will not take focus if one of its parents has
5406     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5407     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5408     *
5409     * See also {@link #focusSearch(int)}, which is what you call to say that you
5410     * have focus, and you want your parent to look for the next one.
5411     *
5412     * You may wish to override this method if your custom {@link View} has an internal
5413     * {@link View} that it wishes to forward the request to.
5414     *
5415     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5416     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5417     *        to give a finer grained hint about where focus is coming from.  May be null
5418     *        if there is no hint.
5419     * @return Whether this view or one of its descendants actually took focus.
5420     */
5421    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5422        // need to be focusable
5423        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5424                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5425            return false;
5426        }
5427
5428        // need to be focusable in touch mode if in touch mode
5429        if (isInTouchMode() &&
5430            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5431               return false;
5432        }
5433
5434        // need to not have any parents blocking us
5435        if (hasAncestorThatBlocksDescendantFocus()) {
5436            return false;
5437        }
5438
5439        handleFocusGainInternal(direction, previouslyFocusedRect);
5440        return true;
5441    }
5442
5443    /** Gets the ViewAncestor, or null if not attached. */
5444    /*package*/ ViewRootImpl getViewRootImpl() {
5445        View root = getRootView();
5446        return root != null ? (ViewRootImpl)root.getParent() : null;
5447    }
5448
5449    /**
5450     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5451     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5452     * touch mode to request focus when they are touched.
5453     *
5454     * @return Whether this view or one of its descendants actually took focus.
5455     *
5456     * @see #isInTouchMode()
5457     *
5458     */
5459    public final boolean requestFocusFromTouch() {
5460        // Leave touch mode if we need to
5461        if (isInTouchMode()) {
5462            ViewRootImpl viewRoot = getViewRootImpl();
5463            if (viewRoot != null) {
5464                viewRoot.ensureTouchMode(false);
5465            }
5466        }
5467        return requestFocus(View.FOCUS_DOWN);
5468    }
5469
5470    /**
5471     * @return Whether any ancestor of this view blocks descendant focus.
5472     */
5473    private boolean hasAncestorThatBlocksDescendantFocus() {
5474        ViewParent ancestor = mParent;
5475        while (ancestor instanceof ViewGroup) {
5476            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5477            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5478                return true;
5479            } else {
5480                ancestor = vgAncestor.getParent();
5481            }
5482        }
5483        return false;
5484    }
5485
5486    /**
5487     * @hide
5488     */
5489    public void dispatchStartTemporaryDetach() {
5490        onStartTemporaryDetach();
5491    }
5492
5493    /**
5494     * This is called when a container is going to temporarily detach a child, with
5495     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5496     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5497     * {@link #onDetachedFromWindow()} when the container is done.
5498     */
5499    public void onStartTemporaryDetach() {
5500        removeUnsetPressCallback();
5501        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5502    }
5503
5504    /**
5505     * @hide
5506     */
5507    public void dispatchFinishTemporaryDetach() {
5508        onFinishTemporaryDetach();
5509    }
5510
5511    /**
5512     * Called after {@link #onStartTemporaryDetach} when the container is done
5513     * changing the view.
5514     */
5515    public void onFinishTemporaryDetach() {
5516    }
5517
5518    /**
5519     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5520     * for this view's window.  Returns null if the view is not currently attached
5521     * to the window.  Normally you will not need to use this directly, but
5522     * just use the standard high-level event callbacks like
5523     * {@link #onKeyDown(int, KeyEvent)}.
5524     */
5525    public KeyEvent.DispatcherState getKeyDispatcherState() {
5526        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5527    }
5528
5529    /**
5530     * Dispatch a key event before it is processed by any input method
5531     * associated with the view hierarchy.  This can be used to intercept
5532     * key events in special situations before the IME consumes them; a
5533     * typical example would be handling the BACK key to update the application's
5534     * UI instead of allowing the IME to see it and close itself.
5535     *
5536     * @param event The key event to be dispatched.
5537     * @return True if the event was handled, false otherwise.
5538     */
5539    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5540        return onKeyPreIme(event.getKeyCode(), event);
5541    }
5542
5543    /**
5544     * Dispatch a key event to the next view on the focus path. This path runs
5545     * from the top of the view tree down to the currently focused view. If this
5546     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5547     * the next node down the focus path. This method also fires any key
5548     * listeners.
5549     *
5550     * @param event The key event to be dispatched.
5551     * @return True if the event was handled, false otherwise.
5552     */
5553    public boolean dispatchKeyEvent(KeyEvent event) {
5554        if (mInputEventConsistencyVerifier != null) {
5555            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5556        }
5557
5558        // Give any attached key listener a first crack at the event.
5559        //noinspection SimplifiableIfStatement
5560        ListenerInfo li = mListenerInfo;
5561        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5562                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5563            return true;
5564        }
5565
5566        if (event.dispatch(this, mAttachInfo != null
5567                ? mAttachInfo.mKeyDispatchState : null, this)) {
5568            return true;
5569        }
5570
5571        if (mInputEventConsistencyVerifier != null) {
5572            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5573        }
5574        return false;
5575    }
5576
5577    /**
5578     * Dispatches a key shortcut event.
5579     *
5580     * @param event The key event to be dispatched.
5581     * @return True if the event was handled by the view, false otherwise.
5582     */
5583    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5584        return onKeyShortcut(event.getKeyCode(), event);
5585    }
5586
5587    /**
5588     * Pass the touch screen motion event down to the target view, or this
5589     * view if it is the target.
5590     *
5591     * @param event The motion event to be dispatched.
5592     * @return True if the event was handled by the view, false otherwise.
5593     */
5594    public boolean dispatchTouchEvent(MotionEvent event) {
5595        if (mInputEventConsistencyVerifier != null) {
5596            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5597        }
5598
5599        if (onFilterTouchEventForSecurity(event)) {
5600            //noinspection SimplifiableIfStatement
5601            ListenerInfo li = mListenerInfo;
5602            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5603                    && li.mOnTouchListener.onTouch(this, event)) {
5604                return true;
5605            }
5606
5607            if (onTouchEvent(event)) {
5608                return true;
5609            }
5610        }
5611
5612        if (mInputEventConsistencyVerifier != null) {
5613            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5614        }
5615        return false;
5616    }
5617
5618    /**
5619     * Filter the touch event to apply security policies.
5620     *
5621     * @param event The motion event to be filtered.
5622     * @return True if the event should be dispatched, false if the event should be dropped.
5623     *
5624     * @see #getFilterTouchesWhenObscured
5625     */
5626    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5627        //noinspection RedundantIfStatement
5628        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5629                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5630            // Window is obscured, drop this touch.
5631            return false;
5632        }
5633        return true;
5634    }
5635
5636    /**
5637     * Pass a trackball motion event down to the focused view.
5638     *
5639     * @param event The motion event to be dispatched.
5640     * @return True if the event was handled by the view, false otherwise.
5641     */
5642    public boolean dispatchTrackballEvent(MotionEvent event) {
5643        if (mInputEventConsistencyVerifier != null) {
5644            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5645        }
5646
5647        return onTrackballEvent(event);
5648    }
5649
5650    /**
5651     * Dispatch a generic motion event.
5652     * <p>
5653     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5654     * are delivered to the view under the pointer.  All other generic motion events are
5655     * delivered to the focused view.  Hover events are handled specially and are delivered
5656     * to {@link #onHoverEvent(MotionEvent)}.
5657     * </p>
5658     *
5659     * @param event The motion event to be dispatched.
5660     * @return True if the event was handled by the view, false otherwise.
5661     */
5662    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5663        if (mInputEventConsistencyVerifier != null) {
5664            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5665        }
5666
5667        final int source = event.getSource();
5668        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5669            final int action = event.getAction();
5670            if (action == MotionEvent.ACTION_HOVER_ENTER
5671                    || action == MotionEvent.ACTION_HOVER_MOVE
5672                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5673                if (dispatchHoverEvent(event)) {
5674                    return true;
5675                }
5676            } else if (dispatchGenericPointerEvent(event)) {
5677                return true;
5678            }
5679        } else if (dispatchGenericFocusedEvent(event)) {
5680            return true;
5681        }
5682
5683        if (dispatchGenericMotionEventInternal(event)) {
5684            return true;
5685        }
5686
5687        if (mInputEventConsistencyVerifier != null) {
5688            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5689        }
5690        return false;
5691    }
5692
5693    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5694        //noinspection SimplifiableIfStatement
5695        ListenerInfo li = mListenerInfo;
5696        if (li != null && li.mOnGenericMotionListener != null
5697                && (mViewFlags & ENABLED_MASK) == ENABLED
5698                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5699            return true;
5700        }
5701
5702        if (onGenericMotionEvent(event)) {
5703            return true;
5704        }
5705
5706        if (mInputEventConsistencyVerifier != null) {
5707            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5708        }
5709        return false;
5710    }
5711
5712    /**
5713     * Dispatch a hover event.
5714     * <p>
5715     * Do not call this method directly.
5716     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5717     * </p>
5718     *
5719     * @param event The motion event to be dispatched.
5720     * @return True if the event was handled by the view, false otherwise.
5721     */
5722    protected boolean dispatchHoverEvent(MotionEvent event) {
5723        //noinspection SimplifiableIfStatement
5724        ListenerInfo li = mListenerInfo;
5725        if (li != null && li.mOnHoverListener != null
5726                && (mViewFlags & ENABLED_MASK) == ENABLED
5727                && li.mOnHoverListener.onHover(this, event)) {
5728            return true;
5729        }
5730
5731        return onHoverEvent(event);
5732    }
5733
5734    /**
5735     * Returns true if the view has a child to which it has recently sent
5736     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5737     * it does not have a hovered child, then it must be the innermost hovered view.
5738     * @hide
5739     */
5740    protected boolean hasHoveredChild() {
5741        return false;
5742    }
5743
5744    /**
5745     * Dispatch a generic motion event to the view under the first pointer.
5746     * <p>
5747     * Do not call this method directly.
5748     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5749     * </p>
5750     *
5751     * @param event The motion event to be dispatched.
5752     * @return True if the event was handled by the view, false otherwise.
5753     */
5754    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5755        return false;
5756    }
5757
5758    /**
5759     * Dispatch a generic motion event to the currently focused view.
5760     * <p>
5761     * Do not call this method directly.
5762     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5763     * </p>
5764     *
5765     * @param event The motion event to be dispatched.
5766     * @return True if the event was handled by the view, false otherwise.
5767     */
5768    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5769        return false;
5770    }
5771
5772    /**
5773     * Dispatch a pointer event.
5774     * <p>
5775     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5776     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5777     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5778     * and should not be expected to handle other pointing device features.
5779     * </p>
5780     *
5781     * @param event The motion event to be dispatched.
5782     * @return True if the event was handled by the view, false otherwise.
5783     * @hide
5784     */
5785    public final boolean dispatchPointerEvent(MotionEvent event) {
5786        if (event.isTouchEvent()) {
5787            return dispatchTouchEvent(event);
5788        } else {
5789            return dispatchGenericMotionEvent(event);
5790        }
5791    }
5792
5793    /**
5794     * Called when the window containing this view gains or loses window focus.
5795     * ViewGroups should override to route to their children.
5796     *
5797     * @param hasFocus True if the window containing this view now has focus,
5798     *        false otherwise.
5799     */
5800    public void dispatchWindowFocusChanged(boolean hasFocus) {
5801        onWindowFocusChanged(hasFocus);
5802    }
5803
5804    /**
5805     * Called when the window containing this view gains or loses focus.  Note
5806     * that this is separate from view focus: to receive key events, both
5807     * your view and its window must have focus.  If a window is displayed
5808     * on top of yours that takes input focus, then your own window will lose
5809     * focus but the view focus will remain unchanged.
5810     *
5811     * @param hasWindowFocus True if the window containing this view now has
5812     *        focus, false otherwise.
5813     */
5814    public void onWindowFocusChanged(boolean hasWindowFocus) {
5815        InputMethodManager imm = InputMethodManager.peekInstance();
5816        if (!hasWindowFocus) {
5817            if (isPressed()) {
5818                setPressed(false);
5819            }
5820            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5821                imm.focusOut(this);
5822            }
5823            removeLongPressCallback();
5824            removeTapCallback();
5825            onFocusLost();
5826        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5827            imm.focusIn(this);
5828        }
5829        refreshDrawableState();
5830    }
5831
5832    /**
5833     * Returns true if this view is in a window that currently has window focus.
5834     * Note that this is not the same as the view itself having focus.
5835     *
5836     * @return True if this view is in a window that currently has window focus.
5837     */
5838    public boolean hasWindowFocus() {
5839        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5840    }
5841
5842    /**
5843     * Dispatch a view visibility change down the view hierarchy.
5844     * ViewGroups should override to route to their children.
5845     * @param changedView The view whose visibility changed. Could be 'this' or
5846     * an ancestor view.
5847     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5848     * {@link #INVISIBLE} or {@link #GONE}.
5849     */
5850    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5851        onVisibilityChanged(changedView, visibility);
5852    }
5853
5854    /**
5855     * Called when the visibility of the view or an ancestor of the view is changed.
5856     * @param changedView The view whose visibility changed. Could be 'this' or
5857     * an ancestor view.
5858     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5859     * {@link #INVISIBLE} or {@link #GONE}.
5860     */
5861    protected void onVisibilityChanged(View changedView, int visibility) {
5862        if (visibility == VISIBLE) {
5863            if (mAttachInfo != null) {
5864                initialAwakenScrollBars();
5865            } else {
5866                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5867            }
5868        }
5869    }
5870
5871    /**
5872     * Dispatch a hint about whether this view is displayed. For instance, when
5873     * a View moves out of the screen, it might receives a display hint indicating
5874     * the view is not displayed. Applications should not <em>rely</em> on this hint
5875     * as there is no guarantee that they will receive one.
5876     *
5877     * @param hint A hint about whether or not this view is displayed:
5878     * {@link #VISIBLE} or {@link #INVISIBLE}.
5879     */
5880    public void dispatchDisplayHint(int hint) {
5881        onDisplayHint(hint);
5882    }
5883
5884    /**
5885     * Gives this view a hint about whether is displayed or not. For instance, when
5886     * a View moves out of the screen, it might receives a display hint indicating
5887     * the view is not displayed. Applications should not <em>rely</em> on this hint
5888     * as there is no guarantee that they will receive one.
5889     *
5890     * @param hint A hint about whether or not this view is displayed:
5891     * {@link #VISIBLE} or {@link #INVISIBLE}.
5892     */
5893    protected void onDisplayHint(int hint) {
5894    }
5895
5896    /**
5897     * Dispatch a window visibility change down the view hierarchy.
5898     * ViewGroups should override to route to their children.
5899     *
5900     * @param visibility The new visibility of the window.
5901     *
5902     * @see #onWindowVisibilityChanged(int)
5903     */
5904    public void dispatchWindowVisibilityChanged(int visibility) {
5905        onWindowVisibilityChanged(visibility);
5906    }
5907
5908    /**
5909     * Called when the window containing has change its visibility
5910     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5911     * that this tells you whether or not your window is being made visible
5912     * to the window manager; this does <em>not</em> tell you whether or not
5913     * your window is obscured by other windows on the screen, even if it
5914     * is itself visible.
5915     *
5916     * @param visibility The new visibility of the window.
5917     */
5918    protected void onWindowVisibilityChanged(int visibility) {
5919        if (visibility == VISIBLE) {
5920            initialAwakenScrollBars();
5921        }
5922    }
5923
5924    /**
5925     * Returns the current visibility of the window this view is attached to
5926     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5927     *
5928     * @return Returns the current visibility of the view's window.
5929     */
5930    public int getWindowVisibility() {
5931        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5932    }
5933
5934    /**
5935     * Retrieve the overall visible display size in which the window this view is
5936     * attached to has been positioned in.  This takes into account screen
5937     * decorations above the window, for both cases where the window itself
5938     * is being position inside of them or the window is being placed under
5939     * then and covered insets are used for the window to position its content
5940     * inside.  In effect, this tells you the available area where content can
5941     * be placed and remain visible to users.
5942     *
5943     * <p>This function requires an IPC back to the window manager to retrieve
5944     * the requested information, so should not be used in performance critical
5945     * code like drawing.
5946     *
5947     * @param outRect Filled in with the visible display frame.  If the view
5948     * is not attached to a window, this is simply the raw display size.
5949     */
5950    public void getWindowVisibleDisplayFrame(Rect outRect) {
5951        if (mAttachInfo != null) {
5952            try {
5953                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5954            } catch (RemoteException e) {
5955                return;
5956            }
5957            // XXX This is really broken, and probably all needs to be done
5958            // in the window manager, and we need to know more about whether
5959            // we want the area behind or in front of the IME.
5960            final Rect insets = mAttachInfo.mVisibleInsets;
5961            outRect.left += insets.left;
5962            outRect.top += insets.top;
5963            outRect.right -= insets.right;
5964            outRect.bottom -= insets.bottom;
5965            return;
5966        }
5967        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5968        d.getRectSize(outRect);
5969    }
5970
5971    /**
5972     * Dispatch a notification about a resource configuration change down
5973     * the view hierarchy.
5974     * ViewGroups should override to route to their children.
5975     *
5976     * @param newConfig The new resource configuration.
5977     *
5978     * @see #onConfigurationChanged(android.content.res.Configuration)
5979     */
5980    public void dispatchConfigurationChanged(Configuration newConfig) {
5981        onConfigurationChanged(newConfig);
5982    }
5983
5984    /**
5985     * Called when the current configuration of the resources being used
5986     * by the application have changed.  You can use this to decide when
5987     * to reload resources that can changed based on orientation and other
5988     * configuration characterstics.  You only need to use this if you are
5989     * not relying on the normal {@link android.app.Activity} mechanism of
5990     * recreating the activity instance upon a configuration change.
5991     *
5992     * @param newConfig The new resource configuration.
5993     */
5994    protected void onConfigurationChanged(Configuration newConfig) {
5995    }
5996
5997    /**
5998     * Private function to aggregate all per-view attributes in to the view
5999     * root.
6000     */
6001    void dispatchCollectViewAttributes(int visibility) {
6002        performCollectViewAttributes(visibility);
6003    }
6004
6005    void performCollectViewAttributes(int visibility) {
6006        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6007            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6008                mAttachInfo.mKeepScreenOn = true;
6009            }
6010            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6011            ListenerInfo li = mListenerInfo;
6012            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6013                mAttachInfo.mHasSystemUiListeners = true;
6014            }
6015        }
6016    }
6017
6018    void needGlobalAttributesUpdate(boolean force) {
6019        final AttachInfo ai = mAttachInfo;
6020        if (ai != null) {
6021            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6022                    || ai.mHasSystemUiListeners) {
6023                ai.mRecomputeGlobalAttributes = true;
6024            }
6025        }
6026    }
6027
6028    /**
6029     * Returns whether the device is currently in touch mode.  Touch mode is entered
6030     * once the user begins interacting with the device by touch, and affects various
6031     * things like whether focus is always visible to the user.
6032     *
6033     * @return Whether the device is in touch mode.
6034     */
6035    @ViewDebug.ExportedProperty
6036    public boolean isInTouchMode() {
6037        if (mAttachInfo != null) {
6038            return mAttachInfo.mInTouchMode;
6039        } else {
6040            return ViewRootImpl.isInTouchMode();
6041        }
6042    }
6043
6044    /**
6045     * Returns the context the view is running in, through which it can
6046     * access the current theme, resources, etc.
6047     *
6048     * @return The view's Context.
6049     */
6050    @ViewDebug.CapturedViewProperty
6051    public final Context getContext() {
6052        return mContext;
6053    }
6054
6055    /**
6056     * Handle a key event before it is processed by any input method
6057     * associated with the view hierarchy.  This can be used to intercept
6058     * key events in special situations before the IME consumes them; a
6059     * typical example would be handling the BACK key to update the application's
6060     * UI instead of allowing the IME to see it and close itself.
6061     *
6062     * @param keyCode The value in event.getKeyCode().
6063     * @param event Description of the key event.
6064     * @return If you handled the event, return true. If you want to allow the
6065     *         event to be handled by the next receiver, return false.
6066     */
6067    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6068        return false;
6069    }
6070
6071    /**
6072     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6073     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6074     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6075     * is released, if the view is enabled and clickable.
6076     *
6077     * @param keyCode A key code that represents the button pressed, from
6078     *                {@link android.view.KeyEvent}.
6079     * @param event   The KeyEvent object that defines the button action.
6080     */
6081    public boolean onKeyDown(int keyCode, KeyEvent event) {
6082        boolean result = false;
6083
6084        switch (keyCode) {
6085            case KeyEvent.KEYCODE_DPAD_CENTER:
6086            case KeyEvent.KEYCODE_ENTER: {
6087                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6088                    return true;
6089                }
6090                // Long clickable items don't necessarily have to be clickable
6091                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6092                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6093                        (event.getRepeatCount() == 0)) {
6094                    setPressed(true);
6095                    checkForLongClick(0);
6096                    return true;
6097                }
6098                break;
6099            }
6100        }
6101        return result;
6102    }
6103
6104    /**
6105     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6106     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6107     * the event).
6108     */
6109    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6110        return false;
6111    }
6112
6113    /**
6114     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6115     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6116     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6117     * {@link KeyEvent#KEYCODE_ENTER} is released.
6118     *
6119     * @param keyCode A key code that represents the button pressed, from
6120     *                {@link android.view.KeyEvent}.
6121     * @param event   The KeyEvent object that defines the button action.
6122     */
6123    public boolean onKeyUp(int keyCode, KeyEvent event) {
6124        boolean result = false;
6125
6126        switch (keyCode) {
6127            case KeyEvent.KEYCODE_DPAD_CENTER:
6128            case KeyEvent.KEYCODE_ENTER: {
6129                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6130                    return true;
6131                }
6132                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6133                    setPressed(false);
6134
6135                    if (!mHasPerformedLongPress) {
6136                        // This is a tap, so remove the longpress check
6137                        removeLongPressCallback();
6138
6139                        result = performClick();
6140                    }
6141                }
6142                break;
6143            }
6144        }
6145        return result;
6146    }
6147
6148    /**
6149     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6150     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6151     * the event).
6152     *
6153     * @param keyCode     A key code that represents the button pressed, from
6154     *                    {@link android.view.KeyEvent}.
6155     * @param repeatCount The number of times the action was made.
6156     * @param event       The KeyEvent object that defines the button action.
6157     */
6158    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6159        return false;
6160    }
6161
6162    /**
6163     * Called on the focused view when a key shortcut event is not handled.
6164     * Override this method to implement local key shortcuts for the View.
6165     * Key shortcuts can also be implemented by setting the
6166     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6167     *
6168     * @param keyCode The value in event.getKeyCode().
6169     * @param event Description of the key event.
6170     * @return If you handled the event, return true. If you want to allow the
6171     *         event to be handled by the next receiver, return false.
6172     */
6173    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6174        return false;
6175    }
6176
6177    /**
6178     * Check whether the called view is a text editor, in which case it
6179     * would make sense to automatically display a soft input window for
6180     * it.  Subclasses should override this if they implement
6181     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6182     * a call on that method would return a non-null InputConnection, and
6183     * they are really a first-class editor that the user would normally
6184     * start typing on when the go into a window containing your view.
6185     *
6186     * <p>The default implementation always returns false.  This does
6187     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6188     * will not be called or the user can not otherwise perform edits on your
6189     * view; it is just a hint to the system that this is not the primary
6190     * purpose of this view.
6191     *
6192     * @return Returns true if this view is a text editor, else false.
6193     */
6194    public boolean onCheckIsTextEditor() {
6195        return false;
6196    }
6197
6198    /**
6199     * Create a new InputConnection for an InputMethod to interact
6200     * with the view.  The default implementation returns null, since it doesn't
6201     * support input methods.  You can override this to implement such support.
6202     * This is only needed for views that take focus and text input.
6203     *
6204     * <p>When implementing this, you probably also want to implement
6205     * {@link #onCheckIsTextEditor()} to indicate you will return a
6206     * non-null InputConnection.
6207     *
6208     * @param outAttrs Fill in with attribute information about the connection.
6209     */
6210    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6211        return null;
6212    }
6213
6214    /**
6215     * Called by the {@link android.view.inputmethod.InputMethodManager}
6216     * when a view who is not the current
6217     * input connection target is trying to make a call on the manager.  The
6218     * default implementation returns false; you can override this to return
6219     * true for certain views if you are performing InputConnection proxying
6220     * to them.
6221     * @param view The View that is making the InputMethodManager call.
6222     * @return Return true to allow the call, false to reject.
6223     */
6224    public boolean checkInputConnectionProxy(View view) {
6225        return false;
6226    }
6227
6228    /**
6229     * Show the context menu for this view. It is not safe to hold on to the
6230     * menu after returning from this method.
6231     *
6232     * You should normally not overload this method. Overload
6233     * {@link #onCreateContextMenu(ContextMenu)} or define an
6234     * {@link OnCreateContextMenuListener} to add items to the context menu.
6235     *
6236     * @param menu The context menu to populate
6237     */
6238    public void createContextMenu(ContextMenu menu) {
6239        ContextMenuInfo menuInfo = getContextMenuInfo();
6240
6241        // Sets the current menu info so all items added to menu will have
6242        // my extra info set.
6243        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6244
6245        onCreateContextMenu(menu);
6246        ListenerInfo li = mListenerInfo;
6247        if (li != null && li.mOnCreateContextMenuListener != null) {
6248            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6249        }
6250
6251        // Clear the extra information so subsequent items that aren't mine don't
6252        // have my extra info.
6253        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6254
6255        if (mParent != null) {
6256            mParent.createContextMenu(menu);
6257        }
6258    }
6259
6260    /**
6261     * Views should implement this if they have extra information to associate
6262     * with the context menu. The return result is supplied as a parameter to
6263     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6264     * callback.
6265     *
6266     * @return Extra information about the item for which the context menu
6267     *         should be shown. This information will vary across different
6268     *         subclasses of View.
6269     */
6270    protected ContextMenuInfo getContextMenuInfo() {
6271        return null;
6272    }
6273
6274    /**
6275     * Views should implement this if the view itself is going to add items to
6276     * the context menu.
6277     *
6278     * @param menu the context menu to populate
6279     */
6280    protected void onCreateContextMenu(ContextMenu menu) {
6281    }
6282
6283    /**
6284     * Implement this method to handle trackball motion events.  The
6285     * <em>relative</em> movement of the trackball since the last event
6286     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6287     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6288     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6289     * they will often be fractional values, representing the more fine-grained
6290     * movement information available from a trackball).
6291     *
6292     * @param event The motion event.
6293     * @return True if the event was handled, false otherwise.
6294     */
6295    public boolean onTrackballEvent(MotionEvent event) {
6296        return false;
6297    }
6298
6299    /**
6300     * Implement this method to handle generic motion events.
6301     * <p>
6302     * Generic motion events describe joystick movements, mouse hovers, track pad
6303     * touches, scroll wheel movements and other input events.  The
6304     * {@link MotionEvent#getSource() source} of the motion event specifies
6305     * the class of input that was received.  Implementations of this method
6306     * must examine the bits in the source before processing the event.
6307     * The following code example shows how this is done.
6308     * </p><p>
6309     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6310     * are delivered to the view under the pointer.  All other generic motion events are
6311     * delivered to the focused view.
6312     * </p>
6313     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6314     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6315     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6316     *             // process the joystick movement...
6317     *             return true;
6318     *         }
6319     *     }
6320     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6321     *         switch (event.getAction()) {
6322     *             case MotionEvent.ACTION_HOVER_MOVE:
6323     *                 // process the mouse hover movement...
6324     *                 return true;
6325     *             case MotionEvent.ACTION_SCROLL:
6326     *                 // process the scroll wheel movement...
6327     *                 return true;
6328     *         }
6329     *     }
6330     *     return super.onGenericMotionEvent(event);
6331     * }</pre>
6332     *
6333     * @param event The generic motion event being processed.
6334     * @return True if the event was handled, false otherwise.
6335     */
6336    public boolean onGenericMotionEvent(MotionEvent event) {
6337        return false;
6338    }
6339
6340    /**
6341     * Implement this method to handle hover events.
6342     * <p>
6343     * This method is called whenever a pointer is hovering into, over, or out of the
6344     * bounds of a view and the view is not currently being touched.
6345     * Hover events are represented as pointer events with action
6346     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6347     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6348     * </p>
6349     * <ul>
6350     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6351     * when the pointer enters the bounds of the view.</li>
6352     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6353     * when the pointer has already entered the bounds of the view and has moved.</li>
6354     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6355     * when the pointer has exited the bounds of the view or when the pointer is
6356     * about to go down due to a button click, tap, or similar user action that
6357     * causes the view to be touched.</li>
6358     * </ul>
6359     * <p>
6360     * The view should implement this method to return true to indicate that it is
6361     * handling the hover event, such as by changing its drawable state.
6362     * </p><p>
6363     * The default implementation calls {@link #setHovered} to update the hovered state
6364     * of the view when a hover enter or hover exit event is received, if the view
6365     * is enabled and is clickable.  The default implementation also sends hover
6366     * accessibility events.
6367     * </p>
6368     *
6369     * @param event The motion event that describes the hover.
6370     * @return True if the view handled the hover event.
6371     *
6372     * @see #isHovered
6373     * @see #setHovered
6374     * @see #onHoverChanged
6375     */
6376    public boolean onHoverEvent(MotionEvent event) {
6377        // The root view may receive hover (or touch) events that are outside the bounds of
6378        // the window.  This code ensures that we only send accessibility events for
6379        // hovers that are actually within the bounds of the root view.
6380        final int action = event.getAction();
6381        if (!mSendingHoverAccessibilityEvents) {
6382            if ((action == MotionEvent.ACTION_HOVER_ENTER
6383                    || action == MotionEvent.ACTION_HOVER_MOVE)
6384                    && !hasHoveredChild()
6385                    && pointInView(event.getX(), event.getY())) {
6386                mSendingHoverAccessibilityEvents = true;
6387                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6388            }
6389        } else {
6390            if (action == MotionEvent.ACTION_HOVER_EXIT
6391                    || (action == MotionEvent.ACTION_HOVER_MOVE
6392                            && !pointInView(event.getX(), event.getY()))) {
6393                mSendingHoverAccessibilityEvents = false;
6394                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6395            }
6396        }
6397
6398        if (isHoverable()) {
6399            switch (action) {
6400                case MotionEvent.ACTION_HOVER_ENTER:
6401                    setHovered(true);
6402                    break;
6403                case MotionEvent.ACTION_HOVER_EXIT:
6404                    setHovered(false);
6405                    break;
6406            }
6407
6408            // Dispatch the event to onGenericMotionEvent before returning true.
6409            // This is to provide compatibility with existing applications that
6410            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6411            // break because of the new default handling for hoverable views
6412            // in onHoverEvent.
6413            // Note that onGenericMotionEvent will be called by default when
6414            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6415            dispatchGenericMotionEventInternal(event);
6416            return true;
6417        }
6418        return false;
6419    }
6420
6421    /**
6422     * Returns true if the view should handle {@link #onHoverEvent}
6423     * by calling {@link #setHovered} to change its hovered state.
6424     *
6425     * @return True if the view is hoverable.
6426     */
6427    private boolean isHoverable() {
6428        final int viewFlags = mViewFlags;
6429        //noinspection SimplifiableIfStatement
6430        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6431            return false;
6432        }
6433
6434        return (viewFlags & CLICKABLE) == CLICKABLE
6435                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6436    }
6437
6438    /**
6439     * Returns true if the view is currently hovered.
6440     *
6441     * @return True if the view is currently hovered.
6442     *
6443     * @see #setHovered
6444     * @see #onHoverChanged
6445     */
6446    @ViewDebug.ExportedProperty
6447    public boolean isHovered() {
6448        return (mPrivateFlags & HOVERED) != 0;
6449    }
6450
6451    /**
6452     * Sets whether the view is currently hovered.
6453     * <p>
6454     * Calling this method also changes the drawable state of the view.  This
6455     * enables the view to react to hover by using different drawable resources
6456     * to change its appearance.
6457     * </p><p>
6458     * The {@link #onHoverChanged} method is called when the hovered state changes.
6459     * </p>
6460     *
6461     * @param hovered True if the view is hovered.
6462     *
6463     * @see #isHovered
6464     * @see #onHoverChanged
6465     */
6466    public void setHovered(boolean hovered) {
6467        if (hovered) {
6468            if ((mPrivateFlags & HOVERED) == 0) {
6469                mPrivateFlags |= HOVERED;
6470                refreshDrawableState();
6471                onHoverChanged(true);
6472            }
6473        } else {
6474            if ((mPrivateFlags & HOVERED) != 0) {
6475                mPrivateFlags &= ~HOVERED;
6476                refreshDrawableState();
6477                onHoverChanged(false);
6478            }
6479        }
6480    }
6481
6482    /**
6483     * Implement this method to handle hover state changes.
6484     * <p>
6485     * This method is called whenever the hover state changes as a result of a
6486     * call to {@link #setHovered}.
6487     * </p>
6488     *
6489     * @param hovered The current hover state, as returned by {@link #isHovered}.
6490     *
6491     * @see #isHovered
6492     * @see #setHovered
6493     */
6494    public void onHoverChanged(boolean hovered) {
6495    }
6496
6497    /**
6498     * Implement this method to handle touch screen motion events.
6499     *
6500     * @param event The motion event.
6501     * @return True if the event was handled, false otherwise.
6502     */
6503    public boolean onTouchEvent(MotionEvent event) {
6504        final int viewFlags = mViewFlags;
6505
6506        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6507            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6508                mPrivateFlags &= ~PRESSED;
6509                refreshDrawableState();
6510            }
6511            // A disabled view that is clickable still consumes the touch
6512            // events, it just doesn't respond to them.
6513            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6514                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6515        }
6516
6517        if (mTouchDelegate != null) {
6518            if (mTouchDelegate.onTouchEvent(event)) {
6519                return true;
6520            }
6521        }
6522
6523        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6524                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6525            switch (event.getAction()) {
6526                case MotionEvent.ACTION_UP:
6527                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6528                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6529                        // take focus if we don't have it already and we should in
6530                        // touch mode.
6531                        boolean focusTaken = false;
6532                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6533                            focusTaken = requestFocus();
6534                        }
6535
6536                        if (prepressed) {
6537                            // The button is being released before we actually
6538                            // showed it as pressed.  Make it show the pressed
6539                            // state now (before scheduling the click) to ensure
6540                            // the user sees it.
6541                            mPrivateFlags |= PRESSED;
6542                            refreshDrawableState();
6543                       }
6544
6545                        if (!mHasPerformedLongPress) {
6546                            // This is a tap, so remove the longpress check
6547                            removeLongPressCallback();
6548
6549                            // Only perform take click actions if we were in the pressed state
6550                            if (!focusTaken) {
6551                                // Use a Runnable and post this rather than calling
6552                                // performClick directly. This lets other visual state
6553                                // of the view update before click actions start.
6554                                if (mPerformClick == null) {
6555                                    mPerformClick = new PerformClick();
6556                                }
6557                                if (!post(mPerformClick)) {
6558                                    performClick();
6559                                }
6560                            }
6561                        }
6562
6563                        if (mUnsetPressedState == null) {
6564                            mUnsetPressedState = new UnsetPressedState();
6565                        }
6566
6567                        if (prepressed) {
6568                            postDelayed(mUnsetPressedState,
6569                                    ViewConfiguration.getPressedStateDuration());
6570                        } else if (!post(mUnsetPressedState)) {
6571                            // If the post failed, unpress right now
6572                            mUnsetPressedState.run();
6573                        }
6574                        removeTapCallback();
6575                    }
6576                    break;
6577
6578                case MotionEvent.ACTION_DOWN:
6579                    mHasPerformedLongPress = false;
6580
6581                    if (performButtonActionOnTouchDown(event)) {
6582                        break;
6583                    }
6584
6585                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6586                    boolean isInScrollingContainer = isInScrollingContainer();
6587
6588                    // For views inside a scrolling container, delay the pressed feedback for
6589                    // a short period in case this is a scroll.
6590                    if (isInScrollingContainer) {
6591                        mPrivateFlags |= PREPRESSED;
6592                        if (mPendingCheckForTap == null) {
6593                            mPendingCheckForTap = new CheckForTap();
6594                        }
6595                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6596                    } else {
6597                        // Not inside a scrolling container, so show the feedback right away
6598                        mPrivateFlags |= PRESSED;
6599                        refreshDrawableState();
6600                        checkForLongClick(0);
6601                    }
6602                    break;
6603
6604                case MotionEvent.ACTION_CANCEL:
6605                    mPrivateFlags &= ~PRESSED;
6606                    refreshDrawableState();
6607                    removeTapCallback();
6608                    break;
6609
6610                case MotionEvent.ACTION_MOVE:
6611                    final int x = (int) event.getX();
6612                    final int y = (int) event.getY();
6613
6614                    // Be lenient about moving outside of buttons
6615                    if (!pointInView(x, y, mTouchSlop)) {
6616                        // Outside button
6617                        removeTapCallback();
6618                        if ((mPrivateFlags & PRESSED) != 0) {
6619                            // Remove any future long press/tap checks
6620                            removeLongPressCallback();
6621
6622                            // Need to switch from pressed to not pressed
6623                            mPrivateFlags &= ~PRESSED;
6624                            refreshDrawableState();
6625                        }
6626                    }
6627                    break;
6628            }
6629            return true;
6630        }
6631
6632        return false;
6633    }
6634
6635    /**
6636     * @hide
6637     */
6638    public boolean isInScrollingContainer() {
6639        ViewParent p = getParent();
6640        while (p != null && p instanceof ViewGroup) {
6641            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6642                return true;
6643            }
6644            p = p.getParent();
6645        }
6646        return false;
6647    }
6648
6649    /**
6650     * Remove the longpress detection timer.
6651     */
6652    private void removeLongPressCallback() {
6653        if (mPendingCheckForLongPress != null) {
6654          removeCallbacks(mPendingCheckForLongPress);
6655        }
6656    }
6657
6658    /**
6659     * Remove the pending click action
6660     */
6661    private void removePerformClickCallback() {
6662        if (mPerformClick != null) {
6663            removeCallbacks(mPerformClick);
6664        }
6665    }
6666
6667    /**
6668     * Remove the prepress detection timer.
6669     */
6670    private void removeUnsetPressCallback() {
6671        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6672            setPressed(false);
6673            removeCallbacks(mUnsetPressedState);
6674        }
6675    }
6676
6677    /**
6678     * Remove the tap detection timer.
6679     */
6680    private void removeTapCallback() {
6681        if (mPendingCheckForTap != null) {
6682            mPrivateFlags &= ~PREPRESSED;
6683            removeCallbacks(mPendingCheckForTap);
6684        }
6685    }
6686
6687    /**
6688     * Cancels a pending long press.  Your subclass can use this if you
6689     * want the context menu to come up if the user presses and holds
6690     * at the same place, but you don't want it to come up if they press
6691     * and then move around enough to cause scrolling.
6692     */
6693    public void cancelLongPress() {
6694        removeLongPressCallback();
6695
6696        /*
6697         * The prepressed state handled by the tap callback is a display
6698         * construct, but the tap callback will post a long press callback
6699         * less its own timeout. Remove it here.
6700         */
6701        removeTapCallback();
6702    }
6703
6704    /**
6705     * Remove the pending callback for sending a
6706     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6707     */
6708    private void removeSendViewScrolledAccessibilityEventCallback() {
6709        if (mSendViewScrolledAccessibilityEvent != null) {
6710            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6711        }
6712    }
6713
6714    /**
6715     * Sets the TouchDelegate for this View.
6716     */
6717    public void setTouchDelegate(TouchDelegate delegate) {
6718        mTouchDelegate = delegate;
6719    }
6720
6721    /**
6722     * Gets the TouchDelegate for this View.
6723     */
6724    public TouchDelegate getTouchDelegate() {
6725        return mTouchDelegate;
6726    }
6727
6728    /**
6729     * Set flags controlling behavior of this view.
6730     *
6731     * @param flags Constant indicating the value which should be set
6732     * @param mask Constant indicating the bit range that should be changed
6733     */
6734    void setFlags(int flags, int mask) {
6735        int old = mViewFlags;
6736        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6737
6738        int changed = mViewFlags ^ old;
6739        if (changed == 0) {
6740            return;
6741        }
6742        int privateFlags = mPrivateFlags;
6743
6744        /* Check if the FOCUSABLE bit has changed */
6745        if (((changed & FOCUSABLE_MASK) != 0) &&
6746                ((privateFlags & HAS_BOUNDS) !=0)) {
6747            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6748                    && ((privateFlags & FOCUSED) != 0)) {
6749                /* Give up focus if we are no longer focusable */
6750                clearFocus();
6751            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6752                    && ((privateFlags & FOCUSED) == 0)) {
6753                /*
6754                 * Tell the view system that we are now available to take focus
6755                 * if no one else already has it.
6756                 */
6757                if (mParent != null) mParent.focusableViewAvailable(this);
6758            }
6759        }
6760
6761        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6762            if ((changed & VISIBILITY_MASK) != 0) {
6763                /*
6764                 * If this view is becoming visible, invalidate it in case it changed while
6765                 * it was not visible. Marking it drawn ensures that the invalidation will
6766                 * go through.
6767                 */
6768                mPrivateFlags |= DRAWN;
6769                invalidate(true);
6770
6771                needGlobalAttributesUpdate(true);
6772
6773                // a view becoming visible is worth notifying the parent
6774                // about in case nothing has focus.  even if this specific view
6775                // isn't focusable, it may contain something that is, so let
6776                // the root view try to give this focus if nothing else does.
6777                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6778                    mParent.focusableViewAvailable(this);
6779                }
6780            }
6781        }
6782
6783        /* Check if the GONE bit has changed */
6784        if ((changed & GONE) != 0) {
6785            needGlobalAttributesUpdate(false);
6786            requestLayout();
6787
6788            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6789                if (hasFocus()) clearFocus();
6790                destroyDrawingCache();
6791                if (mParent instanceof View) {
6792                    // GONE views noop invalidation, so invalidate the parent
6793                    ((View) mParent).invalidate(true);
6794                }
6795                // Mark the view drawn to ensure that it gets invalidated properly the next
6796                // time it is visible and gets invalidated
6797                mPrivateFlags |= DRAWN;
6798            }
6799            if (mAttachInfo != null) {
6800                mAttachInfo.mViewVisibilityChanged = true;
6801            }
6802        }
6803
6804        /* Check if the VISIBLE bit has changed */
6805        if ((changed & INVISIBLE) != 0) {
6806            needGlobalAttributesUpdate(false);
6807            /*
6808             * If this view is becoming invisible, set the DRAWN flag so that
6809             * the next invalidate() will not be skipped.
6810             */
6811            mPrivateFlags |= DRAWN;
6812
6813            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6814                // root view becoming invisible shouldn't clear focus
6815                if (getRootView() != this) {
6816                    clearFocus();
6817                }
6818            }
6819            if (mAttachInfo != null) {
6820                mAttachInfo.mViewVisibilityChanged = true;
6821            }
6822        }
6823
6824        if ((changed & VISIBILITY_MASK) != 0) {
6825            if (mParent instanceof ViewGroup) {
6826                ((ViewGroup) mParent).onChildVisibilityChanged(this,
6827                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
6828                ((View) mParent).invalidate(true);
6829            } else if (mParent != null) {
6830                mParent.invalidateChild(this, null);
6831            }
6832            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6833        }
6834
6835        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6836            destroyDrawingCache();
6837        }
6838
6839        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6840            destroyDrawingCache();
6841            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6842            invalidateParentCaches();
6843        }
6844
6845        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6846            destroyDrawingCache();
6847            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6848        }
6849
6850        if ((changed & DRAW_MASK) != 0) {
6851            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6852                if (mBGDrawable != null) {
6853                    mPrivateFlags &= ~SKIP_DRAW;
6854                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6855                } else {
6856                    mPrivateFlags |= SKIP_DRAW;
6857                }
6858            } else {
6859                mPrivateFlags &= ~SKIP_DRAW;
6860            }
6861            requestLayout();
6862            invalidate(true);
6863        }
6864
6865        if ((changed & KEEP_SCREEN_ON) != 0) {
6866            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6867                mParent.recomputeViewAttributes(this);
6868            }
6869        }
6870
6871        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6872            requestLayout();
6873        }
6874    }
6875
6876    /**
6877     * Change the view's z order in the tree, so it's on top of other sibling
6878     * views
6879     */
6880    public void bringToFront() {
6881        if (mParent != null) {
6882            mParent.bringChildToFront(this);
6883        }
6884    }
6885
6886    /**
6887     * This is called in response to an internal scroll in this view (i.e., the
6888     * view scrolled its own contents). This is typically as a result of
6889     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6890     * called.
6891     *
6892     * @param l Current horizontal scroll origin.
6893     * @param t Current vertical scroll origin.
6894     * @param oldl Previous horizontal scroll origin.
6895     * @param oldt Previous vertical scroll origin.
6896     */
6897    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6898        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6899            postSendViewScrolledAccessibilityEventCallback();
6900        }
6901
6902        mBackgroundSizeChanged = true;
6903
6904        final AttachInfo ai = mAttachInfo;
6905        if (ai != null) {
6906            ai.mViewScrollChanged = true;
6907        }
6908    }
6909
6910    /**
6911     * Interface definition for a callback to be invoked when the layout bounds of a view
6912     * changes due to layout processing.
6913     */
6914    public interface OnLayoutChangeListener {
6915        /**
6916         * Called when the focus state of a view has changed.
6917         *
6918         * @param v The view whose state has changed.
6919         * @param left The new value of the view's left property.
6920         * @param top The new value of the view's top property.
6921         * @param right The new value of the view's right property.
6922         * @param bottom The new value of the view's bottom property.
6923         * @param oldLeft The previous value of the view's left property.
6924         * @param oldTop The previous value of the view's top property.
6925         * @param oldRight The previous value of the view's right property.
6926         * @param oldBottom The previous value of the view's bottom property.
6927         */
6928        void onLayoutChange(View v, int left, int top, int right, int bottom,
6929            int oldLeft, int oldTop, int oldRight, int oldBottom);
6930    }
6931
6932    /**
6933     * This is called during layout when the size of this view has changed. If
6934     * you were just added to the view hierarchy, you're called with the old
6935     * values of 0.
6936     *
6937     * @param w Current width of this view.
6938     * @param h Current height of this view.
6939     * @param oldw Old width of this view.
6940     * @param oldh Old height of this view.
6941     */
6942    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6943    }
6944
6945    /**
6946     * Called by draw to draw the child views. This may be overridden
6947     * by derived classes to gain control just before its children are drawn
6948     * (but after its own view has been drawn).
6949     * @param canvas the canvas on which to draw the view
6950     */
6951    protected void dispatchDraw(Canvas canvas) {
6952    }
6953
6954    /**
6955     * Gets the parent of this view. Note that the parent is a
6956     * ViewParent and not necessarily a View.
6957     *
6958     * @return Parent of this view.
6959     */
6960    public final ViewParent getParent() {
6961        return mParent;
6962    }
6963
6964    /**
6965     * Set the horizontal scrolled position of your view. This will cause a call to
6966     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6967     * invalidated.
6968     * @param value the x position to scroll to
6969     */
6970    public void setScrollX(int value) {
6971        scrollTo(value, mScrollY);
6972    }
6973
6974    /**
6975     * Set the vertical scrolled position of your view. This will cause a call to
6976     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6977     * invalidated.
6978     * @param value the y position to scroll to
6979     */
6980    public void setScrollY(int value) {
6981        scrollTo(mScrollX, value);
6982    }
6983
6984    /**
6985     * Return the scrolled left position of this view. This is the left edge of
6986     * the displayed part of your view. You do not need to draw any pixels
6987     * farther left, since those are outside of the frame of your view on
6988     * screen.
6989     *
6990     * @return The left edge of the displayed part of your view, in pixels.
6991     */
6992    public final int getScrollX() {
6993        return mScrollX;
6994    }
6995
6996    /**
6997     * Return the scrolled top position of this view. This is the top edge of
6998     * the displayed part of your view. You do not need to draw any pixels above
6999     * it, since those are outside of the frame of your view on screen.
7000     *
7001     * @return The top edge of the displayed part of your view, in pixels.
7002     */
7003    public final int getScrollY() {
7004        return mScrollY;
7005    }
7006
7007    /**
7008     * Return the width of the your view.
7009     *
7010     * @return The width of your view, in pixels.
7011     */
7012    @ViewDebug.ExportedProperty(category = "layout")
7013    public final int getWidth() {
7014        return mRight - mLeft;
7015    }
7016
7017    /**
7018     * Return the height of your view.
7019     *
7020     * @return The height of your view, in pixels.
7021     */
7022    @ViewDebug.ExportedProperty(category = "layout")
7023    public final int getHeight() {
7024        return mBottom - mTop;
7025    }
7026
7027    /**
7028     * Return the visible drawing bounds of your view. Fills in the output
7029     * rectangle with the values from getScrollX(), getScrollY(),
7030     * getWidth(), and getHeight().
7031     *
7032     * @param outRect The (scrolled) drawing bounds of the view.
7033     */
7034    public void getDrawingRect(Rect outRect) {
7035        outRect.left = mScrollX;
7036        outRect.top = mScrollY;
7037        outRect.right = mScrollX + (mRight - mLeft);
7038        outRect.bottom = mScrollY + (mBottom - mTop);
7039    }
7040
7041    /**
7042     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7043     * raw width component (that is the result is masked by
7044     * {@link #MEASURED_SIZE_MASK}).
7045     *
7046     * @return The raw measured width of this view.
7047     */
7048    public final int getMeasuredWidth() {
7049        return mMeasuredWidth & MEASURED_SIZE_MASK;
7050    }
7051
7052    /**
7053     * Return the full width measurement information for this view as computed
7054     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7055     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7056     * This should be used during measurement and layout calculations only. Use
7057     * {@link #getWidth()} to see how wide a view is after layout.
7058     *
7059     * @return The measured width of this view as a bit mask.
7060     */
7061    public final int getMeasuredWidthAndState() {
7062        return mMeasuredWidth;
7063    }
7064
7065    /**
7066     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7067     * raw width component (that is the result is masked by
7068     * {@link #MEASURED_SIZE_MASK}).
7069     *
7070     * @return The raw measured height of this view.
7071     */
7072    public final int getMeasuredHeight() {
7073        return mMeasuredHeight & MEASURED_SIZE_MASK;
7074    }
7075
7076    /**
7077     * Return the full height measurement information for this view as computed
7078     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7079     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7080     * This should be used during measurement and layout calculations only. Use
7081     * {@link #getHeight()} to see how wide a view is after layout.
7082     *
7083     * @return The measured width of this view as a bit mask.
7084     */
7085    public final int getMeasuredHeightAndState() {
7086        return mMeasuredHeight;
7087    }
7088
7089    /**
7090     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7091     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7092     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7093     * and the height component is at the shifted bits
7094     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7095     */
7096    public final int getMeasuredState() {
7097        return (mMeasuredWidth&MEASURED_STATE_MASK)
7098                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7099                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7100    }
7101
7102    /**
7103     * The transform matrix of this view, which is calculated based on the current
7104     * roation, scale, and pivot properties.
7105     *
7106     * @see #getRotation()
7107     * @see #getScaleX()
7108     * @see #getScaleY()
7109     * @see #getPivotX()
7110     * @see #getPivotY()
7111     * @return The current transform matrix for the view
7112     */
7113    public Matrix getMatrix() {
7114        if (mTransformationInfo != null) {
7115            updateMatrix();
7116            return mTransformationInfo.mMatrix;
7117        }
7118        return Matrix.IDENTITY_MATRIX;
7119    }
7120
7121    /**
7122     * Utility function to determine if the value is far enough away from zero to be
7123     * considered non-zero.
7124     * @param value A floating point value to check for zero-ness
7125     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7126     */
7127    private static boolean nonzero(float value) {
7128        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7129    }
7130
7131    /**
7132     * Returns true if the transform matrix is the identity matrix.
7133     * Recomputes the matrix if necessary.
7134     *
7135     * @return True if the transform matrix is the identity matrix, false otherwise.
7136     */
7137    final boolean hasIdentityMatrix() {
7138        if (mTransformationInfo != null) {
7139            updateMatrix();
7140            return mTransformationInfo.mMatrixIsIdentity;
7141        }
7142        return true;
7143    }
7144
7145    void ensureTransformationInfo() {
7146        if (mTransformationInfo == null) {
7147            mTransformationInfo = new TransformationInfo();
7148        }
7149    }
7150
7151    /**
7152     * Recomputes the transform matrix if necessary.
7153     */
7154    private void updateMatrix() {
7155        final TransformationInfo info = mTransformationInfo;
7156        if (info == null) {
7157            return;
7158        }
7159        if (info.mMatrixDirty) {
7160            // transform-related properties have changed since the last time someone
7161            // asked for the matrix; recalculate it with the current values
7162
7163            // Figure out if we need to update the pivot point
7164            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7165                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7166                    info.mPrevWidth = mRight - mLeft;
7167                    info.mPrevHeight = mBottom - mTop;
7168                    info.mPivotX = info.mPrevWidth / 2f;
7169                    info.mPivotY = info.mPrevHeight / 2f;
7170                }
7171            }
7172            info.mMatrix.reset();
7173            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7174                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7175                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7176                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7177            } else {
7178                if (info.mCamera == null) {
7179                    info.mCamera = new Camera();
7180                    info.matrix3D = new Matrix();
7181                }
7182                info.mCamera.save();
7183                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7184                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7185                info.mCamera.getMatrix(info.matrix3D);
7186                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7187                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7188                        info.mPivotY + info.mTranslationY);
7189                info.mMatrix.postConcat(info.matrix3D);
7190                info.mCamera.restore();
7191            }
7192            info.mMatrixDirty = false;
7193            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7194            info.mInverseMatrixDirty = true;
7195        }
7196    }
7197
7198    /**
7199     * Utility method to retrieve the inverse of the current mMatrix property.
7200     * We cache the matrix to avoid recalculating it when transform properties
7201     * have not changed.
7202     *
7203     * @return The inverse of the current matrix of this view.
7204     */
7205    final Matrix getInverseMatrix() {
7206        final TransformationInfo info = mTransformationInfo;
7207        if (info != null) {
7208            updateMatrix();
7209            if (info.mInverseMatrixDirty) {
7210                if (info.mInverseMatrix == null) {
7211                    info.mInverseMatrix = new Matrix();
7212                }
7213                info.mMatrix.invert(info.mInverseMatrix);
7214                info.mInverseMatrixDirty = false;
7215            }
7216            return info.mInverseMatrix;
7217        }
7218        return Matrix.IDENTITY_MATRIX;
7219    }
7220
7221    /**
7222     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7223     * views are drawn) from the camera to this view. The camera's distance
7224     * affects 3D transformations, for instance rotations around the X and Y
7225     * axis. If the rotationX or rotationY properties are changed and this view is
7226     * large (more than half the size of the screen), it is recommended to always
7227     * use a camera distance that's greater than the height (X axis rotation) or
7228     * the width (Y axis rotation) of this view.</p>
7229     *
7230     * <p>The distance of the camera from the view plane can have an affect on the
7231     * perspective distortion of the view when it is rotated around the x or y axis.
7232     * For example, a large distance will result in a large viewing angle, and there
7233     * will not be much perspective distortion of the view as it rotates. A short
7234     * distance may cause much more perspective distortion upon rotation, and can
7235     * also result in some drawing artifacts if the rotated view ends up partially
7236     * behind the camera (which is why the recommendation is to use a distance at
7237     * least as far as the size of the view, if the view is to be rotated.)</p>
7238     *
7239     * <p>The distance is expressed in "depth pixels." The default distance depends
7240     * on the screen density. For instance, on a medium density display, the
7241     * default distance is 1280. On a high density display, the default distance
7242     * is 1920.</p>
7243     *
7244     * <p>If you want to specify a distance that leads to visually consistent
7245     * results across various densities, use the following formula:</p>
7246     * <pre>
7247     * float scale = context.getResources().getDisplayMetrics().density;
7248     * view.setCameraDistance(distance * scale);
7249     * </pre>
7250     *
7251     * <p>The density scale factor of a high density display is 1.5,
7252     * and 1920 = 1280 * 1.5.</p>
7253     *
7254     * @param distance The distance in "depth pixels", if negative the opposite
7255     *        value is used
7256     *
7257     * @see #setRotationX(float)
7258     * @see #setRotationY(float)
7259     */
7260    public void setCameraDistance(float distance) {
7261        invalidateParentCaches();
7262        invalidate(false);
7263
7264        ensureTransformationInfo();
7265        final float dpi = mResources.getDisplayMetrics().densityDpi;
7266        final TransformationInfo info = mTransformationInfo;
7267        if (info.mCamera == null) {
7268            info.mCamera = new Camera();
7269            info.matrix3D = new Matrix();
7270        }
7271
7272        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7273        info.mMatrixDirty = true;
7274
7275        invalidate(false);
7276    }
7277
7278    /**
7279     * The degrees that the view is rotated around the pivot point.
7280     *
7281     * @see #setRotation(float)
7282     * @see #getPivotX()
7283     * @see #getPivotY()
7284     *
7285     * @return The degrees of rotation.
7286     */
7287    @ViewDebug.ExportedProperty(category = "drawing")
7288    public float getRotation() {
7289        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7290    }
7291
7292    /**
7293     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7294     * result in clockwise rotation.
7295     *
7296     * @param rotation The degrees of rotation.
7297     *
7298     * @see #getRotation()
7299     * @see #getPivotX()
7300     * @see #getPivotY()
7301     * @see #setRotationX(float)
7302     * @see #setRotationY(float)
7303     *
7304     * @attr ref android.R.styleable#View_rotation
7305     */
7306    public void setRotation(float rotation) {
7307        ensureTransformationInfo();
7308        final TransformationInfo info = mTransformationInfo;
7309        if (info.mRotation != rotation) {
7310            invalidateParentCaches();
7311            // Double-invalidation is necessary to capture view's old and new areas
7312            invalidate(false);
7313            info.mRotation = rotation;
7314            info.mMatrixDirty = true;
7315            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7316            invalidate(false);
7317        }
7318    }
7319
7320    /**
7321     * The degrees that the view is rotated around the vertical axis through the pivot point.
7322     *
7323     * @see #getPivotX()
7324     * @see #getPivotY()
7325     * @see #setRotationY(float)
7326     *
7327     * @return The degrees of Y rotation.
7328     */
7329    @ViewDebug.ExportedProperty(category = "drawing")
7330    public float getRotationY() {
7331        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7332    }
7333
7334    /**
7335     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7336     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7337     * down the y axis.
7338     *
7339     * When rotating large views, it is recommended to adjust the camera distance
7340     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7341     *
7342     * @param rotationY The degrees of Y rotation.
7343     *
7344     * @see #getRotationY()
7345     * @see #getPivotX()
7346     * @see #getPivotY()
7347     * @see #setRotation(float)
7348     * @see #setRotationX(float)
7349     * @see #setCameraDistance(float)
7350     *
7351     * @attr ref android.R.styleable#View_rotationY
7352     */
7353    public void setRotationY(float rotationY) {
7354        ensureTransformationInfo();
7355        final TransformationInfo info = mTransformationInfo;
7356        if (info.mRotationY != rotationY) {
7357            invalidateParentCaches();
7358            // Double-invalidation is necessary to capture view's old and new areas
7359            invalidate(false);
7360            info.mRotationY = rotationY;
7361            info.mMatrixDirty = true;
7362            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7363            invalidate(false);
7364        }
7365    }
7366
7367    /**
7368     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7369     *
7370     * @see #getPivotX()
7371     * @see #getPivotY()
7372     * @see #setRotationX(float)
7373     *
7374     * @return The degrees of X rotation.
7375     */
7376    @ViewDebug.ExportedProperty(category = "drawing")
7377    public float getRotationX() {
7378        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7379    }
7380
7381    /**
7382     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7383     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7384     * x axis.
7385     *
7386     * When rotating large views, it is recommended to adjust the camera distance
7387     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7388     *
7389     * @param rotationX The degrees of X rotation.
7390     *
7391     * @see #getRotationX()
7392     * @see #getPivotX()
7393     * @see #getPivotY()
7394     * @see #setRotation(float)
7395     * @see #setRotationY(float)
7396     * @see #setCameraDistance(float)
7397     *
7398     * @attr ref android.R.styleable#View_rotationX
7399     */
7400    public void setRotationX(float rotationX) {
7401        ensureTransformationInfo();
7402        final TransformationInfo info = mTransformationInfo;
7403        if (info.mRotationX != rotationX) {
7404            invalidateParentCaches();
7405            // Double-invalidation is necessary to capture view's old and new areas
7406            invalidate(false);
7407            info.mRotationX = rotationX;
7408            info.mMatrixDirty = true;
7409            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7410            invalidate(false);
7411        }
7412    }
7413
7414    /**
7415     * The amount that the view is scaled in x around the pivot point, as a proportion of
7416     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7417     *
7418     * <p>By default, this is 1.0f.
7419     *
7420     * @see #getPivotX()
7421     * @see #getPivotY()
7422     * @return The scaling factor.
7423     */
7424    @ViewDebug.ExportedProperty(category = "drawing")
7425    public float getScaleX() {
7426        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7427    }
7428
7429    /**
7430     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7431     * the view's unscaled width. A value of 1 means that no scaling is applied.
7432     *
7433     * @param scaleX The scaling factor.
7434     * @see #getPivotX()
7435     * @see #getPivotY()
7436     *
7437     * @attr ref android.R.styleable#View_scaleX
7438     */
7439    public void setScaleX(float scaleX) {
7440        ensureTransformationInfo();
7441        final TransformationInfo info = mTransformationInfo;
7442        if (info.mScaleX != scaleX) {
7443            invalidateParentCaches();
7444            // Double-invalidation is necessary to capture view's old and new areas
7445            invalidate(false);
7446            info.mScaleX = scaleX;
7447            info.mMatrixDirty = true;
7448            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7449            invalidate(false);
7450        }
7451    }
7452
7453    /**
7454     * The amount that the view is scaled in y around the pivot point, as a proportion of
7455     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7456     *
7457     * <p>By default, this is 1.0f.
7458     *
7459     * @see #getPivotX()
7460     * @see #getPivotY()
7461     * @return The scaling factor.
7462     */
7463    @ViewDebug.ExportedProperty(category = "drawing")
7464    public float getScaleY() {
7465        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7466    }
7467
7468    /**
7469     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7470     * the view's unscaled width. A value of 1 means that no scaling is applied.
7471     *
7472     * @param scaleY The scaling factor.
7473     * @see #getPivotX()
7474     * @see #getPivotY()
7475     *
7476     * @attr ref android.R.styleable#View_scaleY
7477     */
7478    public void setScaleY(float scaleY) {
7479        ensureTransformationInfo();
7480        final TransformationInfo info = mTransformationInfo;
7481        if (info.mScaleY != scaleY) {
7482            invalidateParentCaches();
7483            // Double-invalidation is necessary to capture view's old and new areas
7484            invalidate(false);
7485            info.mScaleY = scaleY;
7486            info.mMatrixDirty = true;
7487            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7488            invalidate(false);
7489        }
7490    }
7491
7492    /**
7493     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7494     * and {@link #setScaleX(float) scaled}.
7495     *
7496     * @see #getRotation()
7497     * @see #getScaleX()
7498     * @see #getScaleY()
7499     * @see #getPivotY()
7500     * @return The x location of the pivot point.
7501     */
7502    @ViewDebug.ExportedProperty(category = "drawing")
7503    public float getPivotX() {
7504        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7505    }
7506
7507    /**
7508     * Sets the x location of the point around which the view is
7509     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7510     * By default, the pivot point is centered on the object.
7511     * Setting this property disables this behavior and causes the view to use only the
7512     * explicitly set pivotX and pivotY values.
7513     *
7514     * @param pivotX The x location of the pivot point.
7515     * @see #getRotation()
7516     * @see #getScaleX()
7517     * @see #getScaleY()
7518     * @see #getPivotY()
7519     *
7520     * @attr ref android.R.styleable#View_transformPivotX
7521     */
7522    public void setPivotX(float pivotX) {
7523        ensureTransformationInfo();
7524        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7525        final TransformationInfo info = mTransformationInfo;
7526        if (info.mPivotX != pivotX) {
7527            invalidateParentCaches();
7528            // Double-invalidation is necessary to capture view's old and new areas
7529            invalidate(false);
7530            info.mPivotX = pivotX;
7531            info.mMatrixDirty = true;
7532            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7533            invalidate(false);
7534        }
7535    }
7536
7537    /**
7538     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7539     * and {@link #setScaleY(float) scaled}.
7540     *
7541     * @see #getRotation()
7542     * @see #getScaleX()
7543     * @see #getScaleY()
7544     * @see #getPivotY()
7545     * @return The y location of the pivot point.
7546     */
7547    @ViewDebug.ExportedProperty(category = "drawing")
7548    public float getPivotY() {
7549        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7550    }
7551
7552    /**
7553     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7554     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7555     * Setting this property disables this behavior and causes the view to use only the
7556     * explicitly set pivotX and pivotY values.
7557     *
7558     * @param pivotY The y location of the pivot point.
7559     * @see #getRotation()
7560     * @see #getScaleX()
7561     * @see #getScaleY()
7562     * @see #getPivotY()
7563     *
7564     * @attr ref android.R.styleable#View_transformPivotY
7565     */
7566    public void setPivotY(float pivotY) {
7567        ensureTransformationInfo();
7568        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7569        final TransformationInfo info = mTransformationInfo;
7570        if (info.mPivotY != pivotY) {
7571            invalidateParentCaches();
7572            // Double-invalidation is necessary to capture view's old and new areas
7573            invalidate(false);
7574            info.mPivotY = pivotY;
7575            info.mMatrixDirty = true;
7576            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7577            invalidate(false);
7578        }
7579    }
7580
7581    /**
7582     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7583     * completely transparent and 1 means the view is completely opaque.
7584     *
7585     * <p>By default this is 1.0f.
7586     * @return The opacity of the view.
7587     */
7588    @ViewDebug.ExportedProperty(category = "drawing")
7589    public float getAlpha() {
7590        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7591    }
7592
7593    /**
7594     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7595     * completely transparent and 1 means the view is completely opaque.</p>
7596     *
7597     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7598     * responsible for applying the opacity itself. Otherwise, calling this method is
7599     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7600     * setting a hardware layer.</p>
7601     *
7602     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7603     * performance implications. It is generally best to use the alpha property sparingly and
7604     * transiently, as in the case of fading animations.</p>
7605     *
7606     * @param alpha The opacity of the view.
7607     *
7608     * @see #setLayerType(int, android.graphics.Paint)
7609     *
7610     * @attr ref android.R.styleable#View_alpha
7611     */
7612    public void setAlpha(float alpha) {
7613        ensureTransformationInfo();
7614        if (mTransformationInfo.mAlpha != alpha) {
7615            mTransformationInfo.mAlpha = alpha;
7616            invalidateParentCaches();
7617            if (onSetAlpha((int) (alpha * 255))) {
7618                mPrivateFlags |= ALPHA_SET;
7619                // subclass is handling alpha - don't optimize rendering cache invalidation
7620                invalidate(true);
7621            } else {
7622                mPrivateFlags &= ~ALPHA_SET;
7623                invalidate(false);
7624            }
7625        }
7626    }
7627
7628    /**
7629     * Faster version of setAlpha() which performs the same steps except there are
7630     * no calls to invalidate(). The caller of this function should perform proper invalidation
7631     * on the parent and this object. The return value indicates whether the subclass handles
7632     * alpha (the return value for onSetAlpha()).
7633     *
7634     * @param alpha The new value for the alpha property
7635     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7636     *         the new value for the alpha property is different from the old value
7637     */
7638    boolean setAlphaNoInvalidation(float alpha) {
7639        ensureTransformationInfo();
7640        if (mTransformationInfo.mAlpha != alpha) {
7641            mTransformationInfo.mAlpha = alpha;
7642            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7643            if (subclassHandlesAlpha) {
7644                mPrivateFlags |= ALPHA_SET;
7645                return true;
7646            } else {
7647                mPrivateFlags &= ~ALPHA_SET;
7648            }
7649        }
7650        return false;
7651    }
7652
7653    /**
7654     * Top position of this view relative to its parent.
7655     *
7656     * @return The top of this view, in pixels.
7657     */
7658    @ViewDebug.CapturedViewProperty
7659    public final int getTop() {
7660        return mTop;
7661    }
7662
7663    /**
7664     * Sets the top position of this view relative to its parent. This method is meant to be called
7665     * by the layout system and should not generally be called otherwise, because the property
7666     * may be changed at any time by the layout.
7667     *
7668     * @param top The top of this view, in pixels.
7669     */
7670    public final void setTop(int top) {
7671        if (top != mTop) {
7672            updateMatrix();
7673            final boolean matrixIsIdentity = mTransformationInfo == null
7674                    || mTransformationInfo.mMatrixIsIdentity;
7675            if (matrixIsIdentity) {
7676                if (mAttachInfo != null) {
7677                    int minTop;
7678                    int yLoc;
7679                    if (top < mTop) {
7680                        minTop = top;
7681                        yLoc = top - mTop;
7682                    } else {
7683                        minTop = mTop;
7684                        yLoc = 0;
7685                    }
7686                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7687                }
7688            } else {
7689                // Double-invalidation is necessary to capture view's old and new areas
7690                invalidate(true);
7691            }
7692
7693            int width = mRight - mLeft;
7694            int oldHeight = mBottom - mTop;
7695
7696            mTop = top;
7697
7698            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7699
7700            if (!matrixIsIdentity) {
7701                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7702                    // A change in dimension means an auto-centered pivot point changes, too
7703                    mTransformationInfo.mMatrixDirty = true;
7704                }
7705                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7706                invalidate(true);
7707            }
7708            mBackgroundSizeChanged = true;
7709            invalidateParentIfNeeded();
7710        }
7711    }
7712
7713    /**
7714     * Bottom position of this view relative to its parent.
7715     *
7716     * @return The bottom of this view, in pixels.
7717     */
7718    @ViewDebug.CapturedViewProperty
7719    public final int getBottom() {
7720        return mBottom;
7721    }
7722
7723    /**
7724     * True if this view has changed since the last time being drawn.
7725     *
7726     * @return The dirty state of this view.
7727     */
7728    public boolean isDirty() {
7729        return (mPrivateFlags & DIRTY_MASK) != 0;
7730    }
7731
7732    /**
7733     * Sets the bottom position of this view relative to its parent. This method is meant to be
7734     * called by the layout system and should not generally be called otherwise, because the
7735     * property may be changed at any time by the layout.
7736     *
7737     * @param bottom The bottom of this view, in pixels.
7738     */
7739    public final void setBottom(int bottom) {
7740        if (bottom != mBottom) {
7741            updateMatrix();
7742            final boolean matrixIsIdentity = mTransformationInfo == null
7743                    || mTransformationInfo.mMatrixIsIdentity;
7744            if (matrixIsIdentity) {
7745                if (mAttachInfo != null) {
7746                    int maxBottom;
7747                    if (bottom < mBottom) {
7748                        maxBottom = mBottom;
7749                    } else {
7750                        maxBottom = bottom;
7751                    }
7752                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7753                }
7754            } else {
7755                // Double-invalidation is necessary to capture view's old and new areas
7756                invalidate(true);
7757            }
7758
7759            int width = mRight - mLeft;
7760            int oldHeight = mBottom - mTop;
7761
7762            mBottom = bottom;
7763
7764            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7765
7766            if (!matrixIsIdentity) {
7767                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7768                    // A change in dimension means an auto-centered pivot point changes, too
7769                    mTransformationInfo.mMatrixDirty = true;
7770                }
7771                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7772                invalidate(true);
7773            }
7774            mBackgroundSizeChanged = true;
7775            invalidateParentIfNeeded();
7776        }
7777    }
7778
7779    /**
7780     * Left position of this view relative to its parent.
7781     *
7782     * @return The left edge of this view, in pixels.
7783     */
7784    @ViewDebug.CapturedViewProperty
7785    public final int getLeft() {
7786        return mLeft;
7787    }
7788
7789    /**
7790     * Sets the left position of this view relative to its parent. This method is meant to be called
7791     * by the layout system and should not generally be called otherwise, because the property
7792     * may be changed at any time by the layout.
7793     *
7794     * @param left The bottom of this view, in pixels.
7795     */
7796    public final void setLeft(int left) {
7797        if (left != mLeft) {
7798            updateMatrix();
7799            final boolean matrixIsIdentity = mTransformationInfo == null
7800                    || mTransformationInfo.mMatrixIsIdentity;
7801            if (matrixIsIdentity) {
7802                if (mAttachInfo != null) {
7803                    int minLeft;
7804                    int xLoc;
7805                    if (left < mLeft) {
7806                        minLeft = left;
7807                        xLoc = left - mLeft;
7808                    } else {
7809                        minLeft = mLeft;
7810                        xLoc = 0;
7811                    }
7812                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7813                }
7814            } else {
7815                // Double-invalidation is necessary to capture view's old and new areas
7816                invalidate(true);
7817            }
7818
7819            int oldWidth = mRight - mLeft;
7820            int height = mBottom - mTop;
7821
7822            mLeft = left;
7823
7824            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7825
7826            if (!matrixIsIdentity) {
7827                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7828                    // A change in dimension means an auto-centered pivot point changes, too
7829                    mTransformationInfo.mMatrixDirty = true;
7830                }
7831                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7832                invalidate(true);
7833            }
7834            mBackgroundSizeChanged = true;
7835            invalidateParentIfNeeded();
7836        }
7837    }
7838
7839    /**
7840     * Right position of this view relative to its parent.
7841     *
7842     * @return The right edge of this view, in pixels.
7843     */
7844    @ViewDebug.CapturedViewProperty
7845    public final int getRight() {
7846        return mRight;
7847    }
7848
7849    /**
7850     * Sets the right position of this view relative to its parent. This method is meant to be called
7851     * by the layout system and should not generally be called otherwise, because the property
7852     * may be changed at any time by the layout.
7853     *
7854     * @param right The bottom of this view, in pixels.
7855     */
7856    public final void setRight(int right) {
7857        if (right != mRight) {
7858            updateMatrix();
7859            final boolean matrixIsIdentity = mTransformationInfo == null
7860                    || mTransformationInfo.mMatrixIsIdentity;
7861            if (matrixIsIdentity) {
7862                if (mAttachInfo != null) {
7863                    int maxRight;
7864                    if (right < mRight) {
7865                        maxRight = mRight;
7866                    } else {
7867                        maxRight = right;
7868                    }
7869                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7870                }
7871            } else {
7872                // Double-invalidation is necessary to capture view's old and new areas
7873                invalidate(true);
7874            }
7875
7876            int oldWidth = mRight - mLeft;
7877            int height = mBottom - mTop;
7878
7879            mRight = right;
7880
7881            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7882
7883            if (!matrixIsIdentity) {
7884                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7885                    // A change in dimension means an auto-centered pivot point changes, too
7886                    mTransformationInfo.mMatrixDirty = true;
7887                }
7888                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7889                invalidate(true);
7890            }
7891            mBackgroundSizeChanged = true;
7892            invalidateParentIfNeeded();
7893        }
7894    }
7895
7896    /**
7897     * The visual x position of this view, in pixels. This is equivalent to the
7898     * {@link #setTranslationX(float) translationX} property plus the current
7899     * {@link #getLeft() left} property.
7900     *
7901     * @return The visual x position of this view, in pixels.
7902     */
7903    @ViewDebug.ExportedProperty(category = "drawing")
7904    public float getX() {
7905        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7906    }
7907
7908    /**
7909     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7910     * {@link #setTranslationX(float) translationX} property to be the difference between
7911     * the x value passed in and the current {@link #getLeft() left} property.
7912     *
7913     * @param x The visual x position of this view, in pixels.
7914     */
7915    public void setX(float x) {
7916        setTranslationX(x - mLeft);
7917    }
7918
7919    /**
7920     * The visual y position of this view, in pixels. This is equivalent to the
7921     * {@link #setTranslationY(float) translationY} property plus the current
7922     * {@link #getTop() top} property.
7923     *
7924     * @return The visual y position of this view, in pixels.
7925     */
7926    @ViewDebug.ExportedProperty(category = "drawing")
7927    public float getY() {
7928        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7929    }
7930
7931    /**
7932     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7933     * {@link #setTranslationY(float) translationY} property to be the difference between
7934     * the y value passed in and the current {@link #getTop() top} property.
7935     *
7936     * @param y The visual y position of this view, in pixels.
7937     */
7938    public void setY(float y) {
7939        setTranslationY(y - mTop);
7940    }
7941
7942
7943    /**
7944     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7945     * This position is post-layout, in addition to wherever the object's
7946     * layout placed it.
7947     *
7948     * @return The horizontal position of this view relative to its left position, in pixels.
7949     */
7950    @ViewDebug.ExportedProperty(category = "drawing")
7951    public float getTranslationX() {
7952        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7953    }
7954
7955    /**
7956     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7957     * This effectively positions the object post-layout, in addition to wherever the object's
7958     * layout placed it.
7959     *
7960     * @param translationX The horizontal position of this view relative to its left position,
7961     * in pixels.
7962     *
7963     * @attr ref android.R.styleable#View_translationX
7964     */
7965    public void setTranslationX(float translationX) {
7966        ensureTransformationInfo();
7967        final TransformationInfo info = mTransformationInfo;
7968        if (info.mTranslationX != translationX) {
7969            invalidateParentCaches();
7970            // Double-invalidation is necessary to capture view's old and new areas
7971            invalidate(false);
7972            info.mTranslationX = translationX;
7973            info.mMatrixDirty = true;
7974            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7975            invalidate(false);
7976        }
7977    }
7978
7979    /**
7980     * The horizontal location of this view relative to its {@link #getTop() top} position.
7981     * This position is post-layout, in addition to wherever the object's
7982     * layout placed it.
7983     *
7984     * @return The vertical position of this view relative to its top position,
7985     * in pixels.
7986     */
7987    @ViewDebug.ExportedProperty(category = "drawing")
7988    public float getTranslationY() {
7989        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7990    }
7991
7992    /**
7993     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7994     * This effectively positions the object post-layout, in addition to wherever the object's
7995     * layout placed it.
7996     *
7997     * @param translationY The vertical position of this view relative to its top position,
7998     * in pixels.
7999     *
8000     * @attr ref android.R.styleable#View_translationY
8001     */
8002    public void setTranslationY(float translationY) {
8003        ensureTransformationInfo();
8004        final TransformationInfo info = mTransformationInfo;
8005        if (info.mTranslationY != translationY) {
8006            invalidateParentCaches();
8007            // Double-invalidation is necessary to capture view's old and new areas
8008            invalidate(false);
8009            info.mTranslationY = translationY;
8010            info.mMatrixDirty = true;
8011            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8012            invalidate(false);
8013        }
8014    }
8015
8016    /**
8017     * Hit rectangle in parent's coordinates
8018     *
8019     * @param outRect The hit rectangle of the view.
8020     */
8021    public void getHitRect(Rect outRect) {
8022        updateMatrix();
8023        final TransformationInfo info = mTransformationInfo;
8024        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8025            outRect.set(mLeft, mTop, mRight, mBottom);
8026        } else {
8027            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8028            tmpRect.set(-info.mPivotX, -info.mPivotY,
8029                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8030            info.mMatrix.mapRect(tmpRect);
8031            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8032                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8033        }
8034    }
8035
8036    /**
8037     * Determines whether the given point, in local coordinates is inside the view.
8038     */
8039    /*package*/ final boolean pointInView(float localX, float localY) {
8040        return localX >= 0 && localX < (mRight - mLeft)
8041                && localY >= 0 && localY < (mBottom - mTop);
8042    }
8043
8044    /**
8045     * Utility method to determine whether the given point, in local coordinates,
8046     * is inside the view, where the area of the view is expanded by the slop factor.
8047     * This method is called while processing touch-move events to determine if the event
8048     * is still within the view.
8049     */
8050    private boolean pointInView(float localX, float localY, float slop) {
8051        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8052                localY < ((mBottom - mTop) + slop);
8053    }
8054
8055    /**
8056     * When a view has focus and the user navigates away from it, the next view is searched for
8057     * starting from the rectangle filled in by this method.
8058     *
8059     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8060     * of the view.  However, if your view maintains some idea of internal selection,
8061     * such as a cursor, or a selected row or column, you should override this method and
8062     * fill in a more specific rectangle.
8063     *
8064     * @param r The rectangle to fill in, in this view's coordinates.
8065     */
8066    public void getFocusedRect(Rect r) {
8067        getDrawingRect(r);
8068    }
8069
8070    /**
8071     * If some part of this view is not clipped by any of its parents, then
8072     * return that area in r in global (root) coordinates. To convert r to local
8073     * coordinates (without taking possible View rotations into account), offset
8074     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8075     * If the view is completely clipped or translated out, return false.
8076     *
8077     * @param r If true is returned, r holds the global coordinates of the
8078     *        visible portion of this view.
8079     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8080     *        between this view and its root. globalOffet may be null.
8081     * @return true if r is non-empty (i.e. part of the view is visible at the
8082     *         root level.
8083     */
8084    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8085        int width = mRight - mLeft;
8086        int height = mBottom - mTop;
8087        if (width > 0 && height > 0) {
8088            r.set(0, 0, width, height);
8089            if (globalOffset != null) {
8090                globalOffset.set(-mScrollX, -mScrollY);
8091            }
8092            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8093        }
8094        return false;
8095    }
8096
8097    public final boolean getGlobalVisibleRect(Rect r) {
8098        return getGlobalVisibleRect(r, null);
8099    }
8100
8101    public final boolean getLocalVisibleRect(Rect r) {
8102        Point offset = new Point();
8103        if (getGlobalVisibleRect(r, offset)) {
8104            r.offset(-offset.x, -offset.y); // make r local
8105            return true;
8106        }
8107        return false;
8108    }
8109
8110    /**
8111     * Offset this view's vertical location by the specified number of pixels.
8112     *
8113     * @param offset the number of pixels to offset the view by
8114     */
8115    public void offsetTopAndBottom(int offset) {
8116        if (offset != 0) {
8117            updateMatrix();
8118            final boolean matrixIsIdentity = mTransformationInfo == null
8119                    || mTransformationInfo.mMatrixIsIdentity;
8120            if (matrixIsIdentity) {
8121                final ViewParent p = mParent;
8122                if (p != null && mAttachInfo != null) {
8123                    final Rect r = mAttachInfo.mTmpInvalRect;
8124                    int minTop;
8125                    int maxBottom;
8126                    int yLoc;
8127                    if (offset < 0) {
8128                        minTop = mTop + offset;
8129                        maxBottom = mBottom;
8130                        yLoc = offset;
8131                    } else {
8132                        minTop = mTop;
8133                        maxBottom = mBottom + offset;
8134                        yLoc = 0;
8135                    }
8136                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8137                    p.invalidateChild(this, r);
8138                }
8139            } else {
8140                invalidate(false);
8141            }
8142
8143            mTop += offset;
8144            mBottom += offset;
8145
8146            if (!matrixIsIdentity) {
8147                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8148                invalidate(false);
8149            }
8150            invalidateParentIfNeeded();
8151        }
8152    }
8153
8154    /**
8155     * Offset this view's horizontal location by the specified amount of pixels.
8156     *
8157     * @param offset the numer of pixels to offset the view by
8158     */
8159    public void offsetLeftAndRight(int offset) {
8160        if (offset != 0) {
8161            updateMatrix();
8162            final boolean matrixIsIdentity = mTransformationInfo == null
8163                    || mTransformationInfo.mMatrixIsIdentity;
8164            if (matrixIsIdentity) {
8165                final ViewParent p = mParent;
8166                if (p != null && mAttachInfo != null) {
8167                    final Rect r = mAttachInfo.mTmpInvalRect;
8168                    int minLeft;
8169                    int maxRight;
8170                    if (offset < 0) {
8171                        minLeft = mLeft + offset;
8172                        maxRight = mRight;
8173                    } else {
8174                        minLeft = mLeft;
8175                        maxRight = mRight + offset;
8176                    }
8177                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8178                    p.invalidateChild(this, r);
8179                }
8180            } else {
8181                invalidate(false);
8182            }
8183
8184            mLeft += offset;
8185            mRight += offset;
8186
8187            if (!matrixIsIdentity) {
8188                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8189                invalidate(false);
8190            }
8191            invalidateParentIfNeeded();
8192        }
8193    }
8194
8195    /**
8196     * Get the LayoutParams associated with this view. All views should have
8197     * layout parameters. These supply parameters to the <i>parent</i> of this
8198     * view specifying how it should be arranged. There are many subclasses of
8199     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8200     * of ViewGroup that are responsible for arranging their children.
8201     *
8202     * This method may return null if this View is not attached to a parent
8203     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8204     * was not invoked successfully. When a View is attached to a parent
8205     * ViewGroup, this method must not return null.
8206     *
8207     * @return The LayoutParams associated with this view, or null if no
8208     *         parameters have been set yet
8209     */
8210    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8211    public ViewGroup.LayoutParams getLayoutParams() {
8212        return mLayoutParams;
8213    }
8214
8215    /**
8216     * Set the layout parameters associated with this view. These supply
8217     * parameters to the <i>parent</i> of this view specifying how it should be
8218     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8219     * correspond to the different subclasses of ViewGroup that are responsible
8220     * for arranging their children.
8221     *
8222     * @param params The layout parameters for this view, cannot be null
8223     */
8224    public void setLayoutParams(ViewGroup.LayoutParams params) {
8225        if (params == null) {
8226            throw new NullPointerException("Layout parameters cannot be null");
8227        }
8228        mLayoutParams = params;
8229        if (mParent instanceof ViewGroup) {
8230            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8231        }
8232        requestLayout();
8233    }
8234
8235    /**
8236     * Set the scrolled position of your view. This will cause a call to
8237     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8238     * invalidated.
8239     * @param x the x position to scroll to
8240     * @param y the y position to scroll to
8241     */
8242    public void scrollTo(int x, int y) {
8243        if (mScrollX != x || mScrollY != y) {
8244            int oldX = mScrollX;
8245            int oldY = mScrollY;
8246            mScrollX = x;
8247            mScrollY = y;
8248            invalidateParentCaches();
8249            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8250            if (!awakenScrollBars()) {
8251                invalidate(true);
8252            }
8253        }
8254    }
8255
8256    /**
8257     * Move the scrolled position of your view. This will cause a call to
8258     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8259     * invalidated.
8260     * @param x the amount of pixels to scroll by horizontally
8261     * @param y the amount of pixels to scroll by vertically
8262     */
8263    public void scrollBy(int x, int y) {
8264        scrollTo(mScrollX + x, mScrollY + y);
8265    }
8266
8267    /**
8268     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8269     * animation to fade the scrollbars out after a default delay. If a subclass
8270     * provides animated scrolling, the start delay should equal the duration
8271     * of the scrolling animation.</p>
8272     *
8273     * <p>The animation starts only if at least one of the scrollbars is
8274     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8275     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8276     * this method returns true, and false otherwise. If the animation is
8277     * started, this method calls {@link #invalidate()}; in that case the
8278     * caller should not call {@link #invalidate()}.</p>
8279     *
8280     * <p>This method should be invoked every time a subclass directly updates
8281     * the scroll parameters.</p>
8282     *
8283     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8284     * and {@link #scrollTo(int, int)}.</p>
8285     *
8286     * @return true if the animation is played, false otherwise
8287     *
8288     * @see #awakenScrollBars(int)
8289     * @see #scrollBy(int, int)
8290     * @see #scrollTo(int, int)
8291     * @see #isHorizontalScrollBarEnabled()
8292     * @see #isVerticalScrollBarEnabled()
8293     * @see #setHorizontalScrollBarEnabled(boolean)
8294     * @see #setVerticalScrollBarEnabled(boolean)
8295     */
8296    protected boolean awakenScrollBars() {
8297        return mScrollCache != null &&
8298                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8299    }
8300
8301    /**
8302     * Trigger the scrollbars to draw.
8303     * This method differs from awakenScrollBars() only in its default duration.
8304     * initialAwakenScrollBars() will show the scroll bars for longer than
8305     * usual to give the user more of a chance to notice them.
8306     *
8307     * @return true if the animation is played, false otherwise.
8308     */
8309    private boolean initialAwakenScrollBars() {
8310        return mScrollCache != null &&
8311                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8312    }
8313
8314    /**
8315     * <p>
8316     * Trigger the scrollbars to draw. When invoked this method starts an
8317     * animation to fade the scrollbars out after a fixed delay. If a subclass
8318     * provides animated scrolling, the start delay should equal the duration of
8319     * the scrolling animation.
8320     * </p>
8321     *
8322     * <p>
8323     * The animation starts only if at least one of the scrollbars is enabled,
8324     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8325     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8326     * this method returns true, and false otherwise. If the animation is
8327     * started, this method calls {@link #invalidate()}; in that case the caller
8328     * should not call {@link #invalidate()}.
8329     * </p>
8330     *
8331     * <p>
8332     * This method should be invoked everytime a subclass directly updates the
8333     * scroll parameters.
8334     * </p>
8335     *
8336     * @param startDelay the delay, in milliseconds, after which the animation
8337     *        should start; when the delay is 0, the animation starts
8338     *        immediately
8339     * @return true if the animation is played, false otherwise
8340     *
8341     * @see #scrollBy(int, int)
8342     * @see #scrollTo(int, int)
8343     * @see #isHorizontalScrollBarEnabled()
8344     * @see #isVerticalScrollBarEnabled()
8345     * @see #setHorizontalScrollBarEnabled(boolean)
8346     * @see #setVerticalScrollBarEnabled(boolean)
8347     */
8348    protected boolean awakenScrollBars(int startDelay) {
8349        return awakenScrollBars(startDelay, true);
8350    }
8351
8352    /**
8353     * <p>
8354     * Trigger the scrollbars to draw. When invoked this method starts an
8355     * animation to fade the scrollbars out after a fixed delay. If a subclass
8356     * provides animated scrolling, the start delay should equal the duration of
8357     * the scrolling animation.
8358     * </p>
8359     *
8360     * <p>
8361     * The animation starts only if at least one of the scrollbars is enabled,
8362     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8363     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8364     * this method returns true, and false otherwise. If the animation is
8365     * started, this method calls {@link #invalidate()} if the invalidate parameter
8366     * is set to true; in that case the caller
8367     * should not call {@link #invalidate()}.
8368     * </p>
8369     *
8370     * <p>
8371     * This method should be invoked everytime a subclass directly updates the
8372     * scroll parameters.
8373     * </p>
8374     *
8375     * @param startDelay the delay, in milliseconds, after which the animation
8376     *        should start; when the delay is 0, the animation starts
8377     *        immediately
8378     *
8379     * @param invalidate Wheter this method should call invalidate
8380     *
8381     * @return true if the animation is played, false otherwise
8382     *
8383     * @see #scrollBy(int, int)
8384     * @see #scrollTo(int, int)
8385     * @see #isHorizontalScrollBarEnabled()
8386     * @see #isVerticalScrollBarEnabled()
8387     * @see #setHorizontalScrollBarEnabled(boolean)
8388     * @see #setVerticalScrollBarEnabled(boolean)
8389     */
8390    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8391        final ScrollabilityCache scrollCache = mScrollCache;
8392
8393        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8394            return false;
8395        }
8396
8397        if (scrollCache.scrollBar == null) {
8398            scrollCache.scrollBar = new ScrollBarDrawable();
8399        }
8400
8401        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8402
8403            if (invalidate) {
8404                // Invalidate to show the scrollbars
8405                invalidate(true);
8406            }
8407
8408            if (scrollCache.state == ScrollabilityCache.OFF) {
8409                // FIXME: this is copied from WindowManagerService.
8410                // We should get this value from the system when it
8411                // is possible to do so.
8412                final int KEY_REPEAT_FIRST_DELAY = 750;
8413                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8414            }
8415
8416            // Tell mScrollCache when we should start fading. This may
8417            // extend the fade start time if one was already scheduled
8418            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8419            scrollCache.fadeStartTime = fadeStartTime;
8420            scrollCache.state = ScrollabilityCache.ON;
8421
8422            // Schedule our fader to run, unscheduling any old ones first
8423            if (mAttachInfo != null) {
8424                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8425                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8426            }
8427
8428            return true;
8429        }
8430
8431        return false;
8432    }
8433
8434    /**
8435     * Do not invalidate views which are not visible and which are not running an animation. They
8436     * will not get drawn and they should not set dirty flags as if they will be drawn
8437     */
8438    private boolean skipInvalidate() {
8439        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8440                (!(mParent instanceof ViewGroup) ||
8441                        !((ViewGroup) mParent).isViewTransitioning(this));
8442    }
8443    /**
8444     * Mark the area defined by dirty as needing to be drawn. If the view is
8445     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8446     * in the future. This must be called from a UI thread. To call from a non-UI
8447     * thread, call {@link #postInvalidate()}.
8448     *
8449     * WARNING: This method is destructive to dirty.
8450     * @param dirty the rectangle representing the bounds of the dirty region
8451     */
8452    public void invalidate(Rect dirty) {
8453        if (ViewDebug.TRACE_HIERARCHY) {
8454            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8455        }
8456
8457        if (skipInvalidate()) {
8458            return;
8459        }
8460        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8461                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8462                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8463            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8464            mPrivateFlags |= INVALIDATED;
8465            mPrivateFlags |= DIRTY;
8466            final ViewParent p = mParent;
8467            final AttachInfo ai = mAttachInfo;
8468            //noinspection PointlessBooleanExpression,ConstantConditions
8469            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8470                if (p != null && ai != null && ai.mHardwareAccelerated) {
8471                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8472                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8473                    p.invalidateChild(this, null);
8474                    return;
8475                }
8476            }
8477            if (p != null && ai != null) {
8478                final int scrollX = mScrollX;
8479                final int scrollY = mScrollY;
8480                final Rect r = ai.mTmpInvalRect;
8481                r.set(dirty.left - scrollX, dirty.top - scrollY,
8482                        dirty.right - scrollX, dirty.bottom - scrollY);
8483                mParent.invalidateChild(this, r);
8484            }
8485        }
8486    }
8487
8488    /**
8489     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8490     * The coordinates of the dirty rect are relative to the view.
8491     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8492     * will be called at some point in the future. This must be called from
8493     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8494     * @param l the left position of the dirty region
8495     * @param t the top position of the dirty region
8496     * @param r the right position of the dirty region
8497     * @param b the bottom position of the dirty region
8498     */
8499    public void invalidate(int l, int t, int r, int b) {
8500        if (ViewDebug.TRACE_HIERARCHY) {
8501            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8502        }
8503
8504        if (skipInvalidate()) {
8505            return;
8506        }
8507        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8508                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8509                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8510            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8511            mPrivateFlags |= INVALIDATED;
8512            mPrivateFlags |= DIRTY;
8513            final ViewParent p = mParent;
8514            final AttachInfo ai = mAttachInfo;
8515            //noinspection PointlessBooleanExpression,ConstantConditions
8516            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8517                if (p != null && ai != null && ai.mHardwareAccelerated) {
8518                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8519                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8520                    p.invalidateChild(this, null);
8521                    return;
8522                }
8523            }
8524            if (p != null && ai != null && l < r && t < b) {
8525                final int scrollX = mScrollX;
8526                final int scrollY = mScrollY;
8527                final Rect tmpr = ai.mTmpInvalRect;
8528                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8529                p.invalidateChild(this, tmpr);
8530            }
8531        }
8532    }
8533
8534    /**
8535     * Invalidate the whole view. If the view is visible,
8536     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8537     * the future. This must be called from a UI thread. To call from a non-UI thread,
8538     * call {@link #postInvalidate()}.
8539     */
8540    public void invalidate() {
8541        invalidate(true);
8542    }
8543
8544    /**
8545     * This is where the invalidate() work actually happens. A full invalidate()
8546     * causes the drawing cache to be invalidated, but this function can be called with
8547     * invalidateCache set to false to skip that invalidation step for cases that do not
8548     * need it (for example, a component that remains at the same dimensions with the same
8549     * content).
8550     *
8551     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8552     * well. This is usually true for a full invalidate, but may be set to false if the
8553     * View's contents or dimensions have not changed.
8554     */
8555    void invalidate(boolean invalidateCache) {
8556        if (ViewDebug.TRACE_HIERARCHY) {
8557            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8558        }
8559
8560        if (skipInvalidate()) {
8561            return;
8562        }
8563        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8564                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8565                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8566            mLastIsOpaque = isOpaque();
8567            mPrivateFlags &= ~DRAWN;
8568            mPrivateFlags |= DIRTY;
8569            if (invalidateCache) {
8570                mPrivateFlags |= INVALIDATED;
8571                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8572            }
8573            final AttachInfo ai = mAttachInfo;
8574            final ViewParent p = mParent;
8575            //noinspection PointlessBooleanExpression,ConstantConditions
8576            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8577                if (p != null && ai != null && ai.mHardwareAccelerated) {
8578                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8579                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8580                    p.invalidateChild(this, null);
8581                    return;
8582                }
8583            }
8584
8585            if (p != null && ai != null) {
8586                final Rect r = ai.mTmpInvalRect;
8587                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8588                // Don't call invalidate -- we don't want to internally scroll
8589                // our own bounds
8590                p.invalidateChild(this, r);
8591            }
8592        }
8593    }
8594
8595    /**
8596     * Used to indicate that the parent of this view should clear its caches. This functionality
8597     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8598     * which is necessary when various parent-managed properties of the view change, such as
8599     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8600     * clears the parent caches and does not causes an invalidate event.
8601     *
8602     * @hide
8603     */
8604    protected void invalidateParentCaches() {
8605        if (mParent instanceof View) {
8606            ((View) mParent).mPrivateFlags |= INVALIDATED;
8607        }
8608    }
8609
8610    /**
8611     * Used to indicate that the parent of this view should be invalidated. This functionality
8612     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8613     * which is necessary when various parent-managed properties of the view change, such as
8614     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8615     * an invalidation event to the parent.
8616     *
8617     * @hide
8618     */
8619    protected void invalidateParentIfNeeded() {
8620        if (isHardwareAccelerated() && mParent instanceof View) {
8621            ((View) mParent).invalidate(true);
8622        }
8623    }
8624
8625    /**
8626     * Indicates whether this View is opaque. An opaque View guarantees that it will
8627     * draw all the pixels overlapping its bounds using a fully opaque color.
8628     *
8629     * Subclasses of View should override this method whenever possible to indicate
8630     * whether an instance is opaque. Opaque Views are treated in a special way by
8631     * the View hierarchy, possibly allowing it to perform optimizations during
8632     * invalidate/draw passes.
8633     *
8634     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8635     */
8636    @ViewDebug.ExportedProperty(category = "drawing")
8637    public boolean isOpaque() {
8638        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8639                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8640                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8641    }
8642
8643    /**
8644     * @hide
8645     */
8646    protected void computeOpaqueFlags() {
8647        // Opaque if:
8648        //   - Has a background
8649        //   - Background is opaque
8650        //   - Doesn't have scrollbars or scrollbars are inside overlay
8651
8652        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8653            mPrivateFlags |= OPAQUE_BACKGROUND;
8654        } else {
8655            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8656        }
8657
8658        final int flags = mViewFlags;
8659        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8660                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8661            mPrivateFlags |= OPAQUE_SCROLLBARS;
8662        } else {
8663            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8664        }
8665    }
8666
8667    /**
8668     * @hide
8669     */
8670    protected boolean hasOpaqueScrollbars() {
8671        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8672    }
8673
8674    /**
8675     * @return A handler associated with the thread running the View. This
8676     * handler can be used to pump events in the UI events queue.
8677     */
8678    public Handler getHandler() {
8679        if (mAttachInfo != null) {
8680            return mAttachInfo.mHandler;
8681        }
8682        return null;
8683    }
8684
8685    /**
8686     * <p>Causes the Runnable to be added to the message queue.
8687     * The runnable will be run on the user interface thread.</p>
8688     *
8689     * <p>This method can be invoked from outside of the UI thread
8690     * only when this View is attached to a window.</p>
8691     *
8692     * @param action The Runnable that will be executed.
8693     *
8694     * @return Returns true if the Runnable was successfully placed in to the
8695     *         message queue.  Returns false on failure, usually because the
8696     *         looper processing the message queue is exiting.
8697     */
8698    public boolean post(Runnable action) {
8699        Handler handler;
8700        AttachInfo attachInfo = mAttachInfo;
8701        if (attachInfo != null) {
8702            handler = attachInfo.mHandler;
8703        } else {
8704            // Assume that post will succeed later
8705            ViewRootImpl.getRunQueue().post(action);
8706            return true;
8707        }
8708
8709        return handler.post(action);
8710    }
8711
8712    /**
8713     * <p>Causes the Runnable to be added to the message queue, to be run
8714     * after the specified amount of time elapses.
8715     * The runnable will be run on the user interface thread.</p>
8716     *
8717     * <p>This method can be invoked from outside of the UI thread
8718     * only when this View is attached to a window.</p>
8719     *
8720     * @param action The Runnable that will be executed.
8721     * @param delayMillis The delay (in milliseconds) until the Runnable
8722     *        will be executed.
8723     *
8724     * @return true if the Runnable was successfully placed in to the
8725     *         message queue.  Returns false on failure, usually because the
8726     *         looper processing the message queue is exiting.  Note that a
8727     *         result of true does not mean the Runnable will be processed --
8728     *         if the looper is quit before the delivery time of the message
8729     *         occurs then the message will be dropped.
8730     */
8731    public boolean postDelayed(Runnable action, long delayMillis) {
8732        Handler handler;
8733        AttachInfo attachInfo = mAttachInfo;
8734        if (attachInfo != null) {
8735            handler = attachInfo.mHandler;
8736        } else {
8737            // Assume that post will succeed later
8738            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8739            return true;
8740        }
8741
8742        return handler.postDelayed(action, delayMillis);
8743    }
8744
8745    /**
8746     * <p>Removes the specified Runnable from the message queue.</p>
8747     *
8748     * <p>This method can be invoked from outside of the UI thread
8749     * only when this View is attached to a window.</p>
8750     *
8751     * @param action The Runnable to remove from the message handling queue
8752     *
8753     * @return true if this view could ask the Handler to remove the Runnable,
8754     *         false otherwise. When the returned value is true, the Runnable
8755     *         may or may not have been actually removed from the message queue
8756     *         (for instance, if the Runnable was not in the queue already.)
8757     */
8758    public boolean removeCallbacks(Runnable action) {
8759        Handler handler;
8760        AttachInfo attachInfo = mAttachInfo;
8761        if (attachInfo != null) {
8762            handler = attachInfo.mHandler;
8763        } else {
8764            // Assume that post will succeed later
8765            ViewRootImpl.getRunQueue().removeCallbacks(action);
8766            return true;
8767        }
8768
8769        handler.removeCallbacks(action);
8770        return true;
8771    }
8772
8773    /**
8774     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8775     * Use this to invalidate the View from a non-UI thread.</p>
8776     *
8777     * <p>This method can be invoked from outside of the UI thread
8778     * only when this View is attached to a window.</p>
8779     *
8780     * @see #invalidate()
8781     */
8782    public void postInvalidate() {
8783        postInvalidateDelayed(0);
8784    }
8785
8786    /**
8787     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8788     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8789     *
8790     * <p>This method can be invoked from outside of the UI thread
8791     * only when this View is attached to a window.</p>
8792     *
8793     * @param left The left coordinate of the rectangle to invalidate.
8794     * @param top The top coordinate of the rectangle to invalidate.
8795     * @param right The right coordinate of the rectangle to invalidate.
8796     * @param bottom The bottom coordinate of the rectangle to invalidate.
8797     *
8798     * @see #invalidate(int, int, int, int)
8799     * @see #invalidate(Rect)
8800     */
8801    public void postInvalidate(int left, int top, int right, int bottom) {
8802        postInvalidateDelayed(0, left, top, right, bottom);
8803    }
8804
8805    /**
8806     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8807     * loop. Waits for the specified amount of time.</p>
8808     *
8809     * <p>This method can be invoked from outside of the UI thread
8810     * only when this View is attached to a window.</p>
8811     *
8812     * @param delayMilliseconds the duration in milliseconds to delay the
8813     *         invalidation by
8814     */
8815    public void postInvalidateDelayed(long delayMilliseconds) {
8816        // We try only with the AttachInfo because there's no point in invalidating
8817        // if we are not attached to our window
8818        AttachInfo attachInfo = mAttachInfo;
8819        if (attachInfo != null) {
8820            Message msg = Message.obtain();
8821            msg.what = AttachInfo.INVALIDATE_MSG;
8822            msg.obj = this;
8823            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8824        }
8825    }
8826
8827    /**
8828     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8829     * through the event loop. Waits for the specified amount of time.</p>
8830     *
8831     * <p>This method can be invoked from outside of the UI thread
8832     * only when this View is attached to a window.</p>
8833     *
8834     * @param delayMilliseconds the duration in milliseconds to delay the
8835     *         invalidation by
8836     * @param left The left coordinate of the rectangle to invalidate.
8837     * @param top The top coordinate of the rectangle to invalidate.
8838     * @param right The right coordinate of the rectangle to invalidate.
8839     * @param bottom The bottom coordinate of the rectangle to invalidate.
8840     */
8841    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8842            int right, int bottom) {
8843
8844        // We try only with the AttachInfo because there's no point in invalidating
8845        // if we are not attached to our window
8846        AttachInfo attachInfo = mAttachInfo;
8847        if (attachInfo != null) {
8848            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8849            info.target = this;
8850            info.left = left;
8851            info.top = top;
8852            info.right = right;
8853            info.bottom = bottom;
8854
8855            final Message msg = Message.obtain();
8856            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8857            msg.obj = info;
8858            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8859        }
8860    }
8861
8862    /**
8863     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8864     * This event is sent at most once every
8865     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8866     */
8867    private void postSendViewScrolledAccessibilityEventCallback() {
8868        if (mSendViewScrolledAccessibilityEvent == null) {
8869            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8870        }
8871        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8872            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8873            postDelayed(mSendViewScrolledAccessibilityEvent,
8874                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8875        }
8876    }
8877
8878    /**
8879     * Called by a parent to request that a child update its values for mScrollX
8880     * and mScrollY if necessary. This will typically be done if the child is
8881     * animating a scroll using a {@link android.widget.Scroller Scroller}
8882     * object.
8883     */
8884    public void computeScroll() {
8885    }
8886
8887    /**
8888     * <p>Indicate whether the horizontal edges are faded when the view is
8889     * scrolled horizontally.</p>
8890     *
8891     * @return true if the horizontal edges should are faded on scroll, false
8892     *         otherwise
8893     *
8894     * @see #setHorizontalFadingEdgeEnabled(boolean)
8895     * @attr ref android.R.styleable#View_requiresFadingEdge
8896     */
8897    public boolean isHorizontalFadingEdgeEnabled() {
8898        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8899    }
8900
8901    /**
8902     * <p>Define whether the horizontal edges should be faded when this view
8903     * is scrolled horizontally.</p>
8904     *
8905     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8906     *                                    be faded when the view is scrolled
8907     *                                    horizontally
8908     *
8909     * @see #isHorizontalFadingEdgeEnabled()
8910     * @attr ref android.R.styleable#View_requiresFadingEdge
8911     */
8912    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8913        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8914            if (horizontalFadingEdgeEnabled) {
8915                initScrollCache();
8916            }
8917
8918            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8919        }
8920    }
8921
8922    /**
8923     * <p>Indicate whether the vertical edges are faded when the view is
8924     * scrolled horizontally.</p>
8925     *
8926     * @return true if the vertical edges should are faded on scroll, false
8927     *         otherwise
8928     *
8929     * @see #setVerticalFadingEdgeEnabled(boolean)
8930     * @attr ref android.R.styleable#View_requiresFadingEdge
8931     */
8932    public boolean isVerticalFadingEdgeEnabled() {
8933        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8934    }
8935
8936    /**
8937     * <p>Define whether the vertical edges should be faded when this view
8938     * is scrolled vertically.</p>
8939     *
8940     * @param verticalFadingEdgeEnabled true if the vertical edges should
8941     *                                  be faded when the view is scrolled
8942     *                                  vertically
8943     *
8944     * @see #isVerticalFadingEdgeEnabled()
8945     * @attr ref android.R.styleable#View_requiresFadingEdge
8946     */
8947    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8948        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8949            if (verticalFadingEdgeEnabled) {
8950                initScrollCache();
8951            }
8952
8953            mViewFlags ^= FADING_EDGE_VERTICAL;
8954        }
8955    }
8956
8957    /**
8958     * Returns the strength, or intensity, of the top faded edge. The strength is
8959     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8960     * returns 0.0 or 1.0 but no value in between.
8961     *
8962     * Subclasses should override this method to provide a smoother fade transition
8963     * when scrolling occurs.
8964     *
8965     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8966     */
8967    protected float getTopFadingEdgeStrength() {
8968        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8969    }
8970
8971    /**
8972     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8973     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8974     * returns 0.0 or 1.0 but no value in between.
8975     *
8976     * Subclasses should override this method to provide a smoother fade transition
8977     * when scrolling occurs.
8978     *
8979     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8980     */
8981    protected float getBottomFadingEdgeStrength() {
8982        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8983                computeVerticalScrollRange() ? 1.0f : 0.0f;
8984    }
8985
8986    /**
8987     * Returns the strength, or intensity, of the left faded edge. The strength is
8988     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8989     * returns 0.0 or 1.0 but no value in between.
8990     *
8991     * Subclasses should override this method to provide a smoother fade transition
8992     * when scrolling occurs.
8993     *
8994     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8995     */
8996    protected float getLeftFadingEdgeStrength() {
8997        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8998    }
8999
9000    /**
9001     * Returns the strength, or intensity, of the right faded edge. The strength is
9002     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9003     * returns 0.0 or 1.0 but no value in between.
9004     *
9005     * Subclasses should override this method to provide a smoother fade transition
9006     * when scrolling occurs.
9007     *
9008     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9009     */
9010    protected float getRightFadingEdgeStrength() {
9011        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9012                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9013    }
9014
9015    /**
9016     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9017     * scrollbar is not drawn by default.</p>
9018     *
9019     * @return true if the horizontal scrollbar should be painted, false
9020     *         otherwise
9021     *
9022     * @see #setHorizontalScrollBarEnabled(boolean)
9023     */
9024    public boolean isHorizontalScrollBarEnabled() {
9025        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9026    }
9027
9028    /**
9029     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9030     * scrollbar is not drawn by default.</p>
9031     *
9032     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9033     *                                   be painted
9034     *
9035     * @see #isHorizontalScrollBarEnabled()
9036     */
9037    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9038        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9039            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9040            computeOpaqueFlags();
9041            resolvePadding();
9042        }
9043    }
9044
9045    /**
9046     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9047     * scrollbar is not drawn by default.</p>
9048     *
9049     * @return true if the vertical scrollbar should be painted, false
9050     *         otherwise
9051     *
9052     * @see #setVerticalScrollBarEnabled(boolean)
9053     */
9054    public boolean isVerticalScrollBarEnabled() {
9055        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9056    }
9057
9058    /**
9059     * <p>Define whether the vertical scrollbar should be drawn or not. The
9060     * scrollbar is not drawn by default.</p>
9061     *
9062     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9063     *                                 be painted
9064     *
9065     * @see #isVerticalScrollBarEnabled()
9066     */
9067    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9068        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9069            mViewFlags ^= SCROLLBARS_VERTICAL;
9070            computeOpaqueFlags();
9071            resolvePadding();
9072        }
9073    }
9074
9075    /**
9076     * @hide
9077     */
9078    protected void recomputePadding() {
9079        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9080    }
9081
9082    /**
9083     * Define whether scrollbars will fade when the view is not scrolling.
9084     *
9085     * @param fadeScrollbars wheter to enable fading
9086     *
9087     */
9088    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9089        initScrollCache();
9090        final ScrollabilityCache scrollabilityCache = mScrollCache;
9091        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9092        if (fadeScrollbars) {
9093            scrollabilityCache.state = ScrollabilityCache.OFF;
9094        } else {
9095            scrollabilityCache.state = ScrollabilityCache.ON;
9096        }
9097    }
9098
9099    /**
9100     *
9101     * Returns true if scrollbars will fade when this view is not scrolling
9102     *
9103     * @return true if scrollbar fading is enabled
9104     */
9105    public boolean isScrollbarFadingEnabled() {
9106        return mScrollCache != null && mScrollCache.fadeScrollBars;
9107    }
9108
9109    /**
9110     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9111     * inset. When inset, they add to the padding of the view. And the scrollbars
9112     * can be drawn inside the padding area or on the edge of the view. For example,
9113     * if a view has a background drawable and you want to draw the scrollbars
9114     * inside the padding specified by the drawable, you can use
9115     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9116     * appear at the edge of the view, ignoring the padding, then you can use
9117     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9118     * @param style the style of the scrollbars. Should be one of
9119     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9120     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9121     * @see #SCROLLBARS_INSIDE_OVERLAY
9122     * @see #SCROLLBARS_INSIDE_INSET
9123     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9124     * @see #SCROLLBARS_OUTSIDE_INSET
9125     */
9126    public void setScrollBarStyle(int style) {
9127        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9128            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9129            computeOpaqueFlags();
9130            resolvePadding();
9131        }
9132    }
9133
9134    /**
9135     * <p>Returns the current scrollbar style.</p>
9136     * @return the current scrollbar style
9137     * @see #SCROLLBARS_INSIDE_OVERLAY
9138     * @see #SCROLLBARS_INSIDE_INSET
9139     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9140     * @see #SCROLLBARS_OUTSIDE_INSET
9141     */
9142    @ViewDebug.ExportedProperty(mapping = {
9143            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9144            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9145            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9146            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9147    })
9148    public int getScrollBarStyle() {
9149        return mViewFlags & SCROLLBARS_STYLE_MASK;
9150    }
9151
9152    /**
9153     * <p>Compute the horizontal range that the horizontal scrollbar
9154     * represents.</p>
9155     *
9156     * <p>The range is expressed in arbitrary units that must be the same as the
9157     * units used by {@link #computeHorizontalScrollExtent()} and
9158     * {@link #computeHorizontalScrollOffset()}.</p>
9159     *
9160     * <p>The default range is the drawing width of this view.</p>
9161     *
9162     * @return the total horizontal range represented by the horizontal
9163     *         scrollbar
9164     *
9165     * @see #computeHorizontalScrollExtent()
9166     * @see #computeHorizontalScrollOffset()
9167     * @see android.widget.ScrollBarDrawable
9168     */
9169    protected int computeHorizontalScrollRange() {
9170        return getWidth();
9171    }
9172
9173    /**
9174     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9175     * within the horizontal range. This value is used to compute the position
9176     * of the thumb within the scrollbar's track.</p>
9177     *
9178     * <p>The range is expressed in arbitrary units that must be the same as the
9179     * units used by {@link #computeHorizontalScrollRange()} and
9180     * {@link #computeHorizontalScrollExtent()}.</p>
9181     *
9182     * <p>The default offset is the scroll offset of this view.</p>
9183     *
9184     * @return the horizontal offset of the scrollbar's thumb
9185     *
9186     * @see #computeHorizontalScrollRange()
9187     * @see #computeHorizontalScrollExtent()
9188     * @see android.widget.ScrollBarDrawable
9189     */
9190    protected int computeHorizontalScrollOffset() {
9191        return mScrollX;
9192    }
9193
9194    /**
9195     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9196     * within the horizontal range. This value is used to compute the length
9197     * of the thumb within the scrollbar's track.</p>
9198     *
9199     * <p>The range is expressed in arbitrary units that must be the same as the
9200     * units used by {@link #computeHorizontalScrollRange()} and
9201     * {@link #computeHorizontalScrollOffset()}.</p>
9202     *
9203     * <p>The default extent is the drawing width of this view.</p>
9204     *
9205     * @return the horizontal extent of the scrollbar's thumb
9206     *
9207     * @see #computeHorizontalScrollRange()
9208     * @see #computeHorizontalScrollOffset()
9209     * @see android.widget.ScrollBarDrawable
9210     */
9211    protected int computeHorizontalScrollExtent() {
9212        return getWidth();
9213    }
9214
9215    /**
9216     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9217     *
9218     * <p>The range is expressed in arbitrary units that must be the same as the
9219     * units used by {@link #computeVerticalScrollExtent()} and
9220     * {@link #computeVerticalScrollOffset()}.</p>
9221     *
9222     * @return the total vertical range represented by the vertical scrollbar
9223     *
9224     * <p>The default range is the drawing height of this view.</p>
9225     *
9226     * @see #computeVerticalScrollExtent()
9227     * @see #computeVerticalScrollOffset()
9228     * @see android.widget.ScrollBarDrawable
9229     */
9230    protected int computeVerticalScrollRange() {
9231        return getHeight();
9232    }
9233
9234    /**
9235     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9236     * within the horizontal range. This value is used to compute the position
9237     * of the thumb within the scrollbar's track.</p>
9238     *
9239     * <p>The range is expressed in arbitrary units that must be the same as the
9240     * units used by {@link #computeVerticalScrollRange()} and
9241     * {@link #computeVerticalScrollExtent()}.</p>
9242     *
9243     * <p>The default offset is the scroll offset of this view.</p>
9244     *
9245     * @return the vertical offset of the scrollbar's thumb
9246     *
9247     * @see #computeVerticalScrollRange()
9248     * @see #computeVerticalScrollExtent()
9249     * @see android.widget.ScrollBarDrawable
9250     */
9251    protected int computeVerticalScrollOffset() {
9252        return mScrollY;
9253    }
9254
9255    /**
9256     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9257     * within the vertical range. This value is used to compute the length
9258     * of the thumb within the scrollbar's track.</p>
9259     *
9260     * <p>The range is expressed in arbitrary units that must be the same as the
9261     * units used by {@link #computeVerticalScrollRange()} and
9262     * {@link #computeVerticalScrollOffset()}.</p>
9263     *
9264     * <p>The default extent is the drawing height of this view.</p>
9265     *
9266     * @return the vertical extent of the scrollbar's thumb
9267     *
9268     * @see #computeVerticalScrollRange()
9269     * @see #computeVerticalScrollOffset()
9270     * @see android.widget.ScrollBarDrawable
9271     */
9272    protected int computeVerticalScrollExtent() {
9273        return getHeight();
9274    }
9275
9276    /**
9277     * Check if this view can be scrolled horizontally in a certain direction.
9278     *
9279     * @param direction Negative to check scrolling left, positive to check scrolling right.
9280     * @return true if this view can be scrolled in the specified direction, false otherwise.
9281     */
9282    public boolean canScrollHorizontally(int direction) {
9283        final int offset = computeHorizontalScrollOffset();
9284        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9285        if (range == 0) return false;
9286        if (direction < 0) {
9287            return offset > 0;
9288        } else {
9289            return offset < range - 1;
9290        }
9291    }
9292
9293    /**
9294     * Check if this view can be scrolled vertically in a certain direction.
9295     *
9296     * @param direction Negative to check scrolling up, positive to check scrolling down.
9297     * @return true if this view can be scrolled in the specified direction, false otherwise.
9298     */
9299    public boolean canScrollVertically(int direction) {
9300        final int offset = computeVerticalScrollOffset();
9301        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9302        if (range == 0) return false;
9303        if (direction < 0) {
9304            return offset > 0;
9305        } else {
9306            return offset < range - 1;
9307        }
9308    }
9309
9310    /**
9311     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9312     * scrollbars are painted only if they have been awakened first.</p>
9313     *
9314     * @param canvas the canvas on which to draw the scrollbars
9315     *
9316     * @see #awakenScrollBars(int)
9317     */
9318    protected final void onDrawScrollBars(Canvas canvas) {
9319        // scrollbars are drawn only when the animation is running
9320        final ScrollabilityCache cache = mScrollCache;
9321        if (cache != null) {
9322
9323            int state = cache.state;
9324
9325            if (state == ScrollabilityCache.OFF) {
9326                return;
9327            }
9328
9329            boolean invalidate = false;
9330
9331            if (state == ScrollabilityCache.FADING) {
9332                // We're fading -- get our fade interpolation
9333                if (cache.interpolatorValues == null) {
9334                    cache.interpolatorValues = new float[1];
9335                }
9336
9337                float[] values = cache.interpolatorValues;
9338
9339                // Stops the animation if we're done
9340                if (cache.scrollBarInterpolator.timeToValues(values) ==
9341                        Interpolator.Result.FREEZE_END) {
9342                    cache.state = ScrollabilityCache.OFF;
9343                } else {
9344                    cache.scrollBar.setAlpha(Math.round(values[0]));
9345                }
9346
9347                // This will make the scroll bars inval themselves after
9348                // drawing. We only want this when we're fading so that
9349                // we prevent excessive redraws
9350                invalidate = true;
9351            } else {
9352                // We're just on -- but we may have been fading before so
9353                // reset alpha
9354                cache.scrollBar.setAlpha(255);
9355            }
9356
9357
9358            final int viewFlags = mViewFlags;
9359
9360            final boolean drawHorizontalScrollBar =
9361                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9362            final boolean drawVerticalScrollBar =
9363                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9364                && !isVerticalScrollBarHidden();
9365
9366            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9367                final int width = mRight - mLeft;
9368                final int height = mBottom - mTop;
9369
9370                final ScrollBarDrawable scrollBar = cache.scrollBar;
9371
9372                final int scrollX = mScrollX;
9373                final int scrollY = mScrollY;
9374                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9375
9376                int left, top, right, bottom;
9377
9378                if (drawHorizontalScrollBar) {
9379                    int size = scrollBar.getSize(false);
9380                    if (size <= 0) {
9381                        size = cache.scrollBarSize;
9382                    }
9383
9384                    scrollBar.setParameters(computeHorizontalScrollRange(),
9385                                            computeHorizontalScrollOffset(),
9386                                            computeHorizontalScrollExtent(), false);
9387                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9388                            getVerticalScrollbarWidth() : 0;
9389                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9390                    left = scrollX + (mPaddingLeft & inside);
9391                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9392                    bottom = top + size;
9393                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9394                    if (invalidate) {
9395                        invalidate(left, top, right, bottom);
9396                    }
9397                }
9398
9399                if (drawVerticalScrollBar) {
9400                    int size = scrollBar.getSize(true);
9401                    if (size <= 0) {
9402                        size = cache.scrollBarSize;
9403                    }
9404
9405                    scrollBar.setParameters(computeVerticalScrollRange(),
9406                                            computeVerticalScrollOffset(),
9407                                            computeVerticalScrollExtent(), true);
9408                    switch (mVerticalScrollbarPosition) {
9409                        default:
9410                        case SCROLLBAR_POSITION_DEFAULT:
9411                        case SCROLLBAR_POSITION_RIGHT:
9412                            left = scrollX + width - size - (mUserPaddingRight & inside);
9413                            break;
9414                        case SCROLLBAR_POSITION_LEFT:
9415                            left = scrollX + (mUserPaddingLeft & inside);
9416                            break;
9417                    }
9418                    top = scrollY + (mPaddingTop & inside);
9419                    right = left + size;
9420                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9421                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9422                    if (invalidate) {
9423                        invalidate(left, top, right, bottom);
9424                    }
9425                }
9426            }
9427        }
9428    }
9429
9430    /**
9431     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9432     * FastScroller is visible.
9433     * @return whether to temporarily hide the vertical scrollbar
9434     * @hide
9435     */
9436    protected boolean isVerticalScrollBarHidden() {
9437        return false;
9438    }
9439
9440    /**
9441     * <p>Draw the horizontal scrollbar if
9442     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9443     *
9444     * @param canvas the canvas on which to draw the scrollbar
9445     * @param scrollBar the scrollbar's drawable
9446     *
9447     * @see #isHorizontalScrollBarEnabled()
9448     * @see #computeHorizontalScrollRange()
9449     * @see #computeHorizontalScrollExtent()
9450     * @see #computeHorizontalScrollOffset()
9451     * @see android.widget.ScrollBarDrawable
9452     * @hide
9453     */
9454    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9455            int l, int t, int r, int b) {
9456        scrollBar.setBounds(l, t, r, b);
9457        scrollBar.draw(canvas);
9458    }
9459
9460    /**
9461     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9462     * returns true.</p>
9463     *
9464     * @param canvas the canvas on which to draw the scrollbar
9465     * @param scrollBar the scrollbar's drawable
9466     *
9467     * @see #isVerticalScrollBarEnabled()
9468     * @see #computeVerticalScrollRange()
9469     * @see #computeVerticalScrollExtent()
9470     * @see #computeVerticalScrollOffset()
9471     * @see android.widget.ScrollBarDrawable
9472     * @hide
9473     */
9474    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9475            int l, int t, int r, int b) {
9476        scrollBar.setBounds(l, t, r, b);
9477        scrollBar.draw(canvas);
9478    }
9479
9480    /**
9481     * Implement this to do your drawing.
9482     *
9483     * @param canvas the canvas on which the background will be drawn
9484     */
9485    protected void onDraw(Canvas canvas) {
9486    }
9487
9488    /*
9489     * Caller is responsible for calling requestLayout if necessary.
9490     * (This allows addViewInLayout to not request a new layout.)
9491     */
9492    void assignParent(ViewParent parent) {
9493        if (mParent == null) {
9494            mParent = parent;
9495        } else if (parent == null) {
9496            mParent = null;
9497        } else {
9498            throw new RuntimeException("view " + this + " being added, but"
9499                    + " it already has a parent");
9500        }
9501    }
9502
9503    /**
9504     * This is called when the view is attached to a window.  At this point it
9505     * has a Surface and will start drawing.  Note that this function is
9506     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9507     * however it may be called any time before the first onDraw -- including
9508     * before or after {@link #onMeasure(int, int)}.
9509     *
9510     * @see #onDetachedFromWindow()
9511     */
9512    protected void onAttachedToWindow() {
9513        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9514            mParent.requestTransparentRegion(this);
9515        }
9516        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9517            initialAwakenScrollBars();
9518            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9519        }
9520        jumpDrawablesToCurrentState();
9521        // Order is important here: LayoutDirection MUST be resolved before Padding
9522        // and TextDirection
9523        resolveLayoutDirectionIfNeeded();
9524        resolvePadding();
9525        resolveTextDirection();
9526        if (isFocused()) {
9527            InputMethodManager imm = InputMethodManager.peekInstance();
9528            imm.focusIn(this);
9529        }
9530    }
9531
9532    /**
9533     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9534     * that the parent directionality can and will be resolved before its children.
9535     */
9536    private void resolveLayoutDirectionIfNeeded() {
9537        // Do not resolve if it is not needed
9538        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9539
9540        // Clear any previous layout direction resolution
9541        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9542
9543        // Set resolved depending on layout direction
9544        switch (getLayoutDirection()) {
9545            case LAYOUT_DIRECTION_INHERIT:
9546                // We cannot do the resolution if there is no parent
9547                if (mParent == null) return;
9548
9549                // If this is root view, no need to look at parent's layout dir.
9550                if (mParent instanceof ViewGroup) {
9551                    ViewGroup viewGroup = ((ViewGroup) mParent);
9552
9553                    // Check if the parent view group can resolve
9554                    if (! viewGroup.canResolveLayoutDirection()) {
9555                        return;
9556                    }
9557                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9558                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9559                    }
9560                }
9561                break;
9562            case LAYOUT_DIRECTION_RTL:
9563                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9564                break;
9565            case LAYOUT_DIRECTION_LOCALE:
9566                if(isLayoutDirectionRtl(Locale.getDefault())) {
9567                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9568                }
9569                break;
9570            default:
9571                // Nothing to do, LTR by default
9572        }
9573
9574        // Set to resolved
9575        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9576    }
9577
9578    /**
9579     * Force padding depending on layout direction.
9580     */
9581    public void resolvePadding() {
9582        // If the user specified the absolute padding (either with android:padding or
9583        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9584        // use the default padding or the padding from the background drawable
9585        // (stored at this point in mPadding*)
9586        int resolvedLayoutDirection = getResolvedLayoutDirection();
9587        switch (resolvedLayoutDirection) {
9588            case LAYOUT_DIRECTION_RTL:
9589                // Start user padding override Right user padding. Otherwise, if Right user
9590                // padding is not defined, use the default Right padding. If Right user padding
9591                // is defined, just use it.
9592                if (mUserPaddingStart >= 0) {
9593                    mUserPaddingRight = mUserPaddingStart;
9594                } else if (mUserPaddingRight < 0) {
9595                    mUserPaddingRight = mPaddingRight;
9596                }
9597                if (mUserPaddingEnd >= 0) {
9598                    mUserPaddingLeft = mUserPaddingEnd;
9599                } else if (mUserPaddingLeft < 0) {
9600                    mUserPaddingLeft = mPaddingLeft;
9601                }
9602                break;
9603            case LAYOUT_DIRECTION_LTR:
9604            default:
9605                // Start user padding override Left user padding. Otherwise, if Left user
9606                // padding is not defined, use the default left padding. If Left user padding
9607                // is defined, just use it.
9608                if (mUserPaddingStart >= 0) {
9609                    mUserPaddingLeft = mUserPaddingStart;
9610                } else if (mUserPaddingLeft < 0) {
9611                    mUserPaddingLeft = mPaddingLeft;
9612                }
9613                if (mUserPaddingEnd >= 0) {
9614                    mUserPaddingRight = mUserPaddingEnd;
9615                } else if (mUserPaddingRight < 0) {
9616                    mUserPaddingRight = mPaddingRight;
9617                }
9618        }
9619
9620        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9621
9622        recomputePadding();
9623        onResolvePadding(resolvedLayoutDirection);
9624    }
9625
9626    /**
9627     * Resolve padding depending on the layout direction. Subclasses that care about
9628     * padding resolution should override this method. The default implementation does
9629     * nothing.
9630     *
9631     * @param layoutDirection the direction of the layout
9632     *
9633     * {@link View#LAYOUT_DIRECTION_LTR}
9634     * {@link View#LAYOUT_DIRECTION_RTL}
9635     */
9636    public void onResolvePadding(int layoutDirection) {
9637    }
9638
9639    /**
9640     * Return true if layout direction resolution can be done
9641     *
9642     * @hide
9643     */
9644    protected boolean canResolveLayoutDirection() {
9645        switch (getLayoutDirection()) {
9646            case LAYOUT_DIRECTION_INHERIT:
9647                return (mParent != null);
9648            default:
9649                return true;
9650        }
9651    }
9652
9653    /**
9654     * Reset the resolved layout direction.
9655     *
9656     * Subclasses need to override this method to clear cached information that depends on the
9657     * resolved layout direction, or to inform child views that inherit their layout direction.
9658     * Overrides must also call the superclass implementation at the start of their implementation.
9659     *
9660     * @hide
9661     */
9662    protected void resetResolvedLayoutDirection() {
9663        // Reset the layout direction resolution
9664        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9665        // Reset also the text direction
9666        resetResolvedTextDirection();
9667    }
9668
9669    /**
9670     * Check if a Locale is corresponding to a RTL script.
9671     *
9672     * @param locale Locale to check
9673     * @return true if a Locale is corresponding to a RTL script.
9674     *
9675     * @hide
9676     */
9677    protected static boolean isLayoutDirectionRtl(Locale locale) {
9678        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9679                LocaleUtil.getLayoutDirectionFromLocale(locale));
9680    }
9681
9682    /**
9683     * This is called when the view is detached from a window.  At this point it
9684     * no longer has a surface for drawing.
9685     *
9686     * @see #onAttachedToWindow()
9687     */
9688    protected void onDetachedFromWindow() {
9689        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9690
9691        removeUnsetPressCallback();
9692        removeLongPressCallback();
9693        removePerformClickCallback();
9694        removeSendViewScrolledAccessibilityEventCallback();
9695
9696        destroyDrawingCache();
9697
9698        destroyLayer();
9699
9700        if (mDisplayList != null) {
9701            mDisplayList.invalidate();
9702        }
9703
9704        if (mAttachInfo != null) {
9705            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9706        }
9707
9708        mCurrentAnimation = null;
9709
9710        resetResolvedLayoutDirection();
9711    }
9712
9713    /**
9714     * @return The number of times this view has been attached to a window
9715     */
9716    protected int getWindowAttachCount() {
9717        return mWindowAttachCount;
9718    }
9719
9720    /**
9721     * Retrieve a unique token identifying the window this view is attached to.
9722     * @return Return the window's token for use in
9723     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9724     */
9725    public IBinder getWindowToken() {
9726        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9727    }
9728
9729    /**
9730     * Retrieve a unique token identifying the top-level "real" window of
9731     * the window that this view is attached to.  That is, this is like
9732     * {@link #getWindowToken}, except if the window this view in is a panel
9733     * window (attached to another containing window), then the token of
9734     * the containing window is returned instead.
9735     *
9736     * @return Returns the associated window token, either
9737     * {@link #getWindowToken()} or the containing window's token.
9738     */
9739    public IBinder getApplicationWindowToken() {
9740        AttachInfo ai = mAttachInfo;
9741        if (ai != null) {
9742            IBinder appWindowToken = ai.mPanelParentWindowToken;
9743            if (appWindowToken == null) {
9744                appWindowToken = ai.mWindowToken;
9745            }
9746            return appWindowToken;
9747        }
9748        return null;
9749    }
9750
9751    /**
9752     * Retrieve private session object this view hierarchy is using to
9753     * communicate with the window manager.
9754     * @return the session object to communicate with the window manager
9755     */
9756    /*package*/ IWindowSession getWindowSession() {
9757        return mAttachInfo != null ? mAttachInfo.mSession : null;
9758    }
9759
9760    /**
9761     * @param info the {@link android.view.View.AttachInfo} to associated with
9762     *        this view
9763     */
9764    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9765        //System.out.println("Attached! " + this);
9766        mAttachInfo = info;
9767        mWindowAttachCount++;
9768        // We will need to evaluate the drawable state at least once.
9769        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9770        if (mFloatingTreeObserver != null) {
9771            info.mTreeObserver.merge(mFloatingTreeObserver);
9772            mFloatingTreeObserver = null;
9773        }
9774        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9775            mAttachInfo.mScrollContainers.add(this);
9776            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9777        }
9778        performCollectViewAttributes(visibility);
9779        onAttachedToWindow();
9780
9781        ListenerInfo li = mListenerInfo;
9782        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9783                li != null ? li.mOnAttachStateChangeListeners : null;
9784        if (listeners != null && listeners.size() > 0) {
9785            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9786            // perform the dispatching. The iterator is a safe guard against listeners that
9787            // could mutate the list by calling the various add/remove methods. This prevents
9788            // the array from being modified while we iterate it.
9789            for (OnAttachStateChangeListener listener : listeners) {
9790                listener.onViewAttachedToWindow(this);
9791            }
9792        }
9793
9794        int vis = info.mWindowVisibility;
9795        if (vis != GONE) {
9796            onWindowVisibilityChanged(vis);
9797        }
9798        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9799            // If nobody has evaluated the drawable state yet, then do it now.
9800            refreshDrawableState();
9801        }
9802    }
9803
9804    void dispatchDetachedFromWindow() {
9805        AttachInfo info = mAttachInfo;
9806        if (info != null) {
9807            int vis = info.mWindowVisibility;
9808            if (vis != GONE) {
9809                onWindowVisibilityChanged(GONE);
9810            }
9811        }
9812
9813        onDetachedFromWindow();
9814
9815        ListenerInfo li = mListenerInfo;
9816        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9817                li != null ? li.mOnAttachStateChangeListeners : null;
9818        if (listeners != null && listeners.size() > 0) {
9819            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9820            // perform the dispatching. The iterator is a safe guard against listeners that
9821            // could mutate the list by calling the various add/remove methods. This prevents
9822            // the array from being modified while we iterate it.
9823            for (OnAttachStateChangeListener listener : listeners) {
9824                listener.onViewDetachedFromWindow(this);
9825            }
9826        }
9827
9828        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9829            mAttachInfo.mScrollContainers.remove(this);
9830            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9831        }
9832
9833        mAttachInfo = null;
9834    }
9835
9836    /**
9837     * Store this view hierarchy's frozen state into the given container.
9838     *
9839     * @param container The SparseArray in which to save the view's state.
9840     *
9841     * @see #restoreHierarchyState(android.util.SparseArray)
9842     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9843     * @see #onSaveInstanceState()
9844     */
9845    public void saveHierarchyState(SparseArray<Parcelable> container) {
9846        dispatchSaveInstanceState(container);
9847    }
9848
9849    /**
9850     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9851     * this view and its children. May be overridden to modify how freezing happens to a
9852     * view's children; for example, some views may want to not store state for their children.
9853     *
9854     * @param container The SparseArray in which to save the view's state.
9855     *
9856     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9857     * @see #saveHierarchyState(android.util.SparseArray)
9858     * @see #onSaveInstanceState()
9859     */
9860    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9861        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9862            mPrivateFlags &= ~SAVE_STATE_CALLED;
9863            Parcelable state = onSaveInstanceState();
9864            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9865                throw new IllegalStateException(
9866                        "Derived class did not call super.onSaveInstanceState()");
9867            }
9868            if (state != null) {
9869                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9870                // + ": " + state);
9871                container.put(mID, state);
9872            }
9873        }
9874    }
9875
9876    /**
9877     * Hook allowing a view to generate a representation of its internal state
9878     * that can later be used to create a new instance with that same state.
9879     * This state should only contain information that is not persistent or can
9880     * not be reconstructed later. For example, you will never store your
9881     * current position on screen because that will be computed again when a
9882     * new instance of the view is placed in its view hierarchy.
9883     * <p>
9884     * Some examples of things you may store here: the current cursor position
9885     * in a text view (but usually not the text itself since that is stored in a
9886     * content provider or other persistent storage), the currently selected
9887     * item in a list view.
9888     *
9889     * @return Returns a Parcelable object containing the view's current dynamic
9890     *         state, or null if there is nothing interesting to save. The
9891     *         default implementation returns null.
9892     * @see #onRestoreInstanceState(android.os.Parcelable)
9893     * @see #saveHierarchyState(android.util.SparseArray)
9894     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9895     * @see #setSaveEnabled(boolean)
9896     */
9897    protected Parcelable onSaveInstanceState() {
9898        mPrivateFlags |= SAVE_STATE_CALLED;
9899        return BaseSavedState.EMPTY_STATE;
9900    }
9901
9902    /**
9903     * Restore this view hierarchy's frozen state from the given container.
9904     *
9905     * @param container The SparseArray which holds previously frozen states.
9906     *
9907     * @see #saveHierarchyState(android.util.SparseArray)
9908     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9909     * @see #onRestoreInstanceState(android.os.Parcelable)
9910     */
9911    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9912        dispatchRestoreInstanceState(container);
9913    }
9914
9915    /**
9916     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9917     * state for this view and its children. May be overridden to modify how restoring
9918     * happens to a view's children; for example, some views may want to not store state
9919     * for their children.
9920     *
9921     * @param container The SparseArray which holds previously saved state.
9922     *
9923     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9924     * @see #restoreHierarchyState(android.util.SparseArray)
9925     * @see #onRestoreInstanceState(android.os.Parcelable)
9926     */
9927    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9928        if (mID != NO_ID) {
9929            Parcelable state = container.get(mID);
9930            if (state != null) {
9931                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9932                // + ": " + state);
9933                mPrivateFlags &= ~SAVE_STATE_CALLED;
9934                onRestoreInstanceState(state);
9935                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9936                    throw new IllegalStateException(
9937                            "Derived class did not call super.onRestoreInstanceState()");
9938                }
9939            }
9940        }
9941    }
9942
9943    /**
9944     * Hook allowing a view to re-apply a representation of its internal state that had previously
9945     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9946     * null state.
9947     *
9948     * @param state The frozen state that had previously been returned by
9949     *        {@link #onSaveInstanceState}.
9950     *
9951     * @see #onSaveInstanceState()
9952     * @see #restoreHierarchyState(android.util.SparseArray)
9953     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9954     */
9955    protected void onRestoreInstanceState(Parcelable state) {
9956        mPrivateFlags |= SAVE_STATE_CALLED;
9957        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9958            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9959                    + "received " + state.getClass().toString() + " instead. This usually happens "
9960                    + "when two views of different type have the same id in the same hierarchy. "
9961                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9962                    + "other views do not use the same id.");
9963        }
9964    }
9965
9966    /**
9967     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9968     *
9969     * @return the drawing start time in milliseconds
9970     */
9971    public long getDrawingTime() {
9972        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9973    }
9974
9975    /**
9976     * <p>Enables or disables the duplication of the parent's state into this view. When
9977     * duplication is enabled, this view gets its drawable state from its parent rather
9978     * than from its own internal properties.</p>
9979     *
9980     * <p>Note: in the current implementation, setting this property to true after the
9981     * view was added to a ViewGroup might have no effect at all. This property should
9982     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9983     *
9984     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9985     * property is enabled, an exception will be thrown.</p>
9986     *
9987     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9988     * parent, these states should not be affected by this method.</p>
9989     *
9990     * @param enabled True to enable duplication of the parent's drawable state, false
9991     *                to disable it.
9992     *
9993     * @see #getDrawableState()
9994     * @see #isDuplicateParentStateEnabled()
9995     */
9996    public void setDuplicateParentStateEnabled(boolean enabled) {
9997        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9998    }
9999
10000    /**
10001     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
10002     *
10003     * @return True if this view's drawable state is duplicated from the parent,
10004     *         false otherwise
10005     *
10006     * @see #getDrawableState()
10007     * @see #setDuplicateParentStateEnabled(boolean)
10008     */
10009    public boolean isDuplicateParentStateEnabled() {
10010        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10011    }
10012
10013    /**
10014     * <p>Specifies the type of layer backing this view. The layer can be
10015     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10016     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10017     *
10018     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10019     * instance that controls how the layer is composed on screen. The following
10020     * properties of the paint are taken into account when composing the layer:</p>
10021     * <ul>
10022     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10023     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10024     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10025     * </ul>
10026     *
10027     * <p>If this view has an alpha value set to < 1.0 by calling
10028     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10029     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10030     * equivalent to setting a hardware layer on this view and providing a paint with
10031     * the desired alpha value.<p>
10032     *
10033     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10034     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10035     * for more information on when and how to use layers.</p>
10036     *
10037     * @param layerType The ype of layer to use with this view, must be one of
10038     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10039     *        {@link #LAYER_TYPE_HARDWARE}
10040     * @param paint The paint used to compose the layer. This argument is optional
10041     *        and can be null. It is ignored when the layer type is
10042     *        {@link #LAYER_TYPE_NONE}
10043     *
10044     * @see #getLayerType()
10045     * @see #LAYER_TYPE_NONE
10046     * @see #LAYER_TYPE_SOFTWARE
10047     * @see #LAYER_TYPE_HARDWARE
10048     * @see #setAlpha(float)
10049     *
10050     * @attr ref android.R.styleable#View_layerType
10051     */
10052    public void setLayerType(int layerType, Paint paint) {
10053        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10054            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10055                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10056        }
10057
10058        if (layerType == mLayerType) {
10059            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10060                mLayerPaint = paint == null ? new Paint() : paint;
10061                invalidateParentCaches();
10062                invalidate(true);
10063            }
10064            return;
10065        }
10066
10067        // Destroy any previous software drawing cache if needed
10068        switch (mLayerType) {
10069            case LAYER_TYPE_HARDWARE:
10070                destroyLayer();
10071                // fall through - non-accelerated views may use software layer mechanism instead
10072            case LAYER_TYPE_SOFTWARE:
10073                destroyDrawingCache();
10074                break;
10075            default:
10076                break;
10077        }
10078
10079        mLayerType = layerType;
10080        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10081        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10082        mLocalDirtyRect = layerDisabled ? null : new Rect();
10083
10084        invalidateParentCaches();
10085        invalidate(true);
10086    }
10087
10088    /**
10089     * Indicates whether this view has a static layer. A view with layer type
10090     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10091     * dynamic.
10092     */
10093    boolean hasStaticLayer() {
10094        return mLayerType == LAYER_TYPE_NONE;
10095    }
10096
10097    /**
10098     * Indicates what type of layer is currently associated with this view. By default
10099     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10100     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10101     * for more information on the different types of layers.
10102     *
10103     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10104     *         {@link #LAYER_TYPE_HARDWARE}
10105     *
10106     * @see #setLayerType(int, android.graphics.Paint)
10107     * @see #buildLayer()
10108     * @see #LAYER_TYPE_NONE
10109     * @see #LAYER_TYPE_SOFTWARE
10110     * @see #LAYER_TYPE_HARDWARE
10111     */
10112    public int getLayerType() {
10113        return mLayerType;
10114    }
10115
10116    /**
10117     * Forces this view's layer to be created and this view to be rendered
10118     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10119     * invoking this method will have no effect.
10120     *
10121     * This method can for instance be used to render a view into its layer before
10122     * starting an animation. If this view is complex, rendering into the layer
10123     * before starting the animation will avoid skipping frames.
10124     *
10125     * @throws IllegalStateException If this view is not attached to a window
10126     *
10127     * @see #setLayerType(int, android.graphics.Paint)
10128     */
10129    public void buildLayer() {
10130        if (mLayerType == LAYER_TYPE_NONE) return;
10131
10132        if (mAttachInfo == null) {
10133            throw new IllegalStateException("This view must be attached to a window first");
10134        }
10135
10136        switch (mLayerType) {
10137            case LAYER_TYPE_HARDWARE:
10138                if (mAttachInfo.mHardwareRenderer != null &&
10139                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10140                        mAttachInfo.mHardwareRenderer.validate()) {
10141                    getHardwareLayer();
10142                }
10143                break;
10144            case LAYER_TYPE_SOFTWARE:
10145                buildDrawingCache(true);
10146                break;
10147        }
10148    }
10149
10150    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10151    void flushLayer() {
10152        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10153            mHardwareLayer.flush();
10154        }
10155    }
10156
10157    /**
10158     * <p>Returns a hardware layer that can be used to draw this view again
10159     * without executing its draw method.</p>
10160     *
10161     * @return A HardwareLayer ready to render, or null if an error occurred.
10162     */
10163    HardwareLayer getHardwareLayer() {
10164        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10165                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10166            return null;
10167        }
10168
10169        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10170
10171        final int width = mRight - mLeft;
10172        final int height = mBottom - mTop;
10173
10174        if (width == 0 || height == 0) {
10175            return null;
10176        }
10177
10178        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10179            if (mHardwareLayer == null) {
10180                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10181                        width, height, isOpaque());
10182                mLocalDirtyRect.setEmpty();
10183            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10184                mHardwareLayer.resize(width, height);
10185                mLocalDirtyRect.setEmpty();
10186            }
10187
10188            // The layer is not valid if the underlying GPU resources cannot be allocated
10189            if (!mHardwareLayer.isValid()) {
10190                return null;
10191            }
10192
10193            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10194            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10195
10196            // Make sure all the GPU resources have been properly allocated
10197            if (canvas == null) {
10198                mHardwareLayer.end(currentCanvas);
10199                return null;
10200            }
10201
10202            mAttachInfo.mHardwareCanvas = canvas;
10203            try {
10204                canvas.setViewport(width, height);
10205                canvas.onPreDraw(mLocalDirtyRect);
10206                mLocalDirtyRect.setEmpty();
10207
10208                final int restoreCount = canvas.save();
10209
10210                computeScroll();
10211                canvas.translate(-mScrollX, -mScrollY);
10212
10213                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10214
10215                // Fast path for layouts with no backgrounds
10216                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10217                    mPrivateFlags &= ~DIRTY_MASK;
10218                    dispatchDraw(canvas);
10219                } else {
10220                    draw(canvas);
10221                }
10222
10223                canvas.restoreToCount(restoreCount);
10224            } finally {
10225                canvas.onPostDraw();
10226                mHardwareLayer.end(currentCanvas);
10227                mAttachInfo.mHardwareCanvas = currentCanvas;
10228            }
10229        }
10230
10231        return mHardwareLayer;
10232    }
10233
10234    /**
10235     * Destroys this View's hardware layer if possible.
10236     *
10237     * @return True if the layer was destroyed, false otherwise.
10238     *
10239     * @see #setLayerType(int, android.graphics.Paint)
10240     * @see #LAYER_TYPE_HARDWARE
10241     */
10242    boolean destroyLayer() {
10243        if (mHardwareLayer != null) {
10244            AttachInfo info = mAttachInfo;
10245            if (info != null && info.mHardwareRenderer != null &&
10246                    info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) {
10247                mHardwareLayer.destroy();
10248                mHardwareLayer = null;
10249
10250                invalidate(true);
10251                invalidateParentCaches();
10252            }
10253            return true;
10254        }
10255        return false;
10256    }
10257
10258    /**
10259     * Destroys all hardware rendering resources. This method is invoked
10260     * when the system needs to reclaim resources. Upon execution of this
10261     * method, you should free any OpenGL resources created by the view.
10262     *
10263     * Note: you <strong>must</strong> call
10264     * <code>super.destroyHardwareResources()</code> when overriding
10265     * this method.
10266     *
10267     * @hide
10268     */
10269    protected void destroyHardwareResources() {
10270        destroyLayer();
10271    }
10272
10273    /**
10274     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10275     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10276     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10277     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10278     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10279     * null.</p>
10280     *
10281     * <p>Enabling the drawing cache is similar to
10282     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10283     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10284     * drawing cache has no effect on rendering because the system uses a different mechanism
10285     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10286     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10287     * for information on how to enable software and hardware layers.</p>
10288     *
10289     * <p>This API can be used to manually generate
10290     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10291     * {@link #getDrawingCache()}.</p>
10292     *
10293     * @param enabled true to enable the drawing cache, false otherwise
10294     *
10295     * @see #isDrawingCacheEnabled()
10296     * @see #getDrawingCache()
10297     * @see #buildDrawingCache()
10298     * @see #setLayerType(int, android.graphics.Paint)
10299     */
10300    public void setDrawingCacheEnabled(boolean enabled) {
10301        mCachingFailed = false;
10302        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10303    }
10304
10305    /**
10306     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10307     *
10308     * @return true if the drawing cache is enabled
10309     *
10310     * @see #setDrawingCacheEnabled(boolean)
10311     * @see #getDrawingCache()
10312     */
10313    @ViewDebug.ExportedProperty(category = "drawing")
10314    public boolean isDrawingCacheEnabled() {
10315        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10316    }
10317
10318    /**
10319     * Debugging utility which recursively outputs the dirty state of a view and its
10320     * descendants.
10321     *
10322     * @hide
10323     */
10324    @SuppressWarnings({"UnusedDeclaration"})
10325    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10326        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10327                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10328                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10329                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10330        if (clear) {
10331            mPrivateFlags &= clearMask;
10332        }
10333        if (this instanceof ViewGroup) {
10334            ViewGroup parent = (ViewGroup) this;
10335            final int count = parent.getChildCount();
10336            for (int i = 0; i < count; i++) {
10337                final View child = parent.getChildAt(i);
10338                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10339            }
10340        }
10341    }
10342
10343    /**
10344     * This method is used by ViewGroup to cause its children to restore or recreate their
10345     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10346     * to recreate its own display list, which would happen if it went through the normal
10347     * draw/dispatchDraw mechanisms.
10348     *
10349     * @hide
10350     */
10351    protected void dispatchGetDisplayList() {}
10352
10353    /**
10354     * A view that is not attached or hardware accelerated cannot create a display list.
10355     * This method checks these conditions and returns the appropriate result.
10356     *
10357     * @return true if view has the ability to create a display list, false otherwise.
10358     *
10359     * @hide
10360     */
10361    public boolean canHaveDisplayList() {
10362        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10363    }
10364
10365    /**
10366     * @return The HardwareRenderer associated with that view or null if hardware rendering
10367     * is not supported or this this has not been attached to a window.
10368     *
10369     * @hide
10370     */
10371    public HardwareRenderer getHardwareRenderer() {
10372        if (mAttachInfo != null) {
10373            return mAttachInfo.mHardwareRenderer;
10374        }
10375        return null;
10376    }
10377
10378    /**
10379     * <p>Returns a display list that can be used to draw this view again
10380     * without executing its draw method.</p>
10381     *
10382     * @return A DisplayList ready to replay, or null if caching is not enabled.
10383     *
10384     * @hide
10385     */
10386    public DisplayList getDisplayList() {
10387        if (!canHaveDisplayList()) {
10388            return null;
10389        }
10390
10391        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10392                mDisplayList == null || !mDisplayList.isValid() ||
10393                mRecreateDisplayList)) {
10394            // Don't need to recreate the display list, just need to tell our
10395            // children to restore/recreate theirs
10396            if (mDisplayList != null && mDisplayList.isValid() &&
10397                    !mRecreateDisplayList) {
10398                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10399                mPrivateFlags &= ~DIRTY_MASK;
10400                dispatchGetDisplayList();
10401
10402                return mDisplayList;
10403            }
10404
10405            // If we got here, we're recreating it. Mark it as such to ensure that
10406            // we copy in child display lists into ours in drawChild()
10407            mRecreateDisplayList = true;
10408            if (mDisplayList == null) {
10409                final String name = getClass().getSimpleName();
10410                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10411                // If we're creating a new display list, make sure our parent gets invalidated
10412                // since they will need to recreate their display list to account for this
10413                // new child display list.
10414                invalidateParentCaches();
10415            }
10416
10417            final HardwareCanvas canvas = mDisplayList.start();
10418            int restoreCount = 0;
10419            try {
10420                int width = mRight - mLeft;
10421                int height = mBottom - mTop;
10422
10423                canvas.setViewport(width, height);
10424                // The dirty rect should always be null for a display list
10425                canvas.onPreDraw(null);
10426
10427                computeScroll();
10428
10429                restoreCount = canvas.save();
10430                canvas.translate(-mScrollX, -mScrollY);
10431                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10432                mPrivateFlags &= ~DIRTY_MASK;
10433
10434                // Fast path for layouts with no backgrounds
10435                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10436                    dispatchDraw(canvas);
10437                } else {
10438                    draw(canvas);
10439                }
10440            } finally {
10441                canvas.restoreToCount(restoreCount);
10442                canvas.onPostDraw();
10443
10444                mDisplayList.end();
10445            }
10446        } else {
10447            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10448            mPrivateFlags &= ~DIRTY_MASK;
10449        }
10450
10451        return mDisplayList;
10452    }
10453
10454    /**
10455     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10456     *
10457     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10458     *
10459     * @see #getDrawingCache(boolean)
10460     */
10461    public Bitmap getDrawingCache() {
10462        return getDrawingCache(false);
10463    }
10464
10465    /**
10466     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10467     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10468     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10469     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10470     * request the drawing cache by calling this method and draw it on screen if the
10471     * returned bitmap is not null.</p>
10472     *
10473     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10474     * this method will create a bitmap of the same size as this view. Because this bitmap
10475     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10476     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10477     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10478     * size than the view. This implies that your application must be able to handle this
10479     * size.</p>
10480     *
10481     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10482     *        the current density of the screen when the application is in compatibility
10483     *        mode.
10484     *
10485     * @return A bitmap representing this view or null if cache is disabled.
10486     *
10487     * @see #setDrawingCacheEnabled(boolean)
10488     * @see #isDrawingCacheEnabled()
10489     * @see #buildDrawingCache(boolean)
10490     * @see #destroyDrawingCache()
10491     */
10492    public Bitmap getDrawingCache(boolean autoScale) {
10493        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10494            return null;
10495        }
10496        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10497            buildDrawingCache(autoScale);
10498        }
10499        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10500    }
10501
10502    /**
10503     * <p>Frees the resources used by the drawing cache. If you call
10504     * {@link #buildDrawingCache()} manually without calling
10505     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10506     * should cleanup the cache with this method afterwards.</p>
10507     *
10508     * @see #setDrawingCacheEnabled(boolean)
10509     * @see #buildDrawingCache()
10510     * @see #getDrawingCache()
10511     */
10512    public void destroyDrawingCache() {
10513        if (mDrawingCache != null) {
10514            mDrawingCache.recycle();
10515            mDrawingCache = null;
10516        }
10517        if (mUnscaledDrawingCache != null) {
10518            mUnscaledDrawingCache.recycle();
10519            mUnscaledDrawingCache = null;
10520        }
10521    }
10522
10523    /**
10524     * Setting a solid background color for the drawing cache's bitmaps will improve
10525     * performance and memory usage. Note, though that this should only be used if this
10526     * view will always be drawn on top of a solid color.
10527     *
10528     * @param color The background color to use for the drawing cache's bitmap
10529     *
10530     * @see #setDrawingCacheEnabled(boolean)
10531     * @see #buildDrawingCache()
10532     * @see #getDrawingCache()
10533     */
10534    public void setDrawingCacheBackgroundColor(int color) {
10535        if (color != mDrawingCacheBackgroundColor) {
10536            mDrawingCacheBackgroundColor = color;
10537            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10538        }
10539    }
10540
10541    /**
10542     * @see #setDrawingCacheBackgroundColor(int)
10543     *
10544     * @return The background color to used for the drawing cache's bitmap
10545     */
10546    public int getDrawingCacheBackgroundColor() {
10547        return mDrawingCacheBackgroundColor;
10548    }
10549
10550    /**
10551     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10552     *
10553     * @see #buildDrawingCache(boolean)
10554     */
10555    public void buildDrawingCache() {
10556        buildDrawingCache(false);
10557    }
10558
10559    /**
10560     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10561     *
10562     * <p>If you call {@link #buildDrawingCache()} manually without calling
10563     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10564     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10565     *
10566     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10567     * this method will create a bitmap of the same size as this view. Because this bitmap
10568     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10569     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10570     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10571     * size than the view. This implies that your application must be able to handle this
10572     * size.</p>
10573     *
10574     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10575     * you do not need the drawing cache bitmap, calling this method will increase memory
10576     * usage and cause the view to be rendered in software once, thus negatively impacting
10577     * performance.</p>
10578     *
10579     * @see #getDrawingCache()
10580     * @see #destroyDrawingCache()
10581     */
10582    public void buildDrawingCache(boolean autoScale) {
10583        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10584                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10585            mCachingFailed = false;
10586
10587            if (ViewDebug.TRACE_HIERARCHY) {
10588                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10589            }
10590
10591            int width = mRight - mLeft;
10592            int height = mBottom - mTop;
10593
10594            final AttachInfo attachInfo = mAttachInfo;
10595            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10596
10597            if (autoScale && scalingRequired) {
10598                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10599                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10600            }
10601
10602            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10603            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10604            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10605
10606            if (width <= 0 || height <= 0 ||
10607                     // Projected bitmap size in bytes
10608                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10609                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10610                destroyDrawingCache();
10611                mCachingFailed = true;
10612                return;
10613            }
10614
10615            boolean clear = true;
10616            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10617
10618            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10619                Bitmap.Config quality;
10620                if (!opaque) {
10621                    // Never pick ARGB_4444 because it looks awful
10622                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10623                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10624                        case DRAWING_CACHE_QUALITY_AUTO:
10625                            quality = Bitmap.Config.ARGB_8888;
10626                            break;
10627                        case DRAWING_CACHE_QUALITY_LOW:
10628                            quality = Bitmap.Config.ARGB_8888;
10629                            break;
10630                        case DRAWING_CACHE_QUALITY_HIGH:
10631                            quality = Bitmap.Config.ARGB_8888;
10632                            break;
10633                        default:
10634                            quality = Bitmap.Config.ARGB_8888;
10635                            break;
10636                    }
10637                } else {
10638                    // Optimization for translucent windows
10639                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10640                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10641                }
10642
10643                // Try to cleanup memory
10644                if (bitmap != null) bitmap.recycle();
10645
10646                try {
10647                    bitmap = Bitmap.createBitmap(width, height, quality);
10648                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10649                    if (autoScale) {
10650                        mDrawingCache = bitmap;
10651                    } else {
10652                        mUnscaledDrawingCache = bitmap;
10653                    }
10654                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10655                } catch (OutOfMemoryError e) {
10656                    // If there is not enough memory to create the bitmap cache, just
10657                    // ignore the issue as bitmap caches are not required to draw the
10658                    // view hierarchy
10659                    if (autoScale) {
10660                        mDrawingCache = null;
10661                    } else {
10662                        mUnscaledDrawingCache = null;
10663                    }
10664                    mCachingFailed = true;
10665                    return;
10666                }
10667
10668                clear = drawingCacheBackgroundColor != 0;
10669            }
10670
10671            Canvas canvas;
10672            if (attachInfo != null) {
10673                canvas = attachInfo.mCanvas;
10674                if (canvas == null) {
10675                    canvas = new Canvas();
10676                }
10677                canvas.setBitmap(bitmap);
10678                // Temporarily clobber the cached Canvas in case one of our children
10679                // is also using a drawing cache. Without this, the children would
10680                // steal the canvas by attaching their own bitmap to it and bad, bad
10681                // thing would happen (invisible views, corrupted drawings, etc.)
10682                attachInfo.mCanvas = null;
10683            } else {
10684                // This case should hopefully never or seldom happen
10685                canvas = new Canvas(bitmap);
10686            }
10687
10688            if (clear) {
10689                bitmap.eraseColor(drawingCacheBackgroundColor);
10690            }
10691
10692            computeScroll();
10693            final int restoreCount = canvas.save();
10694
10695            if (autoScale && scalingRequired) {
10696                final float scale = attachInfo.mApplicationScale;
10697                canvas.scale(scale, scale);
10698            }
10699
10700            canvas.translate(-mScrollX, -mScrollY);
10701
10702            mPrivateFlags |= DRAWN;
10703            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10704                    mLayerType != LAYER_TYPE_NONE) {
10705                mPrivateFlags |= DRAWING_CACHE_VALID;
10706            }
10707
10708            // Fast path for layouts with no backgrounds
10709            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10710                if (ViewDebug.TRACE_HIERARCHY) {
10711                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10712                }
10713                mPrivateFlags &= ~DIRTY_MASK;
10714                dispatchDraw(canvas);
10715            } else {
10716                draw(canvas);
10717            }
10718
10719            canvas.restoreToCount(restoreCount);
10720            canvas.setBitmap(null);
10721
10722            if (attachInfo != null) {
10723                // Restore the cached Canvas for our siblings
10724                attachInfo.mCanvas = canvas;
10725            }
10726        }
10727    }
10728
10729    /**
10730     * Create a snapshot of the view into a bitmap.  We should probably make
10731     * some form of this public, but should think about the API.
10732     */
10733    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10734        int width = mRight - mLeft;
10735        int height = mBottom - mTop;
10736
10737        final AttachInfo attachInfo = mAttachInfo;
10738        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10739        width = (int) ((width * scale) + 0.5f);
10740        height = (int) ((height * scale) + 0.5f);
10741
10742        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10743        if (bitmap == null) {
10744            throw new OutOfMemoryError();
10745        }
10746
10747        Resources resources = getResources();
10748        if (resources != null) {
10749            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10750        }
10751
10752        Canvas canvas;
10753        if (attachInfo != null) {
10754            canvas = attachInfo.mCanvas;
10755            if (canvas == null) {
10756                canvas = new Canvas();
10757            }
10758            canvas.setBitmap(bitmap);
10759            // Temporarily clobber the cached Canvas in case one of our children
10760            // is also using a drawing cache. Without this, the children would
10761            // steal the canvas by attaching their own bitmap to it and bad, bad
10762            // things would happen (invisible views, corrupted drawings, etc.)
10763            attachInfo.mCanvas = null;
10764        } else {
10765            // This case should hopefully never or seldom happen
10766            canvas = new Canvas(bitmap);
10767        }
10768
10769        if ((backgroundColor & 0xff000000) != 0) {
10770            bitmap.eraseColor(backgroundColor);
10771        }
10772
10773        computeScroll();
10774        final int restoreCount = canvas.save();
10775        canvas.scale(scale, scale);
10776        canvas.translate(-mScrollX, -mScrollY);
10777
10778        // Temporarily remove the dirty mask
10779        int flags = mPrivateFlags;
10780        mPrivateFlags &= ~DIRTY_MASK;
10781
10782        // Fast path for layouts with no backgrounds
10783        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10784            dispatchDraw(canvas);
10785        } else {
10786            draw(canvas);
10787        }
10788
10789        mPrivateFlags = flags;
10790
10791        canvas.restoreToCount(restoreCount);
10792        canvas.setBitmap(null);
10793
10794        if (attachInfo != null) {
10795            // Restore the cached Canvas for our siblings
10796            attachInfo.mCanvas = canvas;
10797        }
10798
10799        return bitmap;
10800    }
10801
10802    /**
10803     * Indicates whether this View is currently in edit mode. A View is usually
10804     * in edit mode when displayed within a developer tool. For instance, if
10805     * this View is being drawn by a visual user interface builder, this method
10806     * should return true.
10807     *
10808     * Subclasses should check the return value of this method to provide
10809     * different behaviors if their normal behavior might interfere with the
10810     * host environment. For instance: the class spawns a thread in its
10811     * constructor, the drawing code relies on device-specific features, etc.
10812     *
10813     * This method is usually checked in the drawing code of custom widgets.
10814     *
10815     * @return True if this View is in edit mode, false otherwise.
10816     */
10817    public boolean isInEditMode() {
10818        return false;
10819    }
10820
10821    /**
10822     * If the View draws content inside its padding and enables fading edges,
10823     * it needs to support padding offsets. Padding offsets are added to the
10824     * fading edges to extend the length of the fade so that it covers pixels
10825     * drawn inside the padding.
10826     *
10827     * Subclasses of this class should override this method if they need
10828     * to draw content inside the padding.
10829     *
10830     * @return True if padding offset must be applied, false otherwise.
10831     *
10832     * @see #getLeftPaddingOffset()
10833     * @see #getRightPaddingOffset()
10834     * @see #getTopPaddingOffset()
10835     * @see #getBottomPaddingOffset()
10836     *
10837     * @since CURRENT
10838     */
10839    protected boolean isPaddingOffsetRequired() {
10840        return false;
10841    }
10842
10843    /**
10844     * Amount by which to extend the left fading region. Called only when
10845     * {@link #isPaddingOffsetRequired()} returns true.
10846     *
10847     * @return The left padding offset in pixels.
10848     *
10849     * @see #isPaddingOffsetRequired()
10850     *
10851     * @since CURRENT
10852     */
10853    protected int getLeftPaddingOffset() {
10854        return 0;
10855    }
10856
10857    /**
10858     * Amount by which to extend the right fading region. Called only when
10859     * {@link #isPaddingOffsetRequired()} returns true.
10860     *
10861     * @return The right padding offset in pixels.
10862     *
10863     * @see #isPaddingOffsetRequired()
10864     *
10865     * @since CURRENT
10866     */
10867    protected int getRightPaddingOffset() {
10868        return 0;
10869    }
10870
10871    /**
10872     * Amount by which to extend the top fading region. Called only when
10873     * {@link #isPaddingOffsetRequired()} returns true.
10874     *
10875     * @return The top padding offset in pixels.
10876     *
10877     * @see #isPaddingOffsetRequired()
10878     *
10879     * @since CURRENT
10880     */
10881    protected int getTopPaddingOffset() {
10882        return 0;
10883    }
10884
10885    /**
10886     * Amount by which to extend the bottom fading region. Called only when
10887     * {@link #isPaddingOffsetRequired()} returns true.
10888     *
10889     * @return The bottom padding offset in pixels.
10890     *
10891     * @see #isPaddingOffsetRequired()
10892     *
10893     * @since CURRENT
10894     */
10895    protected int getBottomPaddingOffset() {
10896        return 0;
10897    }
10898
10899    /**
10900     * @hide
10901     * @param offsetRequired
10902     */
10903    protected int getFadeTop(boolean offsetRequired) {
10904        int top = mPaddingTop;
10905        if (offsetRequired) top += getTopPaddingOffset();
10906        return top;
10907    }
10908
10909    /**
10910     * @hide
10911     * @param offsetRequired
10912     */
10913    protected int getFadeHeight(boolean offsetRequired) {
10914        int padding = mPaddingTop;
10915        if (offsetRequired) padding += getTopPaddingOffset();
10916        return mBottom - mTop - mPaddingBottom - padding;
10917    }
10918
10919    /**
10920     * <p>Indicates whether this view is attached to an hardware accelerated
10921     * window or not.</p>
10922     *
10923     * <p>Even if this method returns true, it does not mean that every call
10924     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10925     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10926     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10927     * window is hardware accelerated,
10928     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10929     * return false, and this method will return true.</p>
10930     *
10931     * @return True if the view is attached to a window and the window is
10932     *         hardware accelerated; false in any other case.
10933     */
10934    public boolean isHardwareAccelerated() {
10935        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10936    }
10937
10938    /**
10939     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
10940     * case of an active Animation being run on the view.
10941     */
10942    private boolean drawAnimation(ViewGroup parent, long drawingTime,
10943            Animation a, boolean scalingRequired) {
10944        Transformation invalidationTransform;
10945        final int flags = parent.mGroupFlags;
10946        final boolean initialized = a.isInitialized();
10947        if (!initialized) {
10948            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
10949            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
10950            onAnimationStart();
10951        }
10952
10953        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
10954        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
10955            if (parent.mInvalidationTransformation == null) {
10956                parent.mInvalidationTransformation = new Transformation();
10957            }
10958            invalidationTransform = parent.mInvalidationTransformation;
10959            a.getTransformation(drawingTime, invalidationTransform, 1f);
10960        } else {
10961            invalidationTransform = parent.mChildTransformation;
10962        }
10963        if (more) {
10964            if (!a.willChangeBounds()) {
10965                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
10966                        parent.FLAG_OPTIMIZE_INVALIDATE) {
10967                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
10968                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
10969                    // The child need to draw an animation, potentially offscreen, so
10970                    // make sure we do not cancel invalidate requests
10971                    parent.mPrivateFlags |= DRAW_ANIMATION;
10972                    parent.invalidate(mLeft, mTop, mRight, mBottom);
10973                }
10974            } else {
10975                if (parent.mInvalidateRegion == null) {
10976                    parent.mInvalidateRegion = new RectF();
10977                }
10978                final RectF region = parent.mInvalidateRegion;
10979                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
10980                        invalidationTransform);
10981
10982                // The child need to draw an animation, potentially offscreen, so
10983                // make sure we do not cancel invalidate requests
10984                parent.mPrivateFlags |= DRAW_ANIMATION;
10985
10986                final int left = mLeft + (int) region.left;
10987                final int top = mTop + (int) region.top;
10988                parent.invalidate(left, top, left + (int) (region.width() + .5f),
10989                        top + (int) (region.height() + .5f));
10990            }
10991        }
10992        return more;
10993    }
10994
10995    /**
10996     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
10997     * This draw() method is an implementation detail and is not intended to be overridden or
10998     * to be called from anywhere else other than ViewGroup.drawChild().
10999     */
11000    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
11001        boolean more = false;
11002        final boolean childHasIdentityMatrix = hasIdentityMatrix();
11003        final int flags = parent.mGroupFlags;
11004
11005        if ((flags & parent.FLAG_CLEAR_TRANSFORMATION) == parent.FLAG_CLEAR_TRANSFORMATION) {
11006            parent.mChildTransformation.clear();
11007            parent.mGroupFlags &= ~parent.FLAG_CLEAR_TRANSFORMATION;
11008        }
11009
11010        Transformation transformToApply = null;
11011        boolean concatMatrix = false;
11012
11013        boolean scalingRequired = false;
11014        boolean caching;
11015        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11016
11017        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11018        if ((flags & parent.FLAG_CHILDREN_DRAWN_WITH_CACHE) == parent.FLAG_CHILDREN_DRAWN_WITH_CACHE ||
11019                (flags & parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) == parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) {
11020            caching = true;
11021            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11022        } else {
11023            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11024        }
11025
11026        final Animation a = getAnimation();
11027        if (a != null) {
11028            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11029            concatMatrix = a.willChangeTransformationMatrix();
11030            transformToApply = parent.mChildTransformation;
11031        } else if ((flags & parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
11032                parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
11033            final boolean hasTransform =
11034                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11035            if (hasTransform) {
11036                final int transformType = parent.mChildTransformation.getTransformationType();
11037                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11038                        parent.mChildTransformation : null;
11039                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11040            }
11041        }
11042
11043        concatMatrix |= !childHasIdentityMatrix;
11044
11045        // Sets the flag as early as possible to allow draw() implementations
11046        // to call invalidate() successfully when doing animations
11047        mPrivateFlags |= DRAWN;
11048
11049        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11050                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11051            return more;
11052        }
11053
11054        if (hardwareAccelerated) {
11055            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11056            // retain the flag's value temporarily in the mRecreateDisplayList flag
11057            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11058            mPrivateFlags &= ~INVALIDATED;
11059        }
11060
11061        computeScroll();
11062
11063        final int sx = mScrollX;
11064        final int sy = mScrollY;
11065
11066        DisplayList displayList = null;
11067        Bitmap cache = null;
11068        boolean hasDisplayList = false;
11069        if (caching) {
11070            if (!hardwareAccelerated) {
11071                if (layerType != LAYER_TYPE_NONE) {
11072                    layerType = LAYER_TYPE_SOFTWARE;
11073                    buildDrawingCache(true);
11074                }
11075                cache = getDrawingCache(true);
11076            } else {
11077                switch (layerType) {
11078                    case LAYER_TYPE_SOFTWARE:
11079                        buildDrawingCache(true);
11080                        cache = getDrawingCache(true);
11081                        break;
11082                    case LAYER_TYPE_NONE:
11083                        // Delay getting the display list until animation-driven alpha values are
11084                        // set up and possibly passed on to the view
11085                        hasDisplayList = canHaveDisplayList();
11086                        break;
11087                }
11088            }
11089        }
11090
11091        final boolean hasNoCache = cache == null || hasDisplayList;
11092        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11093                layerType != LAYER_TYPE_HARDWARE;
11094
11095        final int restoreTo = canvas.save();
11096        if (offsetForScroll) {
11097            canvas.translate(mLeft - sx, mTop - sy);
11098        } else {
11099            canvas.translate(mLeft, mTop);
11100            if (scalingRequired) {
11101                // mAttachInfo cannot be null, otherwise scalingRequired == false
11102                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11103                canvas.scale(scale, scale);
11104            }
11105        }
11106
11107        float alpha = getAlpha();
11108        if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) {
11109            if (transformToApply != null || !childHasIdentityMatrix) {
11110                int transX = 0;
11111                int transY = 0;
11112
11113                if (offsetForScroll) {
11114                    transX = -sx;
11115                    transY = -sy;
11116                }
11117
11118                if (transformToApply != null) {
11119                    if (concatMatrix) {
11120                        // Undo the scroll translation, apply the transformation matrix,
11121                        // then redo the scroll translate to get the correct result.
11122                        canvas.translate(-transX, -transY);
11123                        canvas.concat(transformToApply.getMatrix());
11124                        canvas.translate(transX, transY);
11125                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11126                    }
11127
11128                    float transformAlpha = transformToApply.getAlpha();
11129                    if (transformAlpha < 1.0f) {
11130                        alpha *= transformToApply.getAlpha();
11131                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11132                    }
11133                }
11134
11135                if (!childHasIdentityMatrix) {
11136                    canvas.translate(-transX, -transY);
11137                    canvas.concat(getMatrix());
11138                    canvas.translate(transX, transY);
11139                }
11140            }
11141
11142            if (alpha < 1.0f) {
11143                parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11144                if (hasNoCache) {
11145                    final int multipliedAlpha = (int) (255 * alpha);
11146                    if (!onSetAlpha(multipliedAlpha)) {
11147                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11148                        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN ||
11149                                layerType != LAYER_TYPE_NONE) {
11150                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11151                        }
11152                        if (layerType == LAYER_TYPE_NONE) {
11153                            final int scrollX = hasDisplayList ? 0 : sx;
11154                            final int scrollY = hasDisplayList ? 0 : sy;
11155                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11156                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11157                        }
11158                    } else {
11159                        // Alpha is handled by the child directly, clobber the layer's alpha
11160                        mPrivateFlags |= ALPHA_SET;
11161                    }
11162                }
11163            }
11164        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11165            onSetAlpha(255);
11166            mPrivateFlags &= ~ALPHA_SET;
11167        }
11168
11169        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN) {
11170            if (offsetForScroll) {
11171                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11172            } else {
11173                if (!scalingRequired || cache == null) {
11174                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11175                } else {
11176                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11177                }
11178            }
11179        }
11180
11181        if (hasDisplayList) {
11182            displayList = getDisplayList();
11183            if (!displayList.isValid()) {
11184                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11185                // to getDisplayList(), the display list will be marked invalid and we should not
11186                // try to use it again.
11187                displayList = null;
11188                hasDisplayList = false;
11189            }
11190        }
11191
11192        if (hasNoCache) {
11193            boolean layerRendered = false;
11194            if (layerType == LAYER_TYPE_HARDWARE) {
11195                final HardwareLayer layer = getHardwareLayer();
11196                if (layer != null && layer.isValid()) {
11197                    mLayerPaint.setAlpha((int) (alpha * 255));
11198                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11199                    layerRendered = true;
11200                } else {
11201                    final int scrollX = hasDisplayList ? 0 : sx;
11202                    final int scrollY = hasDisplayList ? 0 : sy;
11203                    canvas.saveLayer(scrollX, scrollY,
11204                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11205                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11206                }
11207            }
11208
11209            if (!layerRendered) {
11210                if (!hasDisplayList) {
11211                    // Fast path for layouts with no backgrounds
11212                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11213                        if (ViewDebug.TRACE_HIERARCHY) {
11214                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11215                        }
11216                        mPrivateFlags &= ~DIRTY_MASK;
11217                        dispatchDraw(canvas);
11218                    } else {
11219                        draw(canvas);
11220                    }
11221                } else {
11222                    mPrivateFlags &= ~DIRTY_MASK;
11223                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11224                            mRight - mLeft, mBottom - mTop, null);
11225                }
11226            }
11227        } else if (cache != null) {
11228            mPrivateFlags &= ~DIRTY_MASK;
11229            Paint cachePaint;
11230
11231            if (layerType == LAYER_TYPE_NONE) {
11232                cachePaint = parent.mCachePaint;
11233                if (cachePaint == null) {
11234                    cachePaint = new Paint();
11235                    cachePaint.setDither(false);
11236                    parent.mCachePaint = cachePaint;
11237                }
11238                if (alpha < 1.0f) {
11239                    cachePaint.setAlpha((int) (alpha * 255));
11240                    parent.mGroupFlags |= parent.FLAG_ALPHA_LOWER_THAN_ONE;
11241                } else if  ((flags & parent.FLAG_ALPHA_LOWER_THAN_ONE) ==
11242                        parent.FLAG_ALPHA_LOWER_THAN_ONE) {
11243                    cachePaint.setAlpha(255);
11244                    parent.mGroupFlags &= ~parent.FLAG_ALPHA_LOWER_THAN_ONE;
11245                }
11246            } else {
11247                cachePaint = mLayerPaint;
11248                cachePaint.setAlpha((int) (alpha * 255));
11249            }
11250            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11251        }
11252
11253        canvas.restoreToCount(restoreTo);
11254
11255        if (a != null && !more) {
11256            if (!hardwareAccelerated && !a.getFillAfter()) {
11257                onSetAlpha(255);
11258            }
11259            parent.finishAnimatingView(this, a);
11260        }
11261
11262        if (more && hardwareAccelerated) {
11263            // invalidation is the trigger to recreate display lists, so if we're using
11264            // display lists to render, force an invalidate to allow the animation to
11265            // continue drawing another frame
11266            parent.invalidate(true);
11267            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11268                // alpha animations should cause the child to recreate its display list
11269                invalidate(true);
11270            }
11271        }
11272
11273        mRecreateDisplayList = false;
11274
11275        return more;
11276    }
11277
11278    /**
11279     * Manually render this view (and all of its children) to the given Canvas.
11280     * The view must have already done a full layout before this function is
11281     * called.  When implementing a view, implement
11282     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11283     * If you do need to override this method, call the superclass version.
11284     *
11285     * @param canvas The Canvas to which the View is rendered.
11286     */
11287    public void draw(Canvas canvas) {
11288        if (ViewDebug.TRACE_HIERARCHY) {
11289            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11290        }
11291
11292        final int privateFlags = mPrivateFlags;
11293        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11294                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11295        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11296
11297        /*
11298         * Draw traversal performs several drawing steps which must be executed
11299         * in the appropriate order:
11300         *
11301         *      1. Draw the background
11302         *      2. If necessary, save the canvas' layers to prepare for fading
11303         *      3. Draw view's content
11304         *      4. Draw children
11305         *      5. If necessary, draw the fading edges and restore layers
11306         *      6. Draw decorations (scrollbars for instance)
11307         */
11308
11309        // Step 1, draw the background, if needed
11310        int saveCount;
11311
11312        if (!dirtyOpaque) {
11313            final Drawable background = mBGDrawable;
11314            if (background != null) {
11315                final int scrollX = mScrollX;
11316                final int scrollY = mScrollY;
11317
11318                if (mBackgroundSizeChanged) {
11319                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11320                    mBackgroundSizeChanged = false;
11321                }
11322
11323                if ((scrollX | scrollY) == 0) {
11324                    background.draw(canvas);
11325                } else {
11326                    canvas.translate(scrollX, scrollY);
11327                    background.draw(canvas);
11328                    canvas.translate(-scrollX, -scrollY);
11329                }
11330            }
11331        }
11332
11333        // skip step 2 & 5 if possible (common case)
11334        final int viewFlags = mViewFlags;
11335        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11336        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11337        if (!verticalEdges && !horizontalEdges) {
11338            // Step 3, draw the content
11339            if (!dirtyOpaque) onDraw(canvas);
11340
11341            // Step 4, draw the children
11342            dispatchDraw(canvas);
11343
11344            // Step 6, draw decorations (scrollbars)
11345            onDrawScrollBars(canvas);
11346
11347            // we're done...
11348            return;
11349        }
11350
11351        /*
11352         * Here we do the full fledged routine...
11353         * (this is an uncommon case where speed matters less,
11354         * this is why we repeat some of the tests that have been
11355         * done above)
11356         */
11357
11358        boolean drawTop = false;
11359        boolean drawBottom = false;
11360        boolean drawLeft = false;
11361        boolean drawRight = false;
11362
11363        float topFadeStrength = 0.0f;
11364        float bottomFadeStrength = 0.0f;
11365        float leftFadeStrength = 0.0f;
11366        float rightFadeStrength = 0.0f;
11367
11368        // Step 2, save the canvas' layers
11369        int paddingLeft = mPaddingLeft;
11370
11371        final boolean offsetRequired = isPaddingOffsetRequired();
11372        if (offsetRequired) {
11373            paddingLeft += getLeftPaddingOffset();
11374        }
11375
11376        int left = mScrollX + paddingLeft;
11377        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11378        int top = mScrollY + getFadeTop(offsetRequired);
11379        int bottom = top + getFadeHeight(offsetRequired);
11380
11381        if (offsetRequired) {
11382            right += getRightPaddingOffset();
11383            bottom += getBottomPaddingOffset();
11384        }
11385
11386        final ScrollabilityCache scrollabilityCache = mScrollCache;
11387        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11388        int length = (int) fadeHeight;
11389
11390        // clip the fade length if top and bottom fades overlap
11391        // overlapping fades produce odd-looking artifacts
11392        if (verticalEdges && (top + length > bottom - length)) {
11393            length = (bottom - top) / 2;
11394        }
11395
11396        // also clip horizontal fades if necessary
11397        if (horizontalEdges && (left + length > right - length)) {
11398            length = (right - left) / 2;
11399        }
11400
11401        if (verticalEdges) {
11402            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11403            drawTop = topFadeStrength * fadeHeight > 1.0f;
11404            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11405            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11406        }
11407
11408        if (horizontalEdges) {
11409            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11410            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11411            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11412            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11413        }
11414
11415        saveCount = canvas.getSaveCount();
11416
11417        int solidColor = getSolidColor();
11418        if (solidColor == 0) {
11419            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11420
11421            if (drawTop) {
11422                canvas.saveLayer(left, top, right, top + length, null, flags);
11423            }
11424
11425            if (drawBottom) {
11426                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11427            }
11428
11429            if (drawLeft) {
11430                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11431            }
11432
11433            if (drawRight) {
11434                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11435            }
11436        } else {
11437            scrollabilityCache.setFadeColor(solidColor);
11438        }
11439
11440        // Step 3, draw the content
11441        if (!dirtyOpaque) onDraw(canvas);
11442
11443        // Step 4, draw the children
11444        dispatchDraw(canvas);
11445
11446        // Step 5, draw the fade effect and restore layers
11447        final Paint p = scrollabilityCache.paint;
11448        final Matrix matrix = scrollabilityCache.matrix;
11449        final Shader fade = scrollabilityCache.shader;
11450
11451        if (drawTop) {
11452            matrix.setScale(1, fadeHeight * topFadeStrength);
11453            matrix.postTranslate(left, top);
11454            fade.setLocalMatrix(matrix);
11455            canvas.drawRect(left, top, right, top + length, p);
11456        }
11457
11458        if (drawBottom) {
11459            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11460            matrix.postRotate(180);
11461            matrix.postTranslate(left, bottom);
11462            fade.setLocalMatrix(matrix);
11463            canvas.drawRect(left, bottom - length, right, bottom, p);
11464        }
11465
11466        if (drawLeft) {
11467            matrix.setScale(1, fadeHeight * leftFadeStrength);
11468            matrix.postRotate(-90);
11469            matrix.postTranslate(left, top);
11470            fade.setLocalMatrix(matrix);
11471            canvas.drawRect(left, top, left + length, bottom, p);
11472        }
11473
11474        if (drawRight) {
11475            matrix.setScale(1, fadeHeight * rightFadeStrength);
11476            matrix.postRotate(90);
11477            matrix.postTranslate(right, top);
11478            fade.setLocalMatrix(matrix);
11479            canvas.drawRect(right - length, top, right, bottom, p);
11480        }
11481
11482        canvas.restoreToCount(saveCount);
11483
11484        // Step 6, draw decorations (scrollbars)
11485        onDrawScrollBars(canvas);
11486    }
11487
11488    /**
11489     * Override this if your view is known to always be drawn on top of a solid color background,
11490     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11491     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11492     * should be set to 0xFF.
11493     *
11494     * @see #setVerticalFadingEdgeEnabled(boolean)
11495     * @see #setHorizontalFadingEdgeEnabled(boolean)
11496     *
11497     * @return The known solid color background for this view, or 0 if the color may vary
11498     */
11499    @ViewDebug.ExportedProperty(category = "drawing")
11500    public int getSolidColor() {
11501        return 0;
11502    }
11503
11504    /**
11505     * Build a human readable string representation of the specified view flags.
11506     *
11507     * @param flags the view flags to convert to a string
11508     * @return a String representing the supplied flags
11509     */
11510    private static String printFlags(int flags) {
11511        String output = "";
11512        int numFlags = 0;
11513        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11514            output += "TAKES_FOCUS";
11515            numFlags++;
11516        }
11517
11518        switch (flags & VISIBILITY_MASK) {
11519        case INVISIBLE:
11520            if (numFlags > 0) {
11521                output += " ";
11522            }
11523            output += "INVISIBLE";
11524            // USELESS HERE numFlags++;
11525            break;
11526        case GONE:
11527            if (numFlags > 0) {
11528                output += " ";
11529            }
11530            output += "GONE";
11531            // USELESS HERE numFlags++;
11532            break;
11533        default:
11534            break;
11535        }
11536        return output;
11537    }
11538
11539    /**
11540     * Build a human readable string representation of the specified private
11541     * view flags.
11542     *
11543     * @param privateFlags the private view flags to convert to a string
11544     * @return a String representing the supplied flags
11545     */
11546    private static String printPrivateFlags(int privateFlags) {
11547        String output = "";
11548        int numFlags = 0;
11549
11550        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11551            output += "WANTS_FOCUS";
11552            numFlags++;
11553        }
11554
11555        if ((privateFlags & FOCUSED) == FOCUSED) {
11556            if (numFlags > 0) {
11557                output += " ";
11558            }
11559            output += "FOCUSED";
11560            numFlags++;
11561        }
11562
11563        if ((privateFlags & SELECTED) == SELECTED) {
11564            if (numFlags > 0) {
11565                output += " ";
11566            }
11567            output += "SELECTED";
11568            numFlags++;
11569        }
11570
11571        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11572            if (numFlags > 0) {
11573                output += " ";
11574            }
11575            output += "IS_ROOT_NAMESPACE";
11576            numFlags++;
11577        }
11578
11579        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11580            if (numFlags > 0) {
11581                output += " ";
11582            }
11583            output += "HAS_BOUNDS";
11584            numFlags++;
11585        }
11586
11587        if ((privateFlags & DRAWN) == DRAWN) {
11588            if (numFlags > 0) {
11589                output += " ";
11590            }
11591            output += "DRAWN";
11592            // USELESS HERE numFlags++;
11593        }
11594        return output;
11595    }
11596
11597    /**
11598     * <p>Indicates whether or not this view's layout will be requested during
11599     * the next hierarchy layout pass.</p>
11600     *
11601     * @return true if the layout will be forced during next layout pass
11602     */
11603    public boolean isLayoutRequested() {
11604        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11605    }
11606
11607    /**
11608     * Assign a size and position to a view and all of its
11609     * descendants
11610     *
11611     * <p>This is the second phase of the layout mechanism.
11612     * (The first is measuring). In this phase, each parent calls
11613     * layout on all of its children to position them.
11614     * This is typically done using the child measurements
11615     * that were stored in the measure pass().</p>
11616     *
11617     * <p>Derived classes should not override this method.
11618     * Derived classes with children should override
11619     * onLayout. In that method, they should
11620     * call layout on each of their children.</p>
11621     *
11622     * @param l Left position, relative to parent
11623     * @param t Top position, relative to parent
11624     * @param r Right position, relative to parent
11625     * @param b Bottom position, relative to parent
11626     */
11627    @SuppressWarnings({"unchecked"})
11628    public void layout(int l, int t, int r, int b) {
11629        int oldL = mLeft;
11630        int oldT = mTop;
11631        int oldB = mBottom;
11632        int oldR = mRight;
11633        boolean changed = setFrame(l, t, r, b);
11634        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11635            if (ViewDebug.TRACE_HIERARCHY) {
11636                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11637            }
11638
11639            onLayout(changed, l, t, r, b);
11640            mPrivateFlags &= ~LAYOUT_REQUIRED;
11641
11642            ListenerInfo li = mListenerInfo;
11643            if (li != null && li.mOnLayoutChangeListeners != null) {
11644                ArrayList<OnLayoutChangeListener> listenersCopy =
11645                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
11646                int numListeners = listenersCopy.size();
11647                for (int i = 0; i < numListeners; ++i) {
11648                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11649                }
11650            }
11651        }
11652        mPrivateFlags &= ~FORCE_LAYOUT;
11653    }
11654
11655    /**
11656     * Called from layout when this view should
11657     * assign a size and position to each of its children.
11658     *
11659     * Derived classes with children should override
11660     * this method and call layout on each of
11661     * their children.
11662     * @param changed This is a new size or position for this view
11663     * @param left Left position, relative to parent
11664     * @param top Top position, relative to parent
11665     * @param right Right position, relative to parent
11666     * @param bottom Bottom position, relative to parent
11667     */
11668    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11669    }
11670
11671    /**
11672     * Assign a size and position to this view.
11673     *
11674     * This is called from layout.
11675     *
11676     * @param left Left position, relative to parent
11677     * @param top Top position, relative to parent
11678     * @param right Right position, relative to parent
11679     * @param bottom Bottom position, relative to parent
11680     * @return true if the new size and position are different than the
11681     *         previous ones
11682     * {@hide}
11683     */
11684    protected boolean setFrame(int left, int top, int right, int bottom) {
11685        boolean changed = false;
11686
11687        if (DBG) {
11688            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11689                    + right + "," + bottom + ")");
11690        }
11691
11692        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11693            changed = true;
11694
11695            // Remember our drawn bit
11696            int drawn = mPrivateFlags & DRAWN;
11697
11698            int oldWidth = mRight - mLeft;
11699            int oldHeight = mBottom - mTop;
11700            int newWidth = right - left;
11701            int newHeight = bottom - top;
11702            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11703
11704            // Invalidate our old position
11705            invalidate(sizeChanged);
11706
11707            mLeft = left;
11708            mTop = top;
11709            mRight = right;
11710            mBottom = bottom;
11711
11712            mPrivateFlags |= HAS_BOUNDS;
11713
11714
11715            if (sizeChanged) {
11716                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11717                    // A change in dimension means an auto-centered pivot point changes, too
11718                    if (mTransformationInfo != null) {
11719                        mTransformationInfo.mMatrixDirty = true;
11720                    }
11721                }
11722                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11723            }
11724
11725            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11726                // If we are visible, force the DRAWN bit to on so that
11727                // this invalidate will go through (at least to our parent).
11728                // This is because someone may have invalidated this view
11729                // before this call to setFrame came in, thereby clearing
11730                // the DRAWN bit.
11731                mPrivateFlags |= DRAWN;
11732                invalidate(sizeChanged);
11733                // parent display list may need to be recreated based on a change in the bounds
11734                // of any child
11735                invalidateParentCaches();
11736            }
11737
11738            // Reset drawn bit to original value (invalidate turns it off)
11739            mPrivateFlags |= drawn;
11740
11741            mBackgroundSizeChanged = true;
11742        }
11743        return changed;
11744    }
11745
11746    /**
11747     * Finalize inflating a view from XML.  This is called as the last phase
11748     * of inflation, after all child views have been added.
11749     *
11750     * <p>Even if the subclass overrides onFinishInflate, they should always be
11751     * sure to call the super method, so that we get called.
11752     */
11753    protected void onFinishInflate() {
11754    }
11755
11756    /**
11757     * Returns the resources associated with this view.
11758     *
11759     * @return Resources object.
11760     */
11761    public Resources getResources() {
11762        return mResources;
11763    }
11764
11765    /**
11766     * Invalidates the specified Drawable.
11767     *
11768     * @param drawable the drawable to invalidate
11769     */
11770    public void invalidateDrawable(Drawable drawable) {
11771        if (verifyDrawable(drawable)) {
11772            final Rect dirty = drawable.getBounds();
11773            final int scrollX = mScrollX;
11774            final int scrollY = mScrollY;
11775
11776            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11777                    dirty.right + scrollX, dirty.bottom + scrollY);
11778        }
11779    }
11780
11781    /**
11782     * Schedules an action on a drawable to occur at a specified time.
11783     *
11784     * @param who the recipient of the action
11785     * @param what the action to run on the drawable
11786     * @param when the time at which the action must occur. Uses the
11787     *        {@link SystemClock#uptimeMillis} timebase.
11788     */
11789    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11790        if (verifyDrawable(who) && what != null) {
11791            if (mAttachInfo != null) {
11792                mAttachInfo.mHandler.postAtTime(what, who, when);
11793            } else {
11794                ViewRootImpl.getRunQueue().postDelayed(what, when - SystemClock.uptimeMillis());
11795            }
11796        }
11797    }
11798
11799    /**
11800     * Cancels a scheduled action on a drawable.
11801     *
11802     * @param who the recipient of the action
11803     * @param what the action to cancel
11804     */
11805    public void unscheduleDrawable(Drawable who, Runnable what) {
11806        if (verifyDrawable(who) && what != null) {
11807            if (mAttachInfo != null) {
11808                mAttachInfo.mHandler.removeCallbacks(what, who);
11809            } else {
11810                ViewRootImpl.getRunQueue().removeCallbacks(what);
11811            }
11812        }
11813    }
11814
11815    /**
11816     * Unschedule any events associated with the given Drawable.  This can be
11817     * used when selecting a new Drawable into a view, so that the previous
11818     * one is completely unscheduled.
11819     *
11820     * @param who The Drawable to unschedule.
11821     *
11822     * @see #drawableStateChanged
11823     */
11824    public void unscheduleDrawable(Drawable who) {
11825        if (mAttachInfo != null) {
11826            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11827        }
11828    }
11829
11830    /**
11831    * Return the layout direction of a given Drawable.
11832    *
11833    * @param who the Drawable to query
11834    *
11835    * @hide
11836    */
11837    public int getResolvedLayoutDirection(Drawable who) {
11838        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11839    }
11840
11841    /**
11842     * If your view subclass is displaying its own Drawable objects, it should
11843     * override this function and return true for any Drawable it is
11844     * displaying.  This allows animations for those drawables to be
11845     * scheduled.
11846     *
11847     * <p>Be sure to call through to the super class when overriding this
11848     * function.
11849     *
11850     * @param who The Drawable to verify.  Return true if it is one you are
11851     *            displaying, else return the result of calling through to the
11852     *            super class.
11853     *
11854     * @return boolean If true than the Drawable is being displayed in the
11855     *         view; else false and it is not allowed to animate.
11856     *
11857     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11858     * @see #drawableStateChanged()
11859     */
11860    protected boolean verifyDrawable(Drawable who) {
11861        return who == mBGDrawable;
11862    }
11863
11864    /**
11865     * This function is called whenever the state of the view changes in such
11866     * a way that it impacts the state of drawables being shown.
11867     *
11868     * <p>Be sure to call through to the superclass when overriding this
11869     * function.
11870     *
11871     * @see Drawable#setState(int[])
11872     */
11873    protected void drawableStateChanged() {
11874        Drawable d = mBGDrawable;
11875        if (d != null && d.isStateful()) {
11876            d.setState(getDrawableState());
11877        }
11878    }
11879
11880    /**
11881     * Call this to force a view to update its drawable state. This will cause
11882     * drawableStateChanged to be called on this view. Views that are interested
11883     * in the new state should call getDrawableState.
11884     *
11885     * @see #drawableStateChanged
11886     * @see #getDrawableState
11887     */
11888    public void refreshDrawableState() {
11889        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11890        drawableStateChanged();
11891
11892        ViewParent parent = mParent;
11893        if (parent != null) {
11894            parent.childDrawableStateChanged(this);
11895        }
11896    }
11897
11898    /**
11899     * Return an array of resource IDs of the drawable states representing the
11900     * current state of the view.
11901     *
11902     * @return The current drawable state
11903     *
11904     * @see Drawable#setState(int[])
11905     * @see #drawableStateChanged()
11906     * @see #onCreateDrawableState(int)
11907     */
11908    public final int[] getDrawableState() {
11909        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11910            return mDrawableState;
11911        } else {
11912            mDrawableState = onCreateDrawableState(0);
11913            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11914            return mDrawableState;
11915        }
11916    }
11917
11918    /**
11919     * Generate the new {@link android.graphics.drawable.Drawable} state for
11920     * this view. This is called by the view
11921     * system when the cached Drawable state is determined to be invalid.  To
11922     * retrieve the current state, you should use {@link #getDrawableState}.
11923     *
11924     * @param extraSpace if non-zero, this is the number of extra entries you
11925     * would like in the returned array in which you can place your own
11926     * states.
11927     *
11928     * @return Returns an array holding the current {@link Drawable} state of
11929     * the view.
11930     *
11931     * @see #mergeDrawableStates(int[], int[])
11932     */
11933    protected int[] onCreateDrawableState(int extraSpace) {
11934        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11935                mParent instanceof View) {
11936            return ((View) mParent).onCreateDrawableState(extraSpace);
11937        }
11938
11939        int[] drawableState;
11940
11941        int privateFlags = mPrivateFlags;
11942
11943        int viewStateIndex = 0;
11944        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11945        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11946        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11947        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11948        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11949        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11950        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11951                HardwareRenderer.isAvailable()) {
11952            // This is set if HW acceleration is requested, even if the current
11953            // process doesn't allow it.  This is just to allow app preview
11954            // windows to better match their app.
11955            viewStateIndex |= VIEW_STATE_ACCELERATED;
11956        }
11957        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11958
11959        final int privateFlags2 = mPrivateFlags2;
11960        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11961        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11962
11963        drawableState = VIEW_STATE_SETS[viewStateIndex];
11964
11965        //noinspection ConstantIfStatement
11966        if (false) {
11967            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11968            Log.i("View", toString()
11969                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11970                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11971                    + " fo=" + hasFocus()
11972                    + " sl=" + ((privateFlags & SELECTED) != 0)
11973                    + " wf=" + hasWindowFocus()
11974                    + ": " + Arrays.toString(drawableState));
11975        }
11976
11977        if (extraSpace == 0) {
11978            return drawableState;
11979        }
11980
11981        final int[] fullState;
11982        if (drawableState != null) {
11983            fullState = new int[drawableState.length + extraSpace];
11984            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11985        } else {
11986            fullState = new int[extraSpace];
11987        }
11988
11989        return fullState;
11990    }
11991
11992    /**
11993     * Merge your own state values in <var>additionalState</var> into the base
11994     * state values <var>baseState</var> that were returned by
11995     * {@link #onCreateDrawableState(int)}.
11996     *
11997     * @param baseState The base state values returned by
11998     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11999     * own additional state values.
12000     *
12001     * @param additionalState The additional state values you would like
12002     * added to <var>baseState</var>; this array is not modified.
12003     *
12004     * @return As a convenience, the <var>baseState</var> array you originally
12005     * passed into the function is returned.
12006     *
12007     * @see #onCreateDrawableState(int)
12008     */
12009    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
12010        final int N = baseState.length;
12011        int i = N - 1;
12012        while (i >= 0 && baseState[i] == 0) {
12013            i--;
12014        }
12015        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12016        return baseState;
12017    }
12018
12019    /**
12020     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12021     * on all Drawable objects associated with this view.
12022     */
12023    public void jumpDrawablesToCurrentState() {
12024        if (mBGDrawable != null) {
12025            mBGDrawable.jumpToCurrentState();
12026        }
12027    }
12028
12029    /**
12030     * Sets the background color for this view.
12031     * @param color the color of the background
12032     */
12033    @RemotableViewMethod
12034    public void setBackgroundColor(int color) {
12035        if (mBGDrawable instanceof ColorDrawable) {
12036            ((ColorDrawable) mBGDrawable).setColor(color);
12037        } else {
12038            setBackgroundDrawable(new ColorDrawable(color));
12039        }
12040    }
12041
12042    /**
12043     * Set the background to a given resource. The resource should refer to
12044     * a Drawable object or 0 to remove the background.
12045     * @param resid The identifier of the resource.
12046     * @attr ref android.R.styleable#View_background
12047     */
12048    @RemotableViewMethod
12049    public void setBackgroundResource(int resid) {
12050        if (resid != 0 && resid == mBackgroundResource) {
12051            return;
12052        }
12053
12054        Drawable d= null;
12055        if (resid != 0) {
12056            d = mResources.getDrawable(resid);
12057        }
12058        setBackgroundDrawable(d);
12059
12060        mBackgroundResource = resid;
12061    }
12062
12063    /**
12064     * Set the background to a given Drawable, or remove the background. If the
12065     * background has padding, this View's padding is set to the background's
12066     * padding. However, when a background is removed, this View's padding isn't
12067     * touched. If setting the padding is desired, please use
12068     * {@link #setPadding(int, int, int, int)}.
12069     *
12070     * @param d The Drawable to use as the background, or null to remove the
12071     *        background
12072     */
12073    public void setBackgroundDrawable(Drawable d) {
12074        if (d == mBGDrawable) {
12075            return;
12076        }
12077
12078        boolean requestLayout = false;
12079
12080        mBackgroundResource = 0;
12081
12082        /*
12083         * Regardless of whether we're setting a new background or not, we want
12084         * to clear the previous drawable.
12085         */
12086        if (mBGDrawable != null) {
12087            mBGDrawable.setCallback(null);
12088            unscheduleDrawable(mBGDrawable);
12089        }
12090
12091        if (d != null) {
12092            Rect padding = sThreadLocal.get();
12093            if (padding == null) {
12094                padding = new Rect();
12095                sThreadLocal.set(padding);
12096            }
12097            if (d.getPadding(padding)) {
12098                switch (d.getResolvedLayoutDirectionSelf()) {
12099                    case LAYOUT_DIRECTION_RTL:
12100                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12101                        break;
12102                    case LAYOUT_DIRECTION_LTR:
12103                    default:
12104                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12105                }
12106            }
12107
12108            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12109            // if it has a different minimum size, we should layout again
12110            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12111                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12112                requestLayout = true;
12113            }
12114
12115            d.setCallback(this);
12116            if (d.isStateful()) {
12117                d.setState(getDrawableState());
12118            }
12119            d.setVisible(getVisibility() == VISIBLE, false);
12120            mBGDrawable = d;
12121
12122            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12123                mPrivateFlags &= ~SKIP_DRAW;
12124                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12125                requestLayout = true;
12126            }
12127        } else {
12128            /* Remove the background */
12129            mBGDrawable = null;
12130
12131            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12132                /*
12133                 * This view ONLY drew the background before and we're removing
12134                 * the background, so now it won't draw anything
12135                 * (hence we SKIP_DRAW)
12136                 */
12137                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12138                mPrivateFlags |= SKIP_DRAW;
12139            }
12140
12141            /*
12142             * When the background is set, we try to apply its padding to this
12143             * View. When the background is removed, we don't touch this View's
12144             * padding. This is noted in the Javadocs. Hence, we don't need to
12145             * requestLayout(), the invalidate() below is sufficient.
12146             */
12147
12148            // The old background's minimum size could have affected this
12149            // View's layout, so let's requestLayout
12150            requestLayout = true;
12151        }
12152
12153        computeOpaqueFlags();
12154
12155        if (requestLayout) {
12156            requestLayout();
12157        }
12158
12159        mBackgroundSizeChanged = true;
12160        invalidate(true);
12161    }
12162
12163    /**
12164     * Gets the background drawable
12165     * @return The drawable used as the background for this view, if any.
12166     */
12167    public Drawable getBackground() {
12168        return mBGDrawable;
12169    }
12170
12171    /**
12172     * Sets the padding. The view may add on the space required to display
12173     * the scrollbars, depending on the style and visibility of the scrollbars.
12174     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12175     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12176     * from the values set in this call.
12177     *
12178     * @attr ref android.R.styleable#View_padding
12179     * @attr ref android.R.styleable#View_paddingBottom
12180     * @attr ref android.R.styleable#View_paddingLeft
12181     * @attr ref android.R.styleable#View_paddingRight
12182     * @attr ref android.R.styleable#View_paddingTop
12183     * @param left the left padding in pixels
12184     * @param top the top padding in pixels
12185     * @param right the right padding in pixels
12186     * @param bottom the bottom padding in pixels
12187     */
12188    public void setPadding(int left, int top, int right, int bottom) {
12189        boolean changed = false;
12190
12191        mUserPaddingRelative = false;
12192
12193        mUserPaddingLeft = left;
12194        mUserPaddingRight = right;
12195        mUserPaddingBottom = bottom;
12196
12197        final int viewFlags = mViewFlags;
12198
12199        // Common case is there are no scroll bars.
12200        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12201            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12202                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12203                        ? 0 : getVerticalScrollbarWidth();
12204                switch (mVerticalScrollbarPosition) {
12205                    case SCROLLBAR_POSITION_DEFAULT:
12206                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12207                            left += offset;
12208                        } else {
12209                            right += offset;
12210                        }
12211                        break;
12212                    case SCROLLBAR_POSITION_RIGHT:
12213                        right += offset;
12214                        break;
12215                    case SCROLLBAR_POSITION_LEFT:
12216                        left += offset;
12217                        break;
12218                }
12219            }
12220            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12221                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12222                        ? 0 : getHorizontalScrollbarHeight();
12223            }
12224        }
12225
12226        if (mPaddingLeft != left) {
12227            changed = true;
12228            mPaddingLeft = left;
12229        }
12230        if (mPaddingTop != top) {
12231            changed = true;
12232            mPaddingTop = top;
12233        }
12234        if (mPaddingRight != right) {
12235            changed = true;
12236            mPaddingRight = right;
12237        }
12238        if (mPaddingBottom != bottom) {
12239            changed = true;
12240            mPaddingBottom = bottom;
12241        }
12242
12243        if (changed) {
12244            requestLayout();
12245        }
12246    }
12247
12248    /**
12249     * Sets the relative padding. The view may add on the space required to display
12250     * the scrollbars, depending on the style and visibility of the scrollbars.
12251     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12252     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12253     * from the values set in this call.
12254     *
12255     * @attr ref android.R.styleable#View_padding
12256     * @attr ref android.R.styleable#View_paddingBottom
12257     * @attr ref android.R.styleable#View_paddingStart
12258     * @attr ref android.R.styleable#View_paddingEnd
12259     * @attr ref android.R.styleable#View_paddingTop
12260     * @param start the start padding in pixels
12261     * @param top the top padding in pixels
12262     * @param end the end padding in pixels
12263     * @param bottom the bottom padding in pixels
12264     */
12265    public void setPaddingRelative(int start, int top, int end, int bottom) {
12266        mUserPaddingRelative = true;
12267
12268        mUserPaddingStart = start;
12269        mUserPaddingEnd = end;
12270
12271        switch(getResolvedLayoutDirection()) {
12272            case LAYOUT_DIRECTION_RTL:
12273                setPadding(end, top, start, bottom);
12274                break;
12275            case LAYOUT_DIRECTION_LTR:
12276            default:
12277                setPadding(start, top, end, bottom);
12278        }
12279    }
12280
12281    /**
12282     * Returns the top padding of this view.
12283     *
12284     * @return the top padding in pixels
12285     */
12286    public int getPaddingTop() {
12287        return mPaddingTop;
12288    }
12289
12290    /**
12291     * Returns the bottom padding of this view. If there are inset and enabled
12292     * scrollbars, this value may include the space required to display the
12293     * scrollbars as well.
12294     *
12295     * @return the bottom padding in pixels
12296     */
12297    public int getPaddingBottom() {
12298        return mPaddingBottom;
12299    }
12300
12301    /**
12302     * Returns the left padding of this view. If there are inset and enabled
12303     * scrollbars, this value may include the space required to display the
12304     * scrollbars as well.
12305     *
12306     * @return the left padding in pixels
12307     */
12308    public int getPaddingLeft() {
12309        return mPaddingLeft;
12310    }
12311
12312    /**
12313     * Returns the start padding of this view. If there are inset and enabled
12314     * scrollbars, this value may include the space required to display the
12315     * scrollbars as well.
12316     *
12317     * @return the start padding in pixels
12318     */
12319    public int getPaddingStart() {
12320        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12321                mPaddingRight : mPaddingLeft;
12322    }
12323
12324    /**
12325     * Returns the right padding of this view. If there are inset and enabled
12326     * scrollbars, this value may include the space required to display the
12327     * scrollbars as well.
12328     *
12329     * @return the right padding in pixels
12330     */
12331    public int getPaddingRight() {
12332        return mPaddingRight;
12333    }
12334
12335    /**
12336     * Returns the end padding of this view. If there are inset and enabled
12337     * scrollbars, this value may include the space required to display the
12338     * scrollbars as well.
12339     *
12340     * @return the end padding in pixels
12341     */
12342    public int getPaddingEnd() {
12343        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12344                mPaddingLeft : mPaddingRight;
12345    }
12346
12347    /**
12348     * Return if the padding as been set thru relative values
12349     * {@link #setPaddingRelative(int, int, int, int)} or thru
12350     * @attr ref android.R.styleable#View_paddingStart or
12351     * @attr ref android.R.styleable#View_paddingEnd
12352     *
12353     * @return true if the padding is relative or false if it is not.
12354     */
12355    public boolean isPaddingRelative() {
12356        return mUserPaddingRelative;
12357    }
12358
12359    /**
12360     * Changes the selection state of this view. A view can be selected or not.
12361     * Note that selection is not the same as focus. Views are typically
12362     * selected in the context of an AdapterView like ListView or GridView;
12363     * the selected view is the view that is highlighted.
12364     *
12365     * @param selected true if the view must be selected, false otherwise
12366     */
12367    public void setSelected(boolean selected) {
12368        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12369            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12370            if (!selected) resetPressedState();
12371            invalidate(true);
12372            refreshDrawableState();
12373            dispatchSetSelected(selected);
12374        }
12375    }
12376
12377    /**
12378     * Dispatch setSelected to all of this View's children.
12379     *
12380     * @see #setSelected(boolean)
12381     *
12382     * @param selected The new selected state
12383     */
12384    protected void dispatchSetSelected(boolean selected) {
12385    }
12386
12387    /**
12388     * Indicates the selection state of this view.
12389     *
12390     * @return true if the view is selected, false otherwise
12391     */
12392    @ViewDebug.ExportedProperty
12393    public boolean isSelected() {
12394        return (mPrivateFlags & SELECTED) != 0;
12395    }
12396
12397    /**
12398     * Changes the activated state of this view. A view can be activated or not.
12399     * Note that activation is not the same as selection.  Selection is
12400     * a transient property, representing the view (hierarchy) the user is
12401     * currently interacting with.  Activation is a longer-term state that the
12402     * user can move views in and out of.  For example, in a list view with
12403     * single or multiple selection enabled, the views in the current selection
12404     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12405     * here.)  The activated state is propagated down to children of the view it
12406     * is set on.
12407     *
12408     * @param activated true if the view must be activated, false otherwise
12409     */
12410    public void setActivated(boolean activated) {
12411        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12412            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12413            invalidate(true);
12414            refreshDrawableState();
12415            dispatchSetActivated(activated);
12416        }
12417    }
12418
12419    /**
12420     * Dispatch setActivated to all of this View's children.
12421     *
12422     * @see #setActivated(boolean)
12423     *
12424     * @param activated The new activated state
12425     */
12426    protected void dispatchSetActivated(boolean activated) {
12427    }
12428
12429    /**
12430     * Indicates the activation state of this view.
12431     *
12432     * @return true if the view is activated, false otherwise
12433     */
12434    @ViewDebug.ExportedProperty
12435    public boolean isActivated() {
12436        return (mPrivateFlags & ACTIVATED) != 0;
12437    }
12438
12439    /**
12440     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12441     * observer can be used to get notifications when global events, like
12442     * layout, happen.
12443     *
12444     * The returned ViewTreeObserver observer is not guaranteed to remain
12445     * valid for the lifetime of this View. If the caller of this method keeps
12446     * a long-lived reference to ViewTreeObserver, it should always check for
12447     * the return value of {@link ViewTreeObserver#isAlive()}.
12448     *
12449     * @return The ViewTreeObserver for this view's hierarchy.
12450     */
12451    public ViewTreeObserver getViewTreeObserver() {
12452        if (mAttachInfo != null) {
12453            return mAttachInfo.mTreeObserver;
12454        }
12455        if (mFloatingTreeObserver == null) {
12456            mFloatingTreeObserver = new ViewTreeObserver();
12457        }
12458        return mFloatingTreeObserver;
12459    }
12460
12461    /**
12462     * <p>Finds the topmost view in the current view hierarchy.</p>
12463     *
12464     * @return the topmost view containing this view
12465     */
12466    public View getRootView() {
12467        if (mAttachInfo != null) {
12468            final View v = mAttachInfo.mRootView;
12469            if (v != null) {
12470                return v;
12471            }
12472        }
12473
12474        View parent = this;
12475
12476        while (parent.mParent != null && parent.mParent instanceof View) {
12477            parent = (View) parent.mParent;
12478        }
12479
12480        return parent;
12481    }
12482
12483    /**
12484     * <p>Computes the coordinates of this view on the screen. The argument
12485     * must be an array of two integers. After the method returns, the array
12486     * contains the x and y location in that order.</p>
12487     *
12488     * @param location an array of two integers in which to hold the coordinates
12489     */
12490    public void getLocationOnScreen(int[] location) {
12491        getLocationInWindow(location);
12492
12493        final AttachInfo info = mAttachInfo;
12494        if (info != null) {
12495            location[0] += info.mWindowLeft;
12496            location[1] += info.mWindowTop;
12497        }
12498    }
12499
12500    /**
12501     * <p>Computes the coordinates of this view in its window. The argument
12502     * must be an array of two integers. After the method returns, the array
12503     * contains the x and y location in that order.</p>
12504     *
12505     * @param location an array of two integers in which to hold the coordinates
12506     */
12507    public void getLocationInWindow(int[] location) {
12508        if (location == null || location.length < 2) {
12509            throw new IllegalArgumentException("location must be an array of two integers");
12510        }
12511
12512        if (mAttachInfo == null) {
12513            // When the view is not attached to a window, this method does not make sense
12514            location[0] = location[1] = 0;
12515            return;
12516        }
12517
12518        float[] position = mAttachInfo.mTmpTransformLocation;
12519        position[0] = position[1] = 0.0f;
12520
12521        if (!hasIdentityMatrix()) {
12522            getMatrix().mapPoints(position);
12523        }
12524
12525        position[0] += mLeft;
12526        position[1] += mTop;
12527
12528        ViewParent viewParent = mParent;
12529        while (viewParent instanceof View) {
12530            final View view = (View) viewParent;
12531
12532            position[0] -= view.mScrollX;
12533            position[1] -= view.mScrollY;
12534
12535            if (!view.hasIdentityMatrix()) {
12536                view.getMatrix().mapPoints(position);
12537            }
12538
12539            position[0] += view.mLeft;
12540            position[1] += view.mTop;
12541
12542            viewParent = view.mParent;
12543        }
12544
12545        if (viewParent instanceof ViewRootImpl) {
12546            // *cough*
12547            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12548            position[1] -= vr.mCurScrollY;
12549        }
12550
12551        location[0] = (int) (position[0] + 0.5f);
12552        location[1] = (int) (position[1] + 0.5f);
12553    }
12554
12555    /**
12556     * {@hide}
12557     * @param id the id of the view to be found
12558     * @return the view of the specified id, null if cannot be found
12559     */
12560    protected View findViewTraversal(int id) {
12561        if (id == mID) {
12562            return this;
12563        }
12564        return null;
12565    }
12566
12567    /**
12568     * {@hide}
12569     * @param tag the tag of the view to be found
12570     * @return the view of specified tag, null if cannot be found
12571     */
12572    protected View findViewWithTagTraversal(Object tag) {
12573        if (tag != null && tag.equals(mTag)) {
12574            return this;
12575        }
12576        return null;
12577    }
12578
12579    /**
12580     * {@hide}
12581     * @param predicate The predicate to evaluate.
12582     * @param childToSkip If not null, ignores this child during the recursive traversal.
12583     * @return The first view that matches the predicate or null.
12584     */
12585    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12586        if (predicate.apply(this)) {
12587            return this;
12588        }
12589        return null;
12590    }
12591
12592    /**
12593     * Look for a child view with the given id.  If this view has the given
12594     * id, return this view.
12595     *
12596     * @param id The id to search for.
12597     * @return The view that has the given id in the hierarchy or null
12598     */
12599    public final View findViewById(int id) {
12600        if (id < 0) {
12601            return null;
12602        }
12603        return findViewTraversal(id);
12604    }
12605
12606    /**
12607     * Finds a view by its unuque and stable accessibility id.
12608     *
12609     * @param accessibilityId The searched accessibility id.
12610     * @return The found view.
12611     */
12612    final View findViewByAccessibilityId(int accessibilityId) {
12613        if (accessibilityId < 0) {
12614            return null;
12615        }
12616        return findViewByAccessibilityIdTraversal(accessibilityId);
12617    }
12618
12619    /**
12620     * Performs the traversal to find a view by its unuque and stable accessibility id.
12621     *
12622     * <strong>Note:</strong>This method does not stop at the root namespace
12623     * boundary since the user can touch the screen at an arbitrary location
12624     * potentially crossing the root namespace bounday which will send an
12625     * accessibility event to accessibility services and they should be able
12626     * to obtain the event source. Also accessibility ids are guaranteed to be
12627     * unique in the window.
12628     *
12629     * @param accessibilityId The accessibility id.
12630     * @return The found view.
12631     */
12632    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12633        if (getAccessibilityViewId() == accessibilityId) {
12634            return this;
12635        }
12636        return null;
12637    }
12638
12639    /**
12640     * Look for a child view with the given tag.  If this view has the given
12641     * tag, return this view.
12642     *
12643     * @param tag The tag to search for, using "tag.equals(getTag())".
12644     * @return The View that has the given tag in the hierarchy or null
12645     */
12646    public final View findViewWithTag(Object tag) {
12647        if (tag == null) {
12648            return null;
12649        }
12650        return findViewWithTagTraversal(tag);
12651    }
12652
12653    /**
12654     * {@hide}
12655     * Look for a child view that matches the specified predicate.
12656     * If this view matches the predicate, return this view.
12657     *
12658     * @param predicate The predicate to evaluate.
12659     * @return The first view that matches the predicate or null.
12660     */
12661    public final View findViewByPredicate(Predicate<View> predicate) {
12662        return findViewByPredicateTraversal(predicate, null);
12663    }
12664
12665    /**
12666     * {@hide}
12667     * Look for a child view that matches the specified predicate,
12668     * starting with the specified view and its descendents and then
12669     * recusively searching the ancestors and siblings of that view
12670     * until this view is reached.
12671     *
12672     * This method is useful in cases where the predicate does not match
12673     * a single unique view (perhaps multiple views use the same id)
12674     * and we are trying to find the view that is "closest" in scope to the
12675     * starting view.
12676     *
12677     * @param start The view to start from.
12678     * @param predicate The predicate to evaluate.
12679     * @return The first view that matches the predicate or null.
12680     */
12681    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12682        View childToSkip = null;
12683        for (;;) {
12684            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12685            if (view != null || start == this) {
12686                return view;
12687            }
12688
12689            ViewParent parent = start.getParent();
12690            if (parent == null || !(parent instanceof View)) {
12691                return null;
12692            }
12693
12694            childToSkip = start;
12695            start = (View) parent;
12696        }
12697    }
12698
12699    /**
12700     * Sets the identifier for this view. The identifier does not have to be
12701     * unique in this view's hierarchy. The identifier should be a positive
12702     * number.
12703     *
12704     * @see #NO_ID
12705     * @see #getId()
12706     * @see #findViewById(int)
12707     *
12708     * @param id a number used to identify the view
12709     *
12710     * @attr ref android.R.styleable#View_id
12711     */
12712    public void setId(int id) {
12713        mID = id;
12714    }
12715
12716    /**
12717     * {@hide}
12718     *
12719     * @param isRoot true if the view belongs to the root namespace, false
12720     *        otherwise
12721     */
12722    public void setIsRootNamespace(boolean isRoot) {
12723        if (isRoot) {
12724            mPrivateFlags |= IS_ROOT_NAMESPACE;
12725        } else {
12726            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12727        }
12728    }
12729
12730    /**
12731     * {@hide}
12732     *
12733     * @return true if the view belongs to the root namespace, false otherwise
12734     */
12735    public boolean isRootNamespace() {
12736        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12737    }
12738
12739    /**
12740     * Returns this view's identifier.
12741     *
12742     * @return a positive integer used to identify the view or {@link #NO_ID}
12743     *         if the view has no ID
12744     *
12745     * @see #setId(int)
12746     * @see #findViewById(int)
12747     * @attr ref android.R.styleable#View_id
12748     */
12749    @ViewDebug.CapturedViewProperty
12750    public int getId() {
12751        return mID;
12752    }
12753
12754    /**
12755     * Returns this view's tag.
12756     *
12757     * @return the Object stored in this view as a tag
12758     *
12759     * @see #setTag(Object)
12760     * @see #getTag(int)
12761     */
12762    @ViewDebug.ExportedProperty
12763    public Object getTag() {
12764        return mTag;
12765    }
12766
12767    /**
12768     * Sets the tag associated with this view. A tag can be used to mark
12769     * a view in its hierarchy and does not have to be unique within the
12770     * hierarchy. Tags can also be used to store data within a view without
12771     * resorting to another data structure.
12772     *
12773     * @param tag an Object to tag the view with
12774     *
12775     * @see #getTag()
12776     * @see #setTag(int, Object)
12777     */
12778    public void setTag(final Object tag) {
12779        mTag = tag;
12780    }
12781
12782    /**
12783     * Returns the tag associated with this view and the specified key.
12784     *
12785     * @param key The key identifying the tag
12786     *
12787     * @return the Object stored in this view as a tag
12788     *
12789     * @see #setTag(int, Object)
12790     * @see #getTag()
12791     */
12792    public Object getTag(int key) {
12793        if (mKeyedTags != null) return mKeyedTags.get(key);
12794        return null;
12795    }
12796
12797    /**
12798     * Sets a tag associated with this view and a key. A tag can be used
12799     * to mark a view in its hierarchy and does not have to be unique within
12800     * the hierarchy. Tags can also be used to store data within a view
12801     * without resorting to another data structure.
12802     *
12803     * The specified key should be an id declared in the resources of the
12804     * application to ensure it is unique (see the <a
12805     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12806     * Keys identified as belonging to
12807     * the Android framework or not associated with any package will cause
12808     * an {@link IllegalArgumentException} to be thrown.
12809     *
12810     * @param key The key identifying the tag
12811     * @param tag An Object to tag the view with
12812     *
12813     * @throws IllegalArgumentException If they specified key is not valid
12814     *
12815     * @see #setTag(Object)
12816     * @see #getTag(int)
12817     */
12818    public void setTag(int key, final Object tag) {
12819        // If the package id is 0x00 or 0x01, it's either an undefined package
12820        // or a framework id
12821        if ((key >>> 24) < 2) {
12822            throw new IllegalArgumentException("The key must be an application-specific "
12823                    + "resource id.");
12824        }
12825
12826        setKeyedTag(key, tag);
12827    }
12828
12829    /**
12830     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12831     * framework id.
12832     *
12833     * @hide
12834     */
12835    public void setTagInternal(int key, Object tag) {
12836        if ((key >>> 24) != 0x1) {
12837            throw new IllegalArgumentException("The key must be a framework-specific "
12838                    + "resource id.");
12839        }
12840
12841        setKeyedTag(key, tag);
12842    }
12843
12844    private void setKeyedTag(int key, Object tag) {
12845        if (mKeyedTags == null) {
12846            mKeyedTags = new SparseArray<Object>();
12847        }
12848
12849        mKeyedTags.put(key, tag);
12850    }
12851
12852    /**
12853     * @param consistency The type of consistency. See ViewDebug for more information.
12854     *
12855     * @hide
12856     */
12857    protected boolean dispatchConsistencyCheck(int consistency) {
12858        return onConsistencyCheck(consistency);
12859    }
12860
12861    /**
12862     * Method that subclasses should implement to check their consistency. The type of
12863     * consistency check is indicated by the bit field passed as a parameter.
12864     *
12865     * @param consistency The type of consistency. See ViewDebug for more information.
12866     *
12867     * @throws IllegalStateException if the view is in an inconsistent state.
12868     *
12869     * @hide
12870     */
12871    protected boolean onConsistencyCheck(int consistency) {
12872        boolean result = true;
12873
12874        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12875        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12876
12877        if (checkLayout) {
12878            if (getParent() == null) {
12879                result = false;
12880                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12881                        "View " + this + " does not have a parent.");
12882            }
12883
12884            if (mAttachInfo == null) {
12885                result = false;
12886                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12887                        "View " + this + " is not attached to a window.");
12888            }
12889        }
12890
12891        if (checkDrawing) {
12892            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12893            // from their draw() method
12894
12895            if ((mPrivateFlags & DRAWN) != DRAWN &&
12896                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12897                result = false;
12898                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12899                        "View " + this + " was invalidated but its drawing cache is valid.");
12900            }
12901        }
12902
12903        return result;
12904    }
12905
12906    /**
12907     * Prints information about this view in the log output, with the tag
12908     * {@link #VIEW_LOG_TAG}.
12909     *
12910     * @hide
12911     */
12912    public void debug() {
12913        debug(0);
12914    }
12915
12916    /**
12917     * Prints information about this view in the log output, with the tag
12918     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12919     * indentation defined by the <code>depth</code>.
12920     *
12921     * @param depth the indentation level
12922     *
12923     * @hide
12924     */
12925    protected void debug(int depth) {
12926        String output = debugIndent(depth - 1);
12927
12928        output += "+ " + this;
12929        int id = getId();
12930        if (id != -1) {
12931            output += " (id=" + id + ")";
12932        }
12933        Object tag = getTag();
12934        if (tag != null) {
12935            output += " (tag=" + tag + ")";
12936        }
12937        Log.d(VIEW_LOG_TAG, output);
12938
12939        if ((mPrivateFlags & FOCUSED) != 0) {
12940            output = debugIndent(depth) + " FOCUSED";
12941            Log.d(VIEW_LOG_TAG, output);
12942        }
12943
12944        output = debugIndent(depth);
12945        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12946                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12947                + "} ";
12948        Log.d(VIEW_LOG_TAG, output);
12949
12950        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12951                || mPaddingBottom != 0) {
12952            output = debugIndent(depth);
12953            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12954                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12955            Log.d(VIEW_LOG_TAG, output);
12956        }
12957
12958        output = debugIndent(depth);
12959        output += "mMeasureWidth=" + mMeasuredWidth +
12960                " mMeasureHeight=" + mMeasuredHeight;
12961        Log.d(VIEW_LOG_TAG, output);
12962
12963        output = debugIndent(depth);
12964        if (mLayoutParams == null) {
12965            output += "BAD! no layout params";
12966        } else {
12967            output = mLayoutParams.debug(output);
12968        }
12969        Log.d(VIEW_LOG_TAG, output);
12970
12971        output = debugIndent(depth);
12972        output += "flags={";
12973        output += View.printFlags(mViewFlags);
12974        output += "}";
12975        Log.d(VIEW_LOG_TAG, output);
12976
12977        output = debugIndent(depth);
12978        output += "privateFlags={";
12979        output += View.printPrivateFlags(mPrivateFlags);
12980        output += "}";
12981        Log.d(VIEW_LOG_TAG, output);
12982    }
12983
12984    /**
12985     * Creates an string of whitespaces used for indentation.
12986     *
12987     * @param depth the indentation level
12988     * @return a String containing (depth * 2 + 3) * 2 white spaces
12989     *
12990     * @hide
12991     */
12992    protected static String debugIndent(int depth) {
12993        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12994        for (int i = 0; i < (depth * 2) + 3; i++) {
12995            spaces.append(' ').append(' ');
12996        }
12997        return spaces.toString();
12998    }
12999
13000    /**
13001     * <p>Return the offset of the widget's text baseline from the widget's top
13002     * boundary. If this widget does not support baseline alignment, this
13003     * method returns -1. </p>
13004     *
13005     * @return the offset of the baseline within the widget's bounds or -1
13006     *         if baseline alignment is not supported
13007     */
13008    @ViewDebug.ExportedProperty(category = "layout")
13009    public int getBaseline() {
13010        return -1;
13011    }
13012
13013    /**
13014     * Call this when something has changed which has invalidated the
13015     * layout of this view. This will schedule a layout pass of the view
13016     * tree.
13017     */
13018    public void requestLayout() {
13019        if (ViewDebug.TRACE_HIERARCHY) {
13020            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13021        }
13022
13023        if (getAccessibilityNodeProvider() != null) {
13024            throw new IllegalStateException("Views with AccessibilityNodeProvider"
13025                    + " can't have children.");
13026        }
13027
13028        mPrivateFlags |= FORCE_LAYOUT;
13029        mPrivateFlags |= INVALIDATED;
13030
13031        if (mParent != null) {
13032            if (mLayoutParams != null) {
13033                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
13034            }
13035            if (!mParent.isLayoutRequested()) {
13036                mParent.requestLayout();
13037            }
13038        }
13039    }
13040
13041    /**
13042     * Forces this view to be laid out during the next layout pass.
13043     * This method does not call requestLayout() or forceLayout()
13044     * on the parent.
13045     */
13046    public void forceLayout() {
13047        mPrivateFlags |= FORCE_LAYOUT;
13048        mPrivateFlags |= INVALIDATED;
13049    }
13050
13051    /**
13052     * <p>
13053     * This is called to find out how big a view should be. The parent
13054     * supplies constraint information in the width and height parameters.
13055     * </p>
13056     *
13057     * <p>
13058     * The actual measurement work of a view is performed in
13059     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13060     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13061     * </p>
13062     *
13063     *
13064     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13065     *        parent
13066     * @param heightMeasureSpec Vertical space requirements as imposed by the
13067     *        parent
13068     *
13069     * @see #onMeasure(int, int)
13070     */
13071    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13072        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13073                widthMeasureSpec != mOldWidthMeasureSpec ||
13074                heightMeasureSpec != mOldHeightMeasureSpec) {
13075
13076            // first clears the measured dimension flag
13077            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13078
13079            if (ViewDebug.TRACE_HIERARCHY) {
13080                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13081            }
13082
13083            // measure ourselves, this should set the measured dimension flag back
13084            onMeasure(widthMeasureSpec, heightMeasureSpec);
13085
13086            // flag not set, setMeasuredDimension() was not invoked, we raise
13087            // an exception to warn the developer
13088            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13089                throw new IllegalStateException("onMeasure() did not set the"
13090                        + " measured dimension by calling"
13091                        + " setMeasuredDimension()");
13092            }
13093
13094            mPrivateFlags |= LAYOUT_REQUIRED;
13095        }
13096
13097        mOldWidthMeasureSpec = widthMeasureSpec;
13098        mOldHeightMeasureSpec = heightMeasureSpec;
13099    }
13100
13101    /**
13102     * <p>
13103     * Measure the view and its content to determine the measured width and the
13104     * measured height. This method is invoked by {@link #measure(int, int)} and
13105     * should be overriden by subclasses to provide accurate and efficient
13106     * measurement of their contents.
13107     * </p>
13108     *
13109     * <p>
13110     * <strong>CONTRACT:</strong> When overriding this method, you
13111     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13112     * measured width and height of this view. Failure to do so will trigger an
13113     * <code>IllegalStateException</code>, thrown by
13114     * {@link #measure(int, int)}. Calling the superclass'
13115     * {@link #onMeasure(int, int)} is a valid use.
13116     * </p>
13117     *
13118     * <p>
13119     * The base class implementation of measure defaults to the background size,
13120     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13121     * override {@link #onMeasure(int, int)} to provide better measurements of
13122     * their content.
13123     * </p>
13124     *
13125     * <p>
13126     * If this method is overridden, it is the subclass's responsibility to make
13127     * sure the measured height and width are at least the view's minimum height
13128     * and width ({@link #getSuggestedMinimumHeight()} and
13129     * {@link #getSuggestedMinimumWidth()}).
13130     * </p>
13131     *
13132     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13133     *                         The requirements are encoded with
13134     *                         {@link android.view.View.MeasureSpec}.
13135     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13136     *                         The requirements are encoded with
13137     *                         {@link android.view.View.MeasureSpec}.
13138     *
13139     * @see #getMeasuredWidth()
13140     * @see #getMeasuredHeight()
13141     * @see #setMeasuredDimension(int, int)
13142     * @see #getSuggestedMinimumHeight()
13143     * @see #getSuggestedMinimumWidth()
13144     * @see android.view.View.MeasureSpec#getMode(int)
13145     * @see android.view.View.MeasureSpec#getSize(int)
13146     */
13147    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13148        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13149                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13150    }
13151
13152    /**
13153     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13154     * measured width and measured height. Failing to do so will trigger an
13155     * exception at measurement time.</p>
13156     *
13157     * @param measuredWidth The measured width of this view.  May be a complex
13158     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13159     * {@link #MEASURED_STATE_TOO_SMALL}.
13160     * @param measuredHeight The measured height of this view.  May be a complex
13161     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13162     * {@link #MEASURED_STATE_TOO_SMALL}.
13163     */
13164    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13165        mMeasuredWidth = measuredWidth;
13166        mMeasuredHeight = measuredHeight;
13167
13168        mPrivateFlags |= MEASURED_DIMENSION_SET;
13169    }
13170
13171    /**
13172     * Merge two states as returned by {@link #getMeasuredState()}.
13173     * @param curState The current state as returned from a view or the result
13174     * of combining multiple views.
13175     * @param newState The new view state to combine.
13176     * @return Returns a new integer reflecting the combination of the two
13177     * states.
13178     */
13179    public static int combineMeasuredStates(int curState, int newState) {
13180        return curState | newState;
13181    }
13182
13183    /**
13184     * Version of {@link #resolveSizeAndState(int, int, int)}
13185     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13186     */
13187    public static int resolveSize(int size, int measureSpec) {
13188        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13189    }
13190
13191    /**
13192     * Utility to reconcile a desired size and state, with constraints imposed
13193     * by a MeasureSpec.  Will take the desired size, unless a different size
13194     * is imposed by the constraints.  The returned value is a compound integer,
13195     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13196     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13197     * size is smaller than the size the view wants to be.
13198     *
13199     * @param size How big the view wants to be
13200     * @param measureSpec Constraints imposed by the parent
13201     * @return Size information bit mask as defined by
13202     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13203     */
13204    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13205        int result = size;
13206        int specMode = MeasureSpec.getMode(measureSpec);
13207        int specSize =  MeasureSpec.getSize(measureSpec);
13208        switch (specMode) {
13209        case MeasureSpec.UNSPECIFIED:
13210            result = size;
13211            break;
13212        case MeasureSpec.AT_MOST:
13213            if (specSize < size) {
13214                result = specSize | MEASURED_STATE_TOO_SMALL;
13215            } else {
13216                result = size;
13217            }
13218            break;
13219        case MeasureSpec.EXACTLY:
13220            result = specSize;
13221            break;
13222        }
13223        return result | (childMeasuredState&MEASURED_STATE_MASK);
13224    }
13225
13226    /**
13227     * Utility to return a default size. Uses the supplied size if the
13228     * MeasureSpec imposed no constraints. Will get larger if allowed
13229     * by the MeasureSpec.
13230     *
13231     * @param size Default size for this view
13232     * @param measureSpec Constraints imposed by the parent
13233     * @return The size this view should be.
13234     */
13235    public static int getDefaultSize(int size, int measureSpec) {
13236        int result = size;
13237        int specMode = MeasureSpec.getMode(measureSpec);
13238        int specSize = MeasureSpec.getSize(measureSpec);
13239
13240        switch (specMode) {
13241        case MeasureSpec.UNSPECIFIED:
13242            result = size;
13243            break;
13244        case MeasureSpec.AT_MOST:
13245        case MeasureSpec.EXACTLY:
13246            result = specSize;
13247            break;
13248        }
13249        return result;
13250    }
13251
13252    /**
13253     * Returns the suggested minimum height that the view should use. This
13254     * returns the maximum of the view's minimum height
13255     * and the background's minimum height
13256     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13257     * <p>
13258     * When being used in {@link #onMeasure(int, int)}, the caller should still
13259     * ensure the returned height is within the requirements of the parent.
13260     *
13261     * @return The suggested minimum height of the view.
13262     */
13263    protected int getSuggestedMinimumHeight() {
13264        int suggestedMinHeight = mMinHeight;
13265
13266        if (mBGDrawable != null) {
13267            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13268            if (suggestedMinHeight < bgMinHeight) {
13269                suggestedMinHeight = bgMinHeight;
13270            }
13271        }
13272
13273        return suggestedMinHeight;
13274    }
13275
13276    /**
13277     * Returns the suggested minimum width that the view should use. This
13278     * returns the maximum of the view's minimum width)
13279     * and the background's minimum width
13280     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13281     * <p>
13282     * When being used in {@link #onMeasure(int, int)}, the caller should still
13283     * ensure the returned width is within the requirements of the parent.
13284     *
13285     * @return The suggested minimum width of the view.
13286     */
13287    protected int getSuggestedMinimumWidth() {
13288        int suggestedMinWidth = mMinWidth;
13289
13290        if (mBGDrawable != null) {
13291            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13292            if (suggestedMinWidth < bgMinWidth) {
13293                suggestedMinWidth = bgMinWidth;
13294            }
13295        }
13296
13297        return suggestedMinWidth;
13298    }
13299
13300    /**
13301     * Sets the minimum height of the view. It is not guaranteed the view will
13302     * be able to achieve this minimum height (for example, if its parent layout
13303     * constrains it with less available height).
13304     *
13305     * @param minHeight The minimum height the view will try to be.
13306     */
13307    public void setMinimumHeight(int minHeight) {
13308        mMinHeight = minHeight;
13309    }
13310
13311    /**
13312     * Sets the minimum width of the view. It is not guaranteed the view will
13313     * be able to achieve this minimum width (for example, if its parent layout
13314     * constrains it with less available width).
13315     *
13316     * @param minWidth The minimum width the view will try to be.
13317     */
13318    public void setMinimumWidth(int minWidth) {
13319        mMinWidth = minWidth;
13320    }
13321
13322    /**
13323     * Get the animation currently associated with this view.
13324     *
13325     * @return The animation that is currently playing or
13326     *         scheduled to play for this view.
13327     */
13328    public Animation getAnimation() {
13329        return mCurrentAnimation;
13330    }
13331
13332    /**
13333     * Start the specified animation now.
13334     *
13335     * @param animation the animation to start now
13336     */
13337    public void startAnimation(Animation animation) {
13338        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13339        setAnimation(animation);
13340        invalidateParentCaches();
13341        invalidate(true);
13342    }
13343
13344    /**
13345     * Cancels any animations for this view.
13346     */
13347    public void clearAnimation() {
13348        if (mCurrentAnimation != null) {
13349            mCurrentAnimation.detach();
13350        }
13351        mCurrentAnimation = null;
13352        invalidateParentIfNeeded();
13353    }
13354
13355    /**
13356     * Sets the next animation to play for this view.
13357     * If you want the animation to play immediately, use
13358     * startAnimation. This method provides allows fine-grained
13359     * control over the start time and invalidation, but you
13360     * must make sure that 1) the animation has a start time set, and
13361     * 2) the view will be invalidated when the animation is supposed to
13362     * start.
13363     *
13364     * @param animation The next animation, or null.
13365     */
13366    public void setAnimation(Animation animation) {
13367        mCurrentAnimation = animation;
13368        if (animation != null) {
13369            animation.reset();
13370        }
13371    }
13372
13373    /**
13374     * Invoked by a parent ViewGroup to notify the start of the animation
13375     * currently associated with this view. If you override this method,
13376     * always call super.onAnimationStart();
13377     *
13378     * @see #setAnimation(android.view.animation.Animation)
13379     * @see #getAnimation()
13380     */
13381    protected void onAnimationStart() {
13382        mPrivateFlags |= ANIMATION_STARTED;
13383    }
13384
13385    /**
13386     * Invoked by a parent ViewGroup to notify the end of the animation
13387     * currently associated with this view. If you override this method,
13388     * always call super.onAnimationEnd();
13389     *
13390     * @see #setAnimation(android.view.animation.Animation)
13391     * @see #getAnimation()
13392     */
13393    protected void onAnimationEnd() {
13394        mPrivateFlags &= ~ANIMATION_STARTED;
13395    }
13396
13397    /**
13398     * Invoked if there is a Transform that involves alpha. Subclass that can
13399     * draw themselves with the specified alpha should return true, and then
13400     * respect that alpha when their onDraw() is called. If this returns false
13401     * then the view may be redirected to draw into an offscreen buffer to
13402     * fulfill the request, which will look fine, but may be slower than if the
13403     * subclass handles it internally. The default implementation returns false.
13404     *
13405     * @param alpha The alpha (0..255) to apply to the view's drawing
13406     * @return true if the view can draw with the specified alpha.
13407     */
13408    protected boolean onSetAlpha(int alpha) {
13409        return false;
13410    }
13411
13412    /**
13413     * This is used by the RootView to perform an optimization when
13414     * the view hierarchy contains one or several SurfaceView.
13415     * SurfaceView is always considered transparent, but its children are not,
13416     * therefore all View objects remove themselves from the global transparent
13417     * region (passed as a parameter to this function).
13418     *
13419     * @param region The transparent region for this ViewAncestor (window).
13420     *
13421     * @return Returns true if the effective visibility of the view at this
13422     * point is opaque, regardless of the transparent region; returns false
13423     * if it is possible for underlying windows to be seen behind the view.
13424     *
13425     * {@hide}
13426     */
13427    public boolean gatherTransparentRegion(Region region) {
13428        final AttachInfo attachInfo = mAttachInfo;
13429        if (region != null && attachInfo != null) {
13430            final int pflags = mPrivateFlags;
13431            if ((pflags & SKIP_DRAW) == 0) {
13432                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13433                // remove it from the transparent region.
13434                final int[] location = attachInfo.mTransparentLocation;
13435                getLocationInWindow(location);
13436                region.op(location[0], location[1], location[0] + mRight - mLeft,
13437                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13438            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13439                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13440                // exists, so we remove the background drawable's non-transparent
13441                // parts from this transparent region.
13442                applyDrawableToTransparentRegion(mBGDrawable, region);
13443            }
13444        }
13445        return true;
13446    }
13447
13448    /**
13449     * Play a sound effect for this view.
13450     *
13451     * <p>The framework will play sound effects for some built in actions, such as
13452     * clicking, but you may wish to play these effects in your widget,
13453     * for instance, for internal navigation.
13454     *
13455     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13456     * {@link #isSoundEffectsEnabled()} is true.
13457     *
13458     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13459     */
13460    public void playSoundEffect(int soundConstant) {
13461        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13462            return;
13463        }
13464        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13465    }
13466
13467    /**
13468     * BZZZTT!!1!
13469     *
13470     * <p>Provide haptic feedback to the user for this view.
13471     *
13472     * <p>The framework will provide haptic feedback for some built in actions,
13473     * such as long presses, but you may wish to provide feedback for your
13474     * own widget.
13475     *
13476     * <p>The feedback will only be performed if
13477     * {@link #isHapticFeedbackEnabled()} is true.
13478     *
13479     * @param feedbackConstant One of the constants defined in
13480     * {@link HapticFeedbackConstants}
13481     */
13482    public boolean performHapticFeedback(int feedbackConstant) {
13483        return performHapticFeedback(feedbackConstant, 0);
13484    }
13485
13486    /**
13487     * BZZZTT!!1!
13488     *
13489     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13490     *
13491     * @param feedbackConstant One of the constants defined in
13492     * {@link HapticFeedbackConstants}
13493     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13494     */
13495    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13496        if (mAttachInfo == null) {
13497            return false;
13498        }
13499        //noinspection SimplifiableIfStatement
13500        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13501                && !isHapticFeedbackEnabled()) {
13502            return false;
13503        }
13504        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13505                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13506    }
13507
13508    /**
13509     * Request that the visibility of the status bar be changed.
13510     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13511     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13512     */
13513    public void setSystemUiVisibility(int visibility) {
13514        if (visibility != mSystemUiVisibility) {
13515            mSystemUiVisibility = visibility;
13516            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13517                mParent.recomputeViewAttributes(this);
13518            }
13519        }
13520    }
13521
13522    /**
13523     * Returns the status bar visibility that this view has requested.
13524     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13525     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13526     */
13527    public int getSystemUiVisibility() {
13528        return mSystemUiVisibility;
13529    }
13530
13531    /**
13532     * Set a listener to receive callbacks when the visibility of the system bar changes.
13533     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13534     */
13535    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13536        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13537        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13538            mParent.recomputeViewAttributes(this);
13539        }
13540    }
13541
13542    /**
13543     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13544     * the view hierarchy.
13545     */
13546    public void dispatchSystemUiVisibilityChanged(int visibility) {
13547        ListenerInfo li = mListenerInfo;
13548        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13549            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13550                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13551        }
13552    }
13553
13554    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13555        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13556        if (val != mSystemUiVisibility) {
13557            setSystemUiVisibility(val);
13558        }
13559    }
13560
13561    /**
13562     * Creates an image that the system displays during the drag and drop
13563     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13564     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13565     * appearance as the given View. The default also positions the center of the drag shadow
13566     * directly under the touch point. If no View is provided (the constructor with no parameters
13567     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13568     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13569     * default is an invisible drag shadow.
13570     * <p>
13571     * You are not required to use the View you provide to the constructor as the basis of the
13572     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13573     * anything you want as the drag shadow.
13574     * </p>
13575     * <p>
13576     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13577     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13578     *  size and position of the drag shadow. It uses this data to construct a
13579     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13580     *  so that your application can draw the shadow image in the Canvas.
13581     * </p>
13582     *
13583     * <div class="special reference">
13584     * <h3>Developer Guides</h3>
13585     * <p>For a guide to implementing drag and drop features, read the
13586     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13587     * </div>
13588     */
13589    public static class DragShadowBuilder {
13590        private final WeakReference<View> mView;
13591
13592        /**
13593         * Constructs a shadow image builder based on a View. By default, the resulting drag
13594         * shadow will have the same appearance and dimensions as the View, with the touch point
13595         * over the center of the View.
13596         * @param view A View. Any View in scope can be used.
13597         */
13598        public DragShadowBuilder(View view) {
13599            mView = new WeakReference<View>(view);
13600        }
13601
13602        /**
13603         * Construct a shadow builder object with no associated View.  This
13604         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13605         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13606         * to supply the drag shadow's dimensions and appearance without
13607         * reference to any View object. If they are not overridden, then the result is an
13608         * invisible drag shadow.
13609         */
13610        public DragShadowBuilder() {
13611            mView = new WeakReference<View>(null);
13612        }
13613
13614        /**
13615         * Returns the View object that had been passed to the
13616         * {@link #View.DragShadowBuilder(View)}
13617         * constructor.  If that View parameter was {@code null} or if the
13618         * {@link #View.DragShadowBuilder()}
13619         * constructor was used to instantiate the builder object, this method will return
13620         * null.
13621         *
13622         * @return The View object associate with this builder object.
13623         */
13624        @SuppressWarnings({"JavadocReference"})
13625        final public View getView() {
13626            return mView.get();
13627        }
13628
13629        /**
13630         * Provides the metrics for the shadow image. These include the dimensions of
13631         * the shadow image, and the point within that shadow that should
13632         * be centered under the touch location while dragging.
13633         * <p>
13634         * The default implementation sets the dimensions of the shadow to be the
13635         * same as the dimensions of the View itself and centers the shadow under
13636         * the touch point.
13637         * </p>
13638         *
13639         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13640         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13641         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13642         * image.
13643         *
13644         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13645         * shadow image that should be underneath the touch point during the drag and drop
13646         * operation. Your application must set {@link android.graphics.Point#x} to the
13647         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13648         */
13649        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13650            final View view = mView.get();
13651            if (view != null) {
13652                shadowSize.set(view.getWidth(), view.getHeight());
13653                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13654            } else {
13655                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13656            }
13657        }
13658
13659        /**
13660         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13661         * based on the dimensions it received from the
13662         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13663         *
13664         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13665         */
13666        public void onDrawShadow(Canvas canvas) {
13667            final View view = mView.get();
13668            if (view != null) {
13669                view.draw(canvas);
13670            } else {
13671                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13672            }
13673        }
13674    }
13675
13676    /**
13677     * Starts a drag and drop operation. When your application calls this method, it passes a
13678     * {@link android.view.View.DragShadowBuilder} object to the system. The
13679     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13680     * to get metrics for the drag shadow, and then calls the object's
13681     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13682     * <p>
13683     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13684     *  drag events to all the View objects in your application that are currently visible. It does
13685     *  this either by calling the View object's drag listener (an implementation of
13686     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13687     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13688     *  Both are passed a {@link android.view.DragEvent} object that has a
13689     *  {@link android.view.DragEvent#getAction()} value of
13690     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13691     * </p>
13692     * <p>
13693     * Your application can invoke startDrag() on any attached View object. The View object does not
13694     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13695     * be related to the View the user selected for dragging.
13696     * </p>
13697     * @param data A {@link android.content.ClipData} object pointing to the data to be
13698     * transferred by the drag and drop operation.
13699     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13700     * drag shadow.
13701     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13702     * drop operation. This Object is put into every DragEvent object sent by the system during the
13703     * current drag.
13704     * <p>
13705     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13706     * to the target Views. For example, it can contain flags that differentiate between a
13707     * a copy operation and a move operation.
13708     * </p>
13709     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13710     * so the parameter should be set to 0.
13711     * @return {@code true} if the method completes successfully, or
13712     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13713     * do a drag, and so no drag operation is in progress.
13714     */
13715    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13716            Object myLocalState, int flags) {
13717        if (ViewDebug.DEBUG_DRAG) {
13718            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13719        }
13720        boolean okay = false;
13721
13722        Point shadowSize = new Point();
13723        Point shadowTouchPoint = new Point();
13724        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13725
13726        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13727                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13728            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13729        }
13730
13731        if (ViewDebug.DEBUG_DRAG) {
13732            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13733                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13734        }
13735        Surface surface = new Surface();
13736        try {
13737            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13738                    flags, shadowSize.x, shadowSize.y, surface);
13739            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13740                    + " surface=" + surface);
13741            if (token != null) {
13742                Canvas canvas = surface.lockCanvas(null);
13743                try {
13744                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13745                    shadowBuilder.onDrawShadow(canvas);
13746                } finally {
13747                    surface.unlockCanvasAndPost(canvas);
13748                }
13749
13750                final ViewRootImpl root = getViewRootImpl();
13751
13752                // Cache the local state object for delivery with DragEvents
13753                root.setLocalDragState(myLocalState);
13754
13755                // repurpose 'shadowSize' for the last touch point
13756                root.getLastTouchPoint(shadowSize);
13757
13758                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13759                        shadowSize.x, shadowSize.y,
13760                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13761                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13762
13763                // Off and running!  Release our local surface instance; the drag
13764                // shadow surface is now managed by the system process.
13765                surface.release();
13766            }
13767        } catch (Exception e) {
13768            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13769            surface.destroy();
13770        }
13771
13772        return okay;
13773    }
13774
13775    /**
13776     * Handles drag events sent by the system following a call to
13777     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13778     *<p>
13779     * When the system calls this method, it passes a
13780     * {@link android.view.DragEvent} object. A call to
13781     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13782     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13783     * operation.
13784     * @param event The {@link android.view.DragEvent} sent by the system.
13785     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13786     * in DragEvent, indicating the type of drag event represented by this object.
13787     * @return {@code true} if the method was successful, otherwise {@code false}.
13788     * <p>
13789     *  The method should return {@code true} in response to an action type of
13790     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13791     *  operation.
13792     * </p>
13793     * <p>
13794     *  The method should also return {@code true} in response to an action type of
13795     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13796     *  {@code false} if it didn't.
13797     * </p>
13798     */
13799    public boolean onDragEvent(DragEvent event) {
13800        return false;
13801    }
13802
13803    /**
13804     * Detects if this View is enabled and has a drag event listener.
13805     * If both are true, then it calls the drag event listener with the
13806     * {@link android.view.DragEvent} it received. If the drag event listener returns
13807     * {@code true}, then dispatchDragEvent() returns {@code true}.
13808     * <p>
13809     * For all other cases, the method calls the
13810     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13811     * method and returns its result.
13812     * </p>
13813     * <p>
13814     * This ensures that a drag event is always consumed, even if the View does not have a drag
13815     * event listener. However, if the View has a listener and the listener returns true, then
13816     * onDragEvent() is not called.
13817     * </p>
13818     */
13819    public boolean dispatchDragEvent(DragEvent event) {
13820        //noinspection SimplifiableIfStatement
13821        ListenerInfo li = mListenerInfo;
13822        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13823                && li.mOnDragListener.onDrag(this, event)) {
13824            return true;
13825        }
13826        return onDragEvent(event);
13827    }
13828
13829    boolean canAcceptDrag() {
13830        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13831    }
13832
13833    /**
13834     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13835     * it is ever exposed at all.
13836     * @hide
13837     */
13838    public void onCloseSystemDialogs(String reason) {
13839    }
13840
13841    /**
13842     * Given a Drawable whose bounds have been set to draw into this view,
13843     * update a Region being computed for
13844     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13845     * that any non-transparent parts of the Drawable are removed from the
13846     * given transparent region.
13847     *
13848     * @param dr The Drawable whose transparency is to be applied to the region.
13849     * @param region A Region holding the current transparency information,
13850     * where any parts of the region that are set are considered to be
13851     * transparent.  On return, this region will be modified to have the
13852     * transparency information reduced by the corresponding parts of the
13853     * Drawable that are not transparent.
13854     * {@hide}
13855     */
13856    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13857        if (DBG) {
13858            Log.i("View", "Getting transparent region for: " + this);
13859        }
13860        final Region r = dr.getTransparentRegion();
13861        final Rect db = dr.getBounds();
13862        final AttachInfo attachInfo = mAttachInfo;
13863        if (r != null && attachInfo != null) {
13864            final int w = getRight()-getLeft();
13865            final int h = getBottom()-getTop();
13866            if (db.left > 0) {
13867                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13868                r.op(0, 0, db.left, h, Region.Op.UNION);
13869            }
13870            if (db.right < w) {
13871                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13872                r.op(db.right, 0, w, h, Region.Op.UNION);
13873            }
13874            if (db.top > 0) {
13875                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13876                r.op(0, 0, w, db.top, Region.Op.UNION);
13877            }
13878            if (db.bottom < h) {
13879                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13880                r.op(0, db.bottom, w, h, Region.Op.UNION);
13881            }
13882            final int[] location = attachInfo.mTransparentLocation;
13883            getLocationInWindow(location);
13884            r.translate(location[0], location[1]);
13885            region.op(r, Region.Op.INTERSECT);
13886        } else {
13887            region.op(db, Region.Op.DIFFERENCE);
13888        }
13889    }
13890
13891    private void checkForLongClick(int delayOffset) {
13892        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13893            mHasPerformedLongPress = false;
13894
13895            if (mPendingCheckForLongPress == null) {
13896                mPendingCheckForLongPress = new CheckForLongPress();
13897            }
13898            mPendingCheckForLongPress.rememberWindowAttachCount();
13899            postDelayed(mPendingCheckForLongPress,
13900                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13901        }
13902    }
13903
13904    /**
13905     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13906     * LayoutInflater} class, which provides a full range of options for view inflation.
13907     *
13908     * @param context The Context object for your activity or application.
13909     * @param resource The resource ID to inflate
13910     * @param root A view group that will be the parent.  Used to properly inflate the
13911     * layout_* parameters.
13912     * @see LayoutInflater
13913     */
13914    public static View inflate(Context context, int resource, ViewGroup root) {
13915        LayoutInflater factory = LayoutInflater.from(context);
13916        return factory.inflate(resource, root);
13917    }
13918
13919    /**
13920     * Scroll the view with standard behavior for scrolling beyond the normal
13921     * content boundaries. Views that call this method should override
13922     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13923     * results of an over-scroll operation.
13924     *
13925     * Views can use this method to handle any touch or fling-based scrolling.
13926     *
13927     * @param deltaX Change in X in pixels
13928     * @param deltaY Change in Y in pixels
13929     * @param scrollX Current X scroll value in pixels before applying deltaX
13930     * @param scrollY Current Y scroll value in pixels before applying deltaY
13931     * @param scrollRangeX Maximum content scroll range along the X axis
13932     * @param scrollRangeY Maximum content scroll range along the Y axis
13933     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13934     *          along the X axis.
13935     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13936     *          along the Y axis.
13937     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13938     * @return true if scrolling was clamped to an over-scroll boundary along either
13939     *          axis, false otherwise.
13940     */
13941    @SuppressWarnings({"UnusedParameters"})
13942    protected boolean overScrollBy(int deltaX, int deltaY,
13943            int scrollX, int scrollY,
13944            int scrollRangeX, int scrollRangeY,
13945            int maxOverScrollX, int maxOverScrollY,
13946            boolean isTouchEvent) {
13947        final int overScrollMode = mOverScrollMode;
13948        final boolean canScrollHorizontal =
13949                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13950        final boolean canScrollVertical =
13951                computeVerticalScrollRange() > computeVerticalScrollExtent();
13952        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13953                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13954        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13955                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13956
13957        int newScrollX = scrollX + deltaX;
13958        if (!overScrollHorizontal) {
13959            maxOverScrollX = 0;
13960        }
13961
13962        int newScrollY = scrollY + deltaY;
13963        if (!overScrollVertical) {
13964            maxOverScrollY = 0;
13965        }
13966
13967        // Clamp values if at the limits and record
13968        final int left = -maxOverScrollX;
13969        final int right = maxOverScrollX + scrollRangeX;
13970        final int top = -maxOverScrollY;
13971        final int bottom = maxOverScrollY + scrollRangeY;
13972
13973        boolean clampedX = false;
13974        if (newScrollX > right) {
13975            newScrollX = right;
13976            clampedX = true;
13977        } else if (newScrollX < left) {
13978            newScrollX = left;
13979            clampedX = true;
13980        }
13981
13982        boolean clampedY = false;
13983        if (newScrollY > bottom) {
13984            newScrollY = bottom;
13985            clampedY = true;
13986        } else if (newScrollY < top) {
13987            newScrollY = top;
13988            clampedY = true;
13989        }
13990
13991        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13992
13993        return clampedX || clampedY;
13994    }
13995
13996    /**
13997     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13998     * respond to the results of an over-scroll operation.
13999     *
14000     * @param scrollX New X scroll value in pixels
14001     * @param scrollY New Y scroll value in pixels
14002     * @param clampedX True if scrollX was clamped to an over-scroll boundary
14003     * @param clampedY True if scrollY was clamped to an over-scroll boundary
14004     */
14005    protected void onOverScrolled(int scrollX, int scrollY,
14006            boolean clampedX, boolean clampedY) {
14007        // Intentionally empty.
14008    }
14009
14010    /**
14011     * Returns the over-scroll mode for this view. The result will be
14012     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14013     * (allow over-scrolling only if the view content is larger than the container),
14014     * or {@link #OVER_SCROLL_NEVER}.
14015     *
14016     * @return This view's over-scroll mode.
14017     */
14018    public int getOverScrollMode() {
14019        return mOverScrollMode;
14020    }
14021
14022    /**
14023     * Set the over-scroll mode for this view. Valid over-scroll modes are
14024     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14025     * (allow over-scrolling only if the view content is larger than the container),
14026     * or {@link #OVER_SCROLL_NEVER}.
14027     *
14028     * Setting the over-scroll mode of a view will have an effect only if the
14029     * view is capable of scrolling.
14030     *
14031     * @param overScrollMode The new over-scroll mode for this view.
14032     */
14033    public void setOverScrollMode(int overScrollMode) {
14034        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14035                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14036                overScrollMode != OVER_SCROLL_NEVER) {
14037            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14038        }
14039        mOverScrollMode = overScrollMode;
14040    }
14041
14042    /**
14043     * Gets a scale factor that determines the distance the view should scroll
14044     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14045     * @return The vertical scroll scale factor.
14046     * @hide
14047     */
14048    protected float getVerticalScrollFactor() {
14049        if (mVerticalScrollFactor == 0) {
14050            TypedValue outValue = new TypedValue();
14051            if (!mContext.getTheme().resolveAttribute(
14052                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14053                throw new IllegalStateException(
14054                        "Expected theme to define listPreferredItemHeight.");
14055            }
14056            mVerticalScrollFactor = outValue.getDimension(
14057                    mContext.getResources().getDisplayMetrics());
14058        }
14059        return mVerticalScrollFactor;
14060    }
14061
14062    /**
14063     * Gets a scale factor that determines the distance the view should scroll
14064     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14065     * @return The horizontal scroll scale factor.
14066     * @hide
14067     */
14068    protected float getHorizontalScrollFactor() {
14069        // TODO: Should use something else.
14070        return getVerticalScrollFactor();
14071    }
14072
14073    /**
14074     * Return the value specifying the text direction or policy that was set with
14075     * {@link #setTextDirection(int)}.
14076     *
14077     * @return the defined text direction. It can be one of:
14078     *
14079     * {@link #TEXT_DIRECTION_INHERIT},
14080     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14081     * {@link #TEXT_DIRECTION_ANY_RTL},
14082     * {@link #TEXT_DIRECTION_LTR},
14083     * {@link #TEXT_DIRECTION_RTL},
14084     * {@link #TEXT_DIRECTION_LOCALE},
14085     */
14086    public int getTextDirection() {
14087        return mTextDirection;
14088    }
14089
14090    /**
14091     * Set the text direction.
14092     *
14093     * @param textDirection the direction to set. Should be one of:
14094     *
14095     * {@link #TEXT_DIRECTION_INHERIT},
14096     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14097     * {@link #TEXT_DIRECTION_ANY_RTL},
14098     * {@link #TEXT_DIRECTION_LTR},
14099     * {@link #TEXT_DIRECTION_RTL},
14100     * {@link #TEXT_DIRECTION_LOCALE},
14101     */
14102    public void setTextDirection(int textDirection) {
14103        if (textDirection != mTextDirection) {
14104            mTextDirection = textDirection;
14105            resetResolvedTextDirection();
14106            requestLayout();
14107        }
14108    }
14109
14110    /**
14111     * Return the resolved text direction.
14112     *
14113     * @return the resolved text direction. Return one of:
14114     *
14115     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14116     * {@link #TEXT_DIRECTION_ANY_RTL},
14117     * {@link #TEXT_DIRECTION_LTR},
14118     * {@link #TEXT_DIRECTION_RTL},
14119     * {@link #TEXT_DIRECTION_LOCALE},
14120     */
14121    public int getResolvedTextDirection() {
14122        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
14123            resolveTextDirection();
14124        }
14125        return mResolvedTextDirection;
14126    }
14127
14128    /**
14129     * Resolve the text direction. Will call {@link View#onResolveTextDirection()} when resolution
14130     * is done.
14131     */
14132    public void resolveTextDirection() {
14133        if (mResolvedTextDirection != TEXT_DIRECTION_INHERIT) {
14134            // Resolution has already been done.
14135            return;
14136        }
14137        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
14138            mResolvedTextDirection = mTextDirection;
14139        } else if (mParent != null && mParent instanceof ViewGroup) {
14140            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
14141        } else {
14142            mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
14143        }
14144        onResolveTextDirection();
14145    }
14146
14147    /**
14148     * Called when text direction has been resolved. Subclasses that care about text direction
14149     * resolution should override this method. The default implementation does nothing.
14150     */
14151    public void onResolveTextDirection() {
14152    }
14153
14154    /**
14155     * Reset resolved text direction. Text direction can be resolved with a call to
14156     * getResolvedTextDirection(). Will call {@link View#onResetResolvedTextDirection()} when
14157     * reset is done.
14158     */
14159    public void resetResolvedTextDirection() {
14160        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
14161        onResetResolvedTextDirection();
14162    }
14163
14164    /**
14165     * Called when text direction is reset. Subclasses that care about text direction reset should
14166     * override this method and do a reset of the text direction of their children. The default
14167     * implementation does nothing.
14168     */
14169    public void onResetResolvedTextDirection() {
14170    }
14171
14172    //
14173    // Properties
14174    //
14175    /**
14176     * A Property wrapper around the <code>alpha</code> functionality handled by the
14177     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14178     */
14179    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14180        @Override
14181        public void setValue(View object, float value) {
14182            object.setAlpha(value);
14183        }
14184
14185        @Override
14186        public Float get(View object) {
14187            return object.getAlpha();
14188        }
14189    };
14190
14191    /**
14192     * A Property wrapper around the <code>translationX</code> functionality handled by the
14193     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14194     */
14195    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14196        @Override
14197        public void setValue(View object, float value) {
14198            object.setTranslationX(value);
14199        }
14200
14201                @Override
14202        public Float get(View object) {
14203            return object.getTranslationX();
14204        }
14205    };
14206
14207    /**
14208     * A Property wrapper around the <code>translationY</code> functionality handled by the
14209     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14210     */
14211    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14212        @Override
14213        public void setValue(View object, float value) {
14214            object.setTranslationY(value);
14215        }
14216
14217        @Override
14218        public Float get(View object) {
14219            return object.getTranslationY();
14220        }
14221    };
14222
14223    /**
14224     * A Property wrapper around the <code>x</code> functionality handled by the
14225     * {@link View#setX(float)} and {@link View#getX()} methods.
14226     */
14227    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14228        @Override
14229        public void setValue(View object, float value) {
14230            object.setX(value);
14231        }
14232
14233        @Override
14234        public Float get(View object) {
14235            return object.getX();
14236        }
14237    };
14238
14239    /**
14240     * A Property wrapper around the <code>y</code> functionality handled by the
14241     * {@link View#setY(float)} and {@link View#getY()} methods.
14242     */
14243    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
14244        @Override
14245        public void setValue(View object, float value) {
14246            object.setY(value);
14247        }
14248
14249        @Override
14250        public Float get(View object) {
14251            return object.getY();
14252        }
14253    };
14254
14255    /**
14256     * A Property wrapper around the <code>rotation</code> functionality handled by the
14257     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
14258     */
14259    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
14260        @Override
14261        public void setValue(View object, float value) {
14262            object.setRotation(value);
14263        }
14264
14265        @Override
14266        public Float get(View object) {
14267            return object.getRotation();
14268        }
14269    };
14270
14271    /**
14272     * A Property wrapper around the <code>rotationX</code> functionality handled by the
14273     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
14274     */
14275    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
14276        @Override
14277        public void setValue(View object, float value) {
14278            object.setRotationX(value);
14279        }
14280
14281        @Override
14282        public Float get(View object) {
14283            return object.getRotationX();
14284        }
14285    };
14286
14287    /**
14288     * A Property wrapper around the <code>rotationY</code> functionality handled by the
14289     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
14290     */
14291    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
14292        @Override
14293        public void setValue(View object, float value) {
14294            object.setRotationY(value);
14295        }
14296
14297        @Override
14298        public Float get(View object) {
14299            return object.getRotationY();
14300        }
14301    };
14302
14303    /**
14304     * A Property wrapper around the <code>scaleX</code> functionality handled by the
14305     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
14306     */
14307    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
14308        @Override
14309        public void setValue(View object, float value) {
14310            object.setScaleX(value);
14311        }
14312
14313        @Override
14314        public Float get(View object) {
14315            return object.getScaleX();
14316        }
14317    };
14318
14319    /**
14320     * A Property wrapper around the <code>scaleY</code> functionality handled by the
14321     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
14322     */
14323    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
14324        @Override
14325        public void setValue(View object, float value) {
14326            object.setScaleY(value);
14327        }
14328
14329        @Override
14330        public Float get(View object) {
14331            return object.getScaleY();
14332        }
14333    };
14334
14335    /**
14336     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
14337     * Each MeasureSpec represents a requirement for either the width or the height.
14338     * A MeasureSpec is comprised of a size and a mode. There are three possible
14339     * modes:
14340     * <dl>
14341     * <dt>UNSPECIFIED</dt>
14342     * <dd>
14343     * The parent has not imposed any constraint on the child. It can be whatever size
14344     * it wants.
14345     * </dd>
14346     *
14347     * <dt>EXACTLY</dt>
14348     * <dd>
14349     * The parent has determined an exact size for the child. The child is going to be
14350     * given those bounds regardless of how big it wants to be.
14351     * </dd>
14352     *
14353     * <dt>AT_MOST</dt>
14354     * <dd>
14355     * The child can be as large as it wants up to the specified size.
14356     * </dd>
14357     * </dl>
14358     *
14359     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14360     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14361     */
14362    public static class MeasureSpec {
14363        private static final int MODE_SHIFT = 30;
14364        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14365
14366        /**
14367         * Measure specification mode: The parent has not imposed any constraint
14368         * on the child. It can be whatever size it wants.
14369         */
14370        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14371
14372        /**
14373         * Measure specification mode: The parent has determined an exact size
14374         * for the child. The child is going to be given those bounds regardless
14375         * of how big it wants to be.
14376         */
14377        public static final int EXACTLY     = 1 << MODE_SHIFT;
14378
14379        /**
14380         * Measure specification mode: The child can be as large as it wants up
14381         * to the specified size.
14382         */
14383        public static final int AT_MOST     = 2 << MODE_SHIFT;
14384
14385        /**
14386         * Creates a measure specification based on the supplied size and mode.
14387         *
14388         * The mode must always be one of the following:
14389         * <ul>
14390         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14391         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14392         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14393         * </ul>
14394         *
14395         * @param size the size of the measure specification
14396         * @param mode the mode of the measure specification
14397         * @return the measure specification based on size and mode
14398         */
14399        public static int makeMeasureSpec(int size, int mode) {
14400            return size + mode;
14401        }
14402
14403        /**
14404         * Extracts the mode from the supplied measure specification.
14405         *
14406         * @param measureSpec the measure specification to extract the mode from
14407         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14408         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14409         *         {@link android.view.View.MeasureSpec#EXACTLY}
14410         */
14411        public static int getMode(int measureSpec) {
14412            return (measureSpec & MODE_MASK);
14413        }
14414
14415        /**
14416         * Extracts the size from the supplied measure specification.
14417         *
14418         * @param measureSpec the measure specification to extract the size from
14419         * @return the size in pixels defined in the supplied measure specification
14420         */
14421        public static int getSize(int measureSpec) {
14422            return (measureSpec & ~MODE_MASK);
14423        }
14424
14425        /**
14426         * Returns a String representation of the specified measure
14427         * specification.
14428         *
14429         * @param measureSpec the measure specification to convert to a String
14430         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14431         */
14432        public static String toString(int measureSpec) {
14433            int mode = getMode(measureSpec);
14434            int size = getSize(measureSpec);
14435
14436            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14437
14438            if (mode == UNSPECIFIED)
14439                sb.append("UNSPECIFIED ");
14440            else if (mode == EXACTLY)
14441                sb.append("EXACTLY ");
14442            else if (mode == AT_MOST)
14443                sb.append("AT_MOST ");
14444            else
14445                sb.append(mode).append(" ");
14446
14447            sb.append(size);
14448            return sb.toString();
14449        }
14450    }
14451
14452    class CheckForLongPress implements Runnable {
14453
14454        private int mOriginalWindowAttachCount;
14455
14456        public void run() {
14457            if (isPressed() && (mParent != null)
14458                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14459                if (performLongClick()) {
14460                    mHasPerformedLongPress = true;
14461                }
14462            }
14463        }
14464
14465        public void rememberWindowAttachCount() {
14466            mOriginalWindowAttachCount = mWindowAttachCount;
14467        }
14468    }
14469
14470    private final class CheckForTap implements Runnable {
14471        public void run() {
14472            mPrivateFlags &= ~PREPRESSED;
14473            mPrivateFlags |= PRESSED;
14474            refreshDrawableState();
14475            checkForLongClick(ViewConfiguration.getTapTimeout());
14476        }
14477    }
14478
14479    private final class PerformClick implements Runnable {
14480        public void run() {
14481            performClick();
14482        }
14483    }
14484
14485    /** @hide */
14486    public void hackTurnOffWindowResizeAnim(boolean off) {
14487        mAttachInfo.mTurnOffWindowResizeAnim = off;
14488    }
14489
14490    /**
14491     * This method returns a ViewPropertyAnimator object, which can be used to animate
14492     * specific properties on this View.
14493     *
14494     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14495     */
14496    public ViewPropertyAnimator animate() {
14497        if (mAnimator == null) {
14498            mAnimator = new ViewPropertyAnimator(this);
14499        }
14500        return mAnimator;
14501    }
14502
14503    /**
14504     * Interface definition for a callback to be invoked when a key event is
14505     * dispatched to this view. The callback will be invoked before the key
14506     * event is given to the view.
14507     */
14508    public interface OnKeyListener {
14509        /**
14510         * Called when a key is dispatched to a view. This allows listeners to
14511         * get a chance to respond before the target view.
14512         *
14513         * @param v The view the key has been dispatched to.
14514         * @param keyCode The code for the physical key that was pressed
14515         * @param event The KeyEvent object containing full information about
14516         *        the event.
14517         * @return True if the listener has consumed the event, false otherwise.
14518         */
14519        boolean onKey(View v, int keyCode, KeyEvent event);
14520    }
14521
14522    /**
14523     * Interface definition for a callback to be invoked when a touch event is
14524     * dispatched to this view. The callback will be invoked before the touch
14525     * event is given to the view.
14526     */
14527    public interface OnTouchListener {
14528        /**
14529         * Called when a touch event is dispatched to a view. This allows listeners to
14530         * get a chance to respond before the target view.
14531         *
14532         * @param v The view the touch event has been dispatched to.
14533         * @param event The MotionEvent object containing full information about
14534         *        the event.
14535         * @return True if the listener has consumed the event, false otherwise.
14536         */
14537        boolean onTouch(View v, MotionEvent event);
14538    }
14539
14540    /**
14541     * Interface definition for a callback to be invoked when a hover event is
14542     * dispatched to this view. The callback will be invoked before the hover
14543     * event is given to the view.
14544     */
14545    public interface OnHoverListener {
14546        /**
14547         * Called when a hover event is dispatched to a view. This allows listeners to
14548         * get a chance to respond before the target view.
14549         *
14550         * @param v The view the hover event has been dispatched to.
14551         * @param event The MotionEvent object containing full information about
14552         *        the event.
14553         * @return True if the listener has consumed the event, false otherwise.
14554         */
14555        boolean onHover(View v, MotionEvent event);
14556    }
14557
14558    /**
14559     * Interface definition for a callback to be invoked when a generic motion event is
14560     * dispatched to this view. The callback will be invoked before the generic motion
14561     * event is given to the view.
14562     */
14563    public interface OnGenericMotionListener {
14564        /**
14565         * Called when a generic motion event is dispatched to a view. This allows listeners to
14566         * get a chance to respond before the target view.
14567         *
14568         * @param v The view the generic motion event has been dispatched to.
14569         * @param event The MotionEvent object containing full information about
14570         *        the event.
14571         * @return True if the listener has consumed the event, false otherwise.
14572         */
14573        boolean onGenericMotion(View v, MotionEvent event);
14574    }
14575
14576    /**
14577     * Interface definition for a callback to be invoked when a view has been clicked and held.
14578     */
14579    public interface OnLongClickListener {
14580        /**
14581         * Called when a view has been clicked and held.
14582         *
14583         * @param v The view that was clicked and held.
14584         *
14585         * @return true if the callback consumed the long click, false otherwise.
14586         */
14587        boolean onLongClick(View v);
14588    }
14589
14590    /**
14591     * Interface definition for a callback to be invoked when a drag is being dispatched
14592     * to this view.  The callback will be invoked before the hosting view's own
14593     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14594     * onDrag(event) behavior, it should return 'false' from this callback.
14595     *
14596     * <div class="special reference">
14597     * <h3>Developer Guides</h3>
14598     * <p>For a guide to implementing drag and drop features, read the
14599     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14600     * </div>
14601     */
14602    public interface OnDragListener {
14603        /**
14604         * Called when a drag event is dispatched to a view. This allows listeners
14605         * to get a chance to override base View behavior.
14606         *
14607         * @param v The View that received the drag event.
14608         * @param event The {@link android.view.DragEvent} object for the drag event.
14609         * @return {@code true} if the drag event was handled successfully, or {@code false}
14610         * if the drag event was not handled. Note that {@code false} will trigger the View
14611         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14612         */
14613        boolean onDrag(View v, DragEvent event);
14614    }
14615
14616    /**
14617     * Interface definition for a callback to be invoked when the focus state of
14618     * a view changed.
14619     */
14620    public interface OnFocusChangeListener {
14621        /**
14622         * Called when the focus state of a view has changed.
14623         *
14624         * @param v The view whose state has changed.
14625         * @param hasFocus The new focus state of v.
14626         */
14627        void onFocusChange(View v, boolean hasFocus);
14628    }
14629
14630    /**
14631     * Interface definition for a callback to be invoked when a view is clicked.
14632     */
14633    public interface OnClickListener {
14634        /**
14635         * Called when a view has been clicked.
14636         *
14637         * @param v The view that was clicked.
14638         */
14639        void onClick(View v);
14640    }
14641
14642    /**
14643     * Interface definition for a callback to be invoked when the context menu
14644     * for this view is being built.
14645     */
14646    public interface OnCreateContextMenuListener {
14647        /**
14648         * Called when the context menu for this view is being built. It is not
14649         * safe to hold onto the menu after this method returns.
14650         *
14651         * @param menu The context menu that is being built
14652         * @param v The view for which the context menu is being built
14653         * @param menuInfo Extra information about the item for which the
14654         *            context menu should be shown. This information will vary
14655         *            depending on the class of v.
14656         */
14657        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14658    }
14659
14660    /**
14661     * Interface definition for a callback to be invoked when the status bar changes
14662     * visibility.  This reports <strong>global</strong> changes to the system UI
14663     * state, not just what the application is requesting.
14664     *
14665     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14666     */
14667    public interface OnSystemUiVisibilityChangeListener {
14668        /**
14669         * Called when the status bar changes visibility because of a call to
14670         * {@link View#setSystemUiVisibility(int)}.
14671         *
14672         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14673         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
14674         * <strong>global</strong> state of the UI visibility flags, not what your
14675         * app is currently applying.
14676         */
14677        public void onSystemUiVisibilityChange(int visibility);
14678    }
14679
14680    /**
14681     * Interface definition for a callback to be invoked when this view is attached
14682     * or detached from its window.
14683     */
14684    public interface OnAttachStateChangeListener {
14685        /**
14686         * Called when the view is attached to a window.
14687         * @param v The view that was attached
14688         */
14689        public void onViewAttachedToWindow(View v);
14690        /**
14691         * Called when the view is detached from a window.
14692         * @param v The view that was detached
14693         */
14694        public void onViewDetachedFromWindow(View v);
14695    }
14696
14697    private final class UnsetPressedState implements Runnable {
14698        public void run() {
14699            setPressed(false);
14700        }
14701    }
14702
14703    /**
14704     * Base class for derived classes that want to save and restore their own
14705     * state in {@link android.view.View#onSaveInstanceState()}.
14706     */
14707    public static class BaseSavedState extends AbsSavedState {
14708        /**
14709         * Constructor used when reading from a parcel. Reads the state of the superclass.
14710         *
14711         * @param source
14712         */
14713        public BaseSavedState(Parcel source) {
14714            super(source);
14715        }
14716
14717        /**
14718         * Constructor called by derived classes when creating their SavedState objects
14719         *
14720         * @param superState The state of the superclass of this view
14721         */
14722        public BaseSavedState(Parcelable superState) {
14723            super(superState);
14724        }
14725
14726        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14727                new Parcelable.Creator<BaseSavedState>() {
14728            public BaseSavedState createFromParcel(Parcel in) {
14729                return new BaseSavedState(in);
14730            }
14731
14732            public BaseSavedState[] newArray(int size) {
14733                return new BaseSavedState[size];
14734            }
14735        };
14736    }
14737
14738    /**
14739     * A set of information given to a view when it is attached to its parent
14740     * window.
14741     */
14742    static class AttachInfo {
14743        interface Callbacks {
14744            void playSoundEffect(int effectId);
14745            boolean performHapticFeedback(int effectId, boolean always);
14746        }
14747
14748        /**
14749         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14750         * to a Handler. This class contains the target (View) to invalidate and
14751         * the coordinates of the dirty rectangle.
14752         *
14753         * For performance purposes, this class also implements a pool of up to
14754         * POOL_LIMIT objects that get reused. This reduces memory allocations
14755         * whenever possible.
14756         */
14757        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14758            private static final int POOL_LIMIT = 10;
14759            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14760                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14761                        public InvalidateInfo newInstance() {
14762                            return new InvalidateInfo();
14763                        }
14764
14765                        public void onAcquired(InvalidateInfo element) {
14766                        }
14767
14768                        public void onReleased(InvalidateInfo element) {
14769                            element.target = null;
14770                        }
14771                    }, POOL_LIMIT)
14772            );
14773
14774            private InvalidateInfo mNext;
14775            private boolean mIsPooled;
14776
14777            View target;
14778
14779            int left;
14780            int top;
14781            int right;
14782            int bottom;
14783
14784            public void setNextPoolable(InvalidateInfo element) {
14785                mNext = element;
14786            }
14787
14788            public InvalidateInfo getNextPoolable() {
14789                return mNext;
14790            }
14791
14792            static InvalidateInfo acquire() {
14793                return sPool.acquire();
14794            }
14795
14796            void release() {
14797                sPool.release(this);
14798            }
14799
14800            public boolean isPooled() {
14801                return mIsPooled;
14802            }
14803
14804            public void setPooled(boolean isPooled) {
14805                mIsPooled = isPooled;
14806            }
14807        }
14808
14809        final IWindowSession mSession;
14810
14811        final IWindow mWindow;
14812
14813        final IBinder mWindowToken;
14814
14815        final Callbacks mRootCallbacks;
14816
14817        HardwareCanvas mHardwareCanvas;
14818
14819        /**
14820         * The top view of the hierarchy.
14821         */
14822        View mRootView;
14823
14824        IBinder mPanelParentWindowToken;
14825        Surface mSurface;
14826
14827        boolean mHardwareAccelerated;
14828        boolean mHardwareAccelerationRequested;
14829        HardwareRenderer mHardwareRenderer;
14830
14831        /**
14832         * Scale factor used by the compatibility mode
14833         */
14834        float mApplicationScale;
14835
14836        /**
14837         * Indicates whether the application is in compatibility mode
14838         */
14839        boolean mScalingRequired;
14840
14841        /**
14842         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14843         */
14844        boolean mTurnOffWindowResizeAnim;
14845
14846        /**
14847         * Left position of this view's window
14848         */
14849        int mWindowLeft;
14850
14851        /**
14852         * Top position of this view's window
14853         */
14854        int mWindowTop;
14855
14856        /**
14857         * Indicates whether views need to use 32-bit drawing caches
14858         */
14859        boolean mUse32BitDrawingCache;
14860
14861        /**
14862         * For windows that are full-screen but using insets to layout inside
14863         * of the screen decorations, these are the current insets for the
14864         * content of the window.
14865         */
14866        final Rect mContentInsets = new Rect();
14867
14868        /**
14869         * For windows that are full-screen but using insets to layout inside
14870         * of the screen decorations, these are the current insets for the
14871         * actual visible parts of the window.
14872         */
14873        final Rect mVisibleInsets = new Rect();
14874
14875        /**
14876         * The internal insets given by this window.  This value is
14877         * supplied by the client (through
14878         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14879         * be given to the window manager when changed to be used in laying
14880         * out windows behind it.
14881         */
14882        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14883                = new ViewTreeObserver.InternalInsetsInfo();
14884
14885        /**
14886         * All views in the window's hierarchy that serve as scroll containers,
14887         * used to determine if the window can be resized or must be panned
14888         * to adjust for a soft input area.
14889         */
14890        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14891
14892        final KeyEvent.DispatcherState mKeyDispatchState
14893                = new KeyEvent.DispatcherState();
14894
14895        /**
14896         * Indicates whether the view's window currently has the focus.
14897         */
14898        boolean mHasWindowFocus;
14899
14900        /**
14901         * The current visibility of the window.
14902         */
14903        int mWindowVisibility;
14904
14905        /**
14906         * Indicates the time at which drawing started to occur.
14907         */
14908        long mDrawingTime;
14909
14910        /**
14911         * Indicates whether or not ignoring the DIRTY_MASK flags.
14912         */
14913        boolean mIgnoreDirtyState;
14914
14915        /**
14916         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14917         * to avoid clearing that flag prematurely.
14918         */
14919        boolean mSetIgnoreDirtyState = false;
14920
14921        /**
14922         * Indicates whether the view's window is currently in touch mode.
14923         */
14924        boolean mInTouchMode;
14925
14926        /**
14927         * Indicates that ViewAncestor should trigger a global layout change
14928         * the next time it performs a traversal
14929         */
14930        boolean mRecomputeGlobalAttributes;
14931
14932        /**
14933         * Always report new attributes at next traversal.
14934         */
14935        boolean mForceReportNewAttributes;
14936
14937        /**
14938         * Set during a traveral if any views want to keep the screen on.
14939         */
14940        boolean mKeepScreenOn;
14941
14942        /**
14943         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14944         */
14945        int mSystemUiVisibility;
14946
14947        /**
14948         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14949         * attached.
14950         */
14951        boolean mHasSystemUiListeners;
14952
14953        /**
14954         * Set if the visibility of any views has changed.
14955         */
14956        boolean mViewVisibilityChanged;
14957
14958        /**
14959         * Set to true if a view has been scrolled.
14960         */
14961        boolean mViewScrollChanged;
14962
14963        /**
14964         * Global to the view hierarchy used as a temporary for dealing with
14965         * x/y points in the transparent region computations.
14966         */
14967        final int[] mTransparentLocation = new int[2];
14968
14969        /**
14970         * Global to the view hierarchy used as a temporary for dealing with
14971         * x/y points in the ViewGroup.invalidateChild implementation.
14972         */
14973        final int[] mInvalidateChildLocation = new int[2];
14974
14975
14976        /**
14977         * Global to the view hierarchy used as a temporary for dealing with
14978         * x/y location when view is transformed.
14979         */
14980        final float[] mTmpTransformLocation = new float[2];
14981
14982        /**
14983         * The view tree observer used to dispatch global events like
14984         * layout, pre-draw, touch mode change, etc.
14985         */
14986        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14987
14988        /**
14989         * A Canvas used by the view hierarchy to perform bitmap caching.
14990         */
14991        Canvas mCanvas;
14992
14993        /**
14994         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14995         * handler can be used to pump events in the UI events queue.
14996         */
14997        final Handler mHandler;
14998
14999        /**
15000         * Identifier for messages requesting the view to be invalidated.
15001         * Such messages should be sent to {@link #mHandler}.
15002         */
15003        static final int INVALIDATE_MSG = 0x1;
15004
15005        /**
15006         * Identifier for messages requesting the view to invalidate a region.
15007         * Such messages should be sent to {@link #mHandler}.
15008         */
15009        static final int INVALIDATE_RECT_MSG = 0x2;
15010
15011        /**
15012         * Temporary for use in computing invalidate rectangles while
15013         * calling up the hierarchy.
15014         */
15015        final Rect mTmpInvalRect = new Rect();
15016
15017        /**
15018         * Temporary for use in computing hit areas with transformed views
15019         */
15020        final RectF mTmpTransformRect = new RectF();
15021
15022        /**
15023         * Temporary list for use in collecting focusable descendents of a view.
15024         */
15025        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
15026
15027        /**
15028         * The id of the window for accessibility purposes.
15029         */
15030        int mAccessibilityWindowId = View.NO_ID;
15031
15032        /**
15033         * Creates a new set of attachment information with the specified
15034         * events handler and thread.
15035         *
15036         * @param handler the events handler the view must use
15037         */
15038        AttachInfo(IWindowSession session, IWindow window,
15039                Handler handler, Callbacks effectPlayer) {
15040            mSession = session;
15041            mWindow = window;
15042            mWindowToken = window.asBinder();
15043            mHandler = handler;
15044            mRootCallbacks = effectPlayer;
15045        }
15046    }
15047
15048    /**
15049     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15050     * is supported. This avoids keeping too many unused fields in most
15051     * instances of View.</p>
15052     */
15053    private static class ScrollabilityCache implements Runnable {
15054
15055        /**
15056         * Scrollbars are not visible
15057         */
15058        public static final int OFF = 0;
15059
15060        /**
15061         * Scrollbars are visible
15062         */
15063        public static final int ON = 1;
15064
15065        /**
15066         * Scrollbars are fading away
15067         */
15068        public static final int FADING = 2;
15069
15070        public boolean fadeScrollBars;
15071
15072        public int fadingEdgeLength;
15073        public int scrollBarDefaultDelayBeforeFade;
15074        public int scrollBarFadeDuration;
15075
15076        public int scrollBarSize;
15077        public ScrollBarDrawable scrollBar;
15078        public float[] interpolatorValues;
15079        public View host;
15080
15081        public final Paint paint;
15082        public final Matrix matrix;
15083        public Shader shader;
15084
15085        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15086
15087        private static final float[] OPAQUE = { 255 };
15088        private static final float[] TRANSPARENT = { 0.0f };
15089
15090        /**
15091         * When fading should start. This time moves into the future every time
15092         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15093         */
15094        public long fadeStartTime;
15095
15096
15097        /**
15098         * The current state of the scrollbars: ON, OFF, or FADING
15099         */
15100        public int state = OFF;
15101
15102        private int mLastColor;
15103
15104        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15105            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15106            scrollBarSize = configuration.getScaledScrollBarSize();
15107            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15108            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15109
15110            paint = new Paint();
15111            matrix = new Matrix();
15112            // use use a height of 1, and then wack the matrix each time we
15113            // actually use it.
15114            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15115
15116            paint.setShader(shader);
15117            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15118            this.host = host;
15119        }
15120
15121        public void setFadeColor(int color) {
15122            if (color != 0 && color != mLastColor) {
15123                mLastColor = color;
15124                color |= 0xFF000000;
15125
15126                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15127                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15128
15129                paint.setShader(shader);
15130                // Restore the default transfer mode (src_over)
15131                paint.setXfermode(null);
15132            }
15133        }
15134
15135        public void run() {
15136            long now = AnimationUtils.currentAnimationTimeMillis();
15137            if (now >= fadeStartTime) {
15138
15139                // the animation fades the scrollbars out by changing
15140                // the opacity (alpha) from fully opaque to fully
15141                // transparent
15142                int nextFrame = (int) now;
15143                int framesCount = 0;
15144
15145                Interpolator interpolator = scrollBarInterpolator;
15146
15147                // Start opaque
15148                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15149
15150                // End transparent
15151                nextFrame += scrollBarFadeDuration;
15152                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15153
15154                state = FADING;
15155
15156                // Kick off the fade animation
15157                host.invalidate(true);
15158            }
15159        }
15160    }
15161
15162    /**
15163     * Resuable callback for sending
15164     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15165     */
15166    private class SendViewScrolledAccessibilityEvent implements Runnable {
15167        public volatile boolean mIsPending;
15168
15169        public void run() {
15170            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15171            mIsPending = false;
15172        }
15173    }
15174
15175    /**
15176     * <p>
15177     * This class represents a delegate that can be registered in a {@link View}
15178     * to enhance accessibility support via composition rather via inheritance.
15179     * It is specifically targeted to widget developers that extend basic View
15180     * classes i.e. classes in package android.view, that would like their
15181     * applications to be backwards compatible.
15182     * </p>
15183     * <p>
15184     * A scenario in which a developer would like to use an accessibility delegate
15185     * is overriding a method introduced in a later API version then the minimal API
15186     * version supported by the application. For example, the method
15187     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15188     * in API version 4 when the accessibility APIs were first introduced. If a
15189     * developer would like his application to run on API version 4 devices (assuming
15190     * all other APIs used by the application are version 4 or lower) and take advantage
15191     * of this method, instead of overriding the method which would break the application's
15192     * backwards compatibility, he can override the corresponding method in this
15193     * delegate and register the delegate in the target View if the API version of
15194     * the system is high enough i.e. the API version is same or higher to the API
15195     * version that introduced
15196     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15197     * </p>
15198     * <p>
15199     * Here is an example implementation:
15200     * </p>
15201     * <code><pre><p>
15202     * if (Build.VERSION.SDK_INT >= 14) {
15203     *     // If the API version is equal of higher than the version in
15204     *     // which onInitializeAccessibilityNodeInfo was introduced we
15205     *     // register a delegate with a customized implementation.
15206     *     View view = findViewById(R.id.view_id);
15207     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15208     *         public void onInitializeAccessibilityNodeInfo(View host,
15209     *                 AccessibilityNodeInfo info) {
15210     *             // Let the default implementation populate the info.
15211     *             super.onInitializeAccessibilityNodeInfo(host, info);
15212     *             // Set some other information.
15213     *             info.setEnabled(host.isEnabled());
15214     *         }
15215     *     });
15216     * }
15217     * </code></pre></p>
15218     * <p>
15219     * This delegate contains methods that correspond to the accessibility methods
15220     * in View. If a delegate has been specified the implementation in View hands
15221     * off handling to the corresponding method in this delegate. The default
15222     * implementation the delegate methods behaves exactly as the corresponding
15223     * method in View for the case of no accessibility delegate been set. Hence,
15224     * to customize the behavior of a View method, clients can override only the
15225     * corresponding delegate method without altering the behavior of the rest
15226     * accessibility related methods of the host view.
15227     * </p>
15228     */
15229    public static class AccessibilityDelegate {
15230
15231        /**
15232         * Sends an accessibility event of the given type. If accessibility is not
15233         * enabled this method has no effect.
15234         * <p>
15235         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15236         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15237         * been set.
15238         * </p>
15239         *
15240         * @param host The View hosting the delegate.
15241         * @param eventType The type of the event to send.
15242         *
15243         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
15244         */
15245        public void sendAccessibilityEvent(View host, int eventType) {
15246            host.sendAccessibilityEventInternal(eventType);
15247        }
15248
15249        /**
15250         * Sends an accessibility event. This method behaves exactly as
15251         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
15252         * empty {@link AccessibilityEvent} and does not perform a check whether
15253         * accessibility is enabled.
15254         * <p>
15255         * The default implementation behaves as
15256         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15257         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
15258         * the case of no accessibility delegate been set.
15259         * </p>
15260         *
15261         * @param host The View hosting the delegate.
15262         * @param event The event to send.
15263         *
15264         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15265         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15266         */
15267        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
15268            host.sendAccessibilityEventUncheckedInternal(event);
15269        }
15270
15271        /**
15272         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
15273         * to its children for adding their text content to the event.
15274         * <p>
15275         * The default implementation behaves as
15276         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15277         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
15278         * the case of no accessibility delegate been set.
15279         * </p>
15280         *
15281         * @param host The View hosting the delegate.
15282         * @param event The event.
15283         * @return True if the event population was completed.
15284         *
15285         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15286         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15287         */
15288        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15289            return host.dispatchPopulateAccessibilityEventInternal(event);
15290        }
15291
15292        /**
15293         * Gives a chance to the host View to populate the accessibility event with its
15294         * text content.
15295         * <p>
15296         * The default implementation behaves as
15297         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
15298         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
15299         * the case of no accessibility delegate been set.
15300         * </p>
15301         *
15302         * @param host The View hosting the delegate.
15303         * @param event The accessibility event which to populate.
15304         *
15305         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
15306         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
15307         */
15308        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15309            host.onPopulateAccessibilityEventInternal(event);
15310        }
15311
15312        /**
15313         * Initializes an {@link AccessibilityEvent} with information about the
15314         * the host View which is the event source.
15315         * <p>
15316         * The default implementation behaves as
15317         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
15318         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
15319         * the case of no accessibility delegate been set.
15320         * </p>
15321         *
15322         * @param host The View hosting the delegate.
15323         * @param event The event to initialize.
15324         *
15325         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
15326         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
15327         */
15328        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
15329            host.onInitializeAccessibilityEventInternal(event);
15330        }
15331
15332        /**
15333         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
15334         * <p>
15335         * The default implementation behaves as
15336         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15337         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
15338         * the case of no accessibility delegate been set.
15339         * </p>
15340         *
15341         * @param host The View hosting the delegate.
15342         * @param info The instance to initialize.
15343         *
15344         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15345         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15346         */
15347        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
15348            host.onInitializeAccessibilityNodeInfoInternal(info);
15349        }
15350
15351        /**
15352         * Called when a child of the host View has requested sending an
15353         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
15354         * to augment the event.
15355         * <p>
15356         * The default implementation behaves as
15357         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15358         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15359         * the case of no accessibility delegate been set.
15360         * </p>
15361         *
15362         * @param host The View hosting the delegate.
15363         * @param child The child which requests sending the event.
15364         * @param event The event to be sent.
15365         * @return True if the event should be sent
15366         *
15367         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15368         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15369         */
15370        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15371                AccessibilityEvent event) {
15372            return host.onRequestSendAccessibilityEventInternal(child, event);
15373        }
15374
15375        /**
15376         * Gets the provider for managing a virtual view hierarchy rooted at this View
15377         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15378         * that explore the window content.
15379         * <p>
15380         * The default implementation behaves as
15381         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15382         * the case of no accessibility delegate been set.
15383         * </p>
15384         *
15385         * @return The provider.
15386         *
15387         * @see AccessibilityNodeProvider
15388         */
15389        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15390            return null;
15391        }
15392    }
15393}
15394