View.java revision 9920f4fdeaa3a4c597f62c3d082becc48ea8a7ab
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.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.inputmethod.EditorInfo;
68import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
70import android.widget.ScrollBarDrawable;
71
72import static android.os.Build.VERSION_CODES.*;
73
74import com.android.internal.R;
75import com.android.internal.util.Predicate;
76import com.android.internal.view.menu.MenuBuilder;
77
78import java.lang.ref.WeakReference;
79import java.lang.reflect.InvocationTargetException;
80import java.lang.reflect.Method;
81import java.util.ArrayList;
82import java.util.Arrays;
83import java.util.Locale;
84import java.util.concurrent.CopyOnWriteArrayList;
85
86/**
87 * <p>
88 * This class represents the basic building block for user interface components. A View
89 * occupies a rectangular area on the screen and is responsible for drawing and
90 * event handling. View is the base class for <em>widgets</em>, which are
91 * used to create interactive UI components (buttons, text fields, etc.). The
92 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
93 * are invisible containers that hold other Views (or other ViewGroups) and define
94 * their layout properties.
95 * </p>
96 *
97 * <div class="special reference">
98 * <h3>Developer Guides</h3>
99 * <p>For information about using this class to develop your application's user interface,
100 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
101 * </div>
102 *
103 * <a name="Using"></a>
104 * <h3>Using Views</h3>
105 * <p>
106 * All of the views in a window are arranged in a single tree. You can add views
107 * either from code or by specifying a tree of views in one or more XML layout
108 * files. There are many specialized subclasses of views that act as controls or
109 * are capable of displaying text, images, or other content.
110 * </p>
111 * <p>
112 * Once you have created a tree of views, there are typically a few types of
113 * common operations you may wish to perform:
114 * <ul>
115 * <li><strong>Set properties:</strong> for example setting the text of a
116 * {@link android.widget.TextView}. The available properties and the methods
117 * that set them will vary among the different subclasses of views. Note that
118 * properties that are known at build time can be set in the XML layout
119 * files.</li>
120 * <li><strong>Set focus:</strong> The framework will handled moving focus in
121 * response to user input. To force focus to a specific view, call
122 * {@link #requestFocus}.</li>
123 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
124 * that will be notified when something interesting happens to the view. For
125 * example, all views will let you set a listener to be notified when the view
126 * gains or loses focus. You can register such a listener using
127 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
128 * Other view subclasses offer more specialized listeners. For example, a Button
129 * exposes a listener to notify clients when the button is clicked.</li>
130 * <li><strong>Set visibility:</strong> You can hide or show views using
131 * {@link #setVisibility(int)}.</li>
132 * </ul>
133 * </p>
134 * <p><em>
135 * Note: The Android framework is responsible for measuring, laying out and
136 * drawing views. You should not call methods that perform these actions on
137 * views yourself unless you are actually implementing a
138 * {@link android.view.ViewGroup}.
139 * </em></p>
140 *
141 * <a name="Lifecycle"></a>
142 * <h3>Implementing a Custom View</h3>
143 *
144 * <p>
145 * To implement a custom view, you will usually begin by providing overrides for
146 * some of the standard methods that the framework calls on all views. You do
147 * not need to override all of these methods. In fact, you can start by just
148 * overriding {@link #onDraw(android.graphics.Canvas)}.
149 * <table border="2" width="85%" align="center" cellpadding="5">
150 *     <thead>
151 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
152 *     </thead>
153 *
154 *     <tbody>
155 *     <tr>
156 *         <td rowspan="2">Creation</td>
157 *         <td>Constructors</td>
158 *         <td>There is a form of the constructor that are called when the view
159 *         is created from code and a form that is called when the view is
160 *         inflated from a layout file. The second form should parse and apply
161 *         any attributes defined in the layout file.
162 *         </td>
163 *     </tr>
164 *     <tr>
165 *         <td><code>{@link #onFinishInflate()}</code></td>
166 *         <td>Called after a view and all of its children has been inflated
167 *         from XML.</td>
168 *     </tr>
169 *
170 *     <tr>
171 *         <td rowspan="3">Layout</td>
172 *         <td><code>{@link #onMeasure(int, int)}</code></td>
173 *         <td>Called to determine the size requirements for this view and all
174 *         of its children.
175 *         </td>
176 *     </tr>
177 *     <tr>
178 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
179 *         <td>Called when this view should assign a size and position to all
180 *         of its children.
181 *         </td>
182 *     </tr>
183 *     <tr>
184 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
185 *         <td>Called when the size of this view has changed.
186 *         </td>
187 *     </tr>
188 *
189 *     <tr>
190 *         <td>Drawing</td>
191 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
192 *         <td>Called when the view should render its content.
193 *         </td>
194 *     </tr>
195 *
196 *     <tr>
197 *         <td rowspan="4">Event processing</td>
198 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
199 *         <td>Called when a new key event occurs.
200 *         </td>
201 *     </tr>
202 *     <tr>
203 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
204 *         <td>Called when a key up event occurs.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
209 *         <td>Called when a trackball motion event occurs.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
214 *         <td>Called when a touch screen motion event occurs.
215 *         </td>
216 *     </tr>
217 *
218 *     <tr>
219 *         <td rowspan="2">Focus</td>
220 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
221 *         <td>Called when the view gains or loses focus.
222 *         </td>
223 *     </tr>
224 *
225 *     <tr>
226 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
227 *         <td>Called when the window containing the view gains or loses focus.
228 *         </td>
229 *     </tr>
230 *
231 *     <tr>
232 *         <td rowspan="3">Attaching</td>
233 *         <td><code>{@link #onAttachedToWindow()}</code></td>
234 *         <td>Called when the view is attached to a window.
235 *         </td>
236 *     </tr>
237 *
238 *     <tr>
239 *         <td><code>{@link #onDetachedFromWindow}</code></td>
240 *         <td>Called when the view is detached from its window.
241 *         </td>
242 *     </tr>
243 *
244 *     <tr>
245 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
246 *         <td>Called when the visibility of the window containing the view
247 *         has changed.
248 *         </td>
249 *     </tr>
250 *     </tbody>
251 *
252 * </table>
253 * </p>
254 *
255 * <a name="IDs"></a>
256 * <h3>IDs</h3>
257 * Views may have an integer id associated with them. These ids are typically
258 * assigned in the layout XML files, and are used to find specific views within
259 * the view tree. A common pattern is to:
260 * <ul>
261 * <li>Define a Button in the layout file and assign it a unique ID.
262 * <pre>
263 * &lt;Button
264 *     android:id="@+id/my_button"
265 *     android:layout_width="wrap_content"
266 *     android:layout_height="wrap_content"
267 *     android:text="@string/my_button_text"/&gt;
268 * </pre></li>
269 * <li>From the onCreate method of an Activity, find the Button
270 * <pre class="prettyprint">
271 *      Button myButton = (Button) findViewById(R.id.my_button);
272 * </pre></li>
273 * </ul>
274 * <p>
275 * View IDs need not be unique throughout the tree, but it is good practice to
276 * ensure that they are at least unique within the part of the tree you are
277 * searching.
278 * </p>
279 *
280 * <a name="Position"></a>
281 * <h3>Position</h3>
282 * <p>
283 * The geometry of a view is that of a rectangle. A view has a location,
284 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
285 * two dimensions, expressed as a width and a height. The unit for location
286 * and dimensions is the pixel.
287 * </p>
288 *
289 * <p>
290 * It is possible to retrieve the location of a view by invoking the methods
291 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
292 * coordinate of the rectangle representing the view. The latter returns the
293 * top, or Y, coordinate of the rectangle representing the view. These methods
294 * both return the location of the view relative to its parent. For instance,
295 * when getLeft() returns 20, that means the view is located 20 pixels to the
296 * right of the left edge of its direct parent.
297 * </p>
298 *
299 * <p>
300 * In addition, several convenience methods are offered to avoid unnecessary
301 * computations, namely {@link #getRight()} and {@link #getBottom()}.
302 * These methods return the coordinates of the right and bottom edges of the
303 * rectangle representing the view. For instance, calling {@link #getRight()}
304 * is similar to the following computation: <code>getLeft() + getWidth()</code>
305 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
306 * </p>
307 *
308 * <a name="SizePaddingMargins"></a>
309 * <h3>Size, padding and margins</h3>
310 * <p>
311 * The size of a view is expressed with a width and a height. A view actually
312 * possess two pairs of width and height values.
313 * </p>
314 *
315 * <p>
316 * The first pair is known as <em>measured width</em> and
317 * <em>measured height</em>. These dimensions define how big a view wants to be
318 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
319 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
320 * and {@link #getMeasuredHeight()}.
321 * </p>
322 *
323 * <p>
324 * The second pair is simply known as <em>width</em> and <em>height</em>, or
325 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
326 * dimensions define the actual size of the view on screen, at drawing time and
327 * after layout. These values may, but do not have to, be different from the
328 * measured width and height. The width and height can be obtained by calling
329 * {@link #getWidth()} and {@link #getHeight()}.
330 * </p>
331 *
332 * <p>
333 * To measure its dimensions, a view takes into account its padding. The padding
334 * is expressed in pixels for the left, top, right and bottom parts of the view.
335 * Padding can be used to offset the content of the view by a specific amount of
336 * pixels. For instance, a left padding of 2 will push the view's content by
337 * 2 pixels to the right of the left edge. Padding can be set using the
338 * {@link #setPadding(int, int, int, int)} method and queried by calling
339 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
340 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
341 * </p>
342 *
343 * <p>
344 * Even though a view can define a padding, it does not provide any support for
345 * margins. However, view groups provide such a support. Refer to
346 * {@link android.view.ViewGroup} and
347 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
348 * </p>
349 *
350 * <a name="Layout"></a>
351 * <h3>Layout</h3>
352 * <p>
353 * Layout is a two pass process: a measure pass and a layout pass. The measuring
354 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
355 * of the view tree. Each view pushes dimension specifications down the tree
356 * during the recursion. At the end of the measure pass, every view has stored
357 * its measurements. The second pass happens in
358 * {@link #layout(int,int,int,int)} and is also top-down. During
359 * this pass each parent is responsible for positioning all of its children
360 * using the sizes computed in the measure pass.
361 * </p>
362 *
363 * <p>
364 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
365 * {@link #getMeasuredHeight()} values must be set, along with those for all of
366 * that view's descendants. A view's measured width and measured height values
367 * must respect the constraints imposed by the view's parents. This guarantees
368 * that at the end of the measure pass, all parents accept all of their
369 * children's measurements. A parent view may call measure() more than once on
370 * its children. For example, the parent may measure each child once with
371 * unspecified dimensions to find out how big they want to be, then call
372 * measure() on them again with actual numbers if the sum of all the children's
373 * unconstrained sizes is too big or too small.
374 * </p>
375 *
376 * <p>
377 * The measure pass uses two classes to communicate dimensions. The
378 * {@link MeasureSpec} class is used by views to tell their parents how they
379 * want to be measured and positioned. The base LayoutParams class just
380 * describes how big the view wants to be for both width and height. For each
381 * dimension, it can specify one of:
382 * <ul>
383 * <li> an exact number
384 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
385 * (minus padding)
386 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
387 * enclose its content (plus padding).
388 * </ul>
389 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
390 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
391 * an X and Y value.
392 * </p>
393 *
394 * <p>
395 * MeasureSpecs are used to push requirements down the tree from parent to
396 * child. A MeasureSpec can be in one of three modes:
397 * <ul>
398 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
399 * of a child view. For example, a LinearLayout may call measure() on its child
400 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
401 * tall the child view wants to be given a width of 240 pixels.
402 * <li>EXACTLY: This is used by the parent to impose an exact size on the
403 * child. The child must use this size, and guarantee that all of its
404 * descendants will fit within this size.
405 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
406 * child. The child must gurantee that it and all of its descendants will fit
407 * within this size.
408 * </ul>
409 * </p>
410 *
411 * <p>
412 * To intiate a layout, call {@link #requestLayout}. This method is typically
413 * called by a view on itself when it believes that is can no longer fit within
414 * its current bounds.
415 * </p>
416 *
417 * <a name="Drawing"></a>
418 * <h3>Drawing</h3>
419 * <p>
420 * Drawing is handled by walking the tree and rendering each view that
421 * intersects the the invalid region. Because the tree is traversed in-order,
422 * this means that parents will draw before (i.e., behind) their children, with
423 * siblings drawn in the order they appear in the tree.
424 * If you set a background drawable for a View, then the View will draw it for you
425 * before calling back to its <code>onDraw()</code> method.
426 * </p>
427 *
428 * <p>
429 * Note that the framework will not draw views that are not in the invalid region.
430 * </p>
431 *
432 * <p>
433 * To force a view to draw, call {@link #invalidate()}.
434 * </p>
435 *
436 * <a name="EventHandlingThreading"></a>
437 * <h3>Event Handling and Threading</h3>
438 * <p>
439 * The basic cycle of a view is as follows:
440 * <ol>
441 * <li>An event comes in and is dispatched to the appropriate view. The view
442 * handles the event and notifies any listeners.</li>
443 * <li>If in the course of processing the event, the view's bounds may need
444 * to be changed, the view will call {@link #requestLayout()}.</li>
445 * <li>Similarly, if in the course of processing the event the view's appearance
446 * may need to be changed, the view will call {@link #invalidate()}.</li>
447 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
448 * the framework will take care of measuring, laying out, and drawing the tree
449 * as appropriate.</li>
450 * </ol>
451 * </p>
452 *
453 * <p><em>Note: The entire view tree is single threaded. You must always be on
454 * the UI thread when calling any method on any view.</em>
455 * If you are doing work on other threads and want to update the state of a view
456 * from that thread, you should use a {@link Handler}.
457 * </p>
458 *
459 * <a name="FocusHandling"></a>
460 * <h3>Focus Handling</h3>
461 * <p>
462 * The framework will handle routine focus movement in response to user input.
463 * This includes changing the focus as views are removed or hidden, or as new
464 * views become available. Views indicate their willingness to take focus
465 * through the {@link #isFocusable} method. To change whether a view can take
466 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
467 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
468 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
469 * </p>
470 * <p>
471 * Focus movement is based on an algorithm which finds the nearest neighbor in a
472 * given direction. In rare cases, the default algorithm may not match the
473 * intended behavior of the developer. In these situations, you can provide
474 * explicit overrides by using these XML attributes in the layout file:
475 * <pre>
476 * nextFocusDown
477 * nextFocusLeft
478 * nextFocusRight
479 * nextFocusUp
480 * </pre>
481 * </p>
482 *
483 *
484 * <p>
485 * To get a particular view to take focus, call {@link #requestFocus()}.
486 * </p>
487 *
488 * <a name="TouchMode"></a>
489 * <h3>Touch Mode</h3>
490 * <p>
491 * When a user is navigating a user interface via directional keys such as a D-pad, it is
492 * necessary to give focus to actionable items such as buttons so the user can see
493 * what will take input.  If the device has touch capabilities, however, and the user
494 * begins interacting with the interface by touching it, it is no longer necessary to
495 * always highlight, or give focus to, a particular view.  This motivates a mode
496 * for interaction named 'touch mode'.
497 * </p>
498 * <p>
499 * For a touch capable device, once the user touches the screen, the device
500 * will enter touch mode.  From this point onward, only views for which
501 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
502 * Other views that are touchable, like buttons, will not take focus when touched; they will
503 * only fire the on click listeners.
504 * </p>
505 * <p>
506 * Any time a user hits a directional key, such as a D-pad direction, the view device will
507 * exit touch mode, and find a view to take focus, so that the user may resume interacting
508 * with the user interface without touching the screen again.
509 * </p>
510 * <p>
511 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
512 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
513 * </p>
514 *
515 * <a name="Scrolling"></a>
516 * <h3>Scrolling</h3>
517 * <p>
518 * The framework provides basic support for views that wish to internally
519 * scroll their content. This includes keeping track of the X and Y scroll
520 * offset as well as mechanisms for drawing scrollbars. See
521 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
522 * {@link #awakenScrollBars()} for more details.
523 * </p>
524 *
525 * <a name="Tags"></a>
526 * <h3>Tags</h3>
527 * <p>
528 * Unlike IDs, tags are not used to identify views. Tags are essentially an
529 * extra piece of information that can be associated with a view. They are most
530 * often used as a convenience to store data related to views in the views
531 * themselves rather than by putting them in a separate structure.
532 * </p>
533 *
534 * <a name="Animation"></a>
535 * <h3>Animation</h3>
536 * <p>
537 * You can attach an {@link Animation} object to a view using
538 * {@link #setAnimation(Animation)} or
539 * {@link #startAnimation(Animation)}. The animation can alter the scale,
540 * rotation, translation and alpha of a view over time. If the animation is
541 * attached to a view that has children, the animation will affect the entire
542 * subtree rooted by that node. When an animation is started, the framework will
543 * take care of redrawing the appropriate views until the animation completes.
544 * </p>
545 * <p>
546 * Starting with Android 3.0, the preferred way of animating views is to use the
547 * {@link android.animation} package APIs.
548 * </p>
549 *
550 * <a name="Security"></a>
551 * <h3>Security</h3>
552 * <p>
553 * Sometimes it is essential that an application be able to verify that an action
554 * is being performed with the full knowledge and consent of the user, such as
555 * granting a permission request, making a purchase or clicking on an advertisement.
556 * Unfortunately, a malicious application could try to spoof the user into
557 * performing these actions, unaware, by concealing the intended purpose of the view.
558 * As a remedy, the framework offers a touch filtering mechanism that can be used to
559 * improve the security of views that provide access to sensitive functionality.
560 * </p><p>
561 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
562 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
563 * will discard touches that are received whenever the view's window is obscured by
564 * another visible window.  As a result, the view will not receive touches whenever a
565 * toast, dialog or other window appears above the view's window.
566 * </p><p>
567 * For more fine-grained control over security, consider overriding the
568 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
569 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
570 * </p>
571 *
572 * @attr ref android.R.styleable#View_alpha
573 * @attr ref android.R.styleable#View_background
574 * @attr ref android.R.styleable#View_clickable
575 * @attr ref android.R.styleable#View_contentDescription
576 * @attr ref android.R.styleable#View_drawingCacheQuality
577 * @attr ref android.R.styleable#View_duplicateParentState
578 * @attr ref android.R.styleable#View_id
579 * @attr ref android.R.styleable#View_requiresFadingEdge
580 * @attr ref android.R.styleable#View_fadingEdgeLength
581 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
582 * @attr ref android.R.styleable#View_fitsSystemWindows
583 * @attr ref android.R.styleable#View_isScrollContainer
584 * @attr ref android.R.styleable#View_focusable
585 * @attr ref android.R.styleable#View_focusableInTouchMode
586 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
587 * @attr ref android.R.styleable#View_keepScreenOn
588 * @attr ref android.R.styleable#View_layerType
589 * @attr ref android.R.styleable#View_longClickable
590 * @attr ref android.R.styleable#View_minHeight
591 * @attr ref android.R.styleable#View_minWidth
592 * @attr ref android.R.styleable#View_nextFocusDown
593 * @attr ref android.R.styleable#View_nextFocusLeft
594 * @attr ref android.R.styleable#View_nextFocusRight
595 * @attr ref android.R.styleable#View_nextFocusUp
596 * @attr ref android.R.styleable#View_onClick
597 * @attr ref android.R.styleable#View_padding
598 * @attr ref android.R.styleable#View_paddingBottom
599 * @attr ref android.R.styleable#View_paddingLeft
600 * @attr ref android.R.styleable#View_paddingRight
601 * @attr ref android.R.styleable#View_paddingTop
602 * @attr ref android.R.styleable#View_saveEnabled
603 * @attr ref android.R.styleable#View_rotation
604 * @attr ref android.R.styleable#View_rotationX
605 * @attr ref android.R.styleable#View_rotationY
606 * @attr ref android.R.styleable#View_scaleX
607 * @attr ref android.R.styleable#View_scaleY
608 * @attr ref android.R.styleable#View_scrollX
609 * @attr ref android.R.styleable#View_scrollY
610 * @attr ref android.R.styleable#View_scrollbarSize
611 * @attr ref android.R.styleable#View_scrollbarStyle
612 * @attr ref android.R.styleable#View_scrollbars
613 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
614 * @attr ref android.R.styleable#View_scrollbarFadeDuration
615 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
616 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
617 * @attr ref android.R.styleable#View_scrollbarThumbVertical
618 * @attr ref android.R.styleable#View_scrollbarTrackVertical
619 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
620 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
621 * @attr ref android.R.styleable#View_soundEffectsEnabled
622 * @attr ref android.R.styleable#View_tag
623 * @attr ref android.R.styleable#View_transformPivotX
624 * @attr ref android.R.styleable#View_transformPivotY
625 * @attr ref android.R.styleable#View_translationX
626 * @attr ref android.R.styleable#View_translationY
627 * @attr ref android.R.styleable#View_visibility
628 *
629 * @see android.view.ViewGroup
630 */
631public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
632        AccessibilityEventSource {
633    private static final boolean DBG = false;
634
635    /**
636     * The logging tag used by this class with android.util.Log.
637     */
638    protected static final String VIEW_LOG_TAG = "View";
639
640    /**
641     * Used to mark a View that has no ID.
642     */
643    public static final int NO_ID = -1;
644
645    /**
646     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
647     * calling setFlags.
648     */
649    private static final int NOT_FOCUSABLE = 0x00000000;
650
651    /**
652     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
653     * setFlags.
654     */
655    private static final int FOCUSABLE = 0x00000001;
656
657    /**
658     * Mask for use with setFlags indicating bits used for focus.
659     */
660    private static final int FOCUSABLE_MASK = 0x00000001;
661
662    /**
663     * This view will adjust its padding to fit sytem windows (e.g. status bar)
664     */
665    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
666
667    /**
668     * This view is visible.
669     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
670     * android:visibility}.
671     */
672    public static final int VISIBLE = 0x00000000;
673
674    /**
675     * This view is invisible, but it still takes up space for layout purposes.
676     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
677     * android:visibility}.
678     */
679    public static final int INVISIBLE = 0x00000004;
680
681    /**
682     * This view is invisible, and it doesn't take any space for layout
683     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
684     * android:visibility}.
685     */
686    public static final int GONE = 0x00000008;
687
688    /**
689     * Mask for use with setFlags indicating bits used for visibility.
690     * {@hide}
691     */
692    static final int VISIBILITY_MASK = 0x0000000C;
693
694    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
695
696    /**
697     * This view is enabled. Intrepretation varies by subclass.
698     * Use with ENABLED_MASK when calling setFlags.
699     * {@hide}
700     */
701    static final int ENABLED = 0x00000000;
702
703    /**
704     * This view is disabled. Intrepretation varies by subclass.
705     * Use with ENABLED_MASK when calling setFlags.
706     * {@hide}
707     */
708    static final int DISABLED = 0x00000020;
709
710   /**
711    * Mask for use with setFlags indicating bits used for indicating whether
712    * this view is enabled
713    * {@hide}
714    */
715    static final int ENABLED_MASK = 0x00000020;
716
717    /**
718     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
719     * called and further optimizations will be performed. It is okay to have
720     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
721     * {@hide}
722     */
723    static final int WILL_NOT_DRAW = 0x00000080;
724
725    /**
726     * Mask for use with setFlags indicating bits used for indicating whether
727     * this view is will draw
728     * {@hide}
729     */
730    static final int DRAW_MASK = 0x00000080;
731
732    /**
733     * <p>This view doesn't show scrollbars.</p>
734     * {@hide}
735     */
736    static final int SCROLLBARS_NONE = 0x00000000;
737
738    /**
739     * <p>This view shows horizontal scrollbars.</p>
740     * {@hide}
741     */
742    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
743
744    /**
745     * <p>This view shows vertical scrollbars.</p>
746     * {@hide}
747     */
748    static final int SCROLLBARS_VERTICAL = 0x00000200;
749
750    /**
751     * <p>Mask for use with setFlags indicating bits used for indicating which
752     * scrollbars are enabled.</p>
753     * {@hide}
754     */
755    static final int SCROLLBARS_MASK = 0x00000300;
756
757    /**
758     * Indicates that the view should filter touches when its window is obscured.
759     * Refer to the class comments for more information about this security feature.
760     * {@hide}
761     */
762    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
763
764    // note flag value 0x00000800 is now available for next flags...
765
766    /**
767     * <p>This view doesn't show fading edges.</p>
768     * {@hide}
769     */
770    static final int FADING_EDGE_NONE = 0x00000000;
771
772    /**
773     * <p>This view shows horizontal fading edges.</p>
774     * {@hide}
775     */
776    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
777
778    /**
779     * <p>This view shows vertical fading edges.</p>
780     * {@hide}
781     */
782    static final int FADING_EDGE_VERTICAL = 0x00002000;
783
784    /**
785     * <p>Mask for use with setFlags indicating bits used for indicating which
786     * fading edges are enabled.</p>
787     * {@hide}
788     */
789    static final int FADING_EDGE_MASK = 0x00003000;
790
791    /**
792     * <p>Indicates this view can be clicked. When clickable, a View reacts
793     * to clicks by notifying the OnClickListener.<p>
794     * {@hide}
795     */
796    static final int CLICKABLE = 0x00004000;
797
798    /**
799     * <p>Indicates this view is caching its drawing into a bitmap.</p>
800     * {@hide}
801     */
802    static final int DRAWING_CACHE_ENABLED = 0x00008000;
803
804    /**
805     * <p>Indicates that no icicle should be saved for this view.<p>
806     * {@hide}
807     */
808    static final int SAVE_DISABLED = 0x000010000;
809
810    /**
811     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
812     * property.</p>
813     * {@hide}
814     */
815    static final int SAVE_DISABLED_MASK = 0x000010000;
816
817    /**
818     * <p>Indicates that no drawing cache should ever be created for this view.<p>
819     * {@hide}
820     */
821    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
822
823    /**
824     * <p>Indicates this view can take / keep focus when int touch mode.</p>
825     * {@hide}
826     */
827    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
828
829    /**
830     * <p>Enables low quality mode for the drawing cache.</p>
831     */
832    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
833
834    /**
835     * <p>Enables high quality mode for the drawing cache.</p>
836     */
837    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
838
839    /**
840     * <p>Enables automatic quality mode for the drawing cache.</p>
841     */
842    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
843
844    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
845            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
846    };
847
848    /**
849     * <p>Mask for use with setFlags indicating bits used for the cache
850     * quality property.</p>
851     * {@hide}
852     */
853    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
854
855    /**
856     * <p>
857     * Indicates this view can be long clicked. When long clickable, a View
858     * reacts to long clicks by notifying the OnLongClickListener or showing a
859     * context menu.
860     * </p>
861     * {@hide}
862     */
863    static final int LONG_CLICKABLE = 0x00200000;
864
865    /**
866     * <p>Indicates that this view gets its drawable states from its direct parent
867     * and ignores its original internal states.</p>
868     *
869     * @hide
870     */
871    static final int DUPLICATE_PARENT_STATE = 0x00400000;
872
873    /**
874     * The scrollbar style to display the scrollbars inside the content area,
875     * without increasing the padding. The scrollbars will be overlaid with
876     * translucency on the view's content.
877     */
878    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
879
880    /**
881     * The scrollbar style to display the scrollbars inside the padded area,
882     * increasing the padding of the view. The scrollbars will not overlap the
883     * content area of the view.
884     */
885    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
886
887    /**
888     * The scrollbar style to display the scrollbars at the edge of the view,
889     * without increasing the padding. The scrollbars will be overlaid with
890     * translucency.
891     */
892    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
893
894    /**
895     * The scrollbar style to display the scrollbars at the edge of the view,
896     * increasing the padding of the view. The scrollbars will only overlap the
897     * background, if any.
898     */
899    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
900
901    /**
902     * Mask to check if the scrollbar style is overlay or inset.
903     * {@hide}
904     */
905    static final int SCROLLBARS_INSET_MASK = 0x01000000;
906
907    /**
908     * Mask to check if the scrollbar style is inside or outside.
909     * {@hide}
910     */
911    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
912
913    /**
914     * Mask for scrollbar style.
915     * {@hide}
916     */
917    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
918
919    /**
920     * View flag indicating that the screen should remain on while the
921     * window containing this view is visible to the user.  This effectively
922     * takes care of automatically setting the WindowManager's
923     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
924     */
925    public static final int KEEP_SCREEN_ON = 0x04000000;
926
927    /**
928     * View flag indicating whether this view should have sound effects enabled
929     * for events such as clicking and touching.
930     */
931    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
932
933    /**
934     * View flag indicating whether this view should have haptic feedback
935     * enabled for events such as long presses.
936     */
937    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
938
939    /**
940     * <p>Indicates that the view hierarchy should stop saving state when
941     * it reaches this view.  If state saving is initiated immediately at
942     * the view, it will be allowed.
943     * {@hide}
944     */
945    static final int PARENT_SAVE_DISABLED = 0x20000000;
946
947    /**
948     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
949     * {@hide}
950     */
951    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
952
953    /**
954     * Horizontal direction of this view is from Left to Right.
955     * Use with {@link #setLayoutDirection}.
956     * {@hide}
957     */
958    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
959
960    /**
961     * Horizontal direction of this view is from Right to Left.
962     * Use with {@link #setLayoutDirection}.
963     * {@hide}
964     */
965    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
966
967    /**
968     * Horizontal direction of this view is inherited from its parent.
969     * Use with {@link #setLayoutDirection}.
970     * {@hide}
971     */
972    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
973
974    /**
975     * Horizontal direction of this view is from deduced from the default language
976     * script for the locale. Use with {@link #setLayoutDirection}.
977     * {@hide}
978     */
979    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
980
981    /**
982     * Mask for use with setFlags indicating bits used for horizontalDirection.
983     * {@hide}
984     */
985    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
986
987    /*
988     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
989     * flag value.
990     * {@hide}
991     */
992    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
993        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
994
995    /**
996     * Default horizontalDirection.
997     * {@hide}
998     */
999    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1000
1001    /**
1002     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1003     * should add all focusable Views regardless if they are focusable in touch mode.
1004     */
1005    public static final int FOCUSABLES_ALL = 0x00000000;
1006
1007    /**
1008     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1009     * should add only Views focusable in touch mode.
1010     */
1011    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1012
1013    /**
1014     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1015     * item.
1016     */
1017    public static final int FOCUS_BACKWARD = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1021     * item.
1022     */
1023    public static final int FOCUS_FORWARD = 0x00000002;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the left.
1027     */
1028    public static final int FOCUS_LEFT = 0x00000011;
1029
1030    /**
1031     * Use with {@link #focusSearch(int)}. Move focus up.
1032     */
1033    public static final int FOCUS_UP = 0x00000021;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the right.
1037     */
1038    public static final int FOCUS_RIGHT = 0x00000042;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus down.
1042     */
1043    public static final int FOCUS_DOWN = 0x00000082;
1044
1045    /**
1046     * Bits of {@link #getMeasuredWidthAndState()} and
1047     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1048     */
1049    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1050
1051    /**
1052     * Bits of {@link #getMeasuredWidthAndState()} and
1053     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1054     */
1055    public static final int MEASURED_STATE_MASK = 0xff000000;
1056
1057    /**
1058     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1059     * for functions that combine both width and height into a single int,
1060     * such as {@link #getMeasuredState()} and the childState argument of
1061     * {@link #resolveSizeAndState(int, int, int)}.
1062     */
1063    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1064
1065    /**
1066     * Bit of {@link #getMeasuredWidthAndState()} and
1067     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1068     * is smaller that the space the view would like to have.
1069     */
1070    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1071
1072    /**
1073     * Base View state sets
1074     */
1075    // Singles
1076    /**
1077     * Indicates the view has no states set. States are used with
1078     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1079     * view depending on its state.
1080     *
1081     * @see android.graphics.drawable.Drawable
1082     * @see #getDrawableState()
1083     */
1084    protected static final int[] EMPTY_STATE_SET;
1085    /**
1086     * Indicates the view is enabled. States are used with
1087     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1088     * view depending on its state.
1089     *
1090     * @see android.graphics.drawable.Drawable
1091     * @see #getDrawableState()
1092     */
1093    protected static final int[] ENABLED_STATE_SET;
1094    /**
1095     * Indicates the view is focused. States are used with
1096     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1097     * view depending on its state.
1098     *
1099     * @see android.graphics.drawable.Drawable
1100     * @see #getDrawableState()
1101     */
1102    protected static final int[] FOCUSED_STATE_SET;
1103    /**
1104     * Indicates the view is selected. States are used with
1105     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1106     * view depending on its state.
1107     *
1108     * @see android.graphics.drawable.Drawable
1109     * @see #getDrawableState()
1110     */
1111    protected static final int[] SELECTED_STATE_SET;
1112    /**
1113     * Indicates the view is pressed. States are used with
1114     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1115     * view depending on its state.
1116     *
1117     * @see android.graphics.drawable.Drawable
1118     * @see #getDrawableState()
1119     * @hide
1120     */
1121    protected static final int[] PRESSED_STATE_SET;
1122    /**
1123     * Indicates the view's window has focus. States are used with
1124     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1125     * view depending on its state.
1126     *
1127     * @see android.graphics.drawable.Drawable
1128     * @see #getDrawableState()
1129     */
1130    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1131    // Doubles
1132    /**
1133     * Indicates the view is enabled and has the focus.
1134     *
1135     * @see #ENABLED_STATE_SET
1136     * @see #FOCUSED_STATE_SET
1137     */
1138    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1139    /**
1140     * Indicates the view is enabled and selected.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #SELECTED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_SELECTED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and that its window has focus.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #WINDOW_FOCUSED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1153    /**
1154     * Indicates the view is focused and selected.
1155     *
1156     * @see #FOCUSED_STATE_SET
1157     * @see #SELECTED_STATE_SET
1158     */
1159    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1160    /**
1161     * Indicates the view has the focus and that its window has the focus.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #WINDOW_FOCUSED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1167    /**
1168     * Indicates the view is selected and that its window has the focus.
1169     *
1170     * @see #SELECTED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1174    // Triples
1175    /**
1176     * Indicates the view is enabled, focused and selected.
1177     *
1178     * @see #ENABLED_STATE_SET
1179     * @see #FOCUSED_STATE_SET
1180     * @see #SELECTED_STATE_SET
1181     */
1182    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1183    /**
1184     * Indicates the view is enabled, focused and its window has the focus.
1185     *
1186     * @see #ENABLED_STATE_SET
1187     * @see #FOCUSED_STATE_SET
1188     * @see #WINDOW_FOCUSED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is enabled, selected and its window has the focus.
1193     *
1194     * @see #ENABLED_STATE_SET
1195     * @see #SELECTED_STATE_SET
1196     * @see #WINDOW_FOCUSED_STATE_SET
1197     */
1198    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1199    /**
1200     * Indicates the view is focused, selected and its window has the focus.
1201     *
1202     * @see #FOCUSED_STATE_SET
1203     * @see #SELECTED_STATE_SET
1204     * @see #WINDOW_FOCUSED_STATE_SET
1205     */
1206    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1207    /**
1208     * Indicates the view is enabled, focused, selected and its window
1209     * has the focus.
1210     *
1211     * @see #ENABLED_STATE_SET
1212     * @see #FOCUSED_STATE_SET
1213     * @see #SELECTED_STATE_SET
1214     * @see #WINDOW_FOCUSED_STATE_SET
1215     */
1216    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1217    /**
1218     * Indicates the view is pressed and its window has the focus.
1219     *
1220     * @see #PRESSED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and selected.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #SELECTED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_SELECTED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed, selected and its window has the focus.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     * @see #WINDOW_FOCUSED_STATE_SET
1237     */
1238    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1239    /**
1240     * Indicates the view is pressed and focused.
1241     *
1242     * @see #PRESSED_STATE_SET
1243     * @see #FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed, focused and its window has the focus.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     * @see #WINDOW_FOCUSED_STATE_SET
1252     */
1253    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1254    /**
1255     * Indicates the view is pressed, focused and selected.
1256     *
1257     * @see #PRESSED_STATE_SET
1258     * @see #SELECTED_STATE_SET
1259     * @see #FOCUSED_STATE_SET
1260     */
1261    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1262    /**
1263     * Indicates the view is pressed, focused, selected and its window has the focus.
1264     *
1265     * @see #PRESSED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     * @see #SELECTED_STATE_SET
1268     * @see #WINDOW_FOCUSED_STATE_SET
1269     */
1270    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1271    /**
1272     * Indicates the view is pressed and enabled.
1273     *
1274     * @see #PRESSED_STATE_SET
1275     * @see #ENABLED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_ENABLED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed, enabled and its window has the focus.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     * @see #WINDOW_FOCUSED_STATE_SET
1284     */
1285    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1286    /**
1287     * Indicates the view is pressed, enabled and selected.
1288     *
1289     * @see #PRESSED_STATE_SET
1290     * @see #ENABLED_STATE_SET
1291     * @see #SELECTED_STATE_SET
1292     */
1293    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1294    /**
1295     * Indicates the view is pressed, enabled, selected and its window has the
1296     * focus.
1297     *
1298     * @see #PRESSED_STATE_SET
1299     * @see #ENABLED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #WINDOW_FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, enabled and focused.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #ENABLED_STATE_SET
1309     * @see #FOCUSED_STATE_SET
1310     */
1311    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1312    /**
1313     * Indicates the view is pressed, enabled, focused and its window has the
1314     * focus.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #ENABLED_STATE_SET
1318     * @see #FOCUSED_STATE_SET
1319     * @see #WINDOW_FOCUSED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed, enabled, focused and selected.
1324     *
1325     * @see #PRESSED_STATE_SET
1326     * @see #ENABLED_STATE_SET
1327     * @see #SELECTED_STATE_SET
1328     * @see #FOCUSED_STATE_SET
1329     */
1330    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1331    /**
1332     * Indicates the view is pressed, enabled, focused, selected and its window
1333     * has the focus.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #ENABLED_STATE_SET
1337     * @see #SELECTED_STATE_SET
1338     * @see #FOCUSED_STATE_SET
1339     * @see #WINDOW_FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1342
1343    /**
1344     * The order here is very important to {@link #getDrawableState()}
1345     */
1346    private static final int[][] VIEW_STATE_SETS;
1347
1348    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1349    static final int VIEW_STATE_SELECTED = 1 << 1;
1350    static final int VIEW_STATE_FOCUSED = 1 << 2;
1351    static final int VIEW_STATE_ENABLED = 1 << 3;
1352    static final int VIEW_STATE_PRESSED = 1 << 4;
1353    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1354    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1355    static final int VIEW_STATE_HOVERED = 1 << 7;
1356    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1357    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1358
1359    static final int[] VIEW_STATE_IDS = new int[] {
1360        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1361        R.attr.state_selected,          VIEW_STATE_SELECTED,
1362        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1363        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1364        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1365        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1366        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1367        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1368        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1369        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1370    };
1371
1372    static {
1373        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1374            throw new IllegalStateException(
1375                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1376        }
1377        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1378        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1379            int viewState = R.styleable.ViewDrawableStates[i];
1380            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1381                if (VIEW_STATE_IDS[j] == viewState) {
1382                    orderedIds[i * 2] = viewState;
1383                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1384                }
1385            }
1386        }
1387        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1388        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1389        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1390            int numBits = Integer.bitCount(i);
1391            int[] set = new int[numBits];
1392            int pos = 0;
1393            for (int j = 0; j < orderedIds.length; j += 2) {
1394                if ((i & orderedIds[j+1]) != 0) {
1395                    set[pos++] = orderedIds[j];
1396                }
1397            }
1398            VIEW_STATE_SETS[i] = set;
1399        }
1400
1401        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1402        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1403        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1404        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1405                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1406        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1407        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1409        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1410                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1411        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1413                | VIEW_STATE_FOCUSED];
1414        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1415        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1417        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1419        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421                | VIEW_STATE_ENABLED];
1422        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1426                | VIEW_STATE_ENABLED];
1427        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1429                | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1432                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1433
1434        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1435        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1436                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1437        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1439        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1441                | VIEW_STATE_PRESSED];
1442        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1446                | VIEW_STATE_PRESSED];
1447        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1449                | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1452                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1453        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1455        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1457                | VIEW_STATE_PRESSED];
1458        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1459                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1460                | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1463                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1472                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1475                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1476                | VIEW_STATE_PRESSED];
1477    }
1478
1479    /**
1480     * Accessibility event types that are dispatched for text population.
1481     */
1482    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1483            AccessibilityEvent.TYPE_VIEW_CLICKED
1484            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1485            | AccessibilityEvent.TYPE_VIEW_SELECTED
1486            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1487            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1488            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1489            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1490            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED;
1491
1492    /**
1493     * Temporary Rect currently for use in setBackground().  This will probably
1494     * be extended in the future to hold our own class with more than just
1495     * a Rect. :)
1496     */
1497    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1498
1499    /**
1500     * Map used to store views' tags.
1501     */
1502    private SparseArray<Object> mKeyedTags;
1503
1504    /**
1505     * The next available accessiiblity id.
1506     */
1507    private static int sNextAccessibilityViewId;
1508
1509    /**
1510     * The animation currently associated with this view.
1511     * @hide
1512     */
1513    protected Animation mCurrentAnimation = null;
1514
1515    /**
1516     * Width as measured during measure pass.
1517     * {@hide}
1518     */
1519    @ViewDebug.ExportedProperty(category = "measurement")
1520    int mMeasuredWidth;
1521
1522    /**
1523     * Height as measured during measure pass.
1524     * {@hide}
1525     */
1526    @ViewDebug.ExportedProperty(category = "measurement")
1527    int mMeasuredHeight;
1528
1529    /**
1530     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1531     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1532     * its display list. This flag, used only when hw accelerated, allows us to clear the
1533     * flag while retaining this information until it's needed (at getDisplayList() time and
1534     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1535     *
1536     * {@hide}
1537     */
1538    boolean mRecreateDisplayList = false;
1539
1540    /**
1541     * The view's identifier.
1542     * {@hide}
1543     *
1544     * @see #setId(int)
1545     * @see #getId()
1546     */
1547    @ViewDebug.ExportedProperty(resolveId = true)
1548    int mID = NO_ID;
1549
1550    /**
1551     * The stable ID of this view for accessibility porposes.
1552     */
1553    int mAccessibilityViewId = NO_ID;
1554
1555    /**
1556     * The view's tag.
1557     * {@hide}
1558     *
1559     * @see #setTag(Object)
1560     * @see #getTag()
1561     */
1562    protected Object mTag;
1563
1564    // for mPrivateFlags:
1565    /** {@hide} */
1566    static final int WANTS_FOCUS                    = 0x00000001;
1567    /** {@hide} */
1568    static final int FOCUSED                        = 0x00000002;
1569    /** {@hide} */
1570    static final int SELECTED                       = 0x00000004;
1571    /** {@hide} */
1572    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1573    /** {@hide} */
1574    static final int HAS_BOUNDS                     = 0x00000010;
1575    /** {@hide} */
1576    static final int DRAWN                          = 0x00000020;
1577    /**
1578     * When this flag is set, this view is running an animation on behalf of its
1579     * children and should therefore not cancel invalidate requests, even if they
1580     * lie outside of this view's bounds.
1581     *
1582     * {@hide}
1583     */
1584    static final int DRAW_ANIMATION                 = 0x00000040;
1585    /** {@hide} */
1586    static final int SKIP_DRAW                      = 0x00000080;
1587    /** {@hide} */
1588    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1589    /** {@hide} */
1590    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1591    /** {@hide} */
1592    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1593    /** {@hide} */
1594    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1595    /** {@hide} */
1596    static final int FORCE_LAYOUT                   = 0x00001000;
1597    /** {@hide} */
1598    static final int LAYOUT_REQUIRED                = 0x00002000;
1599
1600    private static final int PRESSED                = 0x00004000;
1601
1602    /** {@hide} */
1603    static final int DRAWING_CACHE_VALID            = 0x00008000;
1604    /**
1605     * Flag used to indicate that this view should be drawn once more (and only once
1606     * more) after its animation has completed.
1607     * {@hide}
1608     */
1609    static final int ANIMATION_STARTED              = 0x00010000;
1610
1611    private static final int SAVE_STATE_CALLED      = 0x00020000;
1612
1613    /**
1614     * Indicates that the View returned true when onSetAlpha() was called and that
1615     * the alpha must be restored.
1616     * {@hide}
1617     */
1618    static final int ALPHA_SET                      = 0x00040000;
1619
1620    /**
1621     * Set by {@link #setScrollContainer(boolean)}.
1622     */
1623    static final int SCROLL_CONTAINER               = 0x00080000;
1624
1625    /**
1626     * Set by {@link #setScrollContainer(boolean)}.
1627     */
1628    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1629
1630    /**
1631     * View flag indicating whether this view was invalidated (fully or partially.)
1632     *
1633     * @hide
1634     */
1635    static final int DIRTY                          = 0x00200000;
1636
1637    /**
1638     * View flag indicating whether this view was invalidated by an opaque
1639     * invalidate request.
1640     *
1641     * @hide
1642     */
1643    static final int DIRTY_OPAQUE                   = 0x00400000;
1644
1645    /**
1646     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1647     *
1648     * @hide
1649     */
1650    static final int DIRTY_MASK                     = 0x00600000;
1651
1652    /**
1653     * Indicates whether the background is opaque.
1654     *
1655     * @hide
1656     */
1657    static final int OPAQUE_BACKGROUND              = 0x00800000;
1658
1659    /**
1660     * Indicates whether the scrollbars are opaque.
1661     *
1662     * @hide
1663     */
1664    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1665
1666    /**
1667     * Indicates whether the view is opaque.
1668     *
1669     * @hide
1670     */
1671    static final int OPAQUE_MASK                    = 0x01800000;
1672
1673    /**
1674     * Indicates a prepressed state;
1675     * the short time between ACTION_DOWN and recognizing
1676     * a 'real' press. Prepressed is used to recognize quick taps
1677     * even when they are shorter than ViewConfiguration.getTapTimeout().
1678     *
1679     * @hide
1680     */
1681    private static final int PREPRESSED             = 0x02000000;
1682
1683    /**
1684     * Indicates whether the view is temporarily detached.
1685     *
1686     * @hide
1687     */
1688    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1689
1690    /**
1691     * Indicates that we should awaken scroll bars once attached
1692     *
1693     * @hide
1694     */
1695    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1696
1697    /**
1698     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1699     * @hide
1700     */
1701    private static final int HOVERED              = 0x10000000;
1702
1703    /**
1704     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1705     * for transform operations
1706     *
1707     * @hide
1708     */
1709    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1710
1711    /** {@hide} */
1712    static final int ACTIVATED                    = 0x40000000;
1713
1714    /**
1715     * Indicates that this view was specifically invalidated, not just dirtied because some
1716     * child view was invalidated. The flag is used to determine when we need to recreate
1717     * a view's display list (as opposed to just returning a reference to its existing
1718     * display list).
1719     *
1720     * @hide
1721     */
1722    static final int INVALIDATED                  = 0x80000000;
1723
1724    /* Masks for mPrivateFlags2 */
1725
1726    /**
1727     * Indicates that this view has reported that it can accept the current drag's content.
1728     * Cleared when the drag operation concludes.
1729     * @hide
1730     */
1731    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1732
1733    /**
1734     * Indicates that this view is currently directly under the drag location in a
1735     * drag-and-drop operation involving content that it can accept.  Cleared when
1736     * the drag exits the view, or when the drag operation concludes.
1737     * @hide
1738     */
1739    static final int DRAG_HOVERED                 = 0x00000002;
1740
1741    /**
1742     * Indicates whether the view layout direction has been resolved and drawn to the
1743     * right-to-left direction.
1744     *
1745     * @hide
1746     */
1747    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1748
1749    /**
1750     * Indicates whether the view layout direction has been resolved.
1751     *
1752     * @hide
1753     */
1754    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1755
1756
1757    /* End of masks for mPrivateFlags2 */
1758
1759    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1760
1761    /**
1762     * Always allow a user to over-scroll this view, provided it is a
1763     * view that can scroll.
1764     *
1765     * @see #getOverScrollMode()
1766     * @see #setOverScrollMode(int)
1767     */
1768    public static final int OVER_SCROLL_ALWAYS = 0;
1769
1770    /**
1771     * Allow a user to over-scroll this view only if the content is large
1772     * enough to meaningfully scroll, provided it is a view that can scroll.
1773     *
1774     * @see #getOverScrollMode()
1775     * @see #setOverScrollMode(int)
1776     */
1777    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1778
1779    /**
1780     * Never allow a user to over-scroll this view.
1781     *
1782     * @see #getOverScrollMode()
1783     * @see #setOverScrollMode(int)
1784     */
1785    public static final int OVER_SCROLL_NEVER = 2;
1786
1787    /**
1788     * View has requested the system UI (status bar) to be visible (the default).
1789     *
1790     * @see #setSystemUiVisibility(int)
1791     */
1792    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1793
1794    /**
1795     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1796     *
1797     * This is for use in games, book readers, video players, or any other "immersive" application
1798     * where the usual system chrome is deemed too distracting.
1799     *
1800     * In low profile mode, the status bar and/or navigation icons may dim.
1801     *
1802     * @see #setSystemUiVisibility(int)
1803     */
1804    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1805
1806    /**
1807     * View has requested that the system navigation be temporarily hidden.
1808     *
1809     * This is an even less obtrusive state than that called for by
1810     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1811     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1812     * those to disappear. This is useful (in conjunction with the
1813     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1814     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1815     * window flags) for displaying content using every last pixel on the display.
1816     *
1817     * There is a limitation: because navigation controls are so important, the least user
1818     * interaction will cause them to reappear immediately.
1819     *
1820     * @see #setSystemUiVisibility(int)
1821     */
1822    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1823
1824    /**
1825     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1826     */
1827    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1828
1829    /**
1830     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1831     */
1832    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1833
1834    /**
1835     * @hide
1836     *
1837     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1838     * out of the public fields to keep the undefined bits out of the developer's way.
1839     *
1840     * Flag to make the status bar not expandable.  Unless you also
1841     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1842     */
1843    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1844
1845    /**
1846     * @hide
1847     *
1848     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1849     * out of the public fields to keep the undefined bits out of the developer's way.
1850     *
1851     * Flag to hide notification icons and scrolling ticker text.
1852     */
1853    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1854
1855    /**
1856     * @hide
1857     *
1858     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1859     * out of the public fields to keep the undefined bits out of the developer's way.
1860     *
1861     * Flag to disable incoming notification alerts.  This will not block
1862     * icons, but it will block sound, vibrating and other visual or aural notifications.
1863     */
1864    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1865
1866    /**
1867     * @hide
1868     *
1869     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1870     * out of the public fields to keep the undefined bits out of the developer's way.
1871     *
1872     * Flag to hide only the scrolling ticker.  Note that
1873     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1874     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1875     */
1876    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1877
1878    /**
1879     * @hide
1880     *
1881     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1882     * out of the public fields to keep the undefined bits out of the developer's way.
1883     *
1884     * Flag to hide the center system info area.
1885     */
1886    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1887
1888    /**
1889     * @hide
1890     *
1891     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1892     * out of the public fields to keep the undefined bits out of the developer's way.
1893     *
1894     * Flag to hide only the navigation buttons.  Don't use this
1895     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1896     *
1897     * THIS DOES NOT DISABLE THE BACK BUTTON
1898     */
1899    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1900
1901    /**
1902     * @hide
1903     *
1904     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1905     * out of the public fields to keep the undefined bits out of the developer's way.
1906     *
1907     * Flag to hide only the back button.  Don't use this
1908     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1909     */
1910    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1911
1912    /**
1913     * @hide
1914     *
1915     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1916     * out of the public fields to keep the undefined bits out of the developer's way.
1917     *
1918     * Flag to hide only the clock.  You might use this if your activity has
1919     * its own clock making the status bar's clock redundant.
1920     */
1921    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1922
1923    /**
1924     * @hide
1925     */
1926    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1927
1928    /**
1929     * These are the system UI flags that can be cleared by events outside
1930     * of an application.  Currently this is just the ability to tap on the
1931     * screen while hiding the navigation bar to have it return.
1932     * @hide
1933     */
1934    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1935            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1936
1937    /**
1938     * Find views that render the specified text.
1939     *
1940     * @see #findViewsWithText(ArrayList, CharSequence, int)
1941     */
1942    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1943
1944    /**
1945     * Find find views that contain the specified content description.
1946     *
1947     * @see #findViewsWithText(ArrayList, CharSequence, int)
1948     */
1949    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1950
1951    /**
1952     * Controls the over-scroll mode for this view.
1953     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1954     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1955     * and {@link #OVER_SCROLL_NEVER}.
1956     */
1957    private int mOverScrollMode;
1958
1959    /**
1960     * The parent this view is attached to.
1961     * {@hide}
1962     *
1963     * @see #getParent()
1964     */
1965    protected ViewParent mParent;
1966
1967    /**
1968     * {@hide}
1969     */
1970    AttachInfo mAttachInfo;
1971
1972    /**
1973     * {@hide}
1974     */
1975    @ViewDebug.ExportedProperty(flagMapping = {
1976        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1977                name = "FORCE_LAYOUT"),
1978        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1979                name = "LAYOUT_REQUIRED"),
1980        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1981            name = "DRAWING_CACHE_INVALID", outputIf = false),
1982        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1983        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1984        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1985        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1986    })
1987    int mPrivateFlags;
1988    int mPrivateFlags2;
1989
1990    /**
1991     * This view's request for the visibility of the status bar.
1992     * @hide
1993     */
1994    @ViewDebug.ExportedProperty(flagMapping = {
1995        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
1996                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
1997                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
1998        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1999                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2000                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2001        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2002                                equals = SYSTEM_UI_FLAG_VISIBLE,
2003                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2004    })
2005    int mSystemUiVisibility;
2006
2007    /**
2008     * Count of how many windows this view has been attached to.
2009     */
2010    int mWindowAttachCount;
2011
2012    /**
2013     * The layout parameters associated with this view and used by the parent
2014     * {@link android.view.ViewGroup} to determine how this view should be
2015     * laid out.
2016     * {@hide}
2017     */
2018    protected ViewGroup.LayoutParams mLayoutParams;
2019
2020    /**
2021     * The view flags hold various views states.
2022     * {@hide}
2023     */
2024    @ViewDebug.ExportedProperty
2025    int mViewFlags;
2026
2027    static class TransformationInfo {
2028        /**
2029         * The transform matrix for the View. This transform is calculated internally
2030         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2031         * is used by default. Do *not* use this variable directly; instead call
2032         * getMatrix(), which will automatically recalculate the matrix if necessary
2033         * to get the correct matrix based on the latest rotation and scale properties.
2034         */
2035        private final Matrix mMatrix = new Matrix();
2036
2037        /**
2038         * The transform matrix for the View. This transform is calculated internally
2039         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2040         * is used by default. Do *not* use this variable directly; instead call
2041         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2042         * to get the correct matrix based on the latest rotation and scale properties.
2043         */
2044        private Matrix mInverseMatrix;
2045
2046        /**
2047         * An internal variable that tracks whether we need to recalculate the
2048         * transform matrix, based on whether the rotation or scaleX/Y properties
2049         * have changed since the matrix was last calculated.
2050         */
2051        boolean mMatrixDirty = false;
2052
2053        /**
2054         * An internal variable that tracks whether we need to recalculate the
2055         * transform matrix, based on whether the rotation or scaleX/Y properties
2056         * have changed since the matrix was last calculated.
2057         */
2058        private boolean mInverseMatrixDirty = true;
2059
2060        /**
2061         * A variable that tracks whether we need to recalculate the
2062         * transform matrix, based on whether the rotation or scaleX/Y properties
2063         * have changed since the matrix was last calculated. This variable
2064         * is only valid after a call to updateMatrix() or to a function that
2065         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2066         */
2067        private boolean mMatrixIsIdentity = true;
2068
2069        /**
2070         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2071         */
2072        private Camera mCamera = null;
2073
2074        /**
2075         * This matrix is used when computing the matrix for 3D rotations.
2076         */
2077        private Matrix matrix3D = null;
2078
2079        /**
2080         * These prev values are used to recalculate a centered pivot point when necessary. The
2081         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2082         * set), so thes values are only used then as well.
2083         */
2084        private int mPrevWidth = -1;
2085        private int mPrevHeight = -1;
2086
2087        /**
2088         * The degrees rotation around the vertical axis through the pivot point.
2089         */
2090        @ViewDebug.ExportedProperty
2091        float mRotationY = 0f;
2092
2093        /**
2094         * The degrees rotation around the horizontal axis through the pivot point.
2095         */
2096        @ViewDebug.ExportedProperty
2097        float mRotationX = 0f;
2098
2099        /**
2100         * The degrees rotation around the pivot point.
2101         */
2102        @ViewDebug.ExportedProperty
2103        float mRotation = 0f;
2104
2105        /**
2106         * The amount of translation of the object away from its left property (post-layout).
2107         */
2108        @ViewDebug.ExportedProperty
2109        float mTranslationX = 0f;
2110
2111        /**
2112         * The amount of translation of the object away from its top property (post-layout).
2113         */
2114        @ViewDebug.ExportedProperty
2115        float mTranslationY = 0f;
2116
2117        /**
2118         * The amount of scale in the x direction around the pivot point. A
2119         * value of 1 means no scaling is applied.
2120         */
2121        @ViewDebug.ExportedProperty
2122        float mScaleX = 1f;
2123
2124        /**
2125         * The amount of scale in the y direction around the pivot point. A
2126         * value of 1 means no scaling is applied.
2127         */
2128        @ViewDebug.ExportedProperty
2129        float mScaleY = 1f;
2130
2131        /**
2132         * The amount of scale in the x direction around the pivot point. A
2133         * value of 1 means no scaling is applied.
2134         */
2135        @ViewDebug.ExportedProperty
2136        float mPivotX = 0f;
2137
2138        /**
2139         * The amount of scale in the y direction around the pivot point. A
2140         * value of 1 means no scaling is applied.
2141         */
2142        @ViewDebug.ExportedProperty
2143        float mPivotY = 0f;
2144
2145        /**
2146         * The opacity of the View. This is a value from 0 to 1, where 0 means
2147         * completely transparent and 1 means completely opaque.
2148         */
2149        @ViewDebug.ExportedProperty
2150        float mAlpha = 1f;
2151    }
2152
2153    TransformationInfo mTransformationInfo;
2154
2155    private boolean mLastIsOpaque;
2156
2157    /**
2158     * Convenience value to check for float values that are close enough to zero to be considered
2159     * zero.
2160     */
2161    private static final float NONZERO_EPSILON = .001f;
2162
2163    /**
2164     * The distance in pixels from the left edge of this view's parent
2165     * to the left edge of this view.
2166     * {@hide}
2167     */
2168    @ViewDebug.ExportedProperty(category = "layout")
2169    protected int mLeft;
2170    /**
2171     * The distance in pixels from the left edge of this view's parent
2172     * to the right edge of this view.
2173     * {@hide}
2174     */
2175    @ViewDebug.ExportedProperty(category = "layout")
2176    protected int mRight;
2177    /**
2178     * The distance in pixels from the top edge of this view's parent
2179     * to the top edge of this view.
2180     * {@hide}
2181     */
2182    @ViewDebug.ExportedProperty(category = "layout")
2183    protected int mTop;
2184    /**
2185     * The distance in pixels from the top edge of this view's parent
2186     * to the bottom edge of this view.
2187     * {@hide}
2188     */
2189    @ViewDebug.ExportedProperty(category = "layout")
2190    protected int mBottom;
2191
2192    /**
2193     * The offset, in pixels, by which the content of this view is scrolled
2194     * horizontally.
2195     * {@hide}
2196     */
2197    @ViewDebug.ExportedProperty(category = "scrolling")
2198    protected int mScrollX;
2199    /**
2200     * The offset, in pixels, by which the content of this view is scrolled
2201     * vertically.
2202     * {@hide}
2203     */
2204    @ViewDebug.ExportedProperty(category = "scrolling")
2205    protected int mScrollY;
2206
2207    /**
2208     * The left padding in pixels, that is the distance in pixels between the
2209     * left edge of this view and the left edge of its content.
2210     * {@hide}
2211     */
2212    @ViewDebug.ExportedProperty(category = "padding")
2213    protected int mPaddingLeft;
2214    /**
2215     * The right padding in pixels, that is the distance in pixels between the
2216     * right edge of this view and the right edge of its content.
2217     * {@hide}
2218     */
2219    @ViewDebug.ExportedProperty(category = "padding")
2220    protected int mPaddingRight;
2221    /**
2222     * The top padding in pixels, that is the distance in pixels between the
2223     * top edge of this view and the top edge of its content.
2224     * {@hide}
2225     */
2226    @ViewDebug.ExportedProperty(category = "padding")
2227    protected int mPaddingTop;
2228    /**
2229     * The bottom padding in pixels, that is the distance in pixels between the
2230     * bottom edge of this view and the bottom edge of its content.
2231     * {@hide}
2232     */
2233    @ViewDebug.ExportedProperty(category = "padding")
2234    protected int mPaddingBottom;
2235
2236    /**
2237     * Briefly describes the view and is primarily used for accessibility support.
2238     */
2239    private CharSequence mContentDescription;
2240
2241    /**
2242     * Cache the paddingRight set by the user to append to the scrollbar's size.
2243     *
2244     * @hide
2245     */
2246    @ViewDebug.ExportedProperty(category = "padding")
2247    protected int mUserPaddingRight;
2248
2249    /**
2250     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2251     *
2252     * @hide
2253     */
2254    @ViewDebug.ExportedProperty(category = "padding")
2255    protected int mUserPaddingBottom;
2256
2257    /**
2258     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2259     *
2260     * @hide
2261     */
2262    @ViewDebug.ExportedProperty(category = "padding")
2263    protected int mUserPaddingLeft;
2264
2265    /**
2266     * Cache if the user padding is relative.
2267     *
2268     */
2269    @ViewDebug.ExportedProperty(category = "padding")
2270    boolean mUserPaddingRelative;
2271
2272    /**
2273     * Cache the paddingStart set by the user to append to the scrollbar's size.
2274     *
2275     */
2276    @ViewDebug.ExportedProperty(category = "padding")
2277    int mUserPaddingStart;
2278
2279    /**
2280     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2281     *
2282     */
2283    @ViewDebug.ExportedProperty(category = "padding")
2284    int mUserPaddingEnd;
2285
2286    /**
2287     * @hide
2288     */
2289    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2290    /**
2291     * @hide
2292     */
2293    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2294
2295    private Drawable mBGDrawable;
2296
2297    private int mBackgroundResource;
2298    private boolean mBackgroundSizeChanged;
2299
2300    /**
2301     * Listener used to dispatch focus change events.
2302     * This field should be made private, so it is hidden from the SDK.
2303     * {@hide}
2304     */
2305    protected OnFocusChangeListener mOnFocusChangeListener;
2306
2307    /**
2308     * Listeners for layout change events.
2309     */
2310    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2311
2312    /**
2313     * Listeners for attach events.
2314     */
2315    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2316
2317    /**
2318     * Listener used to dispatch click events.
2319     * This field should be made private, so it is hidden from the SDK.
2320     * {@hide}
2321     */
2322    protected OnClickListener mOnClickListener;
2323
2324    /**
2325     * Listener used to dispatch long click events.
2326     * This field should be made private, so it is hidden from the SDK.
2327     * {@hide}
2328     */
2329    protected OnLongClickListener mOnLongClickListener;
2330
2331    /**
2332     * Listener used to build the context menu.
2333     * This field should be made private, so it is hidden from the SDK.
2334     * {@hide}
2335     */
2336    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2337
2338    private OnKeyListener mOnKeyListener;
2339
2340    private OnTouchListener mOnTouchListener;
2341
2342    private OnHoverListener mOnHoverListener;
2343
2344    private OnGenericMotionListener mOnGenericMotionListener;
2345
2346    private OnDragListener mOnDragListener;
2347
2348    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2349
2350    /**
2351     * The application environment this view lives in.
2352     * This field should be made private, so it is hidden from the SDK.
2353     * {@hide}
2354     */
2355    protected Context mContext;
2356
2357    private final Resources mResources;
2358
2359    private ScrollabilityCache mScrollCache;
2360
2361    private int[] mDrawableState = null;
2362
2363    /**
2364     * Set to true when drawing cache is enabled and cannot be created.
2365     *
2366     * @hide
2367     */
2368    public boolean mCachingFailed;
2369
2370    private Bitmap mDrawingCache;
2371    private Bitmap mUnscaledDrawingCache;
2372    private HardwareLayer mHardwareLayer;
2373    DisplayList mDisplayList;
2374
2375    /**
2376     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2377     * the user may specify which view to go to next.
2378     */
2379    private int mNextFocusLeftId = View.NO_ID;
2380
2381    /**
2382     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2383     * the user may specify which view to go to next.
2384     */
2385    private int mNextFocusRightId = View.NO_ID;
2386
2387    /**
2388     * When this view has focus and the next focus is {@link #FOCUS_UP},
2389     * the user may specify which view to go to next.
2390     */
2391    private int mNextFocusUpId = View.NO_ID;
2392
2393    /**
2394     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2395     * the user may specify which view to go to next.
2396     */
2397    private int mNextFocusDownId = View.NO_ID;
2398
2399    /**
2400     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2401     * the user may specify which view to go to next.
2402     */
2403    int mNextFocusForwardId = View.NO_ID;
2404
2405    private CheckForLongPress mPendingCheckForLongPress;
2406    private CheckForTap mPendingCheckForTap = null;
2407    private PerformClick mPerformClick;
2408    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2409
2410    private UnsetPressedState mUnsetPressedState;
2411
2412    /**
2413     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2414     * up event while a long press is invoked as soon as the long press duration is reached, so
2415     * a long press could be performed before the tap is checked, in which case the tap's action
2416     * should not be invoked.
2417     */
2418    private boolean mHasPerformedLongPress;
2419
2420    /**
2421     * The minimum height of the view. We'll try our best to have the height
2422     * of this view to at least this amount.
2423     */
2424    @ViewDebug.ExportedProperty(category = "measurement")
2425    private int mMinHeight;
2426
2427    /**
2428     * The minimum width of the view. We'll try our best to have the width
2429     * of this view to at least this amount.
2430     */
2431    @ViewDebug.ExportedProperty(category = "measurement")
2432    private int mMinWidth;
2433
2434    /**
2435     * The delegate to handle touch events that are physically in this view
2436     * but should be handled by another view.
2437     */
2438    private TouchDelegate mTouchDelegate = null;
2439
2440    /**
2441     * Solid color to use as a background when creating the drawing cache. Enables
2442     * the cache to use 16 bit bitmaps instead of 32 bit.
2443     */
2444    private int mDrawingCacheBackgroundColor = 0;
2445
2446    /**
2447     * Special tree observer used when mAttachInfo is null.
2448     */
2449    private ViewTreeObserver mFloatingTreeObserver;
2450
2451    /**
2452     * Cache the touch slop from the context that created the view.
2453     */
2454    private int mTouchSlop;
2455
2456    /**
2457     * Object that handles automatic animation of view properties.
2458     */
2459    private ViewPropertyAnimator mAnimator = null;
2460
2461    /**
2462     * Flag indicating that a drag can cross window boundaries.  When
2463     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2464     * with this flag set, all visible applications will be able to participate
2465     * in the drag operation and receive the dragged content.
2466     *
2467     * @hide
2468     */
2469    public static final int DRAG_FLAG_GLOBAL = 1;
2470
2471    /**
2472     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2473     */
2474    private float mVerticalScrollFactor;
2475
2476    /**
2477     * Position of the vertical scroll bar.
2478     */
2479    private int mVerticalScrollbarPosition;
2480
2481    /**
2482     * Position the scroll bar at the default position as determined by the system.
2483     */
2484    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2485
2486    /**
2487     * Position the scroll bar along the left edge.
2488     */
2489    public static final int SCROLLBAR_POSITION_LEFT = 1;
2490
2491    /**
2492     * Position the scroll bar along the right edge.
2493     */
2494    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2495
2496    /**
2497     * Indicates that the view does not have a layer.
2498     *
2499     * @see #getLayerType()
2500     * @see #setLayerType(int, android.graphics.Paint)
2501     * @see #LAYER_TYPE_SOFTWARE
2502     * @see #LAYER_TYPE_HARDWARE
2503     */
2504    public static final int LAYER_TYPE_NONE = 0;
2505
2506    /**
2507     * <p>Indicates that the view has a software layer. A software layer is backed
2508     * by a bitmap and causes the view to be rendered using Android's software
2509     * rendering pipeline, even if hardware acceleration is enabled.</p>
2510     *
2511     * <p>Software layers have various usages:</p>
2512     * <p>When the application is not using hardware acceleration, a software layer
2513     * is useful to apply a specific color filter and/or blending mode and/or
2514     * translucency to a view and all its children.</p>
2515     * <p>When the application is using hardware acceleration, a software layer
2516     * is useful to render drawing primitives not supported by the hardware
2517     * accelerated pipeline. It can also be used to cache a complex view tree
2518     * into a texture and reduce the complexity of drawing operations. For instance,
2519     * when animating a complex view tree with a translation, a software layer can
2520     * be used to render the view tree only once.</p>
2521     * <p>Software layers should be avoided when the affected view tree updates
2522     * often. Every update will require to re-render the software layer, which can
2523     * potentially be slow (particularly when hardware acceleration is turned on
2524     * since the layer will have to be uploaded into a hardware texture after every
2525     * update.)</p>
2526     *
2527     * @see #getLayerType()
2528     * @see #setLayerType(int, android.graphics.Paint)
2529     * @see #LAYER_TYPE_NONE
2530     * @see #LAYER_TYPE_HARDWARE
2531     */
2532    public static final int LAYER_TYPE_SOFTWARE = 1;
2533
2534    /**
2535     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2536     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2537     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2538     * rendering pipeline, but only if hardware acceleration is turned on for the
2539     * view hierarchy. When hardware acceleration is turned off, hardware layers
2540     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2541     *
2542     * <p>A hardware layer is useful to apply a specific color filter and/or
2543     * blending mode and/or translucency to a view and all its children.</p>
2544     * <p>A hardware layer can be used to cache a complex view tree into a
2545     * texture and reduce the complexity of drawing operations. For instance,
2546     * when animating a complex view tree with a translation, a hardware layer can
2547     * be used to render the view tree only once.</p>
2548     * <p>A hardware layer can also be used to increase the rendering quality when
2549     * rotation transformations are applied on a view. It can also be used to
2550     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2551     *
2552     * @see #getLayerType()
2553     * @see #setLayerType(int, android.graphics.Paint)
2554     * @see #LAYER_TYPE_NONE
2555     * @see #LAYER_TYPE_SOFTWARE
2556     */
2557    public static final int LAYER_TYPE_HARDWARE = 2;
2558
2559    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2560            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2561            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2562            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2563    })
2564    int mLayerType = LAYER_TYPE_NONE;
2565    Paint mLayerPaint;
2566    Rect mLocalDirtyRect;
2567
2568    /**
2569     * Set to true when the view is sending hover accessibility events because it
2570     * is the innermost hovered view.
2571     */
2572    private boolean mSendingHoverAccessibilityEvents;
2573
2574    /**
2575     * Delegate for injecting accessiblity functionality.
2576     */
2577    AccessibilityDelegate mAccessibilityDelegate;
2578
2579    /**
2580     * Text direction is inherited thru {@link ViewGroup}
2581     * @hide
2582     */
2583    public static final int TEXT_DIRECTION_INHERIT = 0;
2584
2585    /**
2586     * Text direction is using "first strong algorithm". The first strong directional character
2587     * determines the paragraph direction. If there is no strong directional character, the
2588     * paragraph direction is the view's resolved ayout direction.
2589     *
2590     * @hide
2591     */
2592    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2593
2594    /**
2595     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2596     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2597     * If there are neither, the paragraph direction is the view's resolved layout direction.
2598     *
2599     * @hide
2600     */
2601    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2602
2603    /**
2604     * Text direction is forced to LTR.
2605     *
2606     * @hide
2607     */
2608    public static final int TEXT_DIRECTION_LTR = 3;
2609
2610    /**
2611     * Text direction is forced to RTL.
2612     *
2613     * @hide
2614     */
2615    public static final int TEXT_DIRECTION_RTL = 4;
2616
2617    /**
2618     * Default text direction is inherited
2619     *
2620     * @hide
2621     */
2622    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2623
2624    /**
2625     * The text direction that has been defined by {@link #setTextDirection(int)}.
2626     *
2627     * {@hide}
2628     */
2629    @ViewDebug.ExportedProperty(category = "text", mapping = {
2630            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2631            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2632            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2633            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2634            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2635    })
2636    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2637
2638    /**
2639     * The resolved text direction.  This needs resolution if the value is
2640     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if that is
2641     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2642     * chain of the view.
2643     *
2644     * {@hide}
2645     */
2646    @ViewDebug.ExportedProperty(category = "text", mapping = {
2647            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2648            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2649            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2650            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2651            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2652    })
2653    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2654
2655    /**
2656     * Consistency verifier for debugging purposes.
2657     * @hide
2658     */
2659    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2660            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2661                    new InputEventConsistencyVerifier(this, 0) : null;
2662
2663    /**
2664     * Simple constructor to use when creating a view from code.
2665     *
2666     * @param context The Context the view is running in, through which it can
2667     *        access the current theme, resources, etc.
2668     */
2669    public View(Context context) {
2670        mContext = context;
2671        mResources = context != null ? context.getResources() : null;
2672        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2673        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2674        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2675        mUserPaddingStart = -1;
2676        mUserPaddingEnd = -1;
2677        mUserPaddingRelative = false;
2678    }
2679
2680    /**
2681     * Constructor that is called when inflating a view from XML. This is called
2682     * when a view is being constructed from an XML file, supplying attributes
2683     * that were specified in the XML file. This version uses a default style of
2684     * 0, so the only attribute values applied are those in the Context's Theme
2685     * and the given AttributeSet.
2686     *
2687     * <p>
2688     * The method onFinishInflate() will be called after all children have been
2689     * added.
2690     *
2691     * @param context The Context the view is running in, through which it can
2692     *        access the current theme, resources, etc.
2693     * @param attrs The attributes of the XML tag that is inflating the view.
2694     * @see #View(Context, AttributeSet, int)
2695     */
2696    public View(Context context, AttributeSet attrs) {
2697        this(context, attrs, 0);
2698    }
2699
2700    /**
2701     * Perform inflation from XML and apply a class-specific base style. This
2702     * constructor of View allows subclasses to use their own base style when
2703     * they are inflating. For example, a Button class's constructor would call
2704     * this version of the super class constructor and supply
2705     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2706     * the theme's button style to modify all of the base view attributes (in
2707     * particular its background) as well as the Button class's attributes.
2708     *
2709     * @param context The Context the view is running in, through which it can
2710     *        access the current theme, resources, etc.
2711     * @param attrs The attributes of the XML tag that is inflating the view.
2712     * @param defStyle The default style to apply to this view. If 0, no style
2713     *        will be applied (beyond what is included in the theme). This may
2714     *        either be an attribute resource, whose value will be retrieved
2715     *        from the current theme, or an explicit style resource.
2716     * @see #View(Context, AttributeSet)
2717     */
2718    public View(Context context, AttributeSet attrs, int defStyle) {
2719        this(context);
2720
2721        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2722                defStyle, 0);
2723
2724        Drawable background = null;
2725
2726        int leftPadding = -1;
2727        int topPadding = -1;
2728        int rightPadding = -1;
2729        int bottomPadding = -1;
2730        int startPadding = -1;
2731        int endPadding = -1;
2732
2733        int padding = -1;
2734
2735        int viewFlagValues = 0;
2736        int viewFlagMasks = 0;
2737
2738        boolean setScrollContainer = false;
2739
2740        int x = 0;
2741        int y = 0;
2742
2743        float tx = 0;
2744        float ty = 0;
2745        float rotation = 0;
2746        float rotationX = 0;
2747        float rotationY = 0;
2748        float sx = 1f;
2749        float sy = 1f;
2750        boolean transformSet = false;
2751
2752        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2753
2754        int overScrollMode = mOverScrollMode;
2755        final int N = a.getIndexCount();
2756        for (int i = 0; i < N; i++) {
2757            int attr = a.getIndex(i);
2758            switch (attr) {
2759                case com.android.internal.R.styleable.View_background:
2760                    background = a.getDrawable(attr);
2761                    break;
2762                case com.android.internal.R.styleable.View_padding:
2763                    padding = a.getDimensionPixelSize(attr, -1);
2764                    break;
2765                 case com.android.internal.R.styleable.View_paddingLeft:
2766                    leftPadding = a.getDimensionPixelSize(attr, -1);
2767                    break;
2768                case com.android.internal.R.styleable.View_paddingTop:
2769                    topPadding = a.getDimensionPixelSize(attr, -1);
2770                    break;
2771                case com.android.internal.R.styleable.View_paddingRight:
2772                    rightPadding = a.getDimensionPixelSize(attr, -1);
2773                    break;
2774                case com.android.internal.R.styleable.View_paddingBottom:
2775                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2776                    break;
2777                case com.android.internal.R.styleable.View_paddingStart:
2778                    startPadding = a.getDimensionPixelSize(attr, -1);
2779                    break;
2780                case com.android.internal.R.styleable.View_paddingEnd:
2781                    endPadding = a.getDimensionPixelSize(attr, -1);
2782                    break;
2783                case com.android.internal.R.styleable.View_scrollX:
2784                    x = a.getDimensionPixelOffset(attr, 0);
2785                    break;
2786                case com.android.internal.R.styleable.View_scrollY:
2787                    y = a.getDimensionPixelOffset(attr, 0);
2788                    break;
2789                case com.android.internal.R.styleable.View_alpha:
2790                    setAlpha(a.getFloat(attr, 1f));
2791                    break;
2792                case com.android.internal.R.styleable.View_transformPivotX:
2793                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2794                    break;
2795                case com.android.internal.R.styleable.View_transformPivotY:
2796                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2797                    break;
2798                case com.android.internal.R.styleable.View_translationX:
2799                    tx = a.getDimensionPixelOffset(attr, 0);
2800                    transformSet = true;
2801                    break;
2802                case com.android.internal.R.styleable.View_translationY:
2803                    ty = a.getDimensionPixelOffset(attr, 0);
2804                    transformSet = true;
2805                    break;
2806                case com.android.internal.R.styleable.View_rotation:
2807                    rotation = a.getFloat(attr, 0);
2808                    transformSet = true;
2809                    break;
2810                case com.android.internal.R.styleable.View_rotationX:
2811                    rotationX = a.getFloat(attr, 0);
2812                    transformSet = true;
2813                    break;
2814                case com.android.internal.R.styleable.View_rotationY:
2815                    rotationY = a.getFloat(attr, 0);
2816                    transformSet = true;
2817                    break;
2818                case com.android.internal.R.styleable.View_scaleX:
2819                    sx = a.getFloat(attr, 1f);
2820                    transformSet = true;
2821                    break;
2822                case com.android.internal.R.styleable.View_scaleY:
2823                    sy = a.getFloat(attr, 1f);
2824                    transformSet = true;
2825                    break;
2826                case com.android.internal.R.styleable.View_id:
2827                    mID = a.getResourceId(attr, NO_ID);
2828                    break;
2829                case com.android.internal.R.styleable.View_tag:
2830                    mTag = a.getText(attr);
2831                    break;
2832                case com.android.internal.R.styleable.View_fitsSystemWindows:
2833                    if (a.getBoolean(attr, false)) {
2834                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2835                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2836                    }
2837                    break;
2838                case com.android.internal.R.styleable.View_focusable:
2839                    if (a.getBoolean(attr, false)) {
2840                        viewFlagValues |= FOCUSABLE;
2841                        viewFlagMasks |= FOCUSABLE_MASK;
2842                    }
2843                    break;
2844                case com.android.internal.R.styleable.View_focusableInTouchMode:
2845                    if (a.getBoolean(attr, false)) {
2846                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2847                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2848                    }
2849                    break;
2850                case com.android.internal.R.styleable.View_clickable:
2851                    if (a.getBoolean(attr, false)) {
2852                        viewFlagValues |= CLICKABLE;
2853                        viewFlagMasks |= CLICKABLE;
2854                    }
2855                    break;
2856                case com.android.internal.R.styleable.View_longClickable:
2857                    if (a.getBoolean(attr, false)) {
2858                        viewFlagValues |= LONG_CLICKABLE;
2859                        viewFlagMasks |= LONG_CLICKABLE;
2860                    }
2861                    break;
2862                case com.android.internal.R.styleable.View_saveEnabled:
2863                    if (!a.getBoolean(attr, true)) {
2864                        viewFlagValues |= SAVE_DISABLED;
2865                        viewFlagMasks |= SAVE_DISABLED_MASK;
2866                    }
2867                    break;
2868                case com.android.internal.R.styleable.View_duplicateParentState:
2869                    if (a.getBoolean(attr, false)) {
2870                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2871                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2872                    }
2873                    break;
2874                case com.android.internal.R.styleable.View_visibility:
2875                    final int visibility = a.getInt(attr, 0);
2876                    if (visibility != 0) {
2877                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2878                        viewFlagMasks |= VISIBILITY_MASK;
2879                    }
2880                    break;
2881                case com.android.internal.R.styleable.View_layoutDirection:
2882                    // Clear any HORIZONTAL_DIRECTION flag already set
2883                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2884                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2885                    final int layoutDirection = a.getInt(attr, -1);
2886                    if (layoutDirection != -1) {
2887                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2888                    } else {
2889                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2890                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2891                    }
2892                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2893                    break;
2894                case com.android.internal.R.styleable.View_drawingCacheQuality:
2895                    final int cacheQuality = a.getInt(attr, 0);
2896                    if (cacheQuality != 0) {
2897                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2898                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2899                    }
2900                    break;
2901                case com.android.internal.R.styleable.View_contentDescription:
2902                    mContentDescription = a.getString(attr);
2903                    break;
2904                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2905                    if (!a.getBoolean(attr, true)) {
2906                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2907                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2908                    }
2909                    break;
2910                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2911                    if (!a.getBoolean(attr, true)) {
2912                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2913                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2914                    }
2915                    break;
2916                case R.styleable.View_scrollbars:
2917                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2918                    if (scrollbars != SCROLLBARS_NONE) {
2919                        viewFlagValues |= scrollbars;
2920                        viewFlagMasks |= SCROLLBARS_MASK;
2921                        initializeScrollbars(a);
2922                    }
2923                    break;
2924                //noinspection deprecation
2925                case R.styleable.View_fadingEdge:
2926                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2927                        // Ignore the attribute starting with ICS
2928                        break;
2929                    }
2930                    // With builds < ICS, fall through and apply fading edges
2931                case R.styleable.View_requiresFadingEdge:
2932                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2933                    if (fadingEdge != FADING_EDGE_NONE) {
2934                        viewFlagValues |= fadingEdge;
2935                        viewFlagMasks |= FADING_EDGE_MASK;
2936                        initializeFadingEdge(a);
2937                    }
2938                    break;
2939                case R.styleable.View_scrollbarStyle:
2940                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2941                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2942                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2943                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2944                    }
2945                    break;
2946                case R.styleable.View_isScrollContainer:
2947                    setScrollContainer = true;
2948                    if (a.getBoolean(attr, false)) {
2949                        setScrollContainer(true);
2950                    }
2951                    break;
2952                case com.android.internal.R.styleable.View_keepScreenOn:
2953                    if (a.getBoolean(attr, false)) {
2954                        viewFlagValues |= KEEP_SCREEN_ON;
2955                        viewFlagMasks |= KEEP_SCREEN_ON;
2956                    }
2957                    break;
2958                case R.styleable.View_filterTouchesWhenObscured:
2959                    if (a.getBoolean(attr, false)) {
2960                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2961                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2962                    }
2963                    break;
2964                case R.styleable.View_nextFocusLeft:
2965                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2966                    break;
2967                case R.styleable.View_nextFocusRight:
2968                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2969                    break;
2970                case R.styleable.View_nextFocusUp:
2971                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2972                    break;
2973                case R.styleable.View_nextFocusDown:
2974                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2975                    break;
2976                case R.styleable.View_nextFocusForward:
2977                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2978                    break;
2979                case R.styleable.View_minWidth:
2980                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2981                    break;
2982                case R.styleable.View_minHeight:
2983                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2984                    break;
2985                case R.styleable.View_onClick:
2986                    if (context.isRestricted()) {
2987                        throw new IllegalStateException("The android:onClick attribute cannot "
2988                                + "be used within a restricted context");
2989                    }
2990
2991                    final String handlerName = a.getString(attr);
2992                    if (handlerName != null) {
2993                        setOnClickListener(new OnClickListener() {
2994                            private Method mHandler;
2995
2996                            public void onClick(View v) {
2997                                if (mHandler == null) {
2998                                    try {
2999                                        mHandler = getContext().getClass().getMethod(handlerName,
3000                                                View.class);
3001                                    } catch (NoSuchMethodException e) {
3002                                        int id = getId();
3003                                        String idText = id == NO_ID ? "" : " with id '"
3004                                                + getContext().getResources().getResourceEntryName(
3005                                                    id) + "'";
3006                                        throw new IllegalStateException("Could not find a method " +
3007                                                handlerName + "(View) in the activity "
3008                                                + getContext().getClass() + " for onClick handler"
3009                                                + " on view " + View.this.getClass() + idText, e);
3010                                    }
3011                                }
3012
3013                                try {
3014                                    mHandler.invoke(getContext(), View.this);
3015                                } catch (IllegalAccessException e) {
3016                                    throw new IllegalStateException("Could not execute non "
3017                                            + "public method of the activity", e);
3018                                } catch (InvocationTargetException e) {
3019                                    throw new IllegalStateException("Could not execute "
3020                                            + "method of the activity", e);
3021                                }
3022                            }
3023                        });
3024                    }
3025                    break;
3026                case R.styleable.View_overScrollMode:
3027                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3028                    break;
3029                case R.styleable.View_verticalScrollbarPosition:
3030                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3031                    break;
3032                case R.styleable.View_layerType:
3033                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3034                    break;
3035                case R.styleable.View_textDirection:
3036                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3037                    break;
3038            }
3039        }
3040
3041        a.recycle();
3042
3043        setOverScrollMode(overScrollMode);
3044
3045        if (background != null) {
3046            setBackgroundDrawable(background);
3047        }
3048
3049        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3050
3051        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3052        // layout direction). Those cached values will be used later during padding resolution.
3053        mUserPaddingStart = startPadding;
3054        mUserPaddingEnd = endPadding;
3055
3056        if (padding >= 0) {
3057            leftPadding = padding;
3058            topPadding = padding;
3059            rightPadding = padding;
3060            bottomPadding = padding;
3061        }
3062
3063        // If the user specified the padding (either with android:padding or
3064        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3065        // use the default padding or the padding from the background drawable
3066        // (stored at this point in mPadding*)
3067        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3068                topPadding >= 0 ? topPadding : mPaddingTop,
3069                rightPadding >= 0 ? rightPadding : mPaddingRight,
3070                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3071
3072        if (viewFlagMasks != 0) {
3073            setFlags(viewFlagValues, viewFlagMasks);
3074        }
3075
3076        // Needs to be called after mViewFlags is set
3077        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3078            recomputePadding();
3079        }
3080
3081        if (x != 0 || y != 0) {
3082            scrollTo(x, y);
3083        }
3084
3085        if (transformSet) {
3086            setTranslationX(tx);
3087            setTranslationY(ty);
3088            setRotation(rotation);
3089            setRotationX(rotationX);
3090            setRotationY(rotationY);
3091            setScaleX(sx);
3092            setScaleY(sy);
3093        }
3094
3095        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3096            setScrollContainer(true);
3097        }
3098
3099        computeOpaqueFlags();
3100    }
3101
3102    /**
3103     * Non-public constructor for use in testing
3104     */
3105    View() {
3106        mResources = null;
3107    }
3108
3109    /**
3110     * <p>
3111     * Initializes the fading edges from a given set of styled attributes. This
3112     * method should be called by subclasses that need fading edges and when an
3113     * instance of these subclasses is created programmatically rather than
3114     * being inflated from XML. This method is automatically called when the XML
3115     * is inflated.
3116     * </p>
3117     *
3118     * @param a the styled attributes set to initialize the fading edges from
3119     */
3120    protected void initializeFadingEdge(TypedArray a) {
3121        initScrollCache();
3122
3123        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3124                R.styleable.View_fadingEdgeLength,
3125                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3126    }
3127
3128    /**
3129     * Returns the size of the vertical faded edges used to indicate that more
3130     * content in this view is visible.
3131     *
3132     * @return The size in pixels of the vertical faded edge or 0 if vertical
3133     *         faded edges are not enabled for this view.
3134     * @attr ref android.R.styleable#View_fadingEdgeLength
3135     */
3136    public int getVerticalFadingEdgeLength() {
3137        if (isVerticalFadingEdgeEnabled()) {
3138            ScrollabilityCache cache = mScrollCache;
3139            if (cache != null) {
3140                return cache.fadingEdgeLength;
3141            }
3142        }
3143        return 0;
3144    }
3145
3146    /**
3147     * Set the size of the faded edge used to indicate that more content in this
3148     * view is available.  Will not change whether the fading edge is enabled; use
3149     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3150     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3151     * for the vertical or horizontal fading edges.
3152     *
3153     * @param length The size in pixels of the faded edge used to indicate that more
3154     *        content in this view is visible.
3155     */
3156    public void setFadingEdgeLength(int length) {
3157        initScrollCache();
3158        mScrollCache.fadingEdgeLength = length;
3159    }
3160
3161    /**
3162     * Returns the size of the horizontal faded edges used to indicate that more
3163     * content in this view is visible.
3164     *
3165     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3166     *         faded edges are not enabled for this view.
3167     * @attr ref android.R.styleable#View_fadingEdgeLength
3168     */
3169    public int getHorizontalFadingEdgeLength() {
3170        if (isHorizontalFadingEdgeEnabled()) {
3171            ScrollabilityCache cache = mScrollCache;
3172            if (cache != null) {
3173                return cache.fadingEdgeLength;
3174            }
3175        }
3176        return 0;
3177    }
3178
3179    /**
3180     * Returns the width of the vertical scrollbar.
3181     *
3182     * @return The width in pixels of the vertical scrollbar or 0 if there
3183     *         is no vertical scrollbar.
3184     */
3185    public int getVerticalScrollbarWidth() {
3186        ScrollabilityCache cache = mScrollCache;
3187        if (cache != null) {
3188            ScrollBarDrawable scrollBar = cache.scrollBar;
3189            if (scrollBar != null) {
3190                int size = scrollBar.getSize(true);
3191                if (size <= 0) {
3192                    size = cache.scrollBarSize;
3193                }
3194                return size;
3195            }
3196            return 0;
3197        }
3198        return 0;
3199    }
3200
3201    /**
3202     * Returns the height of the horizontal scrollbar.
3203     *
3204     * @return The height in pixels of the horizontal scrollbar or 0 if
3205     *         there is no horizontal scrollbar.
3206     */
3207    protected int getHorizontalScrollbarHeight() {
3208        ScrollabilityCache cache = mScrollCache;
3209        if (cache != null) {
3210            ScrollBarDrawable scrollBar = cache.scrollBar;
3211            if (scrollBar != null) {
3212                int size = scrollBar.getSize(false);
3213                if (size <= 0) {
3214                    size = cache.scrollBarSize;
3215                }
3216                return size;
3217            }
3218            return 0;
3219        }
3220        return 0;
3221    }
3222
3223    /**
3224     * <p>
3225     * Initializes the scrollbars from a given set of styled attributes. This
3226     * method should be called by subclasses that need scrollbars and when an
3227     * instance of these subclasses is created programmatically rather than
3228     * being inflated from XML. This method is automatically called when the XML
3229     * is inflated.
3230     * </p>
3231     *
3232     * @param a the styled attributes set to initialize the scrollbars from
3233     */
3234    protected void initializeScrollbars(TypedArray a) {
3235        initScrollCache();
3236
3237        final ScrollabilityCache scrollabilityCache = mScrollCache;
3238
3239        if (scrollabilityCache.scrollBar == null) {
3240            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3241        }
3242
3243        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3244
3245        if (!fadeScrollbars) {
3246            scrollabilityCache.state = ScrollabilityCache.ON;
3247        }
3248        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3249
3250
3251        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3252                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3253                        .getScrollBarFadeDuration());
3254        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3255                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3256                ViewConfiguration.getScrollDefaultDelay());
3257
3258
3259        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3260                com.android.internal.R.styleable.View_scrollbarSize,
3261                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3262
3263        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3264        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3265
3266        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3267        if (thumb != null) {
3268            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3269        }
3270
3271        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3272                false);
3273        if (alwaysDraw) {
3274            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3275        }
3276
3277        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3278        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3279
3280        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3281        if (thumb != null) {
3282            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3283        }
3284
3285        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3286                false);
3287        if (alwaysDraw) {
3288            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3289        }
3290
3291        // Re-apply user/background padding so that scrollbar(s) get added
3292        resolvePadding();
3293    }
3294
3295    /**
3296     * <p>
3297     * Initalizes the scrollability cache if necessary.
3298     * </p>
3299     */
3300    private void initScrollCache() {
3301        if (mScrollCache == null) {
3302            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3303        }
3304    }
3305
3306    /**
3307     * Set the position of the vertical scroll bar. Should be one of
3308     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3309     * {@link #SCROLLBAR_POSITION_RIGHT}.
3310     *
3311     * @param position Where the vertical scroll bar should be positioned.
3312     */
3313    public void setVerticalScrollbarPosition(int position) {
3314        if (mVerticalScrollbarPosition != position) {
3315            mVerticalScrollbarPosition = position;
3316            computeOpaqueFlags();
3317            resolvePadding();
3318        }
3319    }
3320
3321    /**
3322     * @return The position where the vertical scroll bar will show, if applicable.
3323     * @see #setVerticalScrollbarPosition(int)
3324     */
3325    public int getVerticalScrollbarPosition() {
3326        return mVerticalScrollbarPosition;
3327    }
3328
3329    /**
3330     * Register a callback to be invoked when focus of this view changed.
3331     *
3332     * @param l The callback that will run.
3333     */
3334    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3335        mOnFocusChangeListener = l;
3336    }
3337
3338    /**
3339     * Add a listener that will be called when the bounds of the view change due to
3340     * layout processing.
3341     *
3342     * @param listener The listener that will be called when layout bounds change.
3343     */
3344    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3345        if (mOnLayoutChangeListeners == null) {
3346            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3347        }
3348        if (!mOnLayoutChangeListeners.contains(listener)) {
3349            mOnLayoutChangeListeners.add(listener);
3350        }
3351    }
3352
3353    /**
3354     * Remove a listener for layout changes.
3355     *
3356     * @param listener The listener for layout bounds change.
3357     */
3358    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3359        if (mOnLayoutChangeListeners == null) {
3360            return;
3361        }
3362        mOnLayoutChangeListeners.remove(listener);
3363    }
3364
3365    /**
3366     * Add a listener for attach state changes.
3367     *
3368     * This listener will be called whenever this view is attached or detached
3369     * from a window. Remove the listener using
3370     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3371     *
3372     * @param listener Listener to attach
3373     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3374     */
3375    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3376        if (mOnAttachStateChangeListeners == null) {
3377            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3378        }
3379        mOnAttachStateChangeListeners.add(listener);
3380    }
3381
3382    /**
3383     * Remove a listener for attach state changes. The listener will receive no further
3384     * notification of window attach/detach events.
3385     *
3386     * @param listener Listener to remove
3387     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3388     */
3389    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3390        if (mOnAttachStateChangeListeners == null) {
3391            return;
3392        }
3393        mOnAttachStateChangeListeners.remove(listener);
3394    }
3395
3396    /**
3397     * Returns the focus-change callback registered for this view.
3398     *
3399     * @return The callback, or null if one is not registered.
3400     */
3401    public OnFocusChangeListener getOnFocusChangeListener() {
3402        return mOnFocusChangeListener;
3403    }
3404
3405    /**
3406     * Register a callback to be invoked when this view is clicked. If this view is not
3407     * clickable, it becomes clickable.
3408     *
3409     * @param l The callback that will run
3410     *
3411     * @see #setClickable(boolean)
3412     */
3413    public void setOnClickListener(OnClickListener l) {
3414        if (!isClickable()) {
3415            setClickable(true);
3416        }
3417        mOnClickListener = l;
3418    }
3419
3420    /**
3421     * Register a callback to be invoked when this view is clicked and held. If this view is not
3422     * long clickable, it becomes long clickable.
3423     *
3424     * @param l The callback that will run
3425     *
3426     * @see #setLongClickable(boolean)
3427     */
3428    public void setOnLongClickListener(OnLongClickListener l) {
3429        if (!isLongClickable()) {
3430            setLongClickable(true);
3431        }
3432        mOnLongClickListener = l;
3433    }
3434
3435    /**
3436     * Register a callback to be invoked when the context menu for this view is
3437     * being built. If this view is not long clickable, it becomes long clickable.
3438     *
3439     * @param l The callback that will run
3440     *
3441     */
3442    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3443        if (!isLongClickable()) {
3444            setLongClickable(true);
3445        }
3446        mOnCreateContextMenuListener = l;
3447    }
3448
3449    /**
3450     * Call this view's OnClickListener, if it is defined.
3451     *
3452     * @return True there was an assigned OnClickListener that was called, false
3453     *         otherwise is returned.
3454     */
3455    public boolean performClick() {
3456        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3457
3458        if (mOnClickListener != null) {
3459            playSoundEffect(SoundEffectConstants.CLICK);
3460            mOnClickListener.onClick(this);
3461            return true;
3462        }
3463
3464        return false;
3465    }
3466
3467    /**
3468     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3469     * OnLongClickListener did not consume the event.
3470     *
3471     * @return True if one of the above receivers consumed the event, false otherwise.
3472     */
3473    public boolean performLongClick() {
3474        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3475
3476        boolean handled = false;
3477        if (mOnLongClickListener != null) {
3478            handled = mOnLongClickListener.onLongClick(View.this);
3479        }
3480        if (!handled) {
3481            handled = showContextMenu();
3482        }
3483        if (handled) {
3484            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3485        }
3486        return handled;
3487    }
3488
3489    /**
3490     * Performs button-related actions during a touch down event.
3491     *
3492     * @param event The event.
3493     * @return True if the down was consumed.
3494     *
3495     * @hide
3496     */
3497    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3498        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3499            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3500                return true;
3501            }
3502        }
3503        return false;
3504    }
3505
3506    /**
3507     * Bring up the context menu for this view.
3508     *
3509     * @return Whether a context menu was displayed.
3510     */
3511    public boolean showContextMenu() {
3512        return getParent().showContextMenuForChild(this);
3513    }
3514
3515    /**
3516     * Bring up the context menu for this view, referring to the item under the specified point.
3517     *
3518     * @param x The referenced x coordinate.
3519     * @param y The referenced y coordinate.
3520     * @param metaState The keyboard modifiers that were pressed.
3521     * @return Whether a context menu was displayed.
3522     *
3523     * @hide
3524     */
3525    public boolean showContextMenu(float x, float y, int metaState) {
3526        return showContextMenu();
3527    }
3528
3529    /**
3530     * Start an action mode.
3531     *
3532     * @param callback Callback that will control the lifecycle of the action mode
3533     * @return The new action mode if it is started, null otherwise
3534     *
3535     * @see ActionMode
3536     */
3537    public ActionMode startActionMode(ActionMode.Callback callback) {
3538        return getParent().startActionModeForChild(this, callback);
3539    }
3540
3541    /**
3542     * Register a callback to be invoked when a key is pressed in this view.
3543     * @param l the key listener to attach to this view
3544     */
3545    public void setOnKeyListener(OnKeyListener l) {
3546        mOnKeyListener = l;
3547    }
3548
3549    /**
3550     * Register a callback to be invoked when a touch event is sent to this view.
3551     * @param l the touch listener to attach to this view
3552     */
3553    public void setOnTouchListener(OnTouchListener l) {
3554        mOnTouchListener = l;
3555    }
3556
3557    /**
3558     * Register a callback to be invoked when a generic motion event is sent to this view.
3559     * @param l the generic motion listener to attach to this view
3560     */
3561    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3562        mOnGenericMotionListener = l;
3563    }
3564
3565    /**
3566     * Register a callback to be invoked when a hover event is sent to this view.
3567     * @param l the hover listener to attach to this view
3568     */
3569    public void setOnHoverListener(OnHoverListener l) {
3570        mOnHoverListener = l;
3571    }
3572
3573    /**
3574     * Register a drag event listener callback object for this View. The parameter is
3575     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3576     * View, the system calls the
3577     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3578     * @param l An implementation of {@link android.view.View.OnDragListener}.
3579     */
3580    public void setOnDragListener(OnDragListener l) {
3581        mOnDragListener = l;
3582    }
3583
3584    /**
3585     * Give this view focus. This will cause
3586     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3587     *
3588     * Note: this does not check whether this {@link View} should get focus, it just
3589     * gives it focus no matter what.  It should only be called internally by framework
3590     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3591     *
3592     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3593     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3594     *        focus moved when requestFocus() is called. It may not always
3595     *        apply, in which case use the default View.FOCUS_DOWN.
3596     * @param previouslyFocusedRect The rectangle of the view that had focus
3597     *        prior in this View's coordinate system.
3598     */
3599    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3600        if (DBG) {
3601            System.out.println(this + " requestFocus()");
3602        }
3603
3604        if ((mPrivateFlags & FOCUSED) == 0) {
3605            mPrivateFlags |= FOCUSED;
3606
3607            if (mParent != null) {
3608                mParent.requestChildFocus(this, this);
3609            }
3610
3611            onFocusChanged(true, direction, previouslyFocusedRect);
3612            refreshDrawableState();
3613        }
3614    }
3615
3616    /**
3617     * Request that a rectangle of this view be visible on the screen,
3618     * scrolling if necessary just enough.
3619     *
3620     * <p>A View should call this if it maintains some notion of which part
3621     * of its content is interesting.  For example, a text editing view
3622     * should call this when its cursor moves.
3623     *
3624     * @param rectangle The rectangle.
3625     * @return Whether any parent scrolled.
3626     */
3627    public boolean requestRectangleOnScreen(Rect rectangle) {
3628        return requestRectangleOnScreen(rectangle, false);
3629    }
3630
3631    /**
3632     * Request that a rectangle of this view be visible on the screen,
3633     * scrolling if necessary just enough.
3634     *
3635     * <p>A View should call this if it maintains some notion of which part
3636     * of its content is interesting.  For example, a text editing view
3637     * should call this when its cursor moves.
3638     *
3639     * <p>When <code>immediate</code> is set to true, scrolling will not be
3640     * animated.
3641     *
3642     * @param rectangle The rectangle.
3643     * @param immediate True to forbid animated scrolling, false otherwise
3644     * @return Whether any parent scrolled.
3645     */
3646    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3647        View child = this;
3648        ViewParent parent = mParent;
3649        boolean scrolled = false;
3650        while (parent != null) {
3651            scrolled |= parent.requestChildRectangleOnScreen(child,
3652                    rectangle, immediate);
3653
3654            // offset rect so next call has the rectangle in the
3655            // coordinate system of its direct child.
3656            rectangle.offset(child.getLeft(), child.getTop());
3657            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3658
3659            if (!(parent instanceof View)) {
3660                break;
3661            }
3662
3663            child = (View) parent;
3664            parent = child.getParent();
3665        }
3666        return scrolled;
3667    }
3668
3669    /**
3670     * Called when this view wants to give up focus. This will cause
3671     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3672     */
3673    public void clearFocus() {
3674        if (DBG) {
3675            System.out.println(this + " clearFocus()");
3676        }
3677
3678        if ((mPrivateFlags & FOCUSED) != 0) {
3679            mPrivateFlags &= ~FOCUSED;
3680
3681            if (mParent != null) {
3682                mParent.clearChildFocus(this);
3683            }
3684
3685            onFocusChanged(false, 0, null);
3686            refreshDrawableState();
3687        }
3688    }
3689
3690    /**
3691     * Called to clear the focus of a view that is about to be removed.
3692     * Doesn't call clearChildFocus, which prevents this view from taking
3693     * focus again before it has been removed from the parent
3694     */
3695    void clearFocusForRemoval() {
3696        if ((mPrivateFlags & FOCUSED) != 0) {
3697            mPrivateFlags &= ~FOCUSED;
3698
3699            onFocusChanged(false, 0, null);
3700            refreshDrawableState();
3701        }
3702    }
3703
3704    /**
3705     * Called internally by the view system when a new view is getting focus.
3706     * This is what clears the old focus.
3707     */
3708    void unFocus() {
3709        if (DBG) {
3710            System.out.println(this + " unFocus()");
3711        }
3712
3713        if ((mPrivateFlags & FOCUSED) != 0) {
3714            mPrivateFlags &= ~FOCUSED;
3715
3716            onFocusChanged(false, 0, null);
3717            refreshDrawableState();
3718        }
3719    }
3720
3721    /**
3722     * Returns true if this view has focus iteself, or is the ancestor of the
3723     * view that has focus.
3724     *
3725     * @return True if this view has or contains focus, false otherwise.
3726     */
3727    @ViewDebug.ExportedProperty(category = "focus")
3728    public boolean hasFocus() {
3729        return (mPrivateFlags & FOCUSED) != 0;
3730    }
3731
3732    /**
3733     * Returns true if this view is focusable or if it contains a reachable View
3734     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3735     * is a View whose parents do not block descendants focus.
3736     *
3737     * Only {@link #VISIBLE} views are considered focusable.
3738     *
3739     * @return True if the view is focusable or if the view contains a focusable
3740     *         View, false otherwise.
3741     *
3742     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3743     */
3744    public boolean hasFocusable() {
3745        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3746    }
3747
3748    /**
3749     * Called by the view system when the focus state of this view changes.
3750     * When the focus change event is caused by directional navigation, direction
3751     * and previouslyFocusedRect provide insight into where the focus is coming from.
3752     * When overriding, be sure to call up through to the super class so that
3753     * the standard focus handling will occur.
3754     *
3755     * @param gainFocus True if the View has focus; false otherwise.
3756     * @param direction The direction focus has moved when requestFocus()
3757     *                  is called to give this view focus. Values are
3758     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3759     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3760     *                  It may not always apply, in which case use the default.
3761     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3762     *        system, of the previously focused view.  If applicable, this will be
3763     *        passed in as finer grained information about where the focus is coming
3764     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3765     */
3766    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3767        if (gainFocus) {
3768            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3769        }
3770
3771        InputMethodManager imm = InputMethodManager.peekInstance();
3772        if (!gainFocus) {
3773            if (isPressed()) {
3774                setPressed(false);
3775            }
3776            if (imm != null && mAttachInfo != null
3777                    && mAttachInfo.mHasWindowFocus) {
3778                imm.focusOut(this);
3779            }
3780            onFocusLost();
3781        } else if (imm != null && mAttachInfo != null
3782                && mAttachInfo.mHasWindowFocus) {
3783            imm.focusIn(this);
3784        }
3785
3786        invalidate(true);
3787        if (mOnFocusChangeListener != null) {
3788            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3789        }
3790
3791        if (mAttachInfo != null) {
3792            mAttachInfo.mKeyDispatchState.reset(this);
3793        }
3794    }
3795
3796    /**
3797     * Sends an accessibility event of the given type. If accessiiblity is
3798     * not enabled this method has no effect. The default implementation calls
3799     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3800     * to populate information about the event source (this View), then calls
3801     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3802     * populate the text content of the event source including its descendants,
3803     * and last calls
3804     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3805     * on its parent to resuest sending of the event to interested parties.
3806     * <p>
3807     * If an {@link AccessibilityDelegate} has been specified via calling
3808     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3809     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3810     * responsible for handling this call.
3811     * </p>
3812     *
3813     * @param eventType The type of the event to send.
3814     *
3815     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3816     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3817     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3818     * @see AccessibilityDelegate
3819     */
3820    public void sendAccessibilityEvent(int eventType) {
3821        if (mAccessibilityDelegate != null) {
3822            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3823        } else {
3824            sendAccessibilityEventInternal(eventType);
3825        }
3826    }
3827
3828    /**
3829     * @see #sendAccessibilityEvent(int)
3830     *
3831     * Note: Called from the default {@link AccessibilityDelegate}.
3832     */
3833    void sendAccessibilityEventInternal(int eventType) {
3834        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3835            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3836        }
3837    }
3838
3839    /**
3840     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3841     * takes as an argument an empty {@link AccessibilityEvent} and does not
3842     * perform a check whether accessibility is enabled.
3843     * <p>
3844     * If an {@link AccessibilityDelegate} has been specified via calling
3845     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3846     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3847     * is responsible for handling this call.
3848     * </p>
3849     *
3850     * @param event The event to send.
3851     *
3852     * @see #sendAccessibilityEvent(int)
3853     */
3854    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3855        if (mAccessibilityDelegate != null) {
3856           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3857        } else {
3858            sendAccessibilityEventUncheckedInternal(event);
3859        }
3860    }
3861
3862    /**
3863     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3864     *
3865     * Note: Called from the default {@link AccessibilityDelegate}.
3866     */
3867    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3868        if (!isShown()) {
3869            return;
3870        }
3871        onInitializeAccessibilityEvent(event);
3872        // Only a subset of accessibility events populates text content.
3873        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
3874            dispatchPopulateAccessibilityEvent(event);
3875        }
3876        // In the beginning we called #isShown(), so we know that getParent() is not null.
3877        getParent().requestSendAccessibilityEvent(this, event);
3878    }
3879
3880    /**
3881     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3882     * to its children for adding their text content to the event. Note that the
3883     * event text is populated in a separate dispatch path since we add to the
3884     * event not only the text of the source but also the text of all its descendants.
3885     * A typical implementation will call
3886     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3887     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3888     * on each child. Override this method if custom population of the event text
3889     * content is required.
3890     * <p>
3891     * If an {@link AccessibilityDelegate} has been specified via calling
3892     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3893     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
3894     * is responsible for handling this call.
3895     * </p>
3896     * <p>
3897     * <em>Note:</em> Accessibility events of certain types are not dispatched for
3898     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
3899     * </p>
3900     *
3901     * @param event The event.
3902     *
3903     * @return True if the event population was completed.
3904     */
3905    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3906        if (mAccessibilityDelegate != null) {
3907            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
3908        } else {
3909            return dispatchPopulateAccessibilityEventInternal(event);
3910        }
3911    }
3912
3913    /**
3914     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3915     *
3916     * Note: Called from the default {@link AccessibilityDelegate}.
3917     */
3918    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
3919        onPopulateAccessibilityEvent(event);
3920        return false;
3921    }
3922
3923    /**
3924     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3925     * giving a chance to this View to populate the accessibility event with its
3926     * text content. While the implementation is free to modify other event
3927     * attributes this should be performed in
3928     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3929     * <p>
3930     * Example: Adding formatted date string to an accessibility event in addition
3931     *          to the text added by the super implementation.
3932     * </p><p><pre><code>
3933     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3934     *     super.onPopulateAccessibilityEvent(event);
3935     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3936     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3937     *         mCurrentDate.getTimeInMillis(), flags);
3938     *     event.getText().add(selectedDateUtterance);
3939     * }
3940     * </code></pre></p>
3941     * <p>
3942     * If an {@link AccessibilityDelegate} has been specified via calling
3943     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3944     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
3945     * is responsible for handling this call.
3946     * </p>
3947     *
3948     * @param event The accessibility event which to populate.
3949     *
3950     * @see #sendAccessibilityEvent(int)
3951     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3952     */
3953    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3954        if (mAccessibilityDelegate != null) {
3955            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
3956        } else {
3957            onPopulateAccessibilityEventInternal(event);
3958        }
3959    }
3960
3961    /**
3962     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
3963     *
3964     * Note: Called from the default {@link AccessibilityDelegate}.
3965     */
3966    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
3967
3968    }
3969
3970    /**
3971     * Initializes an {@link AccessibilityEvent} with information about
3972     * this View which is the event source. In other words, the source of
3973     * an accessibility event is the view whose state change triggered firing
3974     * the event.
3975     * <p>
3976     * Example: Setting the password property of an event in addition
3977     *          to properties set by the super implementation.
3978     * </p><p><pre><code>
3979     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3980     *    super.onInitializeAccessibilityEvent(event);
3981     *    event.setPassword(true);
3982     * }
3983     * </code></pre></p>
3984     * <p>
3985     * If an {@link AccessibilityDelegate} has been specified via calling
3986     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3987     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
3988     * is responsible for handling this call.
3989     * </p>
3990     *
3991     * @param event The event to initialize.
3992     *
3993     * @see #sendAccessibilityEvent(int)
3994     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3995     */
3996    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3997        if (mAccessibilityDelegate != null) {
3998            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
3999        } else {
4000            onInitializeAccessibilityEventInternal(event);
4001        }
4002    }
4003
4004    /**
4005     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4006     *
4007     * Note: Called from the default {@link AccessibilityDelegate}.
4008     */
4009    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4010        event.setSource(this);
4011        event.setClassName(getClass().getName());
4012        event.setPackageName(getContext().getPackageName());
4013        event.setEnabled(isEnabled());
4014        event.setContentDescription(mContentDescription);
4015
4016        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4017            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4018            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4019                    FOCUSABLES_ALL);
4020            event.setItemCount(focusablesTempList.size());
4021            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4022            focusablesTempList.clear();
4023        }
4024    }
4025
4026    /**
4027     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4028     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4029     * This method is responsible for obtaining an accessibility node info from a
4030     * pool of reusable instances and calling
4031     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4032     * initialize the former.
4033     * <p>
4034     * Note: The client is responsible for recycling the obtained instance by calling
4035     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4036     * </p>
4037     * @return A populated {@link AccessibilityNodeInfo}.
4038     *
4039     * @see AccessibilityNodeInfo
4040     */
4041    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4042        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4043        onInitializeAccessibilityNodeInfo(info);
4044        return info;
4045    }
4046
4047    /**
4048     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4049     * The base implementation sets:
4050     * <ul>
4051     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4052     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4053     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4054     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4055     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4056     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4057     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4058     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4059     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4060     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4061     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4062     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4063     * </ul>
4064     * <p>
4065     * Subclasses should override this method, call the super implementation,
4066     * and set additional attributes.
4067     * </p>
4068     * <p>
4069     * If an {@link AccessibilityDelegate} has been specified via calling
4070     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4071     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4072     * is responsible for handling this call.
4073     * </p>
4074     *
4075     * @param info The instance to initialize.
4076     */
4077    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4078        if (mAccessibilityDelegate != null) {
4079            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4080        } else {
4081            onInitializeAccessibilityNodeInfoInternal(info);
4082        }
4083    }
4084
4085    /**
4086     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4087     *
4088     * Note: Called from the default {@link AccessibilityDelegate}.
4089     */
4090    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4091        Rect bounds = mAttachInfo.mTmpInvalRect;
4092        getDrawingRect(bounds);
4093        info.setBoundsInParent(bounds);
4094
4095        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4096        getLocationOnScreen(locationOnScreen);
4097        bounds.offsetTo(0, 0);
4098        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4099        info.setBoundsInScreen(bounds);
4100
4101        ViewParent parent = getParent();
4102        if (parent instanceof View) {
4103            View parentView = (View) parent;
4104            info.setParent(parentView);
4105        }
4106
4107        info.setPackageName(mContext.getPackageName());
4108        info.setClassName(getClass().getName());
4109        info.setContentDescription(getContentDescription());
4110
4111        info.setEnabled(isEnabled());
4112        info.setClickable(isClickable());
4113        info.setFocusable(isFocusable());
4114        info.setFocused(isFocused());
4115        info.setSelected(isSelected());
4116        info.setLongClickable(isLongClickable());
4117
4118        // TODO: These make sense only if we are in an AdapterView but all
4119        // views can be selected. Maybe from accessiiblity perspective
4120        // we should report as selectable view in an AdapterView.
4121        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4122        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4123
4124        if (isFocusable()) {
4125            if (isFocused()) {
4126                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4127            } else {
4128                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4129            }
4130        }
4131    }
4132
4133    /**
4134     * Sets a delegate for implementing accessibility support via compositon as
4135     * opposed to inheritance. The delegate's primary use is for implementing
4136     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4137     *
4138     * @param delegate The delegate instance.
4139     *
4140     * @see AccessibilityDelegate
4141     */
4142    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4143        mAccessibilityDelegate = delegate;
4144    }
4145
4146    /**
4147     * Gets the unique identifier of this view on the screen for accessibility purposes.
4148     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4149     *
4150     * @return The view accessibility id.
4151     *
4152     * @hide
4153     */
4154    public int getAccessibilityViewId() {
4155        if (mAccessibilityViewId == NO_ID) {
4156            mAccessibilityViewId = sNextAccessibilityViewId++;
4157        }
4158        return mAccessibilityViewId;
4159    }
4160
4161    /**
4162     * Gets the unique identifier of the window in which this View reseides.
4163     *
4164     * @return The window accessibility id.
4165     *
4166     * @hide
4167     */
4168    public int getAccessibilityWindowId() {
4169        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4170    }
4171
4172    /**
4173     * Gets the {@link View} description. It briefly describes the view and is
4174     * primarily used for accessibility support. Set this property to enable
4175     * better accessibility support for your application. This is especially
4176     * true for views that do not have textual representation (For example,
4177     * ImageButton).
4178     *
4179     * @return The content descriptiopn.
4180     *
4181     * @attr ref android.R.styleable#View_contentDescription
4182     */
4183    public CharSequence getContentDescription() {
4184        return mContentDescription;
4185    }
4186
4187    /**
4188     * Sets the {@link View} description. It briefly describes the view and is
4189     * primarily used for accessibility support. Set this property to enable
4190     * better accessibility support for your application. This is especially
4191     * true for views that do not have textual representation (For example,
4192     * ImageButton).
4193     *
4194     * @param contentDescription The content description.
4195     *
4196     * @attr ref android.R.styleable#View_contentDescription
4197     */
4198    public void setContentDescription(CharSequence contentDescription) {
4199        mContentDescription = contentDescription;
4200    }
4201
4202    /**
4203     * Invoked whenever this view loses focus, either by losing window focus or by losing
4204     * focus within its window. This method can be used to clear any state tied to the
4205     * focus. For instance, if a button is held pressed with the trackball and the window
4206     * loses focus, this method can be used to cancel the press.
4207     *
4208     * Subclasses of View overriding this method should always call super.onFocusLost().
4209     *
4210     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4211     * @see #onWindowFocusChanged(boolean)
4212     *
4213     * @hide pending API council approval
4214     */
4215    protected void onFocusLost() {
4216        resetPressedState();
4217    }
4218
4219    private void resetPressedState() {
4220        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4221            return;
4222        }
4223
4224        if (isPressed()) {
4225            setPressed(false);
4226
4227            if (!mHasPerformedLongPress) {
4228                removeLongPressCallback();
4229            }
4230        }
4231    }
4232
4233    /**
4234     * Returns true if this view has focus
4235     *
4236     * @return True if this view has focus, false otherwise.
4237     */
4238    @ViewDebug.ExportedProperty(category = "focus")
4239    public boolean isFocused() {
4240        return (mPrivateFlags & FOCUSED) != 0;
4241    }
4242
4243    /**
4244     * Find the view in the hierarchy rooted at this view that currently has
4245     * focus.
4246     *
4247     * @return The view that currently has focus, or null if no focused view can
4248     *         be found.
4249     */
4250    public View findFocus() {
4251        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4252    }
4253
4254    /**
4255     * Change whether this view is one of the set of scrollable containers in
4256     * its window.  This will be used to determine whether the window can
4257     * resize or must pan when a soft input area is open -- scrollable
4258     * containers allow the window to use resize mode since the container
4259     * will appropriately shrink.
4260     */
4261    public void setScrollContainer(boolean isScrollContainer) {
4262        if (isScrollContainer) {
4263            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4264                mAttachInfo.mScrollContainers.add(this);
4265                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4266            }
4267            mPrivateFlags |= SCROLL_CONTAINER;
4268        } else {
4269            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4270                mAttachInfo.mScrollContainers.remove(this);
4271            }
4272            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4273        }
4274    }
4275
4276    /**
4277     * Returns the quality of the drawing cache.
4278     *
4279     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4280     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4281     *
4282     * @see #setDrawingCacheQuality(int)
4283     * @see #setDrawingCacheEnabled(boolean)
4284     * @see #isDrawingCacheEnabled()
4285     *
4286     * @attr ref android.R.styleable#View_drawingCacheQuality
4287     */
4288    public int getDrawingCacheQuality() {
4289        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4290    }
4291
4292    /**
4293     * Set the drawing cache quality of this view. This value is used only when the
4294     * drawing cache is enabled
4295     *
4296     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4297     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4298     *
4299     * @see #getDrawingCacheQuality()
4300     * @see #setDrawingCacheEnabled(boolean)
4301     * @see #isDrawingCacheEnabled()
4302     *
4303     * @attr ref android.R.styleable#View_drawingCacheQuality
4304     */
4305    public void setDrawingCacheQuality(int quality) {
4306        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4307    }
4308
4309    /**
4310     * Returns whether the screen should remain on, corresponding to the current
4311     * value of {@link #KEEP_SCREEN_ON}.
4312     *
4313     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4314     *
4315     * @see #setKeepScreenOn(boolean)
4316     *
4317     * @attr ref android.R.styleable#View_keepScreenOn
4318     */
4319    public boolean getKeepScreenOn() {
4320        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4321    }
4322
4323    /**
4324     * Controls whether the screen should remain on, modifying the
4325     * value of {@link #KEEP_SCREEN_ON}.
4326     *
4327     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4328     *
4329     * @see #getKeepScreenOn()
4330     *
4331     * @attr ref android.R.styleable#View_keepScreenOn
4332     */
4333    public void setKeepScreenOn(boolean keepScreenOn) {
4334        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4335    }
4336
4337    /**
4338     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4339     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4340     *
4341     * @attr ref android.R.styleable#View_nextFocusLeft
4342     */
4343    public int getNextFocusLeftId() {
4344        return mNextFocusLeftId;
4345    }
4346
4347    /**
4348     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4349     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4350     * decide automatically.
4351     *
4352     * @attr ref android.R.styleable#View_nextFocusLeft
4353     */
4354    public void setNextFocusLeftId(int nextFocusLeftId) {
4355        mNextFocusLeftId = nextFocusLeftId;
4356    }
4357
4358    /**
4359     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4360     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4361     *
4362     * @attr ref android.R.styleable#View_nextFocusRight
4363     */
4364    public int getNextFocusRightId() {
4365        return mNextFocusRightId;
4366    }
4367
4368    /**
4369     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4370     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4371     * decide automatically.
4372     *
4373     * @attr ref android.R.styleable#View_nextFocusRight
4374     */
4375    public void setNextFocusRightId(int nextFocusRightId) {
4376        mNextFocusRightId = nextFocusRightId;
4377    }
4378
4379    /**
4380     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4381     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4382     *
4383     * @attr ref android.R.styleable#View_nextFocusUp
4384     */
4385    public int getNextFocusUpId() {
4386        return mNextFocusUpId;
4387    }
4388
4389    /**
4390     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4391     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4392     * decide automatically.
4393     *
4394     * @attr ref android.R.styleable#View_nextFocusUp
4395     */
4396    public void setNextFocusUpId(int nextFocusUpId) {
4397        mNextFocusUpId = nextFocusUpId;
4398    }
4399
4400    /**
4401     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4402     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4403     *
4404     * @attr ref android.R.styleable#View_nextFocusDown
4405     */
4406    public int getNextFocusDownId() {
4407        return mNextFocusDownId;
4408    }
4409
4410    /**
4411     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4412     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4413     * decide automatically.
4414     *
4415     * @attr ref android.R.styleable#View_nextFocusDown
4416     */
4417    public void setNextFocusDownId(int nextFocusDownId) {
4418        mNextFocusDownId = nextFocusDownId;
4419    }
4420
4421    /**
4422     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4423     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4424     *
4425     * @attr ref android.R.styleable#View_nextFocusForward
4426     */
4427    public int getNextFocusForwardId() {
4428        return mNextFocusForwardId;
4429    }
4430
4431    /**
4432     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4433     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4434     * decide automatically.
4435     *
4436     * @attr ref android.R.styleable#View_nextFocusForward
4437     */
4438    public void setNextFocusForwardId(int nextFocusForwardId) {
4439        mNextFocusForwardId = nextFocusForwardId;
4440    }
4441
4442    /**
4443     * Returns the visibility of this view and all of its ancestors
4444     *
4445     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4446     */
4447    public boolean isShown() {
4448        View current = this;
4449        //noinspection ConstantConditions
4450        do {
4451            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4452                return false;
4453            }
4454            ViewParent parent = current.mParent;
4455            if (parent == null) {
4456                return false; // We are not attached to the view root
4457            }
4458            if (!(parent instanceof View)) {
4459                return true;
4460            }
4461            current = (View) parent;
4462        } while (current != null);
4463
4464        return false;
4465    }
4466
4467    /**
4468     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4469     * is set
4470     *
4471     * @param insets Insets for system windows
4472     *
4473     * @return True if this view applied the insets, false otherwise
4474     */
4475    protected boolean fitSystemWindows(Rect insets) {
4476        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4477            mPaddingLeft = insets.left;
4478            mPaddingTop = insets.top;
4479            mPaddingRight = insets.right;
4480            mPaddingBottom = insets.bottom;
4481            requestLayout();
4482            return true;
4483        }
4484        return false;
4485    }
4486
4487    /**
4488     * Set whether or not this view should account for system screen decorations
4489     * such as the status bar and inset its content. This allows this view to be
4490     * positioned in absolute screen coordinates and remain visible to the user.
4491     *
4492     * <p>This should only be used by top-level window decor views.
4493     *
4494     * @param fitSystemWindows true to inset content for system screen decorations, false for
4495     *                         default behavior.
4496     *
4497     * @attr ref android.R.styleable#View_fitsSystemWindows
4498     */
4499    public void setFitsSystemWindows(boolean fitSystemWindows) {
4500        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4501    }
4502
4503    /**
4504     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4505     * will account for system screen decorations such as the status bar and inset its
4506     * content. This allows the view to be positioned in absolute screen coordinates
4507     * and remain visible to the user.
4508     *
4509     * @return true if this view will adjust its content bounds for system screen decorations.
4510     *
4511     * @attr ref android.R.styleable#View_fitsSystemWindows
4512     */
4513    public boolean fitsSystemWindows() {
4514        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4515    }
4516
4517    /**
4518     * Returns the visibility status for this view.
4519     *
4520     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4521     * @attr ref android.R.styleable#View_visibility
4522     */
4523    @ViewDebug.ExportedProperty(mapping = {
4524        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4525        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4526        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4527    })
4528    public int getVisibility() {
4529        return mViewFlags & VISIBILITY_MASK;
4530    }
4531
4532    /**
4533     * Set the enabled state of this view.
4534     *
4535     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4536     * @attr ref android.R.styleable#View_visibility
4537     */
4538    @RemotableViewMethod
4539    public void setVisibility(int visibility) {
4540        setFlags(visibility, VISIBILITY_MASK);
4541        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4542    }
4543
4544    /**
4545     * Returns the enabled status for this view. The interpretation of the
4546     * enabled state varies by subclass.
4547     *
4548     * @return True if this view is enabled, false otherwise.
4549     */
4550    @ViewDebug.ExportedProperty
4551    public boolean isEnabled() {
4552        return (mViewFlags & ENABLED_MASK) == ENABLED;
4553    }
4554
4555    /**
4556     * Set the enabled state of this view. The interpretation of the enabled
4557     * state varies by subclass.
4558     *
4559     * @param enabled True if this view is enabled, false otherwise.
4560     */
4561    @RemotableViewMethod
4562    public void setEnabled(boolean enabled) {
4563        if (enabled == isEnabled()) return;
4564
4565        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4566
4567        /*
4568         * The View most likely has to change its appearance, so refresh
4569         * the drawable state.
4570         */
4571        refreshDrawableState();
4572
4573        // Invalidate too, since the default behavior for views is to be
4574        // be drawn at 50% alpha rather than to change the drawable.
4575        invalidate(true);
4576    }
4577
4578    /**
4579     * Set whether this view can receive the focus.
4580     *
4581     * Setting this to false will also ensure that this view is not focusable
4582     * in touch mode.
4583     *
4584     * @param focusable If true, this view can receive the focus.
4585     *
4586     * @see #setFocusableInTouchMode(boolean)
4587     * @attr ref android.R.styleable#View_focusable
4588     */
4589    public void setFocusable(boolean focusable) {
4590        if (!focusable) {
4591            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4592        }
4593        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4594    }
4595
4596    /**
4597     * Set whether this view can receive focus while in touch mode.
4598     *
4599     * Setting this to true will also ensure that this view is focusable.
4600     *
4601     * @param focusableInTouchMode If true, this view can receive the focus while
4602     *   in touch mode.
4603     *
4604     * @see #setFocusable(boolean)
4605     * @attr ref android.R.styleable#View_focusableInTouchMode
4606     */
4607    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4608        // Focusable in touch mode should always be set before the focusable flag
4609        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4610        // which, in touch mode, will not successfully request focus on this view
4611        // because the focusable in touch mode flag is not set
4612        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4613        if (focusableInTouchMode) {
4614            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4615        }
4616    }
4617
4618    /**
4619     * Set whether this view should have sound effects enabled for events such as
4620     * clicking and touching.
4621     *
4622     * <p>You may wish to disable sound effects for a view if you already play sounds,
4623     * for instance, a dial key that plays dtmf tones.
4624     *
4625     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4626     * @see #isSoundEffectsEnabled()
4627     * @see #playSoundEffect(int)
4628     * @attr ref android.R.styleable#View_soundEffectsEnabled
4629     */
4630    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4631        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4632    }
4633
4634    /**
4635     * @return whether this view should have sound effects enabled for events such as
4636     *     clicking and touching.
4637     *
4638     * @see #setSoundEffectsEnabled(boolean)
4639     * @see #playSoundEffect(int)
4640     * @attr ref android.R.styleable#View_soundEffectsEnabled
4641     */
4642    @ViewDebug.ExportedProperty
4643    public boolean isSoundEffectsEnabled() {
4644        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4645    }
4646
4647    /**
4648     * Set whether this view should have haptic feedback for events such as
4649     * long presses.
4650     *
4651     * <p>You may wish to disable haptic feedback if your view already controls
4652     * its own haptic feedback.
4653     *
4654     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4655     * @see #isHapticFeedbackEnabled()
4656     * @see #performHapticFeedback(int)
4657     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4658     */
4659    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4660        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4661    }
4662
4663    /**
4664     * @return whether this view should have haptic feedback enabled for events
4665     * long presses.
4666     *
4667     * @see #setHapticFeedbackEnabled(boolean)
4668     * @see #performHapticFeedback(int)
4669     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4670     */
4671    @ViewDebug.ExportedProperty
4672    public boolean isHapticFeedbackEnabled() {
4673        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4674    }
4675
4676    /**
4677     * Returns the layout direction for this view.
4678     *
4679     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4680     *   {@link #LAYOUT_DIRECTION_RTL},
4681     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4682     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4683     * @attr ref android.R.styleable#View_layoutDirection
4684     *
4685     * @hide
4686     */
4687    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4688        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4689        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4690        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4691        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4692    })
4693    public int getLayoutDirection() {
4694        return mViewFlags & LAYOUT_DIRECTION_MASK;
4695    }
4696
4697    /**
4698     * Set the layout direction for this view. This will propagate a reset of layout direction
4699     * resolution to the view's children and resolve layout direction for this view.
4700     *
4701     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4702     *   {@link #LAYOUT_DIRECTION_RTL},
4703     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4704     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4705     *
4706     * @attr ref android.R.styleable#View_layoutDirection
4707     *
4708     * @hide
4709     */
4710    @RemotableViewMethod
4711    public void setLayoutDirection(int layoutDirection) {
4712        if (getLayoutDirection() != layoutDirection) {
4713            resetResolvedLayoutDirection();
4714            // Setting the flag will also request a layout.
4715            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4716        }
4717    }
4718
4719    /**
4720     * Returns the resolved layout direction for this view.
4721     *
4722     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4723     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4724     *
4725     * @hide
4726     */
4727    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4728        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4729        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4730    })
4731    public int getResolvedLayoutDirection() {
4732        resolveLayoutDirectionIfNeeded();
4733        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4734                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4735    }
4736
4737    /**
4738     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4739     * layout attribute and/or the inherited value from the parent.</p>
4740     *
4741     * @return true if the layout is right-to-left.
4742     *
4743     * @hide
4744     */
4745    @ViewDebug.ExportedProperty(category = "layout")
4746    public boolean isLayoutRtl() {
4747        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4748    }
4749
4750    /**
4751     * If this view doesn't do any drawing on its own, set this flag to
4752     * allow further optimizations. By default, this flag is not set on
4753     * View, but could be set on some View subclasses such as ViewGroup.
4754     *
4755     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4756     * you should clear this flag.
4757     *
4758     * @param willNotDraw whether or not this View draw on its own
4759     */
4760    public void setWillNotDraw(boolean willNotDraw) {
4761        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4762    }
4763
4764    /**
4765     * Returns whether or not this View draws on its own.
4766     *
4767     * @return true if this view has nothing to draw, false otherwise
4768     */
4769    @ViewDebug.ExportedProperty(category = "drawing")
4770    public boolean willNotDraw() {
4771        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4772    }
4773
4774    /**
4775     * When a View's drawing cache is enabled, drawing is redirected to an
4776     * offscreen bitmap. Some views, like an ImageView, must be able to
4777     * bypass this mechanism if they already draw a single bitmap, to avoid
4778     * unnecessary usage of the memory.
4779     *
4780     * @param willNotCacheDrawing true if this view does not cache its
4781     *        drawing, false otherwise
4782     */
4783    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4784        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4785    }
4786
4787    /**
4788     * Returns whether or not this View can cache its drawing or not.
4789     *
4790     * @return true if this view does not cache its drawing, false otherwise
4791     */
4792    @ViewDebug.ExportedProperty(category = "drawing")
4793    public boolean willNotCacheDrawing() {
4794        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4795    }
4796
4797    /**
4798     * Indicates whether this view reacts to click events or not.
4799     *
4800     * @return true if the view is clickable, false otherwise
4801     *
4802     * @see #setClickable(boolean)
4803     * @attr ref android.R.styleable#View_clickable
4804     */
4805    @ViewDebug.ExportedProperty
4806    public boolean isClickable() {
4807        return (mViewFlags & CLICKABLE) == CLICKABLE;
4808    }
4809
4810    /**
4811     * Enables or disables click events for this view. When a view
4812     * is clickable it will change its state to "pressed" on every click.
4813     * Subclasses should set the view clickable to visually react to
4814     * user's clicks.
4815     *
4816     * @param clickable true to make the view clickable, false otherwise
4817     *
4818     * @see #isClickable()
4819     * @attr ref android.R.styleable#View_clickable
4820     */
4821    public void setClickable(boolean clickable) {
4822        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4823    }
4824
4825    /**
4826     * Indicates whether this view reacts to long click events or not.
4827     *
4828     * @return true if the view is long clickable, false otherwise
4829     *
4830     * @see #setLongClickable(boolean)
4831     * @attr ref android.R.styleable#View_longClickable
4832     */
4833    public boolean isLongClickable() {
4834        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4835    }
4836
4837    /**
4838     * Enables or disables long click events for this view. When a view is long
4839     * clickable it reacts to the user holding down the button for a longer
4840     * duration than a tap. This event can either launch the listener or a
4841     * context menu.
4842     *
4843     * @param longClickable true to make the view long clickable, false otherwise
4844     * @see #isLongClickable()
4845     * @attr ref android.R.styleable#View_longClickable
4846     */
4847    public void setLongClickable(boolean longClickable) {
4848        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4849    }
4850
4851    /**
4852     * Sets the pressed state for this view.
4853     *
4854     * @see #isClickable()
4855     * @see #setClickable(boolean)
4856     *
4857     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4858     *        the View's internal state from a previously set "pressed" state.
4859     */
4860    public void setPressed(boolean pressed) {
4861        if (pressed) {
4862            mPrivateFlags |= PRESSED;
4863        } else {
4864            mPrivateFlags &= ~PRESSED;
4865        }
4866        refreshDrawableState();
4867        dispatchSetPressed(pressed);
4868    }
4869
4870    /**
4871     * Dispatch setPressed to all of this View's children.
4872     *
4873     * @see #setPressed(boolean)
4874     *
4875     * @param pressed The new pressed state
4876     */
4877    protected void dispatchSetPressed(boolean pressed) {
4878    }
4879
4880    /**
4881     * Indicates whether the view is currently in pressed state. Unless
4882     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4883     * the pressed state.
4884     *
4885     * @see #setPressed(boolean)
4886     * @see #isClickable()
4887     * @see #setClickable(boolean)
4888     *
4889     * @return true if the view is currently pressed, false otherwise
4890     */
4891    public boolean isPressed() {
4892        return (mPrivateFlags & PRESSED) == PRESSED;
4893    }
4894
4895    /**
4896     * Indicates whether this view will save its state (that is,
4897     * whether its {@link #onSaveInstanceState} method will be called).
4898     *
4899     * @return Returns true if the view state saving is enabled, else false.
4900     *
4901     * @see #setSaveEnabled(boolean)
4902     * @attr ref android.R.styleable#View_saveEnabled
4903     */
4904    public boolean isSaveEnabled() {
4905        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4906    }
4907
4908    /**
4909     * Controls whether the saving of this view's state is
4910     * enabled (that is, whether its {@link #onSaveInstanceState} method
4911     * will be called).  Note that even if freezing is enabled, the
4912     * view still must have an id assigned to it (via {@link #setId(int)})
4913     * for its state to be saved.  This flag can only disable the
4914     * saving of this view; any child views may still have their state saved.
4915     *
4916     * @param enabled Set to false to <em>disable</em> state saving, or true
4917     * (the default) to allow it.
4918     *
4919     * @see #isSaveEnabled()
4920     * @see #setId(int)
4921     * @see #onSaveInstanceState()
4922     * @attr ref android.R.styleable#View_saveEnabled
4923     */
4924    public void setSaveEnabled(boolean enabled) {
4925        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4926    }
4927
4928    /**
4929     * Gets whether the framework should discard touches when the view's
4930     * window is obscured by another visible window.
4931     * Refer to the {@link View} security documentation for more details.
4932     *
4933     * @return True if touch filtering is enabled.
4934     *
4935     * @see #setFilterTouchesWhenObscured(boolean)
4936     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4937     */
4938    @ViewDebug.ExportedProperty
4939    public boolean getFilterTouchesWhenObscured() {
4940        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4941    }
4942
4943    /**
4944     * Sets whether the framework should discard touches when the view's
4945     * window is obscured by another visible window.
4946     * Refer to the {@link View} security documentation for more details.
4947     *
4948     * @param enabled True if touch filtering should be enabled.
4949     *
4950     * @see #getFilterTouchesWhenObscured
4951     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4952     */
4953    public void setFilterTouchesWhenObscured(boolean enabled) {
4954        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4955                FILTER_TOUCHES_WHEN_OBSCURED);
4956    }
4957
4958    /**
4959     * Indicates whether the entire hierarchy under this view will save its
4960     * state when a state saving traversal occurs from its parent.  The default
4961     * is true; if false, these views will not be saved unless
4962     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4963     *
4964     * @return Returns true if the view state saving from parent is enabled, else false.
4965     *
4966     * @see #setSaveFromParentEnabled(boolean)
4967     */
4968    public boolean isSaveFromParentEnabled() {
4969        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4970    }
4971
4972    /**
4973     * Controls whether the entire hierarchy under this view will save its
4974     * state when a state saving traversal occurs from its parent.  The default
4975     * is true; if false, these views will not be saved unless
4976     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4977     *
4978     * @param enabled Set to false to <em>disable</em> state saving, or true
4979     * (the default) to allow it.
4980     *
4981     * @see #isSaveFromParentEnabled()
4982     * @see #setId(int)
4983     * @see #onSaveInstanceState()
4984     */
4985    public void setSaveFromParentEnabled(boolean enabled) {
4986        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4987    }
4988
4989
4990    /**
4991     * Returns whether this View is able to take focus.
4992     *
4993     * @return True if this view can take focus, or false otherwise.
4994     * @attr ref android.R.styleable#View_focusable
4995     */
4996    @ViewDebug.ExportedProperty(category = "focus")
4997    public final boolean isFocusable() {
4998        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4999    }
5000
5001    /**
5002     * When a view is focusable, it may not want to take focus when in touch mode.
5003     * For example, a button would like focus when the user is navigating via a D-pad
5004     * so that the user can click on it, but once the user starts touching the screen,
5005     * the button shouldn't take focus
5006     * @return Whether the view is focusable in touch mode.
5007     * @attr ref android.R.styleable#View_focusableInTouchMode
5008     */
5009    @ViewDebug.ExportedProperty
5010    public final boolean isFocusableInTouchMode() {
5011        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5012    }
5013
5014    /**
5015     * Find the nearest view in the specified direction that can take focus.
5016     * This does not actually give focus to that view.
5017     *
5018     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5019     *
5020     * @return The nearest focusable in the specified direction, or null if none
5021     *         can be found.
5022     */
5023    public View focusSearch(int direction) {
5024        if (mParent != null) {
5025            return mParent.focusSearch(this, direction);
5026        } else {
5027            return null;
5028        }
5029    }
5030
5031    /**
5032     * This method is the last chance for the focused view and its ancestors to
5033     * respond to an arrow key. This is called when the focused view did not
5034     * consume the key internally, nor could the view system find a new view in
5035     * the requested direction to give focus to.
5036     *
5037     * @param focused The currently focused view.
5038     * @param direction The direction focus wants to move. One of FOCUS_UP,
5039     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5040     * @return True if the this view consumed this unhandled move.
5041     */
5042    public boolean dispatchUnhandledMove(View focused, int direction) {
5043        return false;
5044    }
5045
5046    /**
5047     * If a user manually specified the next view id for a particular direction,
5048     * use the root to look up the view.
5049     * @param root The root view of the hierarchy containing this view.
5050     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5051     * or FOCUS_BACKWARD.
5052     * @return The user specified next view, or null if there is none.
5053     */
5054    View findUserSetNextFocus(View root, int direction) {
5055        switch (direction) {
5056            case FOCUS_LEFT:
5057                if (mNextFocusLeftId == View.NO_ID) return null;
5058                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5059            case FOCUS_RIGHT:
5060                if (mNextFocusRightId == View.NO_ID) return null;
5061                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5062            case FOCUS_UP:
5063                if (mNextFocusUpId == View.NO_ID) return null;
5064                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5065            case FOCUS_DOWN:
5066                if (mNextFocusDownId == View.NO_ID) return null;
5067                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5068            case FOCUS_FORWARD:
5069                if (mNextFocusForwardId == View.NO_ID) return null;
5070                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5071            case FOCUS_BACKWARD: {
5072                final int id = mID;
5073                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5074                    @Override
5075                    public boolean apply(View t) {
5076                        return t.mNextFocusForwardId == id;
5077                    }
5078                });
5079            }
5080        }
5081        return null;
5082    }
5083
5084    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5085        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5086            @Override
5087            public boolean apply(View t) {
5088                return t.mID == childViewId;
5089            }
5090        });
5091
5092        if (result == null) {
5093            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5094                    + "by user for id " + childViewId);
5095        }
5096        return result;
5097    }
5098
5099    /**
5100     * Find and return all focusable views that are descendants of this view,
5101     * possibly including this view if it is focusable itself.
5102     *
5103     * @param direction The direction of the focus
5104     * @return A list of focusable views
5105     */
5106    public ArrayList<View> getFocusables(int direction) {
5107        ArrayList<View> result = new ArrayList<View>(24);
5108        addFocusables(result, direction);
5109        return result;
5110    }
5111
5112    /**
5113     * Add any focusable views that are descendants of this view (possibly
5114     * including this view if it is focusable itself) to views.  If we are in touch mode,
5115     * only add views that are also focusable in touch mode.
5116     *
5117     * @param views Focusable views found so far
5118     * @param direction The direction of the focus
5119     */
5120    public void addFocusables(ArrayList<View> views, int direction) {
5121        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5122    }
5123
5124    /**
5125     * Adds any focusable views that are descendants of this view (possibly
5126     * including this view if it is focusable itself) to views. This method
5127     * adds all focusable views regardless if we are in touch mode or
5128     * only views focusable in touch mode if we are in touch mode depending on
5129     * the focusable mode paramater.
5130     *
5131     * @param views Focusable views found so far or null if all we are interested is
5132     *        the number of focusables.
5133     * @param direction The direction of the focus.
5134     * @param focusableMode The type of focusables to be added.
5135     *
5136     * @see #FOCUSABLES_ALL
5137     * @see #FOCUSABLES_TOUCH_MODE
5138     */
5139    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5140        if (!isFocusable()) {
5141            return;
5142        }
5143
5144        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5145                isInTouchMode() && !isFocusableInTouchMode()) {
5146            return;
5147        }
5148
5149        if (views != null) {
5150            views.add(this);
5151        }
5152    }
5153
5154    /**
5155     * Finds the Views that contain given text. The containment is case insensitive.
5156     * The search is performed by either the text that the View renders or the content
5157     * description that describes the view for accessibility purposes and the view does
5158     * not render or both. Clients can specify how the search is to be performed via
5159     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5160     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5161     *
5162     * @param outViews The output list of matching Views.
5163     * @param searched The text to match against.
5164     *
5165     * @see #FIND_VIEWS_WITH_TEXT
5166     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5167     * @see #setContentDescription(CharSequence)
5168     */
5169    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5170        if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 && !TextUtils.isEmpty(searched)
5171                && !TextUtils.isEmpty(mContentDescription)) {
5172            String searchedLowerCase = searched.toString().toLowerCase();
5173            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5174            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5175                outViews.add(this);
5176            }
5177        }
5178    }
5179
5180    /**
5181     * Find and return all touchable views that are descendants of this view,
5182     * possibly including this view if it is touchable itself.
5183     *
5184     * @return A list of touchable views
5185     */
5186    public ArrayList<View> getTouchables() {
5187        ArrayList<View> result = new ArrayList<View>();
5188        addTouchables(result);
5189        return result;
5190    }
5191
5192    /**
5193     * Add any touchable views that are descendants of this view (possibly
5194     * including this view if it is touchable itself) to views.
5195     *
5196     * @param views Touchable views found so far
5197     */
5198    public void addTouchables(ArrayList<View> views) {
5199        final int viewFlags = mViewFlags;
5200
5201        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5202                && (viewFlags & ENABLED_MASK) == ENABLED) {
5203            views.add(this);
5204        }
5205    }
5206
5207    /**
5208     * Call this to try to give focus to a specific view or to one of its
5209     * descendants.
5210     *
5211     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5212     * false), or if it is focusable and it is not focusable in touch mode
5213     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5214     *
5215     * See also {@link #focusSearch(int)}, which is what you call to say that you
5216     * have focus, and you want your parent to look for the next one.
5217     *
5218     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5219     * {@link #FOCUS_DOWN} and <code>null</code>.
5220     *
5221     * @return Whether this view or one of its descendants actually took focus.
5222     */
5223    public final boolean requestFocus() {
5224        return requestFocus(View.FOCUS_DOWN);
5225    }
5226
5227
5228    /**
5229     * Call this to try to give focus to a specific view or to one of its
5230     * descendants and give it a hint about what direction focus is heading.
5231     *
5232     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5233     * false), or if it is focusable and it is not focusable in touch mode
5234     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5235     *
5236     * See also {@link #focusSearch(int)}, which is what you call to say that you
5237     * have focus, and you want your parent to look for the next one.
5238     *
5239     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5240     * <code>null</code> set for the previously focused rectangle.
5241     *
5242     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5243     * @return Whether this view or one of its descendants actually took focus.
5244     */
5245    public final boolean requestFocus(int direction) {
5246        return requestFocus(direction, null);
5247    }
5248
5249    /**
5250     * Call this to try to give focus to a specific view or to one of its descendants
5251     * and give it hints about the direction and a specific rectangle that the focus
5252     * is coming from.  The rectangle can help give larger views a finer grained hint
5253     * about where focus is coming from, and therefore, where to show selection, or
5254     * forward focus change internally.
5255     *
5256     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5257     * false), or if it is focusable and it is not focusable in touch mode
5258     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5259     *
5260     * A View will not take focus if it is not visible.
5261     *
5262     * A View will not take focus if one of its parents has
5263     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5264     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5265     *
5266     * See also {@link #focusSearch(int)}, which is what you call to say that you
5267     * have focus, and you want your parent to look for the next one.
5268     *
5269     * You may wish to override this method if your custom {@link View} has an internal
5270     * {@link View} that it wishes to forward the request to.
5271     *
5272     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5273     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5274     *        to give a finer grained hint about where focus is coming from.  May be null
5275     *        if there is no hint.
5276     * @return Whether this view or one of its descendants actually took focus.
5277     */
5278    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5279        // need to be focusable
5280        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5281                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5282            return false;
5283        }
5284
5285        // need to be focusable in touch mode if in touch mode
5286        if (isInTouchMode() &&
5287            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5288               return false;
5289        }
5290
5291        // need to not have any parents blocking us
5292        if (hasAncestorThatBlocksDescendantFocus()) {
5293            return false;
5294        }
5295
5296        handleFocusGainInternal(direction, previouslyFocusedRect);
5297        return true;
5298    }
5299
5300    /** Gets the ViewAncestor, or null if not attached. */
5301    /*package*/ ViewRootImpl getViewRootImpl() {
5302        View root = getRootView();
5303        return root != null ? (ViewRootImpl)root.getParent() : null;
5304    }
5305
5306    /**
5307     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5308     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5309     * touch mode to request focus when they are touched.
5310     *
5311     * @return Whether this view or one of its descendants actually took focus.
5312     *
5313     * @see #isInTouchMode()
5314     *
5315     */
5316    public final boolean requestFocusFromTouch() {
5317        // Leave touch mode if we need to
5318        if (isInTouchMode()) {
5319            ViewRootImpl viewRoot = getViewRootImpl();
5320            if (viewRoot != null) {
5321                viewRoot.ensureTouchMode(false);
5322            }
5323        }
5324        return requestFocus(View.FOCUS_DOWN);
5325    }
5326
5327    /**
5328     * @return Whether any ancestor of this view blocks descendant focus.
5329     */
5330    private boolean hasAncestorThatBlocksDescendantFocus() {
5331        ViewParent ancestor = mParent;
5332        while (ancestor instanceof ViewGroup) {
5333            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5334            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5335                return true;
5336            } else {
5337                ancestor = vgAncestor.getParent();
5338            }
5339        }
5340        return false;
5341    }
5342
5343    /**
5344     * @hide
5345     */
5346    public void dispatchStartTemporaryDetach() {
5347        onStartTemporaryDetach();
5348    }
5349
5350    /**
5351     * This is called when a container is going to temporarily detach a child, with
5352     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5353     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5354     * {@link #onDetachedFromWindow()} when the container is done.
5355     */
5356    public void onStartTemporaryDetach() {
5357        removeUnsetPressCallback();
5358        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5359    }
5360
5361    /**
5362     * @hide
5363     */
5364    public void dispatchFinishTemporaryDetach() {
5365        onFinishTemporaryDetach();
5366    }
5367
5368    /**
5369     * Called after {@link #onStartTemporaryDetach} when the container is done
5370     * changing the view.
5371     */
5372    public void onFinishTemporaryDetach() {
5373    }
5374
5375    /**
5376     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5377     * for this view's window.  Returns null if the view is not currently attached
5378     * to the window.  Normally you will not need to use this directly, but
5379     * just use the standard high-level event callbacks like
5380     * {@link #onKeyDown(int, KeyEvent)}.
5381     */
5382    public KeyEvent.DispatcherState getKeyDispatcherState() {
5383        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5384    }
5385
5386    /**
5387     * Dispatch a key event before it is processed by any input method
5388     * associated with the view hierarchy.  This can be used to intercept
5389     * key events in special situations before the IME consumes them; a
5390     * typical example would be handling the BACK key to update the application's
5391     * UI instead of allowing the IME to see it and close itself.
5392     *
5393     * @param event The key event to be dispatched.
5394     * @return True if the event was handled, false otherwise.
5395     */
5396    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5397        return onKeyPreIme(event.getKeyCode(), event);
5398    }
5399
5400    /**
5401     * Dispatch a key event to the next view on the focus path. This path runs
5402     * from the top of the view tree down to the currently focused view. If this
5403     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5404     * the next node down the focus path. This method also fires any key
5405     * listeners.
5406     *
5407     * @param event The key event to be dispatched.
5408     * @return True if the event was handled, false otherwise.
5409     */
5410    public boolean dispatchKeyEvent(KeyEvent event) {
5411        if (mInputEventConsistencyVerifier != null) {
5412            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5413        }
5414
5415        // Give any attached key listener a first crack at the event.
5416        //noinspection SimplifiableIfStatement
5417        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5418                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5419            return true;
5420        }
5421
5422        if (event.dispatch(this, mAttachInfo != null
5423                ? mAttachInfo.mKeyDispatchState : null, this)) {
5424            return true;
5425        }
5426
5427        if (mInputEventConsistencyVerifier != null) {
5428            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5429        }
5430        return false;
5431    }
5432
5433    /**
5434     * Dispatches a key shortcut event.
5435     *
5436     * @param event The key event to be dispatched.
5437     * @return True if the event was handled by the view, false otherwise.
5438     */
5439    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5440        return onKeyShortcut(event.getKeyCode(), event);
5441    }
5442
5443    /**
5444     * Pass the touch screen motion event down to the target view, or this
5445     * view if it is the target.
5446     *
5447     * @param event The motion event to be dispatched.
5448     * @return True if the event was handled by the view, false otherwise.
5449     */
5450    public boolean dispatchTouchEvent(MotionEvent event) {
5451        if (mInputEventConsistencyVerifier != null) {
5452            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5453        }
5454
5455        if (onFilterTouchEventForSecurity(event)) {
5456            //noinspection SimplifiableIfStatement
5457            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
5458                    mOnTouchListener.onTouch(this, event)) {
5459                return true;
5460            }
5461
5462            if (onTouchEvent(event)) {
5463                return true;
5464            }
5465        }
5466
5467        if (mInputEventConsistencyVerifier != null) {
5468            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5469        }
5470        return false;
5471    }
5472
5473    /**
5474     * Filter the touch event to apply security policies.
5475     *
5476     * @param event The motion event to be filtered.
5477     * @return True if the event should be dispatched, false if the event should be dropped.
5478     *
5479     * @see #getFilterTouchesWhenObscured
5480     */
5481    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5482        //noinspection RedundantIfStatement
5483        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5484                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5485            // Window is obscured, drop this touch.
5486            return false;
5487        }
5488        return true;
5489    }
5490
5491    /**
5492     * Pass a trackball motion event down to the focused view.
5493     *
5494     * @param event The motion event to be dispatched.
5495     * @return True if the event was handled by the view, false otherwise.
5496     */
5497    public boolean dispatchTrackballEvent(MotionEvent event) {
5498        if (mInputEventConsistencyVerifier != null) {
5499            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5500        }
5501
5502        return onTrackballEvent(event);
5503    }
5504
5505    /**
5506     * Dispatch a generic motion event.
5507     * <p>
5508     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5509     * are delivered to the view under the pointer.  All other generic motion events are
5510     * delivered to the focused view.  Hover events are handled specially and are delivered
5511     * to {@link #onHoverEvent(MotionEvent)}.
5512     * </p>
5513     *
5514     * @param event The motion event to be dispatched.
5515     * @return True if the event was handled by the view, false otherwise.
5516     */
5517    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5518        if (mInputEventConsistencyVerifier != null) {
5519            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5520        }
5521
5522        final int source = event.getSource();
5523        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5524            final int action = event.getAction();
5525            if (action == MotionEvent.ACTION_HOVER_ENTER
5526                    || action == MotionEvent.ACTION_HOVER_MOVE
5527                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5528                if (dispatchHoverEvent(event)) {
5529                    return true;
5530                }
5531            } else if (dispatchGenericPointerEvent(event)) {
5532                return true;
5533            }
5534        } else if (dispatchGenericFocusedEvent(event)) {
5535            return true;
5536        }
5537
5538        if (dispatchGenericMotionEventInternal(event)) {
5539            return true;
5540        }
5541
5542        if (mInputEventConsistencyVerifier != null) {
5543            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5544        }
5545        return false;
5546    }
5547
5548    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5549        //noinspection SimplifiableIfStatement
5550        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5551                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5552            return true;
5553        }
5554
5555        if (onGenericMotionEvent(event)) {
5556            return true;
5557        }
5558
5559        if (mInputEventConsistencyVerifier != null) {
5560            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5561        }
5562        return false;
5563    }
5564
5565    /**
5566     * Dispatch a hover event.
5567     * <p>
5568     * Do not call this method directly.
5569     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5570     * </p>
5571     *
5572     * @param event The motion event to be dispatched.
5573     * @return True if the event was handled by the view, false otherwise.
5574     */
5575    protected boolean dispatchHoverEvent(MotionEvent event) {
5576        //noinspection SimplifiableIfStatement
5577        if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5578                && mOnHoverListener.onHover(this, event)) {
5579            return true;
5580        }
5581
5582        return onHoverEvent(event);
5583    }
5584
5585    /**
5586     * Returns true if the view has a child to which it has recently sent
5587     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5588     * it does not have a hovered child, then it must be the innermost hovered view.
5589     * @hide
5590     */
5591    protected boolean hasHoveredChild() {
5592        return false;
5593    }
5594
5595    /**
5596     * Dispatch a generic motion event to the view under the first pointer.
5597     * <p>
5598     * Do not call this method directly.
5599     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5600     * </p>
5601     *
5602     * @param event The motion event to be dispatched.
5603     * @return True if the event was handled by the view, false otherwise.
5604     */
5605    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5606        return false;
5607    }
5608
5609    /**
5610     * Dispatch a generic motion event to the currently focused view.
5611     * <p>
5612     * Do not call this method directly.
5613     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5614     * </p>
5615     *
5616     * @param event The motion event to be dispatched.
5617     * @return True if the event was handled by the view, false otherwise.
5618     */
5619    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5620        return false;
5621    }
5622
5623    /**
5624     * Dispatch a pointer event.
5625     * <p>
5626     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5627     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5628     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5629     * and should not be expected to handle other pointing device features.
5630     * </p>
5631     *
5632     * @param event The motion event to be dispatched.
5633     * @return True if the event was handled by the view, false otherwise.
5634     * @hide
5635     */
5636    public final boolean dispatchPointerEvent(MotionEvent event) {
5637        if (event.isTouchEvent()) {
5638            return dispatchTouchEvent(event);
5639        } else {
5640            return dispatchGenericMotionEvent(event);
5641        }
5642    }
5643
5644    /**
5645     * Called when the window containing this view gains or loses window focus.
5646     * ViewGroups should override to route to their children.
5647     *
5648     * @param hasFocus True if the window containing this view now has focus,
5649     *        false otherwise.
5650     */
5651    public void dispatchWindowFocusChanged(boolean hasFocus) {
5652        onWindowFocusChanged(hasFocus);
5653    }
5654
5655    /**
5656     * Called when the window containing this view gains or loses focus.  Note
5657     * that this is separate from view focus: to receive key events, both
5658     * your view and its window must have focus.  If a window is displayed
5659     * on top of yours that takes input focus, then your own window will lose
5660     * focus but the view focus will remain unchanged.
5661     *
5662     * @param hasWindowFocus True if the window containing this view now has
5663     *        focus, false otherwise.
5664     */
5665    public void onWindowFocusChanged(boolean hasWindowFocus) {
5666        InputMethodManager imm = InputMethodManager.peekInstance();
5667        if (!hasWindowFocus) {
5668            if (isPressed()) {
5669                setPressed(false);
5670            }
5671            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5672                imm.focusOut(this);
5673            }
5674            removeLongPressCallback();
5675            removeTapCallback();
5676            onFocusLost();
5677        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5678            imm.focusIn(this);
5679        }
5680        refreshDrawableState();
5681    }
5682
5683    /**
5684     * Returns true if this view is in a window that currently has window focus.
5685     * Note that this is not the same as the view itself having focus.
5686     *
5687     * @return True if this view is in a window that currently has window focus.
5688     */
5689    public boolean hasWindowFocus() {
5690        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5691    }
5692
5693    /**
5694     * Dispatch a view visibility change down the view hierarchy.
5695     * ViewGroups should override to route to their children.
5696     * @param changedView The view whose visibility changed. Could be 'this' or
5697     * an ancestor view.
5698     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5699     * {@link #INVISIBLE} or {@link #GONE}.
5700     */
5701    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5702        onVisibilityChanged(changedView, visibility);
5703    }
5704
5705    /**
5706     * Called when the visibility of the view or an ancestor of the view is changed.
5707     * @param changedView The view whose visibility changed. Could be 'this' or
5708     * an ancestor view.
5709     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5710     * {@link #INVISIBLE} or {@link #GONE}.
5711     */
5712    protected void onVisibilityChanged(View changedView, int visibility) {
5713        if (visibility == VISIBLE) {
5714            if (mAttachInfo != null) {
5715                initialAwakenScrollBars();
5716            } else {
5717                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5718            }
5719        }
5720    }
5721
5722    /**
5723     * Dispatch a hint about whether this view is displayed. For instance, when
5724     * a View moves out of the screen, it might receives a display hint indicating
5725     * the view is not displayed. Applications should not <em>rely</em> on this hint
5726     * as there is no guarantee that they will receive one.
5727     *
5728     * @param hint A hint about whether or not this view is displayed:
5729     * {@link #VISIBLE} or {@link #INVISIBLE}.
5730     */
5731    public void dispatchDisplayHint(int hint) {
5732        onDisplayHint(hint);
5733    }
5734
5735    /**
5736     * Gives this view a hint about whether is displayed or not. For instance, when
5737     * a View moves out of the screen, it might receives a display hint indicating
5738     * the view is not displayed. Applications should not <em>rely</em> on this hint
5739     * as there is no guarantee that they will receive one.
5740     *
5741     * @param hint A hint about whether or not this view is displayed:
5742     * {@link #VISIBLE} or {@link #INVISIBLE}.
5743     */
5744    protected void onDisplayHint(int hint) {
5745    }
5746
5747    /**
5748     * Dispatch a window visibility change down the view hierarchy.
5749     * ViewGroups should override to route to their children.
5750     *
5751     * @param visibility The new visibility of the window.
5752     *
5753     * @see #onWindowVisibilityChanged(int)
5754     */
5755    public void dispatchWindowVisibilityChanged(int visibility) {
5756        onWindowVisibilityChanged(visibility);
5757    }
5758
5759    /**
5760     * Called when the window containing has change its visibility
5761     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5762     * that this tells you whether or not your window is being made visible
5763     * to the window manager; this does <em>not</em> tell you whether or not
5764     * your window is obscured by other windows on the screen, even if it
5765     * is itself visible.
5766     *
5767     * @param visibility The new visibility of the window.
5768     */
5769    protected void onWindowVisibilityChanged(int visibility) {
5770        if (visibility == VISIBLE) {
5771            initialAwakenScrollBars();
5772        }
5773    }
5774
5775    /**
5776     * Returns the current visibility of the window this view is attached to
5777     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5778     *
5779     * @return Returns the current visibility of the view's window.
5780     */
5781    public int getWindowVisibility() {
5782        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5783    }
5784
5785    /**
5786     * Retrieve the overall visible display size in which the window this view is
5787     * attached to has been positioned in.  This takes into account screen
5788     * decorations above the window, for both cases where the window itself
5789     * is being position inside of them or the window is being placed under
5790     * then and covered insets are used for the window to position its content
5791     * inside.  In effect, this tells you the available area where content can
5792     * be placed and remain visible to users.
5793     *
5794     * <p>This function requires an IPC back to the window manager to retrieve
5795     * the requested information, so should not be used in performance critical
5796     * code like drawing.
5797     *
5798     * @param outRect Filled in with the visible display frame.  If the view
5799     * is not attached to a window, this is simply the raw display size.
5800     */
5801    public void getWindowVisibleDisplayFrame(Rect outRect) {
5802        if (mAttachInfo != null) {
5803            try {
5804                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5805            } catch (RemoteException e) {
5806                return;
5807            }
5808            // XXX This is really broken, and probably all needs to be done
5809            // in the window manager, and we need to know more about whether
5810            // we want the area behind or in front of the IME.
5811            final Rect insets = mAttachInfo.mVisibleInsets;
5812            outRect.left += insets.left;
5813            outRect.top += insets.top;
5814            outRect.right -= insets.right;
5815            outRect.bottom -= insets.bottom;
5816            return;
5817        }
5818        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5819        d.getRectSize(outRect);
5820    }
5821
5822    /**
5823     * Dispatch a notification about a resource configuration change down
5824     * the view hierarchy.
5825     * ViewGroups should override to route to their children.
5826     *
5827     * @param newConfig The new resource configuration.
5828     *
5829     * @see #onConfigurationChanged(android.content.res.Configuration)
5830     */
5831    public void dispatchConfigurationChanged(Configuration newConfig) {
5832        onConfigurationChanged(newConfig);
5833    }
5834
5835    /**
5836     * Called when the current configuration of the resources being used
5837     * by the application have changed.  You can use this to decide when
5838     * to reload resources that can changed based on orientation and other
5839     * configuration characterstics.  You only need to use this if you are
5840     * not relying on the normal {@link android.app.Activity} mechanism of
5841     * recreating the activity instance upon a configuration change.
5842     *
5843     * @param newConfig The new resource configuration.
5844     */
5845    protected void onConfigurationChanged(Configuration newConfig) {
5846    }
5847
5848    /**
5849     * Private function to aggregate all per-view attributes in to the view
5850     * root.
5851     */
5852    void dispatchCollectViewAttributes(int visibility) {
5853        performCollectViewAttributes(visibility);
5854    }
5855
5856    void performCollectViewAttributes(int visibility) {
5857        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5858            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5859                mAttachInfo.mKeepScreenOn = true;
5860            }
5861            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5862            if (mOnSystemUiVisibilityChangeListener != null) {
5863                mAttachInfo.mHasSystemUiListeners = true;
5864            }
5865        }
5866    }
5867
5868    void needGlobalAttributesUpdate(boolean force) {
5869        final AttachInfo ai = mAttachInfo;
5870        if (ai != null) {
5871            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5872                    || ai.mHasSystemUiListeners) {
5873                ai.mRecomputeGlobalAttributes = true;
5874            }
5875        }
5876    }
5877
5878    /**
5879     * Returns whether the device is currently in touch mode.  Touch mode is entered
5880     * once the user begins interacting with the device by touch, and affects various
5881     * things like whether focus is always visible to the user.
5882     *
5883     * @return Whether the device is in touch mode.
5884     */
5885    @ViewDebug.ExportedProperty
5886    public boolean isInTouchMode() {
5887        if (mAttachInfo != null) {
5888            return mAttachInfo.mInTouchMode;
5889        } else {
5890            return ViewRootImpl.isInTouchMode();
5891        }
5892    }
5893
5894    /**
5895     * Returns the context the view is running in, through which it can
5896     * access the current theme, resources, etc.
5897     *
5898     * @return The view's Context.
5899     */
5900    @ViewDebug.CapturedViewProperty
5901    public final Context getContext() {
5902        return mContext;
5903    }
5904
5905    /**
5906     * Handle a key event before it is processed by any input method
5907     * associated with the view hierarchy.  This can be used to intercept
5908     * key events in special situations before the IME consumes them; a
5909     * typical example would be handling the BACK key to update the application's
5910     * UI instead of allowing the IME to see it and close itself.
5911     *
5912     * @param keyCode The value in event.getKeyCode().
5913     * @param event Description of the key event.
5914     * @return If you handled the event, return true. If you want to allow the
5915     *         event to be handled by the next receiver, return false.
5916     */
5917    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5918        return false;
5919    }
5920
5921    /**
5922     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5923     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5924     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5925     * is released, if the view is enabled and clickable.
5926     *
5927     * @param keyCode A key code that represents the button pressed, from
5928     *                {@link android.view.KeyEvent}.
5929     * @param event   The KeyEvent object that defines the button action.
5930     */
5931    public boolean onKeyDown(int keyCode, KeyEvent event) {
5932        boolean result = false;
5933
5934        switch (keyCode) {
5935            case KeyEvent.KEYCODE_DPAD_CENTER:
5936            case KeyEvent.KEYCODE_ENTER: {
5937                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5938                    return true;
5939                }
5940                // Long clickable items don't necessarily have to be clickable
5941                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5942                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5943                        (event.getRepeatCount() == 0)) {
5944                    setPressed(true);
5945                    checkForLongClick(0);
5946                    return true;
5947                }
5948                break;
5949            }
5950        }
5951        return result;
5952    }
5953
5954    /**
5955     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5956     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5957     * the event).
5958     */
5959    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5960        return false;
5961    }
5962
5963    /**
5964     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5965     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5966     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5967     * {@link KeyEvent#KEYCODE_ENTER} is released.
5968     *
5969     * @param keyCode A key code that represents the button pressed, from
5970     *                {@link android.view.KeyEvent}.
5971     * @param event   The KeyEvent object that defines the button action.
5972     */
5973    public boolean onKeyUp(int keyCode, KeyEvent event) {
5974        boolean result = false;
5975
5976        switch (keyCode) {
5977            case KeyEvent.KEYCODE_DPAD_CENTER:
5978            case KeyEvent.KEYCODE_ENTER: {
5979                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5980                    return true;
5981                }
5982                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5983                    setPressed(false);
5984
5985                    if (!mHasPerformedLongPress) {
5986                        // This is a tap, so remove the longpress check
5987                        removeLongPressCallback();
5988
5989                        result = performClick();
5990                    }
5991                }
5992                break;
5993            }
5994        }
5995        return result;
5996    }
5997
5998    /**
5999     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6000     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6001     * the event).
6002     *
6003     * @param keyCode     A key code that represents the button pressed, from
6004     *                    {@link android.view.KeyEvent}.
6005     * @param repeatCount The number of times the action was made.
6006     * @param event       The KeyEvent object that defines the button action.
6007     */
6008    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6009        return false;
6010    }
6011
6012    /**
6013     * Called on the focused view when a key shortcut event is not handled.
6014     * Override this method to implement local key shortcuts for the View.
6015     * Key shortcuts can also be implemented by setting the
6016     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6017     *
6018     * @param keyCode The value in event.getKeyCode().
6019     * @param event Description of the key event.
6020     * @return If you handled the event, return true. If you want to allow the
6021     *         event to be handled by the next receiver, return false.
6022     */
6023    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6024        return false;
6025    }
6026
6027    /**
6028     * Check whether the called view is a text editor, in which case it
6029     * would make sense to automatically display a soft input window for
6030     * it.  Subclasses should override this if they implement
6031     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6032     * a call on that method would return a non-null InputConnection, and
6033     * they are really a first-class editor that the user would normally
6034     * start typing on when the go into a window containing your view.
6035     *
6036     * <p>The default implementation always returns false.  This does
6037     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6038     * will not be called or the user can not otherwise perform edits on your
6039     * view; it is just a hint to the system that this is not the primary
6040     * purpose of this view.
6041     *
6042     * @return Returns true if this view is a text editor, else false.
6043     */
6044    public boolean onCheckIsTextEditor() {
6045        return false;
6046    }
6047
6048    /**
6049     * Create a new InputConnection for an InputMethod to interact
6050     * with the view.  The default implementation returns null, since it doesn't
6051     * support input methods.  You can override this to implement such support.
6052     * This is only needed for views that take focus and text input.
6053     *
6054     * <p>When implementing this, you probably also want to implement
6055     * {@link #onCheckIsTextEditor()} to indicate you will return a
6056     * non-null InputConnection.
6057     *
6058     * @param outAttrs Fill in with attribute information about the connection.
6059     */
6060    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6061        return null;
6062    }
6063
6064    /**
6065     * Called by the {@link android.view.inputmethod.InputMethodManager}
6066     * when a view who is not the current
6067     * input connection target is trying to make a call on the manager.  The
6068     * default implementation returns false; you can override this to return
6069     * true for certain views if you are performing InputConnection proxying
6070     * to them.
6071     * @param view The View that is making the InputMethodManager call.
6072     * @return Return true to allow the call, false to reject.
6073     */
6074    public boolean checkInputConnectionProxy(View view) {
6075        return false;
6076    }
6077
6078    /**
6079     * Show the context menu for this view. It is not safe to hold on to the
6080     * menu after returning from this method.
6081     *
6082     * You should normally not overload this method. Overload
6083     * {@link #onCreateContextMenu(ContextMenu)} or define an
6084     * {@link OnCreateContextMenuListener} to add items to the context menu.
6085     *
6086     * @param menu The context menu to populate
6087     */
6088    public void createContextMenu(ContextMenu menu) {
6089        ContextMenuInfo menuInfo = getContextMenuInfo();
6090
6091        // Sets the current menu info so all items added to menu will have
6092        // my extra info set.
6093        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6094
6095        onCreateContextMenu(menu);
6096        if (mOnCreateContextMenuListener != null) {
6097            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6098        }
6099
6100        // Clear the extra information so subsequent items that aren't mine don't
6101        // have my extra info.
6102        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6103
6104        if (mParent != null) {
6105            mParent.createContextMenu(menu);
6106        }
6107    }
6108
6109    /**
6110     * Views should implement this if they have extra information to associate
6111     * with the context menu. The return result is supplied as a parameter to
6112     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6113     * callback.
6114     *
6115     * @return Extra information about the item for which the context menu
6116     *         should be shown. This information will vary across different
6117     *         subclasses of View.
6118     */
6119    protected ContextMenuInfo getContextMenuInfo() {
6120        return null;
6121    }
6122
6123    /**
6124     * Views should implement this if the view itself is going to add items to
6125     * the context menu.
6126     *
6127     * @param menu the context menu to populate
6128     */
6129    protected void onCreateContextMenu(ContextMenu menu) {
6130    }
6131
6132    /**
6133     * Implement this method to handle trackball motion events.  The
6134     * <em>relative</em> movement of the trackball since the last event
6135     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6136     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6137     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6138     * they will often be fractional values, representing the more fine-grained
6139     * movement information available from a trackball).
6140     *
6141     * @param event The motion event.
6142     * @return True if the event was handled, false otherwise.
6143     */
6144    public boolean onTrackballEvent(MotionEvent event) {
6145        return false;
6146    }
6147
6148    /**
6149     * Implement this method to handle generic motion events.
6150     * <p>
6151     * Generic motion events describe joystick movements, mouse hovers, track pad
6152     * touches, scroll wheel movements and other input events.  The
6153     * {@link MotionEvent#getSource() source} of the motion event specifies
6154     * the class of input that was received.  Implementations of this method
6155     * must examine the bits in the source before processing the event.
6156     * The following code example shows how this is done.
6157     * </p><p>
6158     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6159     * are delivered to the view under the pointer.  All other generic motion events are
6160     * delivered to the focused view.
6161     * </p>
6162     * <code>
6163     * public boolean onGenericMotionEvent(MotionEvent event) {
6164     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6165     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6166     *             // process the joystick movement...
6167     *             return true;
6168     *         }
6169     *     }
6170     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6171     *         switch (event.getAction()) {
6172     *             case MotionEvent.ACTION_HOVER_MOVE:
6173     *                 // process the mouse hover movement...
6174     *                 return true;
6175     *             case MotionEvent.ACTION_SCROLL:
6176     *                 // process the scroll wheel movement...
6177     *                 return true;
6178     *         }
6179     *     }
6180     *     return super.onGenericMotionEvent(event);
6181     * }
6182     * </code>
6183     *
6184     * @param event The generic motion event being processed.
6185     * @return True if the event was handled, false otherwise.
6186     */
6187    public boolean onGenericMotionEvent(MotionEvent event) {
6188        return false;
6189    }
6190
6191    /**
6192     * Implement this method to handle hover events.
6193     * <p>
6194     * This method is called whenever a pointer is hovering into, over, or out of the
6195     * bounds of a view and the view is not currently being touched.
6196     * Hover events are represented as pointer events with action
6197     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6198     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6199     * </p>
6200     * <ul>
6201     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6202     * when the pointer enters the bounds of the view.</li>
6203     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6204     * when the pointer has already entered the bounds of the view and has moved.</li>
6205     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6206     * when the pointer has exited the bounds of the view or when the pointer is
6207     * about to go down due to a button click, tap, or similar user action that
6208     * causes the view to be touched.</li>
6209     * </ul>
6210     * <p>
6211     * The view should implement this method to return true to indicate that it is
6212     * handling the hover event, such as by changing its drawable state.
6213     * </p><p>
6214     * The default implementation calls {@link #setHovered} to update the hovered state
6215     * of the view when a hover enter or hover exit event is received, if the view
6216     * is enabled and is clickable.  The default implementation also sends hover
6217     * accessibility events.
6218     * </p>
6219     *
6220     * @param event The motion event that describes the hover.
6221     * @return True if the view handled the hover event.
6222     *
6223     * @see #isHovered
6224     * @see #setHovered
6225     * @see #onHoverChanged
6226     */
6227    public boolean onHoverEvent(MotionEvent event) {
6228        // The root view may receive hover (or touch) events that are outside the bounds of
6229        // the window.  This code ensures that we only send accessibility events for
6230        // hovers that are actually within the bounds of the root view.
6231        final int action = event.getAction();
6232        if (!mSendingHoverAccessibilityEvents) {
6233            if ((action == MotionEvent.ACTION_HOVER_ENTER
6234                    || action == MotionEvent.ACTION_HOVER_MOVE)
6235                    && !hasHoveredChild()
6236                    && pointInView(event.getX(), event.getY())) {
6237                mSendingHoverAccessibilityEvents = true;
6238                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6239            }
6240        } else {
6241            if (action == MotionEvent.ACTION_HOVER_EXIT
6242                    || (action == MotionEvent.ACTION_HOVER_MOVE
6243                            && !pointInView(event.getX(), event.getY()))) {
6244                mSendingHoverAccessibilityEvents = false;
6245                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6246            }
6247        }
6248
6249        if (isHoverable()) {
6250            switch (action) {
6251                case MotionEvent.ACTION_HOVER_ENTER:
6252                    setHovered(true);
6253                    break;
6254                case MotionEvent.ACTION_HOVER_EXIT:
6255                    setHovered(false);
6256                    break;
6257            }
6258
6259            // Dispatch the event to onGenericMotionEvent before returning true.
6260            // This is to provide compatibility with existing applications that
6261            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6262            // break because of the new default handling for hoverable views
6263            // in onHoverEvent.
6264            // Note that onGenericMotionEvent will be called by default when
6265            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6266            dispatchGenericMotionEventInternal(event);
6267            return true;
6268        }
6269        return false;
6270    }
6271
6272    /**
6273     * Returns true if the view should handle {@link #onHoverEvent}
6274     * by calling {@link #setHovered} to change its hovered state.
6275     *
6276     * @return True if the view is hoverable.
6277     */
6278    private boolean isHoverable() {
6279        final int viewFlags = mViewFlags;
6280        //noinspection SimplifiableIfStatement
6281        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6282            return false;
6283        }
6284
6285        return (viewFlags & CLICKABLE) == CLICKABLE
6286                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6287    }
6288
6289    /**
6290     * Returns true if the view is currently hovered.
6291     *
6292     * @return True if the view is currently hovered.
6293     *
6294     * @see #setHovered
6295     * @see #onHoverChanged
6296     */
6297    @ViewDebug.ExportedProperty
6298    public boolean isHovered() {
6299        return (mPrivateFlags & HOVERED) != 0;
6300    }
6301
6302    /**
6303     * Sets whether the view is currently hovered.
6304     * <p>
6305     * Calling this method also changes the drawable state of the view.  This
6306     * enables the view to react to hover by using different drawable resources
6307     * to change its appearance.
6308     * </p><p>
6309     * The {@link #onHoverChanged} method is called when the hovered state changes.
6310     * </p>
6311     *
6312     * @param hovered True if the view is hovered.
6313     *
6314     * @see #isHovered
6315     * @see #onHoverChanged
6316     */
6317    public void setHovered(boolean hovered) {
6318        if (hovered) {
6319            if ((mPrivateFlags & HOVERED) == 0) {
6320                mPrivateFlags |= HOVERED;
6321                refreshDrawableState();
6322                onHoverChanged(true);
6323            }
6324        } else {
6325            if ((mPrivateFlags & HOVERED) != 0) {
6326                mPrivateFlags &= ~HOVERED;
6327                refreshDrawableState();
6328                onHoverChanged(false);
6329            }
6330        }
6331    }
6332
6333    /**
6334     * Implement this method to handle hover state changes.
6335     * <p>
6336     * This method is called whenever the hover state changes as a result of a
6337     * call to {@link #setHovered}.
6338     * </p>
6339     *
6340     * @param hovered The current hover state, as returned by {@link #isHovered}.
6341     *
6342     * @see #isHovered
6343     * @see #setHovered
6344     */
6345    public void onHoverChanged(boolean hovered) {
6346    }
6347
6348    /**
6349     * Implement this method to handle touch screen motion events.
6350     *
6351     * @param event The motion event.
6352     * @return True if the event was handled, false otherwise.
6353     */
6354    public boolean onTouchEvent(MotionEvent event) {
6355        final int viewFlags = mViewFlags;
6356
6357        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6358            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6359                mPrivateFlags &= ~PRESSED;
6360                refreshDrawableState();
6361            }
6362            // A disabled view that is clickable still consumes the touch
6363            // events, it just doesn't respond to them.
6364            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6365                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6366        }
6367
6368        if (mTouchDelegate != null) {
6369            if (mTouchDelegate.onTouchEvent(event)) {
6370                return true;
6371            }
6372        }
6373
6374        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6375                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6376            switch (event.getAction()) {
6377                case MotionEvent.ACTION_UP:
6378                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6379                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6380                        // take focus if we don't have it already and we should in
6381                        // touch mode.
6382                        boolean focusTaken = false;
6383                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6384                            focusTaken = requestFocus();
6385                        }
6386
6387                        if (prepressed) {
6388                            // The button is being released before we actually
6389                            // showed it as pressed.  Make it show the pressed
6390                            // state now (before scheduling the click) to ensure
6391                            // the user sees it.
6392                            mPrivateFlags |= PRESSED;
6393                            refreshDrawableState();
6394                       }
6395
6396                        if (!mHasPerformedLongPress) {
6397                            // This is a tap, so remove the longpress check
6398                            removeLongPressCallback();
6399
6400                            // Only perform take click actions if we were in the pressed state
6401                            if (!focusTaken) {
6402                                // Use a Runnable and post this rather than calling
6403                                // performClick directly. This lets other visual state
6404                                // of the view update before click actions start.
6405                                if (mPerformClick == null) {
6406                                    mPerformClick = new PerformClick();
6407                                }
6408                                if (!post(mPerformClick)) {
6409                                    performClick();
6410                                }
6411                            }
6412                        }
6413
6414                        if (mUnsetPressedState == null) {
6415                            mUnsetPressedState = new UnsetPressedState();
6416                        }
6417
6418                        if (prepressed) {
6419                            postDelayed(mUnsetPressedState,
6420                                    ViewConfiguration.getPressedStateDuration());
6421                        } else if (!post(mUnsetPressedState)) {
6422                            // If the post failed, unpress right now
6423                            mUnsetPressedState.run();
6424                        }
6425                        removeTapCallback();
6426                    }
6427                    break;
6428
6429                case MotionEvent.ACTION_DOWN:
6430                    mHasPerformedLongPress = false;
6431
6432                    if (performButtonActionOnTouchDown(event)) {
6433                        break;
6434                    }
6435
6436                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6437                    boolean isInScrollingContainer = isInScrollingContainer();
6438
6439                    // For views inside a scrolling container, delay the pressed feedback for
6440                    // a short period in case this is a scroll.
6441                    if (isInScrollingContainer) {
6442                        mPrivateFlags |= PREPRESSED;
6443                        if (mPendingCheckForTap == null) {
6444                            mPendingCheckForTap = new CheckForTap();
6445                        }
6446                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6447                    } else {
6448                        // Not inside a scrolling container, so show the feedback right away
6449                        mPrivateFlags |= PRESSED;
6450                        refreshDrawableState();
6451                        checkForLongClick(0);
6452                    }
6453                    break;
6454
6455                case MotionEvent.ACTION_CANCEL:
6456                    mPrivateFlags &= ~PRESSED;
6457                    refreshDrawableState();
6458                    removeTapCallback();
6459                    break;
6460
6461                case MotionEvent.ACTION_MOVE:
6462                    final int x = (int) event.getX();
6463                    final int y = (int) event.getY();
6464
6465                    // Be lenient about moving outside of buttons
6466                    if (!pointInView(x, y, mTouchSlop)) {
6467                        // Outside button
6468                        removeTapCallback();
6469                        if ((mPrivateFlags & PRESSED) != 0) {
6470                            // Remove any future long press/tap checks
6471                            removeLongPressCallback();
6472
6473                            // Need to switch from pressed to not pressed
6474                            mPrivateFlags &= ~PRESSED;
6475                            refreshDrawableState();
6476                        }
6477                    }
6478                    break;
6479            }
6480            return true;
6481        }
6482
6483        return false;
6484    }
6485
6486    /**
6487     * @hide
6488     */
6489    public boolean isInScrollingContainer() {
6490        ViewParent p = getParent();
6491        while (p != null && p instanceof ViewGroup) {
6492            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6493                return true;
6494            }
6495            p = p.getParent();
6496        }
6497        return false;
6498    }
6499
6500    /**
6501     * Remove the longpress detection timer.
6502     */
6503    private void removeLongPressCallback() {
6504        if (mPendingCheckForLongPress != null) {
6505          removeCallbacks(mPendingCheckForLongPress);
6506        }
6507    }
6508
6509    /**
6510     * Remove the pending click action
6511     */
6512    private void removePerformClickCallback() {
6513        if (mPerformClick != null) {
6514            removeCallbacks(mPerformClick);
6515        }
6516    }
6517
6518    /**
6519     * Remove the prepress detection timer.
6520     */
6521    private void removeUnsetPressCallback() {
6522        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6523            setPressed(false);
6524            removeCallbacks(mUnsetPressedState);
6525        }
6526    }
6527
6528    /**
6529     * Remove the tap detection timer.
6530     */
6531    private void removeTapCallback() {
6532        if (mPendingCheckForTap != null) {
6533            mPrivateFlags &= ~PREPRESSED;
6534            removeCallbacks(mPendingCheckForTap);
6535        }
6536    }
6537
6538    /**
6539     * Cancels a pending long press.  Your subclass can use this if you
6540     * want the context menu to come up if the user presses and holds
6541     * at the same place, but you don't want it to come up if they press
6542     * and then move around enough to cause scrolling.
6543     */
6544    public void cancelLongPress() {
6545        removeLongPressCallback();
6546
6547        /*
6548         * The prepressed state handled by the tap callback is a display
6549         * construct, but the tap callback will post a long press callback
6550         * less its own timeout. Remove it here.
6551         */
6552        removeTapCallback();
6553    }
6554
6555    /**
6556     * Remove the pending callback for sending a
6557     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6558     */
6559    private void removeSendViewScrolledAccessibilityEventCallback() {
6560        if (mSendViewScrolledAccessibilityEvent != null) {
6561            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6562        }
6563    }
6564
6565    /**
6566     * Sets the TouchDelegate for this View.
6567     */
6568    public void setTouchDelegate(TouchDelegate delegate) {
6569        mTouchDelegate = delegate;
6570    }
6571
6572    /**
6573     * Gets the TouchDelegate for this View.
6574     */
6575    public TouchDelegate getTouchDelegate() {
6576        return mTouchDelegate;
6577    }
6578
6579    /**
6580     * Set flags controlling behavior of this view.
6581     *
6582     * @param flags Constant indicating the value which should be set
6583     * @param mask Constant indicating the bit range that should be changed
6584     */
6585    void setFlags(int flags, int mask) {
6586        int old = mViewFlags;
6587        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6588
6589        int changed = mViewFlags ^ old;
6590        if (changed == 0) {
6591            return;
6592        }
6593        int privateFlags = mPrivateFlags;
6594
6595        /* Check if the FOCUSABLE bit has changed */
6596        if (((changed & FOCUSABLE_MASK) != 0) &&
6597                ((privateFlags & HAS_BOUNDS) !=0)) {
6598            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6599                    && ((privateFlags & FOCUSED) != 0)) {
6600                /* Give up focus if we are no longer focusable */
6601                clearFocus();
6602            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6603                    && ((privateFlags & FOCUSED) == 0)) {
6604                /*
6605                 * Tell the view system that we are now available to take focus
6606                 * if no one else already has it.
6607                 */
6608                if (mParent != null) mParent.focusableViewAvailable(this);
6609            }
6610        }
6611
6612        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6613            if ((changed & VISIBILITY_MASK) != 0) {
6614                /*
6615                 * If this view is becoming visible, invalidate it in case it changed while
6616                 * it was not visible. Marking it drawn ensures that the invalidation will
6617                 * go through.
6618                 */
6619                mPrivateFlags |= DRAWN;
6620                invalidate(true);
6621
6622                needGlobalAttributesUpdate(true);
6623
6624                // a view becoming visible is worth notifying the parent
6625                // about in case nothing has focus.  even if this specific view
6626                // isn't focusable, it may contain something that is, so let
6627                // the root view try to give this focus if nothing else does.
6628                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6629                    mParent.focusableViewAvailable(this);
6630                }
6631            }
6632        }
6633
6634        /* Check if the GONE bit has changed */
6635        if ((changed & GONE) != 0) {
6636            needGlobalAttributesUpdate(false);
6637            requestLayout();
6638
6639            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6640                if (hasFocus()) clearFocus();
6641                destroyDrawingCache();
6642                if (mParent instanceof View) {
6643                    // GONE views noop invalidation, so invalidate the parent
6644                    ((View) mParent).invalidate(true);
6645                }
6646                // Mark the view drawn to ensure that it gets invalidated properly the next
6647                // time it is visible and gets invalidated
6648                mPrivateFlags |= DRAWN;
6649            }
6650            if (mAttachInfo != null) {
6651                mAttachInfo.mViewVisibilityChanged = true;
6652            }
6653        }
6654
6655        /* Check if the VISIBLE bit has changed */
6656        if ((changed & INVISIBLE) != 0) {
6657            needGlobalAttributesUpdate(false);
6658            /*
6659             * If this view is becoming invisible, set the DRAWN flag so that
6660             * the next invalidate() will not be skipped.
6661             */
6662            mPrivateFlags |= DRAWN;
6663
6664            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6665                // root view becoming invisible shouldn't clear focus
6666                if (getRootView() != this) {
6667                    clearFocus();
6668                }
6669            }
6670            if (mAttachInfo != null) {
6671                mAttachInfo.mViewVisibilityChanged = true;
6672            }
6673        }
6674
6675        if ((changed & VISIBILITY_MASK) != 0) {
6676            if (mParent instanceof ViewGroup) {
6677                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6678                ((View) mParent).invalidate(true);
6679            } else if (mParent != null) {
6680                mParent.invalidateChild(this, null);
6681            }
6682            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6683        }
6684
6685        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6686            destroyDrawingCache();
6687        }
6688
6689        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6690            destroyDrawingCache();
6691            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6692            invalidateParentCaches();
6693        }
6694
6695        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6696            destroyDrawingCache();
6697            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6698        }
6699
6700        if ((changed & DRAW_MASK) != 0) {
6701            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6702                if (mBGDrawable != null) {
6703                    mPrivateFlags &= ~SKIP_DRAW;
6704                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6705                } else {
6706                    mPrivateFlags |= SKIP_DRAW;
6707                }
6708            } else {
6709                mPrivateFlags &= ~SKIP_DRAW;
6710            }
6711            requestLayout();
6712            invalidate(true);
6713        }
6714
6715        if ((changed & KEEP_SCREEN_ON) != 0) {
6716            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6717                mParent.recomputeViewAttributes(this);
6718            }
6719        }
6720
6721        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6722            requestLayout();
6723        }
6724    }
6725
6726    /**
6727     * Change the view's z order in the tree, so it's on top of other sibling
6728     * views
6729     */
6730    public void bringToFront() {
6731        if (mParent != null) {
6732            mParent.bringChildToFront(this);
6733        }
6734    }
6735
6736    /**
6737     * This is called in response to an internal scroll in this view (i.e., the
6738     * view scrolled its own contents). This is typically as a result of
6739     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6740     * called.
6741     *
6742     * @param l Current horizontal scroll origin.
6743     * @param t Current vertical scroll origin.
6744     * @param oldl Previous horizontal scroll origin.
6745     * @param oldt Previous vertical scroll origin.
6746     */
6747    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6748        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6749            postSendViewScrolledAccessibilityEventCallback();
6750        }
6751
6752        mBackgroundSizeChanged = true;
6753
6754        final AttachInfo ai = mAttachInfo;
6755        if (ai != null) {
6756            ai.mViewScrollChanged = true;
6757        }
6758    }
6759
6760    /**
6761     * Interface definition for a callback to be invoked when the layout bounds of a view
6762     * changes due to layout processing.
6763     */
6764    public interface OnLayoutChangeListener {
6765        /**
6766         * Called when the focus state of a view has changed.
6767         *
6768         * @param v The view whose state has changed.
6769         * @param left The new value of the view's left property.
6770         * @param top The new value of the view's top property.
6771         * @param right The new value of the view's right property.
6772         * @param bottom The new value of the view's bottom property.
6773         * @param oldLeft The previous value of the view's left property.
6774         * @param oldTop The previous value of the view's top property.
6775         * @param oldRight The previous value of the view's right property.
6776         * @param oldBottom The previous value of the view's bottom property.
6777         */
6778        void onLayoutChange(View v, int left, int top, int right, int bottom,
6779            int oldLeft, int oldTop, int oldRight, int oldBottom);
6780    }
6781
6782    /**
6783     * This is called during layout when the size of this view has changed. If
6784     * you were just added to the view hierarchy, you're called with the old
6785     * values of 0.
6786     *
6787     * @param w Current width of this view.
6788     * @param h Current height of this view.
6789     * @param oldw Old width of this view.
6790     * @param oldh Old height of this view.
6791     */
6792    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6793    }
6794
6795    /**
6796     * Called by draw to draw the child views. This may be overridden
6797     * by derived classes to gain control just before its children are drawn
6798     * (but after its own view has been drawn).
6799     * @param canvas the canvas on which to draw the view
6800     */
6801    protected void dispatchDraw(Canvas canvas) {
6802    }
6803
6804    /**
6805     * Gets the parent of this view. Note that the parent is a
6806     * ViewParent and not necessarily a View.
6807     *
6808     * @return Parent of this view.
6809     */
6810    public final ViewParent getParent() {
6811        return mParent;
6812    }
6813
6814    /**
6815     * Set the horizontal scrolled position of your view. This will cause a call to
6816     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6817     * invalidated.
6818     * @param value the x position to scroll to
6819     */
6820    public void setScrollX(int value) {
6821        scrollTo(value, mScrollY);
6822    }
6823
6824    /**
6825     * Set the vertical scrolled position of your view. This will cause a call to
6826     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6827     * invalidated.
6828     * @param value the y position to scroll to
6829     */
6830    public void setScrollY(int value) {
6831        scrollTo(mScrollX, value);
6832    }
6833
6834    /**
6835     * Return the scrolled left position of this view. This is the left edge of
6836     * the displayed part of your view. You do not need to draw any pixels
6837     * farther left, since those are outside of the frame of your view on
6838     * screen.
6839     *
6840     * @return The left edge of the displayed part of your view, in pixels.
6841     */
6842    public final int getScrollX() {
6843        return mScrollX;
6844    }
6845
6846    /**
6847     * Return the scrolled top position of this view. This is the top edge of
6848     * the displayed part of your view. You do not need to draw any pixels above
6849     * it, since those are outside of the frame of your view on screen.
6850     *
6851     * @return The top edge of the displayed part of your view, in pixels.
6852     */
6853    public final int getScrollY() {
6854        return mScrollY;
6855    }
6856
6857    /**
6858     * Return the width of the your view.
6859     *
6860     * @return The width of your view, in pixels.
6861     */
6862    @ViewDebug.ExportedProperty(category = "layout")
6863    public final int getWidth() {
6864        return mRight - mLeft;
6865    }
6866
6867    /**
6868     * Return the height of your view.
6869     *
6870     * @return The height of your view, in pixels.
6871     */
6872    @ViewDebug.ExportedProperty(category = "layout")
6873    public final int getHeight() {
6874        return mBottom - mTop;
6875    }
6876
6877    /**
6878     * Return the visible drawing bounds of your view. Fills in the output
6879     * rectangle with the values from getScrollX(), getScrollY(),
6880     * getWidth(), and getHeight().
6881     *
6882     * @param outRect The (scrolled) drawing bounds of the view.
6883     */
6884    public void getDrawingRect(Rect outRect) {
6885        outRect.left = mScrollX;
6886        outRect.top = mScrollY;
6887        outRect.right = mScrollX + (mRight - mLeft);
6888        outRect.bottom = mScrollY + (mBottom - mTop);
6889    }
6890
6891    /**
6892     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6893     * raw width component (that is the result is masked by
6894     * {@link #MEASURED_SIZE_MASK}).
6895     *
6896     * @return The raw measured width of this view.
6897     */
6898    public final int getMeasuredWidth() {
6899        return mMeasuredWidth & MEASURED_SIZE_MASK;
6900    }
6901
6902    /**
6903     * Return the full width measurement information for this view as computed
6904     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6905     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6906     * This should be used during measurement and layout calculations only. Use
6907     * {@link #getWidth()} to see how wide a view is after layout.
6908     *
6909     * @return The measured width of this view as a bit mask.
6910     */
6911    public final int getMeasuredWidthAndState() {
6912        return mMeasuredWidth;
6913    }
6914
6915    /**
6916     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6917     * raw width component (that is the result is masked by
6918     * {@link #MEASURED_SIZE_MASK}).
6919     *
6920     * @return The raw measured height of this view.
6921     */
6922    public final int getMeasuredHeight() {
6923        return mMeasuredHeight & MEASURED_SIZE_MASK;
6924    }
6925
6926    /**
6927     * Return the full height measurement information for this view as computed
6928     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6929     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6930     * This should be used during measurement and layout calculations only. Use
6931     * {@link #getHeight()} to see how wide a view is after layout.
6932     *
6933     * @return The measured width of this view as a bit mask.
6934     */
6935    public final int getMeasuredHeightAndState() {
6936        return mMeasuredHeight;
6937    }
6938
6939    /**
6940     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6941     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6942     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6943     * and the height component is at the shifted bits
6944     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6945     */
6946    public final int getMeasuredState() {
6947        return (mMeasuredWidth&MEASURED_STATE_MASK)
6948                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6949                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6950    }
6951
6952    /**
6953     * The transform matrix of this view, which is calculated based on the current
6954     * roation, scale, and pivot properties.
6955     *
6956     * @see #getRotation()
6957     * @see #getScaleX()
6958     * @see #getScaleY()
6959     * @see #getPivotX()
6960     * @see #getPivotY()
6961     * @return The current transform matrix for the view
6962     */
6963    public Matrix getMatrix() {
6964        if (mTransformationInfo != null) {
6965            updateMatrix();
6966            return mTransformationInfo.mMatrix;
6967        }
6968        return Matrix.IDENTITY_MATRIX;
6969    }
6970
6971    /**
6972     * Utility function to determine if the value is far enough away from zero to be
6973     * considered non-zero.
6974     * @param value A floating point value to check for zero-ness
6975     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6976     */
6977    private static boolean nonzero(float value) {
6978        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6979    }
6980
6981    /**
6982     * Returns true if the transform matrix is the identity matrix.
6983     * Recomputes the matrix if necessary.
6984     *
6985     * @return True if the transform matrix is the identity matrix, false otherwise.
6986     */
6987    final boolean hasIdentityMatrix() {
6988        if (mTransformationInfo != null) {
6989            updateMatrix();
6990            return mTransformationInfo.mMatrixIsIdentity;
6991        }
6992        return true;
6993    }
6994
6995    void ensureTransformationInfo() {
6996        if (mTransformationInfo == null) {
6997            mTransformationInfo = new TransformationInfo();
6998        }
6999    }
7000
7001    /**
7002     * Recomputes the transform matrix if necessary.
7003     */
7004    private void updateMatrix() {
7005        final TransformationInfo info = mTransformationInfo;
7006        if (info == null) {
7007            return;
7008        }
7009        if (info.mMatrixDirty) {
7010            // transform-related properties have changed since the last time someone
7011            // asked for the matrix; recalculate it with the current values
7012
7013            // Figure out if we need to update the pivot point
7014            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7015                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7016                    info.mPrevWidth = mRight - mLeft;
7017                    info.mPrevHeight = mBottom - mTop;
7018                    info.mPivotX = info.mPrevWidth / 2f;
7019                    info.mPivotY = info.mPrevHeight / 2f;
7020                }
7021            }
7022            info.mMatrix.reset();
7023            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7024                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7025                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7026                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7027            } else {
7028                if (info.mCamera == null) {
7029                    info.mCamera = new Camera();
7030                    info.matrix3D = new Matrix();
7031                }
7032                info.mCamera.save();
7033                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7034                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7035                info.mCamera.getMatrix(info.matrix3D);
7036                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7037                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7038                        info.mPivotY + info.mTranslationY);
7039                info.mMatrix.postConcat(info.matrix3D);
7040                info.mCamera.restore();
7041            }
7042            info.mMatrixDirty = false;
7043            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7044            info.mInverseMatrixDirty = true;
7045        }
7046    }
7047
7048    /**
7049     * Utility method to retrieve the inverse of the current mMatrix property.
7050     * We cache the matrix to avoid recalculating it when transform properties
7051     * have not changed.
7052     *
7053     * @return The inverse of the current matrix of this view.
7054     */
7055    final Matrix getInverseMatrix() {
7056        final TransformationInfo info = mTransformationInfo;
7057        if (info != null) {
7058            updateMatrix();
7059            if (info.mInverseMatrixDirty) {
7060                if (info.mInverseMatrix == null) {
7061                    info.mInverseMatrix = new Matrix();
7062                }
7063                info.mMatrix.invert(info.mInverseMatrix);
7064                info.mInverseMatrixDirty = false;
7065            }
7066            return info.mInverseMatrix;
7067        }
7068        return Matrix.IDENTITY_MATRIX;
7069    }
7070
7071    /**
7072     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7073     * views are drawn) from the camera to this view. The camera's distance
7074     * affects 3D transformations, for instance rotations around the X and Y
7075     * axis. If the rotationX or rotationY properties are changed and this view is
7076     * large (more than half the size of the screen), it is recommended to always
7077     * use a camera distance that's greater than the height (X axis rotation) or
7078     * the width (Y axis rotation) of this view.</p>
7079     *
7080     * <p>The distance of the camera from the view plane can have an affect on the
7081     * perspective distortion of the view when it is rotated around the x or y axis.
7082     * For example, a large distance will result in a large viewing angle, and there
7083     * will not be much perspective distortion of the view as it rotates. A short
7084     * distance may cause much more perspective distortion upon rotation, and can
7085     * also result in some drawing artifacts if the rotated view ends up partially
7086     * behind the camera (which is why the recommendation is to use a distance at
7087     * least as far as the size of the view, if the view is to be rotated.)</p>
7088     *
7089     * <p>The distance is expressed in "depth pixels." The default distance depends
7090     * on the screen density. For instance, on a medium density display, the
7091     * default distance is 1280. On a high density display, the default distance
7092     * is 1920.</p>
7093     *
7094     * <p>If you want to specify a distance that leads to visually consistent
7095     * results across various densities, use the following formula:</p>
7096     * <pre>
7097     * float scale = context.getResources().getDisplayMetrics().density;
7098     * view.setCameraDistance(distance * scale);
7099     * </pre>
7100     *
7101     * <p>The density scale factor of a high density display is 1.5,
7102     * and 1920 = 1280 * 1.5.</p>
7103     *
7104     * @param distance The distance in "depth pixels", if negative the opposite
7105     *        value is used
7106     *
7107     * @see #setRotationX(float)
7108     * @see #setRotationY(float)
7109     */
7110    public void setCameraDistance(float distance) {
7111        invalidateParentCaches();
7112        invalidate(false);
7113
7114        ensureTransformationInfo();
7115        final float dpi = mResources.getDisplayMetrics().densityDpi;
7116        final TransformationInfo info = mTransformationInfo;
7117        if (info.mCamera == null) {
7118            info.mCamera = new Camera();
7119            info.matrix3D = new Matrix();
7120        }
7121
7122        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7123        info.mMatrixDirty = true;
7124
7125        invalidate(false);
7126    }
7127
7128    /**
7129     * The degrees that the view is rotated around the pivot point.
7130     *
7131     * @see #setRotation(float)
7132     * @see #getPivotX()
7133     * @see #getPivotY()
7134     *
7135     * @return The degrees of rotation.
7136     */
7137    public float getRotation() {
7138        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7139    }
7140
7141    /**
7142     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7143     * result in clockwise rotation.
7144     *
7145     * @param rotation The degrees of rotation.
7146     *
7147     * @see #getRotation()
7148     * @see #getPivotX()
7149     * @see #getPivotY()
7150     * @see #setRotationX(float)
7151     * @see #setRotationY(float)
7152     *
7153     * @attr ref android.R.styleable#View_rotation
7154     */
7155    public void setRotation(float rotation) {
7156        ensureTransformationInfo();
7157        final TransformationInfo info = mTransformationInfo;
7158        if (info.mRotation != rotation) {
7159            invalidateParentCaches();
7160            // Double-invalidation is necessary to capture view's old and new areas
7161            invalidate(false);
7162            info.mRotation = rotation;
7163            info.mMatrixDirty = true;
7164            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7165            invalidate(false);
7166        }
7167    }
7168
7169    /**
7170     * The degrees that the view is rotated around the vertical axis through the pivot point.
7171     *
7172     * @see #getPivotX()
7173     * @see #getPivotY()
7174     * @see #setRotationY(float)
7175     *
7176     * @return The degrees of Y rotation.
7177     */
7178    public float getRotationY() {
7179        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7180    }
7181
7182    /**
7183     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7184     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7185     * down the y axis.
7186     *
7187     * When rotating large views, it is recommended to adjust the camera distance
7188     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7189     *
7190     * @param rotationY The degrees of Y rotation.
7191     *
7192     * @see #getRotationY()
7193     * @see #getPivotX()
7194     * @see #getPivotY()
7195     * @see #setRotation(float)
7196     * @see #setRotationX(float)
7197     * @see #setCameraDistance(float)
7198     *
7199     * @attr ref android.R.styleable#View_rotationY
7200     */
7201    public void setRotationY(float rotationY) {
7202        ensureTransformationInfo();
7203        final TransformationInfo info = mTransformationInfo;
7204        if (info.mRotationY != rotationY) {
7205            invalidateParentCaches();
7206            // Double-invalidation is necessary to capture view's old and new areas
7207            invalidate(false);
7208            info.mRotationY = rotationY;
7209            info.mMatrixDirty = true;
7210            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7211            invalidate(false);
7212        }
7213    }
7214
7215    /**
7216     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7217     *
7218     * @see #getPivotX()
7219     * @see #getPivotY()
7220     * @see #setRotationX(float)
7221     *
7222     * @return The degrees of X rotation.
7223     */
7224    public float getRotationX() {
7225        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7226    }
7227
7228    /**
7229     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7230     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7231     * x axis.
7232     *
7233     * When rotating large views, it is recommended to adjust the camera distance
7234     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7235     *
7236     * @param rotationX The degrees of X rotation.
7237     *
7238     * @see #getRotationX()
7239     * @see #getPivotX()
7240     * @see #getPivotY()
7241     * @see #setRotation(float)
7242     * @see #setRotationY(float)
7243     * @see #setCameraDistance(float)
7244     *
7245     * @attr ref android.R.styleable#View_rotationX
7246     */
7247    public void setRotationX(float rotationX) {
7248        ensureTransformationInfo();
7249        final TransformationInfo info = mTransformationInfo;
7250        if (info.mRotationX != rotationX) {
7251            invalidateParentCaches();
7252            // Double-invalidation is necessary to capture view's old and new areas
7253            invalidate(false);
7254            info.mRotationX = rotationX;
7255            info.mMatrixDirty = true;
7256            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7257            invalidate(false);
7258        }
7259    }
7260
7261    /**
7262     * The amount that the view is scaled in x around the pivot point, as a proportion of
7263     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7264     *
7265     * <p>By default, this is 1.0f.
7266     *
7267     * @see #getPivotX()
7268     * @see #getPivotY()
7269     * @return The scaling factor.
7270     */
7271    public float getScaleX() {
7272        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7273    }
7274
7275    /**
7276     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7277     * the view's unscaled width. A value of 1 means that no scaling is applied.
7278     *
7279     * @param scaleX The scaling factor.
7280     * @see #getPivotX()
7281     * @see #getPivotY()
7282     *
7283     * @attr ref android.R.styleable#View_scaleX
7284     */
7285    public void setScaleX(float scaleX) {
7286        ensureTransformationInfo();
7287        final TransformationInfo info = mTransformationInfo;
7288        if (info.mScaleX != scaleX) {
7289            invalidateParentCaches();
7290            // Double-invalidation is necessary to capture view's old and new areas
7291            invalidate(false);
7292            info.mScaleX = scaleX;
7293            info.mMatrixDirty = true;
7294            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7295            invalidate(false);
7296        }
7297    }
7298
7299    /**
7300     * The amount that the view is scaled in y around the pivot point, as a proportion of
7301     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7302     *
7303     * <p>By default, this is 1.0f.
7304     *
7305     * @see #getPivotX()
7306     * @see #getPivotY()
7307     * @return The scaling factor.
7308     */
7309    public float getScaleY() {
7310        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7311    }
7312
7313    /**
7314     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7315     * the view's unscaled width. A value of 1 means that no scaling is applied.
7316     *
7317     * @param scaleY The scaling factor.
7318     * @see #getPivotX()
7319     * @see #getPivotY()
7320     *
7321     * @attr ref android.R.styleable#View_scaleY
7322     */
7323    public void setScaleY(float scaleY) {
7324        ensureTransformationInfo();
7325        final TransformationInfo info = mTransformationInfo;
7326        if (info.mScaleY != scaleY) {
7327            invalidateParentCaches();
7328            // Double-invalidation is necessary to capture view's old and new areas
7329            invalidate(false);
7330            info.mScaleY = scaleY;
7331            info.mMatrixDirty = true;
7332            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7333            invalidate(false);
7334        }
7335    }
7336
7337    /**
7338     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7339     * and {@link #setScaleX(float) scaled}.
7340     *
7341     * @see #getRotation()
7342     * @see #getScaleX()
7343     * @see #getScaleY()
7344     * @see #getPivotY()
7345     * @return The x location of the pivot point.
7346     */
7347    public float getPivotX() {
7348        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7349    }
7350
7351    /**
7352     * Sets the x location of the point around which the view is
7353     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7354     * By default, the pivot point is centered on the object.
7355     * Setting this property disables this behavior and causes the view to use only the
7356     * explicitly set pivotX and pivotY values.
7357     *
7358     * @param pivotX The x location of the pivot point.
7359     * @see #getRotation()
7360     * @see #getScaleX()
7361     * @see #getScaleY()
7362     * @see #getPivotY()
7363     *
7364     * @attr ref android.R.styleable#View_transformPivotX
7365     */
7366    public void setPivotX(float pivotX) {
7367        ensureTransformationInfo();
7368        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7369        final TransformationInfo info = mTransformationInfo;
7370        if (info.mPivotX != pivotX) {
7371            invalidateParentCaches();
7372            // Double-invalidation is necessary to capture view's old and new areas
7373            invalidate(false);
7374            info.mPivotX = pivotX;
7375            info.mMatrixDirty = true;
7376            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7377            invalidate(false);
7378        }
7379    }
7380
7381    /**
7382     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7383     * and {@link #setScaleY(float) scaled}.
7384     *
7385     * @see #getRotation()
7386     * @see #getScaleX()
7387     * @see #getScaleY()
7388     * @see #getPivotY()
7389     * @return The y location of the pivot point.
7390     */
7391    public float getPivotY() {
7392        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7393    }
7394
7395    /**
7396     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7397     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7398     * Setting this property disables this behavior and causes the view to use only the
7399     * explicitly set pivotX and pivotY values.
7400     *
7401     * @param pivotY The y location of the pivot point.
7402     * @see #getRotation()
7403     * @see #getScaleX()
7404     * @see #getScaleY()
7405     * @see #getPivotY()
7406     *
7407     * @attr ref android.R.styleable#View_transformPivotY
7408     */
7409    public void setPivotY(float pivotY) {
7410        ensureTransformationInfo();
7411        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7412        final TransformationInfo info = mTransformationInfo;
7413        if (info.mPivotY != pivotY) {
7414            invalidateParentCaches();
7415            // Double-invalidation is necessary to capture view's old and new areas
7416            invalidate(false);
7417            info.mPivotY = pivotY;
7418            info.mMatrixDirty = true;
7419            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7420            invalidate(false);
7421        }
7422    }
7423
7424    /**
7425     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7426     * completely transparent and 1 means the view is completely opaque.
7427     *
7428     * <p>By default this is 1.0f.
7429     * @return The opacity of the view.
7430     */
7431    public float getAlpha() {
7432        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7433    }
7434
7435    /**
7436     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7437     * completely transparent and 1 means the view is completely opaque.</p>
7438     *
7439     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7440     * responsible for applying the opacity itself. Otherwise, calling this method is
7441     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7442     * setting a hardware layer.</p>
7443     *
7444     * @param alpha The opacity of the view.
7445     *
7446     * @see #setLayerType(int, android.graphics.Paint)
7447     *
7448     * @attr ref android.R.styleable#View_alpha
7449     */
7450    public void setAlpha(float alpha) {
7451        ensureTransformationInfo();
7452        mTransformationInfo.mAlpha = alpha;
7453        invalidateParentCaches();
7454        if (onSetAlpha((int) (alpha * 255))) {
7455            mPrivateFlags |= ALPHA_SET;
7456            // subclass is handling alpha - don't optimize rendering cache invalidation
7457            invalidate(true);
7458        } else {
7459            mPrivateFlags &= ~ALPHA_SET;
7460            invalidate(false);
7461        }
7462    }
7463
7464    /**
7465     * Faster version of setAlpha() which performs the same steps except there are
7466     * no calls to invalidate(). The caller of this function should perform proper invalidation
7467     * on the parent and this object. The return value indicates whether the subclass handles
7468     * alpha (the return value for onSetAlpha()).
7469     *
7470     * @param alpha The new value for the alpha property
7471     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
7472     */
7473    boolean setAlphaNoInvalidation(float alpha) {
7474        ensureTransformationInfo();
7475        mTransformationInfo.mAlpha = alpha;
7476        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7477        if (subclassHandlesAlpha) {
7478            mPrivateFlags |= ALPHA_SET;
7479        } else {
7480            mPrivateFlags &= ~ALPHA_SET;
7481        }
7482        return subclassHandlesAlpha;
7483    }
7484
7485    /**
7486     * Top position of this view relative to its parent.
7487     *
7488     * @return The top of this view, in pixels.
7489     */
7490    @ViewDebug.CapturedViewProperty
7491    public final int getTop() {
7492        return mTop;
7493    }
7494
7495    /**
7496     * Sets the top position of this view relative to its parent. This method is meant to be called
7497     * by the layout system and should not generally be called otherwise, because the property
7498     * may be changed at any time by the layout.
7499     *
7500     * @param top The top of this view, in pixels.
7501     */
7502    public final void setTop(int top) {
7503        if (top != mTop) {
7504            updateMatrix();
7505            final boolean matrixIsIdentity = mTransformationInfo == null
7506                    || mTransformationInfo.mMatrixIsIdentity;
7507            if (matrixIsIdentity) {
7508                if (mAttachInfo != null) {
7509                    int minTop;
7510                    int yLoc;
7511                    if (top < mTop) {
7512                        minTop = top;
7513                        yLoc = top - mTop;
7514                    } else {
7515                        minTop = mTop;
7516                        yLoc = 0;
7517                    }
7518                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7519                }
7520            } else {
7521                // Double-invalidation is necessary to capture view's old and new areas
7522                invalidate(true);
7523            }
7524
7525            int width = mRight - mLeft;
7526            int oldHeight = mBottom - mTop;
7527
7528            mTop = top;
7529
7530            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7531
7532            if (!matrixIsIdentity) {
7533                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7534                    // A change in dimension means an auto-centered pivot point changes, too
7535                    mTransformationInfo.mMatrixDirty = true;
7536                }
7537                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7538                invalidate(true);
7539            }
7540            mBackgroundSizeChanged = true;
7541            invalidateParentIfNeeded();
7542        }
7543    }
7544
7545    /**
7546     * Bottom position of this view relative to its parent.
7547     *
7548     * @return The bottom of this view, in pixels.
7549     */
7550    @ViewDebug.CapturedViewProperty
7551    public final int getBottom() {
7552        return mBottom;
7553    }
7554
7555    /**
7556     * True if this view has changed since the last time being drawn.
7557     *
7558     * @return The dirty state of this view.
7559     */
7560    public boolean isDirty() {
7561        return (mPrivateFlags & DIRTY_MASK) != 0;
7562    }
7563
7564    /**
7565     * Sets the bottom position of this view relative to its parent. This method is meant to be
7566     * called by the layout system and should not generally be called otherwise, because the
7567     * property may be changed at any time by the layout.
7568     *
7569     * @param bottom The bottom of this view, in pixels.
7570     */
7571    public final void setBottom(int bottom) {
7572        if (bottom != mBottom) {
7573            updateMatrix();
7574            final boolean matrixIsIdentity = mTransformationInfo == null
7575                    || mTransformationInfo.mMatrixIsIdentity;
7576            if (matrixIsIdentity) {
7577                if (mAttachInfo != null) {
7578                    int maxBottom;
7579                    if (bottom < mBottom) {
7580                        maxBottom = mBottom;
7581                    } else {
7582                        maxBottom = bottom;
7583                    }
7584                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7585                }
7586            } else {
7587                // Double-invalidation is necessary to capture view's old and new areas
7588                invalidate(true);
7589            }
7590
7591            int width = mRight - mLeft;
7592            int oldHeight = mBottom - mTop;
7593
7594            mBottom = bottom;
7595
7596            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7597
7598            if (!matrixIsIdentity) {
7599                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7600                    // A change in dimension means an auto-centered pivot point changes, too
7601                    mTransformationInfo.mMatrixDirty = true;
7602                }
7603                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7604                invalidate(true);
7605            }
7606            mBackgroundSizeChanged = true;
7607            invalidateParentIfNeeded();
7608        }
7609    }
7610
7611    /**
7612     * Left position of this view relative to its parent.
7613     *
7614     * @return The left edge of this view, in pixels.
7615     */
7616    @ViewDebug.CapturedViewProperty
7617    public final int getLeft() {
7618        return mLeft;
7619    }
7620
7621    /**
7622     * Sets the left position of this view relative to its parent. This method is meant to be called
7623     * by the layout system and should not generally be called otherwise, because the property
7624     * may be changed at any time by the layout.
7625     *
7626     * @param left The bottom of this view, in pixels.
7627     */
7628    public final void setLeft(int left) {
7629        if (left != mLeft) {
7630            updateMatrix();
7631            final boolean matrixIsIdentity = mTransformationInfo == null
7632                    || mTransformationInfo.mMatrixIsIdentity;
7633            if (matrixIsIdentity) {
7634                if (mAttachInfo != null) {
7635                    int minLeft;
7636                    int xLoc;
7637                    if (left < mLeft) {
7638                        minLeft = left;
7639                        xLoc = left - mLeft;
7640                    } else {
7641                        minLeft = mLeft;
7642                        xLoc = 0;
7643                    }
7644                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7645                }
7646            } else {
7647                // Double-invalidation is necessary to capture view's old and new areas
7648                invalidate(true);
7649            }
7650
7651            int oldWidth = mRight - mLeft;
7652            int height = mBottom - mTop;
7653
7654            mLeft = left;
7655
7656            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7657
7658            if (!matrixIsIdentity) {
7659                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7660                    // A change in dimension means an auto-centered pivot point changes, too
7661                    mTransformationInfo.mMatrixDirty = true;
7662                }
7663                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7664                invalidate(true);
7665            }
7666            mBackgroundSizeChanged = true;
7667            invalidateParentIfNeeded();
7668        }
7669    }
7670
7671    /**
7672     * Right position of this view relative to its parent.
7673     *
7674     * @return The right edge of this view, in pixels.
7675     */
7676    @ViewDebug.CapturedViewProperty
7677    public final int getRight() {
7678        return mRight;
7679    }
7680
7681    /**
7682     * Sets the right position of this view relative to its parent. This method is meant to be called
7683     * by the layout system and should not generally be called otherwise, because the property
7684     * may be changed at any time by the layout.
7685     *
7686     * @param right The bottom of this view, in pixels.
7687     */
7688    public final void setRight(int right) {
7689        if (right != mRight) {
7690            updateMatrix();
7691            final boolean matrixIsIdentity = mTransformationInfo == null
7692                    || mTransformationInfo.mMatrixIsIdentity;
7693            if (matrixIsIdentity) {
7694                if (mAttachInfo != null) {
7695                    int maxRight;
7696                    if (right < mRight) {
7697                        maxRight = mRight;
7698                    } else {
7699                        maxRight = right;
7700                    }
7701                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7702                }
7703            } else {
7704                // Double-invalidation is necessary to capture view's old and new areas
7705                invalidate(true);
7706            }
7707
7708            int oldWidth = mRight - mLeft;
7709            int height = mBottom - mTop;
7710
7711            mRight = right;
7712
7713            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7714
7715            if (!matrixIsIdentity) {
7716                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7717                    // A change in dimension means an auto-centered pivot point changes, too
7718                    mTransformationInfo.mMatrixDirty = true;
7719                }
7720                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7721                invalidate(true);
7722            }
7723            mBackgroundSizeChanged = true;
7724            invalidateParentIfNeeded();
7725        }
7726    }
7727
7728    /**
7729     * The visual x position of this view, in pixels. This is equivalent to the
7730     * {@link #setTranslationX(float) translationX} property plus the current
7731     * {@link #getLeft() left} property.
7732     *
7733     * @return The visual x position of this view, in pixels.
7734     */
7735    public float getX() {
7736        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7737    }
7738
7739    /**
7740     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7741     * {@link #setTranslationX(float) translationX} property to be the difference between
7742     * the x value passed in and the current {@link #getLeft() left} property.
7743     *
7744     * @param x The visual x position of this view, in pixels.
7745     */
7746    public void setX(float x) {
7747        setTranslationX(x - mLeft);
7748    }
7749
7750    /**
7751     * The visual y position of this view, in pixels. This is equivalent to the
7752     * {@link #setTranslationY(float) translationY} property plus the current
7753     * {@link #getTop() top} property.
7754     *
7755     * @return The visual y position of this view, in pixels.
7756     */
7757    public float getY() {
7758        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7759    }
7760
7761    /**
7762     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7763     * {@link #setTranslationY(float) translationY} property to be the difference between
7764     * the y value passed in and the current {@link #getTop() top} property.
7765     *
7766     * @param y The visual y position of this view, in pixels.
7767     */
7768    public void setY(float y) {
7769        setTranslationY(y - mTop);
7770    }
7771
7772
7773    /**
7774     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7775     * This position is post-layout, in addition to wherever the object's
7776     * layout placed it.
7777     *
7778     * @return The horizontal position of this view relative to its left position, in pixels.
7779     */
7780    public float getTranslationX() {
7781        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7782    }
7783
7784    /**
7785     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7786     * This effectively positions the object post-layout, in addition to wherever the object's
7787     * layout placed it.
7788     *
7789     * @param translationX The horizontal position of this view relative to its left position,
7790     * in pixels.
7791     *
7792     * @attr ref android.R.styleable#View_translationX
7793     */
7794    public void setTranslationX(float translationX) {
7795        ensureTransformationInfo();
7796        final TransformationInfo info = mTransformationInfo;
7797        if (info.mTranslationX != translationX) {
7798            invalidateParentCaches();
7799            // Double-invalidation is necessary to capture view's old and new areas
7800            invalidate(false);
7801            info.mTranslationX = translationX;
7802            info.mMatrixDirty = true;
7803            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7804            invalidate(false);
7805        }
7806    }
7807
7808    /**
7809     * The horizontal location of this view relative to its {@link #getTop() top} position.
7810     * This position is post-layout, in addition to wherever the object's
7811     * layout placed it.
7812     *
7813     * @return The vertical position of this view relative to its top position,
7814     * in pixels.
7815     */
7816    public float getTranslationY() {
7817        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7818    }
7819
7820    /**
7821     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7822     * This effectively positions the object post-layout, in addition to wherever the object's
7823     * layout placed it.
7824     *
7825     * @param translationY The vertical position of this view relative to its top position,
7826     * in pixels.
7827     *
7828     * @attr ref android.R.styleable#View_translationY
7829     */
7830    public void setTranslationY(float translationY) {
7831        ensureTransformationInfo();
7832        final TransformationInfo info = mTransformationInfo;
7833        if (info.mTranslationY != translationY) {
7834            invalidateParentCaches();
7835            // Double-invalidation is necessary to capture view's old and new areas
7836            invalidate(false);
7837            info.mTranslationY = translationY;
7838            info.mMatrixDirty = true;
7839            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7840            invalidate(false);
7841        }
7842    }
7843
7844    /**
7845     * @hide
7846     */
7847    public void setFastTranslationX(float x) {
7848        ensureTransformationInfo();
7849        final TransformationInfo info = mTransformationInfo;
7850        info.mTranslationX = x;
7851        info.mMatrixDirty = true;
7852    }
7853
7854    /**
7855     * @hide
7856     */
7857    public void setFastTranslationY(float y) {
7858        ensureTransformationInfo();
7859        final TransformationInfo info = mTransformationInfo;
7860        info.mTranslationY = y;
7861        info.mMatrixDirty = true;
7862    }
7863
7864    /**
7865     * @hide
7866     */
7867    public void setFastX(float x) {
7868        ensureTransformationInfo();
7869        final TransformationInfo info = mTransformationInfo;
7870        info.mTranslationX = x - mLeft;
7871        info.mMatrixDirty = true;
7872    }
7873
7874    /**
7875     * @hide
7876     */
7877    public void setFastY(float y) {
7878        ensureTransformationInfo();
7879        final TransformationInfo info = mTransformationInfo;
7880        info.mTranslationY = y - mTop;
7881        info.mMatrixDirty = true;
7882    }
7883
7884    /**
7885     * @hide
7886     */
7887    public void setFastScaleX(float x) {
7888        ensureTransformationInfo();
7889        final TransformationInfo info = mTransformationInfo;
7890        info.mScaleX = x;
7891        info.mMatrixDirty = true;
7892    }
7893
7894    /**
7895     * @hide
7896     */
7897    public void setFastScaleY(float y) {
7898        ensureTransformationInfo();
7899        final TransformationInfo info = mTransformationInfo;
7900        info.mScaleY = y;
7901        info.mMatrixDirty = true;
7902    }
7903
7904    /**
7905     * @hide
7906     */
7907    public void setFastAlpha(float alpha) {
7908        ensureTransformationInfo();
7909        mTransformationInfo.mAlpha = alpha;
7910    }
7911
7912    /**
7913     * @hide
7914     */
7915    public void setFastRotationY(float y) {
7916        ensureTransformationInfo();
7917        final TransformationInfo info = mTransformationInfo;
7918        info.mRotationY = y;
7919        info.mMatrixDirty = true;
7920    }
7921
7922    /**
7923     * Hit rectangle in parent's coordinates
7924     *
7925     * @param outRect The hit rectangle of the view.
7926     */
7927    public void getHitRect(Rect outRect) {
7928        updateMatrix();
7929        final TransformationInfo info = mTransformationInfo;
7930        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
7931            outRect.set(mLeft, mTop, mRight, mBottom);
7932        } else {
7933            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7934            tmpRect.set(-info.mPivotX, -info.mPivotY,
7935                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
7936            info.mMatrix.mapRect(tmpRect);
7937            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7938                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7939        }
7940    }
7941
7942    /**
7943     * Determines whether the given point, in local coordinates is inside the view.
7944     */
7945    /*package*/ final boolean pointInView(float localX, float localY) {
7946        return localX >= 0 && localX < (mRight - mLeft)
7947                && localY >= 0 && localY < (mBottom - mTop);
7948    }
7949
7950    /**
7951     * Utility method to determine whether the given point, in local coordinates,
7952     * is inside the view, where the area of the view is expanded by the slop factor.
7953     * This method is called while processing touch-move events to determine if the event
7954     * is still within the view.
7955     */
7956    private boolean pointInView(float localX, float localY, float slop) {
7957        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7958                localY < ((mBottom - mTop) + slop);
7959    }
7960
7961    /**
7962     * When a view has focus and the user navigates away from it, the next view is searched for
7963     * starting from the rectangle filled in by this method.
7964     *
7965     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7966     * of the view.  However, if your view maintains some idea of internal selection,
7967     * such as a cursor, or a selected row or column, you should override this method and
7968     * fill in a more specific rectangle.
7969     *
7970     * @param r The rectangle to fill in, in this view's coordinates.
7971     */
7972    public void getFocusedRect(Rect r) {
7973        getDrawingRect(r);
7974    }
7975
7976    /**
7977     * If some part of this view is not clipped by any of its parents, then
7978     * return that area in r in global (root) coordinates. To convert r to local
7979     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7980     * -globalOffset.y)) If the view is completely clipped or translated out,
7981     * return false.
7982     *
7983     * @param r If true is returned, r holds the global coordinates of the
7984     *        visible portion of this view.
7985     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7986     *        between this view and its root. globalOffet may be null.
7987     * @return true if r is non-empty (i.e. part of the view is visible at the
7988     *         root level.
7989     */
7990    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7991        int width = mRight - mLeft;
7992        int height = mBottom - mTop;
7993        if (width > 0 && height > 0) {
7994            r.set(0, 0, width, height);
7995            if (globalOffset != null) {
7996                globalOffset.set(-mScrollX, -mScrollY);
7997            }
7998            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
7999        }
8000        return false;
8001    }
8002
8003    public final boolean getGlobalVisibleRect(Rect r) {
8004        return getGlobalVisibleRect(r, null);
8005    }
8006
8007    public final boolean getLocalVisibleRect(Rect r) {
8008        Point offset = new Point();
8009        if (getGlobalVisibleRect(r, offset)) {
8010            r.offset(-offset.x, -offset.y); // make r local
8011            return true;
8012        }
8013        return false;
8014    }
8015
8016    /**
8017     * Offset this view's vertical location by the specified number of pixels.
8018     *
8019     * @param offset the number of pixels to offset the view by
8020     */
8021    public void offsetTopAndBottom(int offset) {
8022        if (offset != 0) {
8023            updateMatrix();
8024            final boolean matrixIsIdentity = mTransformationInfo == null
8025                    || mTransformationInfo.mMatrixIsIdentity;
8026            if (matrixIsIdentity) {
8027                final ViewParent p = mParent;
8028                if (p != null && mAttachInfo != null) {
8029                    final Rect r = mAttachInfo.mTmpInvalRect;
8030                    int minTop;
8031                    int maxBottom;
8032                    int yLoc;
8033                    if (offset < 0) {
8034                        minTop = mTop + offset;
8035                        maxBottom = mBottom;
8036                        yLoc = offset;
8037                    } else {
8038                        minTop = mTop;
8039                        maxBottom = mBottom + offset;
8040                        yLoc = 0;
8041                    }
8042                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8043                    p.invalidateChild(this, r);
8044                }
8045            } else {
8046                invalidate(false);
8047            }
8048
8049            mTop += offset;
8050            mBottom += offset;
8051
8052            if (!matrixIsIdentity) {
8053                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8054                invalidate(false);
8055            }
8056            invalidateParentIfNeeded();
8057        }
8058    }
8059
8060    /**
8061     * Offset this view's horizontal location by the specified amount of pixels.
8062     *
8063     * @param offset the numer of pixels to offset the view by
8064     */
8065    public void offsetLeftAndRight(int offset) {
8066        if (offset != 0) {
8067            updateMatrix();
8068            final boolean matrixIsIdentity = mTransformationInfo == null
8069                    || mTransformationInfo.mMatrixIsIdentity;
8070            if (matrixIsIdentity) {
8071                final ViewParent p = mParent;
8072                if (p != null && mAttachInfo != null) {
8073                    final Rect r = mAttachInfo.mTmpInvalRect;
8074                    int minLeft;
8075                    int maxRight;
8076                    if (offset < 0) {
8077                        minLeft = mLeft + offset;
8078                        maxRight = mRight;
8079                    } else {
8080                        minLeft = mLeft;
8081                        maxRight = mRight + offset;
8082                    }
8083                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8084                    p.invalidateChild(this, r);
8085                }
8086            } else {
8087                invalidate(false);
8088            }
8089
8090            mLeft += offset;
8091            mRight += offset;
8092
8093            if (!matrixIsIdentity) {
8094                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8095                invalidate(false);
8096            }
8097            invalidateParentIfNeeded();
8098        }
8099    }
8100
8101    /**
8102     * Get the LayoutParams associated with this view. All views should have
8103     * layout parameters. These supply parameters to the <i>parent</i> of this
8104     * view specifying how it should be arranged. There are many subclasses of
8105     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8106     * of ViewGroup that are responsible for arranging their children.
8107     *
8108     * This method may return null if this View is not attached to a parent
8109     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8110     * was not invoked successfully. When a View is attached to a parent
8111     * ViewGroup, this method must not return null.
8112     *
8113     * @return The LayoutParams associated with this view, or null if no
8114     *         parameters have been set yet
8115     */
8116    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8117    public ViewGroup.LayoutParams getLayoutParams() {
8118        return mLayoutParams;
8119    }
8120
8121    /**
8122     * Set the layout parameters associated with this view. These supply
8123     * parameters to the <i>parent</i> of this view specifying how it should be
8124     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8125     * correspond to the different subclasses of ViewGroup that are responsible
8126     * for arranging their children.
8127     *
8128     * @param params The layout parameters for this view, cannot be null
8129     */
8130    public void setLayoutParams(ViewGroup.LayoutParams params) {
8131        if (params == null) {
8132            throw new NullPointerException("Layout parameters cannot be null");
8133        }
8134        mLayoutParams = params;
8135        requestLayout();
8136    }
8137
8138    /**
8139     * Set the scrolled position of your view. This will cause a call to
8140     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8141     * invalidated.
8142     * @param x the x position to scroll to
8143     * @param y the y position to scroll to
8144     */
8145    public void scrollTo(int x, int y) {
8146        if (mScrollX != x || mScrollY != y) {
8147            int oldX = mScrollX;
8148            int oldY = mScrollY;
8149            mScrollX = x;
8150            mScrollY = y;
8151            invalidateParentCaches();
8152            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8153            if (!awakenScrollBars()) {
8154                invalidate(true);
8155            }
8156        }
8157    }
8158
8159    /**
8160     * Move the scrolled position of your view. This will cause a call to
8161     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8162     * invalidated.
8163     * @param x the amount of pixels to scroll by horizontally
8164     * @param y the amount of pixels to scroll by vertically
8165     */
8166    public void scrollBy(int x, int y) {
8167        scrollTo(mScrollX + x, mScrollY + y);
8168    }
8169
8170    /**
8171     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8172     * animation to fade the scrollbars out after a default delay. If a subclass
8173     * provides animated scrolling, the start delay should equal the duration
8174     * of the scrolling animation.</p>
8175     *
8176     * <p>The animation starts only if at least one of the scrollbars is
8177     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8178     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8179     * this method returns true, and false otherwise. If the animation is
8180     * started, this method calls {@link #invalidate()}; in that case the
8181     * caller should not call {@link #invalidate()}.</p>
8182     *
8183     * <p>This method should be invoked every time a subclass directly updates
8184     * the scroll parameters.</p>
8185     *
8186     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8187     * and {@link #scrollTo(int, int)}.</p>
8188     *
8189     * @return true if the animation is played, false otherwise
8190     *
8191     * @see #awakenScrollBars(int)
8192     * @see #scrollBy(int, int)
8193     * @see #scrollTo(int, int)
8194     * @see #isHorizontalScrollBarEnabled()
8195     * @see #isVerticalScrollBarEnabled()
8196     * @see #setHorizontalScrollBarEnabled(boolean)
8197     * @see #setVerticalScrollBarEnabled(boolean)
8198     */
8199    protected boolean awakenScrollBars() {
8200        return mScrollCache != null &&
8201                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8202    }
8203
8204    /**
8205     * Trigger the scrollbars to draw.
8206     * This method differs from awakenScrollBars() only in its default duration.
8207     * initialAwakenScrollBars() will show the scroll bars for longer than
8208     * usual to give the user more of a chance to notice them.
8209     *
8210     * @return true if the animation is played, false otherwise.
8211     */
8212    private boolean initialAwakenScrollBars() {
8213        return mScrollCache != null &&
8214                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8215    }
8216
8217    /**
8218     * <p>
8219     * Trigger the scrollbars to draw. When invoked this method starts an
8220     * animation to fade the scrollbars out after a fixed delay. If a subclass
8221     * provides animated scrolling, the start delay should equal the duration of
8222     * the scrolling animation.
8223     * </p>
8224     *
8225     * <p>
8226     * The animation starts only if at least one of the scrollbars is enabled,
8227     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8228     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8229     * this method returns true, and false otherwise. If the animation is
8230     * started, this method calls {@link #invalidate()}; in that case the caller
8231     * should not call {@link #invalidate()}.
8232     * </p>
8233     *
8234     * <p>
8235     * This method should be invoked everytime a subclass directly updates the
8236     * scroll parameters.
8237     * </p>
8238     *
8239     * @param startDelay the delay, in milliseconds, after which the animation
8240     *        should start; when the delay is 0, the animation starts
8241     *        immediately
8242     * @return true if the animation is played, false otherwise
8243     *
8244     * @see #scrollBy(int, int)
8245     * @see #scrollTo(int, int)
8246     * @see #isHorizontalScrollBarEnabled()
8247     * @see #isVerticalScrollBarEnabled()
8248     * @see #setHorizontalScrollBarEnabled(boolean)
8249     * @see #setVerticalScrollBarEnabled(boolean)
8250     */
8251    protected boolean awakenScrollBars(int startDelay) {
8252        return awakenScrollBars(startDelay, true);
8253    }
8254
8255    /**
8256     * <p>
8257     * Trigger the scrollbars to draw. When invoked this method starts an
8258     * animation to fade the scrollbars out after a fixed delay. If a subclass
8259     * provides animated scrolling, the start delay should equal the duration of
8260     * the scrolling animation.
8261     * </p>
8262     *
8263     * <p>
8264     * The animation starts only if at least one of the scrollbars is enabled,
8265     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8266     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8267     * this method returns true, and false otherwise. If the animation is
8268     * started, this method calls {@link #invalidate()} if the invalidate parameter
8269     * is set to true; in that case the caller
8270     * should not call {@link #invalidate()}.
8271     * </p>
8272     *
8273     * <p>
8274     * This method should be invoked everytime a subclass directly updates the
8275     * scroll parameters.
8276     * </p>
8277     *
8278     * @param startDelay the delay, in milliseconds, after which the animation
8279     *        should start; when the delay is 0, the animation starts
8280     *        immediately
8281     *
8282     * @param invalidate Wheter this method should call invalidate
8283     *
8284     * @return true if the animation is played, false otherwise
8285     *
8286     * @see #scrollBy(int, int)
8287     * @see #scrollTo(int, int)
8288     * @see #isHorizontalScrollBarEnabled()
8289     * @see #isVerticalScrollBarEnabled()
8290     * @see #setHorizontalScrollBarEnabled(boolean)
8291     * @see #setVerticalScrollBarEnabled(boolean)
8292     */
8293    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8294        final ScrollabilityCache scrollCache = mScrollCache;
8295
8296        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8297            return false;
8298        }
8299
8300        if (scrollCache.scrollBar == null) {
8301            scrollCache.scrollBar = new ScrollBarDrawable();
8302        }
8303
8304        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8305
8306            if (invalidate) {
8307                // Invalidate to show the scrollbars
8308                invalidate(true);
8309            }
8310
8311            if (scrollCache.state == ScrollabilityCache.OFF) {
8312                // FIXME: this is copied from WindowManagerService.
8313                // We should get this value from the system when it
8314                // is possible to do so.
8315                final int KEY_REPEAT_FIRST_DELAY = 750;
8316                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8317            }
8318
8319            // Tell mScrollCache when we should start fading. This may
8320            // extend the fade start time if one was already scheduled
8321            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8322            scrollCache.fadeStartTime = fadeStartTime;
8323            scrollCache.state = ScrollabilityCache.ON;
8324
8325            // Schedule our fader to run, unscheduling any old ones first
8326            if (mAttachInfo != null) {
8327                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8328                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8329            }
8330
8331            return true;
8332        }
8333
8334        return false;
8335    }
8336
8337    /**
8338     * Do not invalidate views which are not visible and which are not running an animation. They
8339     * will not get drawn and they should not set dirty flags as if they will be drawn
8340     */
8341    private boolean skipInvalidate() {
8342        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8343                (!(mParent instanceof ViewGroup) ||
8344                        !((ViewGroup) mParent).isViewTransitioning(this));
8345    }
8346    /**
8347     * Mark the the area defined by dirty as needing to be drawn. If the view is
8348     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8349     * in the future. This must be called from a UI thread. To call from a non-UI
8350     * thread, call {@link #postInvalidate()}.
8351     *
8352     * WARNING: This method is destructive to dirty.
8353     * @param dirty the rectangle representing the bounds of the dirty region
8354     */
8355    public void invalidate(Rect dirty) {
8356        if (ViewDebug.TRACE_HIERARCHY) {
8357            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8358        }
8359
8360        if (skipInvalidate()) {
8361            return;
8362        }
8363        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8364                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8365                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8366            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8367            mPrivateFlags |= INVALIDATED;
8368            mPrivateFlags |= DIRTY;
8369            final ViewParent p = mParent;
8370            final AttachInfo ai = mAttachInfo;
8371            //noinspection PointlessBooleanExpression,ConstantConditions
8372            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8373                if (p != null && ai != null && ai.mHardwareAccelerated) {
8374                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8375                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8376                    p.invalidateChild(this, null);
8377                    return;
8378                }
8379            }
8380            if (p != null && ai != null) {
8381                final int scrollX = mScrollX;
8382                final int scrollY = mScrollY;
8383                final Rect r = ai.mTmpInvalRect;
8384                r.set(dirty.left - scrollX, dirty.top - scrollY,
8385                        dirty.right - scrollX, dirty.bottom - scrollY);
8386                mParent.invalidateChild(this, r);
8387            }
8388        }
8389    }
8390
8391    /**
8392     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
8393     * The coordinates of the dirty rect are relative to the view.
8394     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8395     * will be called at some point in the future. This must be called from
8396     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8397     * @param l the left position of the dirty region
8398     * @param t the top position of the dirty region
8399     * @param r the right position of the dirty region
8400     * @param b the bottom position of the dirty region
8401     */
8402    public void invalidate(int l, int t, int r, int b) {
8403        if (ViewDebug.TRACE_HIERARCHY) {
8404            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8405        }
8406
8407        if (skipInvalidate()) {
8408            return;
8409        }
8410        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8411                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8412                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8413            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8414            mPrivateFlags |= INVALIDATED;
8415            mPrivateFlags |= DIRTY;
8416            final ViewParent p = mParent;
8417            final AttachInfo ai = mAttachInfo;
8418            //noinspection PointlessBooleanExpression,ConstantConditions
8419            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8420                if (p != null && ai != null && ai.mHardwareAccelerated) {
8421                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8422                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8423                    p.invalidateChild(this, null);
8424                    return;
8425                }
8426            }
8427            if (p != null && ai != null && l < r && t < b) {
8428                final int scrollX = mScrollX;
8429                final int scrollY = mScrollY;
8430                final Rect tmpr = ai.mTmpInvalRect;
8431                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8432                p.invalidateChild(this, tmpr);
8433            }
8434        }
8435    }
8436
8437    /**
8438     * Invalidate the whole view. If the view is visible,
8439     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8440     * the future. This must be called from a UI thread. To call from a non-UI thread,
8441     * call {@link #postInvalidate()}.
8442     */
8443    public void invalidate() {
8444        invalidate(true);
8445    }
8446
8447    /**
8448     * This is where the invalidate() work actually happens. A full invalidate()
8449     * causes the drawing cache to be invalidated, but this function can be called with
8450     * invalidateCache set to false to skip that invalidation step for cases that do not
8451     * need it (for example, a component that remains at the same dimensions with the same
8452     * content).
8453     *
8454     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8455     * well. This is usually true for a full invalidate, but may be set to false if the
8456     * View's contents or dimensions have not changed.
8457     */
8458    void invalidate(boolean invalidateCache) {
8459        if (ViewDebug.TRACE_HIERARCHY) {
8460            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8461        }
8462
8463        if (skipInvalidate()) {
8464            return;
8465        }
8466        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8467                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8468                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8469            mLastIsOpaque = isOpaque();
8470            mPrivateFlags &= ~DRAWN;
8471            mPrivateFlags |= DIRTY;
8472            if (invalidateCache) {
8473                mPrivateFlags |= INVALIDATED;
8474                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8475            }
8476            final AttachInfo ai = mAttachInfo;
8477            final ViewParent p = mParent;
8478            //noinspection PointlessBooleanExpression,ConstantConditions
8479            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8480                if (p != null && ai != null && ai.mHardwareAccelerated) {
8481                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8482                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8483                    p.invalidateChild(this, null);
8484                    return;
8485                }
8486            }
8487
8488            if (p != null && ai != null) {
8489                final Rect r = ai.mTmpInvalRect;
8490                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8491                // Don't call invalidate -- we don't want to internally scroll
8492                // our own bounds
8493                p.invalidateChild(this, r);
8494            }
8495        }
8496    }
8497
8498    /**
8499     * @hide
8500     */
8501    public void fastInvalidate() {
8502        if (skipInvalidate()) {
8503            return;
8504        }
8505        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8506            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8507            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8508            if (mParent instanceof View) {
8509                ((View) mParent).mPrivateFlags |= INVALIDATED;
8510            }
8511            mPrivateFlags &= ~DRAWN;
8512            mPrivateFlags |= DIRTY;
8513            mPrivateFlags |= INVALIDATED;
8514            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8515            if (mParent != null && mAttachInfo != null) {
8516                if (mAttachInfo.mHardwareAccelerated) {
8517                    mParent.invalidateChild(this, null);
8518                } else {
8519                    final Rect r = mAttachInfo.mTmpInvalRect;
8520                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
8521                    // Don't call invalidate -- we don't want to internally scroll
8522                    // our own bounds
8523                    mParent.invalidateChild(this, r);
8524                }
8525            }
8526        }
8527    }
8528
8529    /**
8530     * Used to indicate that the parent of this view should clear its caches. This functionality
8531     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8532     * which is necessary when various parent-managed properties of the view change, such as
8533     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8534     * clears the parent caches and does not causes an invalidate event.
8535     *
8536     * @hide
8537     */
8538    protected void invalidateParentCaches() {
8539        if (mParent instanceof View) {
8540            ((View) mParent).mPrivateFlags |= INVALIDATED;
8541        }
8542    }
8543
8544    /**
8545     * Used to indicate that the parent of this view should be invalidated. This functionality
8546     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8547     * which is necessary when various parent-managed properties of the view change, such as
8548     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8549     * an invalidation event to the parent.
8550     *
8551     * @hide
8552     */
8553    protected void invalidateParentIfNeeded() {
8554        if (isHardwareAccelerated() && mParent instanceof View) {
8555            ((View) mParent).invalidate(true);
8556        }
8557    }
8558
8559    /**
8560     * Indicates whether this View is opaque. An opaque View guarantees that it will
8561     * draw all the pixels overlapping its bounds using a fully opaque color.
8562     *
8563     * Subclasses of View should override this method whenever possible to indicate
8564     * whether an instance is opaque. Opaque Views are treated in a special way by
8565     * the View hierarchy, possibly allowing it to perform optimizations during
8566     * invalidate/draw passes.
8567     *
8568     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8569     */
8570    @ViewDebug.ExportedProperty(category = "drawing")
8571    public boolean isOpaque() {
8572        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8573                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8574                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8575    }
8576
8577    /**
8578     * @hide
8579     */
8580    protected void computeOpaqueFlags() {
8581        // Opaque if:
8582        //   - Has a background
8583        //   - Background is opaque
8584        //   - Doesn't have scrollbars or scrollbars are inside overlay
8585
8586        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8587            mPrivateFlags |= OPAQUE_BACKGROUND;
8588        } else {
8589            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8590        }
8591
8592        final int flags = mViewFlags;
8593        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8594                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8595            mPrivateFlags |= OPAQUE_SCROLLBARS;
8596        } else {
8597            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8598        }
8599    }
8600
8601    /**
8602     * @hide
8603     */
8604    protected boolean hasOpaqueScrollbars() {
8605        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8606    }
8607
8608    /**
8609     * @return A handler associated with the thread running the View. This
8610     * handler can be used to pump events in the UI events queue.
8611     */
8612    public Handler getHandler() {
8613        if (mAttachInfo != null) {
8614            return mAttachInfo.mHandler;
8615        }
8616        return null;
8617    }
8618
8619    /**
8620     * <p>Causes the Runnable to be added to the message queue.
8621     * The runnable will be run on the user interface thread.</p>
8622     *
8623     * <p>This method can be invoked from outside of the UI thread
8624     * only when this View is attached to a window.</p>
8625     *
8626     * @param action The Runnable that will be executed.
8627     *
8628     * @return Returns true if the Runnable was successfully placed in to the
8629     *         message queue.  Returns false on failure, usually because the
8630     *         looper processing the message queue is exiting.
8631     */
8632    public boolean post(Runnable action) {
8633        Handler handler;
8634        AttachInfo attachInfo = mAttachInfo;
8635        if (attachInfo != null) {
8636            handler = attachInfo.mHandler;
8637        } else {
8638            // Assume that post will succeed later
8639            ViewRootImpl.getRunQueue().post(action);
8640            return true;
8641        }
8642
8643        return handler.post(action);
8644    }
8645
8646    /**
8647     * <p>Causes the Runnable to be added to the message queue, to be run
8648     * after the specified amount of time elapses.
8649     * The runnable will be run on the user interface thread.</p>
8650     *
8651     * <p>This method can be invoked from outside of the UI thread
8652     * only when this View is attached to a window.</p>
8653     *
8654     * @param action The Runnable that will be executed.
8655     * @param delayMillis The delay (in milliseconds) until the Runnable
8656     *        will be executed.
8657     *
8658     * @return true if the Runnable was successfully placed in to the
8659     *         message queue.  Returns false on failure, usually because the
8660     *         looper processing the message queue is exiting.  Note that a
8661     *         result of true does not mean the Runnable will be processed --
8662     *         if the looper is quit before the delivery time of the message
8663     *         occurs then the message will be dropped.
8664     */
8665    public boolean postDelayed(Runnable action, long delayMillis) {
8666        Handler handler;
8667        AttachInfo attachInfo = mAttachInfo;
8668        if (attachInfo != null) {
8669            handler = attachInfo.mHandler;
8670        } else {
8671            // Assume that post will succeed later
8672            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8673            return true;
8674        }
8675
8676        return handler.postDelayed(action, delayMillis);
8677    }
8678
8679    /**
8680     * <p>Removes the specified Runnable from the message queue.</p>
8681     *
8682     * <p>This method can be invoked from outside of the UI thread
8683     * only when this View is attached to a window.</p>
8684     *
8685     * @param action The Runnable to remove from the message handling queue
8686     *
8687     * @return true if this view could ask the Handler to remove the Runnable,
8688     *         false otherwise. When the returned value is true, the Runnable
8689     *         may or may not have been actually removed from the message queue
8690     *         (for instance, if the Runnable was not in the queue already.)
8691     */
8692    public boolean removeCallbacks(Runnable action) {
8693        Handler handler;
8694        AttachInfo attachInfo = mAttachInfo;
8695        if (attachInfo != null) {
8696            handler = attachInfo.mHandler;
8697        } else {
8698            // Assume that post will succeed later
8699            ViewRootImpl.getRunQueue().removeCallbacks(action);
8700            return true;
8701        }
8702
8703        handler.removeCallbacks(action);
8704        return true;
8705    }
8706
8707    /**
8708     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8709     * Use this to invalidate the View from a non-UI thread.</p>
8710     *
8711     * <p>This method can be invoked from outside of the UI thread
8712     * only when this View is attached to a window.</p>
8713     *
8714     * @see #invalidate()
8715     */
8716    public void postInvalidate() {
8717        postInvalidateDelayed(0);
8718    }
8719
8720    /**
8721     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8722     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8723     *
8724     * <p>This method can be invoked from outside of the UI thread
8725     * only when this View is attached to a window.</p>
8726     *
8727     * @param left The left coordinate of the rectangle to invalidate.
8728     * @param top The top coordinate of the rectangle to invalidate.
8729     * @param right The right coordinate of the rectangle to invalidate.
8730     * @param bottom The bottom coordinate of the rectangle to invalidate.
8731     *
8732     * @see #invalidate(int, int, int, int)
8733     * @see #invalidate(Rect)
8734     */
8735    public void postInvalidate(int left, int top, int right, int bottom) {
8736        postInvalidateDelayed(0, left, top, right, bottom);
8737    }
8738
8739    /**
8740     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8741     * loop. Waits for the specified amount of time.</p>
8742     *
8743     * <p>This method can be invoked from outside of the UI thread
8744     * only when this View is attached to a window.</p>
8745     *
8746     * @param delayMilliseconds the duration in milliseconds to delay the
8747     *         invalidation by
8748     */
8749    public void postInvalidateDelayed(long delayMilliseconds) {
8750        // We try only with the AttachInfo because there's no point in invalidating
8751        // if we are not attached to our window
8752        AttachInfo attachInfo = mAttachInfo;
8753        if (attachInfo != null) {
8754            Message msg = Message.obtain();
8755            msg.what = AttachInfo.INVALIDATE_MSG;
8756            msg.obj = this;
8757            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8758        }
8759    }
8760
8761    /**
8762     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8763     * through the event loop. Waits for the specified amount of time.</p>
8764     *
8765     * <p>This method can be invoked from outside of the UI thread
8766     * only when this View is attached to a window.</p>
8767     *
8768     * @param delayMilliseconds the duration in milliseconds to delay the
8769     *         invalidation by
8770     * @param left The left coordinate of the rectangle to invalidate.
8771     * @param top The top coordinate of the rectangle to invalidate.
8772     * @param right The right coordinate of the rectangle to invalidate.
8773     * @param bottom The bottom coordinate of the rectangle to invalidate.
8774     */
8775    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8776            int right, int bottom) {
8777
8778        // We try only with the AttachInfo because there's no point in invalidating
8779        // if we are not attached to our window
8780        AttachInfo attachInfo = mAttachInfo;
8781        if (attachInfo != null) {
8782            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8783            info.target = this;
8784            info.left = left;
8785            info.top = top;
8786            info.right = right;
8787            info.bottom = bottom;
8788
8789            final Message msg = Message.obtain();
8790            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8791            msg.obj = info;
8792            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8793        }
8794    }
8795
8796    /**
8797     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8798     * This event is sent at most once every
8799     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8800     */
8801    private void postSendViewScrolledAccessibilityEventCallback() {
8802        if (mSendViewScrolledAccessibilityEvent == null) {
8803            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8804        }
8805        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8806            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8807            postDelayed(mSendViewScrolledAccessibilityEvent,
8808                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8809        }
8810    }
8811
8812    /**
8813     * Called by a parent to request that a child update its values for mScrollX
8814     * and mScrollY if necessary. This will typically be done if the child is
8815     * animating a scroll using a {@link android.widget.Scroller Scroller}
8816     * object.
8817     */
8818    public void computeScroll() {
8819    }
8820
8821    /**
8822     * <p>Indicate whether the horizontal edges are faded when the view is
8823     * scrolled horizontally.</p>
8824     *
8825     * @return true if the horizontal edges should are faded on scroll, false
8826     *         otherwise
8827     *
8828     * @see #setHorizontalFadingEdgeEnabled(boolean)
8829     * @attr ref android.R.styleable#View_requiresFadingEdge
8830     */
8831    public boolean isHorizontalFadingEdgeEnabled() {
8832        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8833    }
8834
8835    /**
8836     * <p>Define whether the horizontal edges should be faded when this view
8837     * is scrolled horizontally.</p>
8838     *
8839     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8840     *                                    be faded when the view is scrolled
8841     *                                    horizontally
8842     *
8843     * @see #isHorizontalFadingEdgeEnabled()
8844     * @attr ref android.R.styleable#View_requiresFadingEdge
8845     */
8846    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8847        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8848            if (horizontalFadingEdgeEnabled) {
8849                initScrollCache();
8850            }
8851
8852            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8853        }
8854    }
8855
8856    /**
8857     * <p>Indicate whether the vertical edges are faded when the view is
8858     * scrolled horizontally.</p>
8859     *
8860     * @return true if the vertical edges should are faded on scroll, false
8861     *         otherwise
8862     *
8863     * @see #setVerticalFadingEdgeEnabled(boolean)
8864     * @attr ref android.R.styleable#View_requiresFadingEdge
8865     */
8866    public boolean isVerticalFadingEdgeEnabled() {
8867        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8868    }
8869
8870    /**
8871     * <p>Define whether the vertical edges should be faded when this view
8872     * is scrolled vertically.</p>
8873     *
8874     * @param verticalFadingEdgeEnabled true if the vertical edges should
8875     *                                  be faded when the view is scrolled
8876     *                                  vertically
8877     *
8878     * @see #isVerticalFadingEdgeEnabled()
8879     * @attr ref android.R.styleable#View_requiresFadingEdge
8880     */
8881    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8882        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8883            if (verticalFadingEdgeEnabled) {
8884                initScrollCache();
8885            }
8886
8887            mViewFlags ^= FADING_EDGE_VERTICAL;
8888        }
8889    }
8890
8891    /**
8892     * Returns the strength, or intensity, of the top faded edge. The strength is
8893     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8894     * returns 0.0 or 1.0 but no value in between.
8895     *
8896     * Subclasses should override this method to provide a smoother fade transition
8897     * when scrolling occurs.
8898     *
8899     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8900     */
8901    protected float getTopFadingEdgeStrength() {
8902        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8903    }
8904
8905    /**
8906     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8907     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8908     * returns 0.0 or 1.0 but no value in between.
8909     *
8910     * Subclasses should override this method to provide a smoother fade transition
8911     * when scrolling occurs.
8912     *
8913     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8914     */
8915    protected float getBottomFadingEdgeStrength() {
8916        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8917                computeVerticalScrollRange() ? 1.0f : 0.0f;
8918    }
8919
8920    /**
8921     * Returns the strength, or intensity, of the left faded edge. The strength is
8922     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8923     * returns 0.0 or 1.0 but no value in between.
8924     *
8925     * Subclasses should override this method to provide a smoother fade transition
8926     * when scrolling occurs.
8927     *
8928     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8929     */
8930    protected float getLeftFadingEdgeStrength() {
8931        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8932    }
8933
8934    /**
8935     * Returns the strength, or intensity, of the right faded edge. The strength is
8936     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8937     * returns 0.0 or 1.0 but no value in between.
8938     *
8939     * Subclasses should override this method to provide a smoother fade transition
8940     * when scrolling occurs.
8941     *
8942     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8943     */
8944    protected float getRightFadingEdgeStrength() {
8945        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8946                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8947    }
8948
8949    /**
8950     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8951     * scrollbar is not drawn by default.</p>
8952     *
8953     * @return true if the horizontal scrollbar should be painted, false
8954     *         otherwise
8955     *
8956     * @see #setHorizontalScrollBarEnabled(boolean)
8957     */
8958    public boolean isHorizontalScrollBarEnabled() {
8959        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8960    }
8961
8962    /**
8963     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8964     * scrollbar is not drawn by default.</p>
8965     *
8966     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8967     *                                   be painted
8968     *
8969     * @see #isHorizontalScrollBarEnabled()
8970     */
8971    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8972        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8973            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8974            computeOpaqueFlags();
8975            resolvePadding();
8976        }
8977    }
8978
8979    /**
8980     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8981     * scrollbar is not drawn by default.</p>
8982     *
8983     * @return true if the vertical scrollbar should be painted, false
8984     *         otherwise
8985     *
8986     * @see #setVerticalScrollBarEnabled(boolean)
8987     */
8988    public boolean isVerticalScrollBarEnabled() {
8989        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8990    }
8991
8992    /**
8993     * <p>Define whether the vertical scrollbar should be drawn or not. The
8994     * scrollbar is not drawn by default.</p>
8995     *
8996     * @param verticalScrollBarEnabled true if the vertical scrollbar should
8997     *                                 be painted
8998     *
8999     * @see #isVerticalScrollBarEnabled()
9000     */
9001    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9002        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9003            mViewFlags ^= SCROLLBARS_VERTICAL;
9004            computeOpaqueFlags();
9005            resolvePadding();
9006        }
9007    }
9008
9009    /**
9010     * @hide
9011     */
9012    protected void recomputePadding() {
9013        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9014    }
9015
9016    /**
9017     * Define whether scrollbars will fade when the view is not scrolling.
9018     *
9019     * @param fadeScrollbars wheter to enable fading
9020     *
9021     */
9022    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9023        initScrollCache();
9024        final ScrollabilityCache scrollabilityCache = mScrollCache;
9025        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9026        if (fadeScrollbars) {
9027            scrollabilityCache.state = ScrollabilityCache.OFF;
9028        } else {
9029            scrollabilityCache.state = ScrollabilityCache.ON;
9030        }
9031    }
9032
9033    /**
9034     *
9035     * Returns true if scrollbars will fade when this view is not scrolling
9036     *
9037     * @return true if scrollbar fading is enabled
9038     */
9039    public boolean isScrollbarFadingEnabled() {
9040        return mScrollCache != null && mScrollCache.fadeScrollBars;
9041    }
9042
9043    /**
9044     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9045     * inset. When inset, they add to the padding of the view. And the scrollbars
9046     * can be drawn inside the padding area or on the edge of the view. For example,
9047     * if a view has a background drawable and you want to draw the scrollbars
9048     * inside the padding specified by the drawable, you can use
9049     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9050     * appear at the edge of the view, ignoring the padding, then you can use
9051     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9052     * @param style the style of the scrollbars. Should be one of
9053     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9054     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9055     * @see #SCROLLBARS_INSIDE_OVERLAY
9056     * @see #SCROLLBARS_INSIDE_INSET
9057     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9058     * @see #SCROLLBARS_OUTSIDE_INSET
9059     */
9060    public void setScrollBarStyle(int style) {
9061        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9062            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9063            computeOpaqueFlags();
9064            resolvePadding();
9065        }
9066    }
9067
9068    /**
9069     * <p>Returns the current scrollbar style.</p>
9070     * @return the current scrollbar style
9071     * @see #SCROLLBARS_INSIDE_OVERLAY
9072     * @see #SCROLLBARS_INSIDE_INSET
9073     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9074     * @see #SCROLLBARS_OUTSIDE_INSET
9075     */
9076    @ViewDebug.ExportedProperty(mapping = {
9077            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9078            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9079            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9080            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9081    })
9082    public int getScrollBarStyle() {
9083        return mViewFlags & SCROLLBARS_STYLE_MASK;
9084    }
9085
9086    /**
9087     * <p>Compute the horizontal range that the horizontal scrollbar
9088     * represents.</p>
9089     *
9090     * <p>The range is expressed in arbitrary units that must be the same as the
9091     * units used by {@link #computeHorizontalScrollExtent()} and
9092     * {@link #computeHorizontalScrollOffset()}.</p>
9093     *
9094     * <p>The default range is the drawing width of this view.</p>
9095     *
9096     * @return the total horizontal range represented by the horizontal
9097     *         scrollbar
9098     *
9099     * @see #computeHorizontalScrollExtent()
9100     * @see #computeHorizontalScrollOffset()
9101     * @see android.widget.ScrollBarDrawable
9102     */
9103    protected int computeHorizontalScrollRange() {
9104        return getWidth();
9105    }
9106
9107    /**
9108     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9109     * within the horizontal range. This value is used to compute the position
9110     * of the thumb within the scrollbar's track.</p>
9111     *
9112     * <p>The range is expressed in arbitrary units that must be the same as the
9113     * units used by {@link #computeHorizontalScrollRange()} and
9114     * {@link #computeHorizontalScrollExtent()}.</p>
9115     *
9116     * <p>The default offset is the scroll offset of this view.</p>
9117     *
9118     * @return the horizontal offset of the scrollbar's thumb
9119     *
9120     * @see #computeHorizontalScrollRange()
9121     * @see #computeHorizontalScrollExtent()
9122     * @see android.widget.ScrollBarDrawable
9123     */
9124    protected int computeHorizontalScrollOffset() {
9125        return mScrollX;
9126    }
9127
9128    /**
9129     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9130     * within the horizontal range. This value is used to compute the length
9131     * of the thumb within the scrollbar's track.</p>
9132     *
9133     * <p>The range is expressed in arbitrary units that must be the same as the
9134     * units used by {@link #computeHorizontalScrollRange()} and
9135     * {@link #computeHorizontalScrollOffset()}.</p>
9136     *
9137     * <p>The default extent is the drawing width of this view.</p>
9138     *
9139     * @return the horizontal extent of the scrollbar's thumb
9140     *
9141     * @see #computeHorizontalScrollRange()
9142     * @see #computeHorizontalScrollOffset()
9143     * @see android.widget.ScrollBarDrawable
9144     */
9145    protected int computeHorizontalScrollExtent() {
9146        return getWidth();
9147    }
9148
9149    /**
9150     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9151     *
9152     * <p>The range is expressed in arbitrary units that must be the same as the
9153     * units used by {@link #computeVerticalScrollExtent()} and
9154     * {@link #computeVerticalScrollOffset()}.</p>
9155     *
9156     * @return the total vertical range represented by the vertical scrollbar
9157     *
9158     * <p>The default range is the drawing height of this view.</p>
9159     *
9160     * @see #computeVerticalScrollExtent()
9161     * @see #computeVerticalScrollOffset()
9162     * @see android.widget.ScrollBarDrawable
9163     */
9164    protected int computeVerticalScrollRange() {
9165        return getHeight();
9166    }
9167
9168    /**
9169     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9170     * within the horizontal range. This value is used to compute the position
9171     * of the thumb within the scrollbar's track.</p>
9172     *
9173     * <p>The range is expressed in arbitrary units that must be the same as the
9174     * units used by {@link #computeVerticalScrollRange()} and
9175     * {@link #computeVerticalScrollExtent()}.</p>
9176     *
9177     * <p>The default offset is the scroll offset of this view.</p>
9178     *
9179     * @return the vertical offset of the scrollbar's thumb
9180     *
9181     * @see #computeVerticalScrollRange()
9182     * @see #computeVerticalScrollExtent()
9183     * @see android.widget.ScrollBarDrawable
9184     */
9185    protected int computeVerticalScrollOffset() {
9186        return mScrollY;
9187    }
9188
9189    /**
9190     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9191     * within the vertical range. This value is used to compute the length
9192     * of the thumb within the scrollbar's track.</p>
9193     *
9194     * <p>The range is expressed in arbitrary units that must be the same as the
9195     * units used by {@link #computeVerticalScrollRange()} and
9196     * {@link #computeVerticalScrollOffset()}.</p>
9197     *
9198     * <p>The default extent is the drawing height of this view.</p>
9199     *
9200     * @return the vertical extent of the scrollbar's thumb
9201     *
9202     * @see #computeVerticalScrollRange()
9203     * @see #computeVerticalScrollOffset()
9204     * @see android.widget.ScrollBarDrawable
9205     */
9206    protected int computeVerticalScrollExtent() {
9207        return getHeight();
9208    }
9209
9210    /**
9211     * Check if this view can be scrolled horizontally in a certain direction.
9212     *
9213     * @param direction Negative to check scrolling left, positive to check scrolling right.
9214     * @return true if this view can be scrolled in the specified direction, false otherwise.
9215     */
9216    public boolean canScrollHorizontally(int direction) {
9217        final int offset = computeHorizontalScrollOffset();
9218        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9219        if (range == 0) return false;
9220        if (direction < 0) {
9221            return offset > 0;
9222        } else {
9223            return offset < range - 1;
9224        }
9225    }
9226
9227    /**
9228     * Check if this view can be scrolled vertically in a certain direction.
9229     *
9230     * @param direction Negative to check scrolling up, positive to check scrolling down.
9231     * @return true if this view can be scrolled in the specified direction, false otherwise.
9232     */
9233    public boolean canScrollVertically(int direction) {
9234        final int offset = computeVerticalScrollOffset();
9235        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9236        if (range == 0) return false;
9237        if (direction < 0) {
9238            return offset > 0;
9239        } else {
9240            return offset < range - 1;
9241        }
9242    }
9243
9244    /**
9245     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9246     * scrollbars are painted only if they have been awakened first.</p>
9247     *
9248     * @param canvas the canvas on which to draw the scrollbars
9249     *
9250     * @see #awakenScrollBars(int)
9251     */
9252    protected final void onDrawScrollBars(Canvas canvas) {
9253        // scrollbars are drawn only when the animation is running
9254        final ScrollabilityCache cache = mScrollCache;
9255        if (cache != null) {
9256
9257            int state = cache.state;
9258
9259            if (state == ScrollabilityCache.OFF) {
9260                return;
9261            }
9262
9263            boolean invalidate = false;
9264
9265            if (state == ScrollabilityCache.FADING) {
9266                // We're fading -- get our fade interpolation
9267                if (cache.interpolatorValues == null) {
9268                    cache.interpolatorValues = new float[1];
9269                }
9270
9271                float[] values = cache.interpolatorValues;
9272
9273                // Stops the animation if we're done
9274                if (cache.scrollBarInterpolator.timeToValues(values) ==
9275                        Interpolator.Result.FREEZE_END) {
9276                    cache.state = ScrollabilityCache.OFF;
9277                } else {
9278                    cache.scrollBar.setAlpha(Math.round(values[0]));
9279                }
9280
9281                // This will make the scroll bars inval themselves after
9282                // drawing. We only want this when we're fading so that
9283                // we prevent excessive redraws
9284                invalidate = true;
9285            } else {
9286                // We're just on -- but we may have been fading before so
9287                // reset alpha
9288                cache.scrollBar.setAlpha(255);
9289            }
9290
9291
9292            final int viewFlags = mViewFlags;
9293
9294            final boolean drawHorizontalScrollBar =
9295                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9296            final boolean drawVerticalScrollBar =
9297                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9298                && !isVerticalScrollBarHidden();
9299
9300            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9301                final int width = mRight - mLeft;
9302                final int height = mBottom - mTop;
9303
9304                final ScrollBarDrawable scrollBar = cache.scrollBar;
9305
9306                final int scrollX = mScrollX;
9307                final int scrollY = mScrollY;
9308                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9309
9310                int left, top, right, bottom;
9311
9312                if (drawHorizontalScrollBar) {
9313                    int size = scrollBar.getSize(false);
9314                    if (size <= 0) {
9315                        size = cache.scrollBarSize;
9316                    }
9317
9318                    scrollBar.setParameters(computeHorizontalScrollRange(),
9319                                            computeHorizontalScrollOffset(),
9320                                            computeHorizontalScrollExtent(), false);
9321                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9322                            getVerticalScrollbarWidth() : 0;
9323                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9324                    left = scrollX + (mPaddingLeft & inside);
9325                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9326                    bottom = top + size;
9327                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9328                    if (invalidate) {
9329                        invalidate(left, top, right, bottom);
9330                    }
9331                }
9332
9333                if (drawVerticalScrollBar) {
9334                    int size = scrollBar.getSize(true);
9335                    if (size <= 0) {
9336                        size = cache.scrollBarSize;
9337                    }
9338
9339                    scrollBar.setParameters(computeVerticalScrollRange(),
9340                                            computeVerticalScrollOffset(),
9341                                            computeVerticalScrollExtent(), true);
9342                    switch (mVerticalScrollbarPosition) {
9343                        default:
9344                        case SCROLLBAR_POSITION_DEFAULT:
9345                        case SCROLLBAR_POSITION_RIGHT:
9346                            left = scrollX + width - size - (mUserPaddingRight & inside);
9347                            break;
9348                        case SCROLLBAR_POSITION_LEFT:
9349                            left = scrollX + (mUserPaddingLeft & inside);
9350                            break;
9351                    }
9352                    top = scrollY + (mPaddingTop & inside);
9353                    right = left + size;
9354                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9355                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9356                    if (invalidate) {
9357                        invalidate(left, top, right, bottom);
9358                    }
9359                }
9360            }
9361        }
9362    }
9363
9364    /**
9365     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9366     * FastScroller is visible.
9367     * @return whether to temporarily hide the vertical scrollbar
9368     * @hide
9369     */
9370    protected boolean isVerticalScrollBarHidden() {
9371        return false;
9372    }
9373
9374    /**
9375     * <p>Draw the horizontal scrollbar if
9376     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9377     *
9378     * @param canvas the canvas on which to draw the scrollbar
9379     * @param scrollBar the scrollbar's drawable
9380     *
9381     * @see #isHorizontalScrollBarEnabled()
9382     * @see #computeHorizontalScrollRange()
9383     * @see #computeHorizontalScrollExtent()
9384     * @see #computeHorizontalScrollOffset()
9385     * @see android.widget.ScrollBarDrawable
9386     * @hide
9387     */
9388    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9389            int l, int t, int r, int b) {
9390        scrollBar.setBounds(l, t, r, b);
9391        scrollBar.draw(canvas);
9392    }
9393
9394    /**
9395     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9396     * returns true.</p>
9397     *
9398     * @param canvas the canvas on which to draw the scrollbar
9399     * @param scrollBar the scrollbar's drawable
9400     *
9401     * @see #isVerticalScrollBarEnabled()
9402     * @see #computeVerticalScrollRange()
9403     * @see #computeVerticalScrollExtent()
9404     * @see #computeVerticalScrollOffset()
9405     * @see android.widget.ScrollBarDrawable
9406     * @hide
9407     */
9408    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9409            int l, int t, int r, int b) {
9410        scrollBar.setBounds(l, t, r, b);
9411        scrollBar.draw(canvas);
9412    }
9413
9414    /**
9415     * Implement this to do your drawing.
9416     *
9417     * @param canvas the canvas on which the background will be drawn
9418     */
9419    protected void onDraw(Canvas canvas) {
9420    }
9421
9422    /*
9423     * Caller is responsible for calling requestLayout if necessary.
9424     * (This allows addViewInLayout to not request a new layout.)
9425     */
9426    void assignParent(ViewParent parent) {
9427        if (mParent == null) {
9428            mParent = parent;
9429        } else if (parent == null) {
9430            mParent = null;
9431        } else {
9432            throw new RuntimeException("view " + this + " being added, but"
9433                    + " it already has a parent");
9434        }
9435    }
9436
9437    /**
9438     * This is called when the view is attached to a window.  At this point it
9439     * has a Surface and will start drawing.  Note that this function is
9440     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9441     * however it may be called any time before the first onDraw -- including
9442     * before or after {@link #onMeasure(int, int)}.
9443     *
9444     * @see #onDetachedFromWindow()
9445     */
9446    protected void onAttachedToWindow() {
9447        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9448            mParent.requestTransparentRegion(this);
9449        }
9450        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9451            initialAwakenScrollBars();
9452            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9453        }
9454        jumpDrawablesToCurrentState();
9455        // Order is important here: LayoutDirection MUST be resolved before Padding
9456        // and TextDirection
9457        resolveLayoutDirectionIfNeeded();
9458        resolvePadding();
9459        resolveTextDirection();
9460        if (isFocused()) {
9461            InputMethodManager imm = InputMethodManager.peekInstance();
9462            imm.focusIn(this);
9463        }
9464    }
9465
9466    /**
9467     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9468     * that the parent directionality can and will be resolved before its children.
9469     */
9470    private void resolveLayoutDirectionIfNeeded() {
9471        // Do not resolve if it is not needed
9472        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9473
9474        // Clear any previous layout direction resolution
9475        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9476
9477        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9478        // TextDirectionHeuristic
9479        resetResolvedTextDirection();
9480
9481        // Set resolved depending on layout direction
9482        switch (getLayoutDirection()) {
9483            case LAYOUT_DIRECTION_INHERIT:
9484                // We cannot do the resolution if there is no parent
9485                if (mParent == null) return;
9486
9487                // If this is root view, no need to look at parent's layout dir.
9488                if (mParent instanceof ViewGroup) {
9489                    ViewGroup viewGroup = ((ViewGroup) mParent);
9490
9491                    // Check if the parent view group can resolve
9492                    if (! viewGroup.canResolveLayoutDirection()) {
9493                        return;
9494                    }
9495                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9496                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9497                    }
9498                }
9499                break;
9500            case LAYOUT_DIRECTION_RTL:
9501                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9502                break;
9503            case LAYOUT_DIRECTION_LOCALE:
9504                if(isLayoutDirectionRtl(Locale.getDefault())) {
9505                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9506                }
9507                break;
9508            default:
9509                // Nothing to do, LTR by default
9510        }
9511
9512        // Set to resolved
9513        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9514    }
9515
9516    /**
9517     * @hide
9518     */
9519    protected void resolvePadding() {
9520        // If the user specified the absolute padding (either with android:padding or
9521        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9522        // use the default padding or the padding from the background drawable
9523        // (stored at this point in mPadding*)
9524        switch (getResolvedLayoutDirection()) {
9525            case LAYOUT_DIRECTION_RTL:
9526                // Start user padding override Right user padding. Otherwise, if Right user
9527                // padding is not defined, use the default Right padding. If Right user padding
9528                // is defined, just use it.
9529                if (mUserPaddingStart >= 0) {
9530                    mUserPaddingRight = mUserPaddingStart;
9531                } else if (mUserPaddingRight < 0) {
9532                    mUserPaddingRight = mPaddingRight;
9533                }
9534                if (mUserPaddingEnd >= 0) {
9535                    mUserPaddingLeft = mUserPaddingEnd;
9536                } else if (mUserPaddingLeft < 0) {
9537                    mUserPaddingLeft = mPaddingLeft;
9538                }
9539                break;
9540            case LAYOUT_DIRECTION_LTR:
9541            default:
9542                // Start user padding override Left user padding. Otherwise, if Left user
9543                // padding is not defined, use the default left padding. If Left user padding
9544                // is defined, just use it.
9545                if (mUserPaddingStart >= 0) {
9546                    mUserPaddingLeft = mUserPaddingStart;
9547                } else if (mUserPaddingLeft < 0) {
9548                    mUserPaddingLeft = mPaddingLeft;
9549                }
9550                if (mUserPaddingEnd >= 0) {
9551                    mUserPaddingRight = mUserPaddingEnd;
9552                } else if (mUserPaddingRight < 0) {
9553                    mUserPaddingRight = mPaddingRight;
9554                }
9555        }
9556
9557        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9558
9559        recomputePadding();
9560    }
9561
9562    /**
9563     * Return true if layout direction resolution can be done
9564     *
9565     * @hide
9566     */
9567    protected boolean canResolveLayoutDirection() {
9568        switch (getLayoutDirection()) {
9569            case LAYOUT_DIRECTION_INHERIT:
9570                return (mParent != null);
9571            default:
9572                return true;
9573        }
9574    }
9575
9576    /**
9577     * Reset the resolved layout direction.
9578     *
9579     * Subclasses need to override this method to clear cached information that depends on the
9580     * resolved layout direction, or to inform child views that inherit their layout direction.
9581     * Overrides must also call the superclass implementation at the start of their implementation.
9582     *
9583     * @hide
9584     */
9585    protected void resetResolvedLayoutDirection() {
9586        // Reset the current View resolution
9587        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9588    }
9589
9590    /**
9591     * Check if a Locale is corresponding to a RTL script.
9592     *
9593     * @param locale Locale to check
9594     * @return true if a Locale is corresponding to a RTL script.
9595     *
9596     * @hide
9597     */
9598    protected static boolean isLayoutDirectionRtl(Locale locale) {
9599        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9600                LocaleUtil.getLayoutDirectionFromLocale(locale));
9601    }
9602
9603    /**
9604     * This is called when the view is detached from a window.  At this point it
9605     * no longer has a surface for drawing.
9606     *
9607     * @see #onAttachedToWindow()
9608     */
9609    protected void onDetachedFromWindow() {
9610        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9611
9612        removeUnsetPressCallback();
9613        removeLongPressCallback();
9614        removePerformClickCallback();
9615        removeSendViewScrolledAccessibilityEventCallback();
9616
9617        destroyDrawingCache();
9618
9619        destroyLayer();
9620
9621        if (mDisplayList != null) {
9622            mDisplayList.invalidate();
9623        }
9624
9625        if (mAttachInfo != null) {
9626            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9627        }
9628
9629        mCurrentAnimation = null;
9630
9631        resetResolvedLayoutDirection();
9632        resetResolvedTextDirection();
9633    }
9634
9635    /**
9636     * @return The number of times this view has been attached to a window
9637     */
9638    protected int getWindowAttachCount() {
9639        return mWindowAttachCount;
9640    }
9641
9642    /**
9643     * Retrieve a unique token identifying the window this view is attached to.
9644     * @return Return the window's token for use in
9645     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9646     */
9647    public IBinder getWindowToken() {
9648        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9649    }
9650
9651    /**
9652     * Retrieve a unique token identifying the top-level "real" window of
9653     * the window that this view is attached to.  That is, this is like
9654     * {@link #getWindowToken}, except if the window this view in is a panel
9655     * window (attached to another containing window), then the token of
9656     * the containing window is returned instead.
9657     *
9658     * @return Returns the associated window token, either
9659     * {@link #getWindowToken()} or the containing window's token.
9660     */
9661    public IBinder getApplicationWindowToken() {
9662        AttachInfo ai = mAttachInfo;
9663        if (ai != null) {
9664            IBinder appWindowToken = ai.mPanelParentWindowToken;
9665            if (appWindowToken == null) {
9666                appWindowToken = ai.mWindowToken;
9667            }
9668            return appWindowToken;
9669        }
9670        return null;
9671    }
9672
9673    /**
9674     * Retrieve private session object this view hierarchy is using to
9675     * communicate with the window manager.
9676     * @return the session object to communicate with the window manager
9677     */
9678    /*package*/ IWindowSession getWindowSession() {
9679        return mAttachInfo != null ? mAttachInfo.mSession : null;
9680    }
9681
9682    /**
9683     * @param info the {@link android.view.View.AttachInfo} to associated with
9684     *        this view
9685     */
9686    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9687        //System.out.println("Attached! " + this);
9688        mAttachInfo = info;
9689        mWindowAttachCount++;
9690        // We will need to evaluate the drawable state at least once.
9691        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9692        if (mFloatingTreeObserver != null) {
9693            info.mTreeObserver.merge(mFloatingTreeObserver);
9694            mFloatingTreeObserver = null;
9695        }
9696        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9697            mAttachInfo.mScrollContainers.add(this);
9698            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9699        }
9700        performCollectViewAttributes(visibility);
9701        onAttachedToWindow();
9702
9703        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9704                mOnAttachStateChangeListeners;
9705        if (listeners != null && listeners.size() > 0) {
9706            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9707            // perform the dispatching. The iterator is a safe guard against listeners that
9708            // could mutate the list by calling the various add/remove methods. This prevents
9709            // the array from being modified while we iterate it.
9710            for (OnAttachStateChangeListener listener : listeners) {
9711                listener.onViewAttachedToWindow(this);
9712            }
9713        }
9714
9715        int vis = info.mWindowVisibility;
9716        if (vis != GONE) {
9717            onWindowVisibilityChanged(vis);
9718        }
9719        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9720            // If nobody has evaluated the drawable state yet, then do it now.
9721            refreshDrawableState();
9722        }
9723    }
9724
9725    void dispatchDetachedFromWindow() {
9726        AttachInfo info = mAttachInfo;
9727        if (info != null) {
9728            int vis = info.mWindowVisibility;
9729            if (vis != GONE) {
9730                onWindowVisibilityChanged(GONE);
9731            }
9732        }
9733
9734        onDetachedFromWindow();
9735
9736        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9737                mOnAttachStateChangeListeners;
9738        if (listeners != null && listeners.size() > 0) {
9739            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9740            // perform the dispatching. The iterator is a safe guard against listeners that
9741            // could mutate the list by calling the various add/remove methods. This prevents
9742            // the array from being modified while we iterate it.
9743            for (OnAttachStateChangeListener listener : listeners) {
9744                listener.onViewDetachedFromWindow(this);
9745            }
9746        }
9747
9748        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9749            mAttachInfo.mScrollContainers.remove(this);
9750            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9751        }
9752
9753        mAttachInfo = null;
9754    }
9755
9756    /**
9757     * Store this view hierarchy's frozen state into the given container.
9758     *
9759     * @param container The SparseArray in which to save the view's state.
9760     *
9761     * @see #restoreHierarchyState(android.util.SparseArray)
9762     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9763     * @see #onSaveInstanceState()
9764     */
9765    public void saveHierarchyState(SparseArray<Parcelable> container) {
9766        dispatchSaveInstanceState(container);
9767    }
9768
9769    /**
9770     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9771     * this view and its children. May be overridden to modify how freezing happens to a
9772     * view's children; for example, some views may want to not store state for their children.
9773     *
9774     * @param container The SparseArray in which to save the view's state.
9775     *
9776     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9777     * @see #saveHierarchyState(android.util.SparseArray)
9778     * @see #onSaveInstanceState()
9779     */
9780    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9781        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9782            mPrivateFlags &= ~SAVE_STATE_CALLED;
9783            Parcelable state = onSaveInstanceState();
9784            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9785                throw new IllegalStateException(
9786                        "Derived class did not call super.onSaveInstanceState()");
9787            }
9788            if (state != null) {
9789                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9790                // + ": " + state);
9791                container.put(mID, state);
9792            }
9793        }
9794    }
9795
9796    /**
9797     * Hook allowing a view to generate a representation of its internal state
9798     * that can later be used to create a new instance with that same state.
9799     * This state should only contain information that is not persistent or can
9800     * not be reconstructed later. For example, you will never store your
9801     * current position on screen because that will be computed again when a
9802     * new instance of the view is placed in its view hierarchy.
9803     * <p>
9804     * Some examples of things you may store here: the current cursor position
9805     * in a text view (but usually not the text itself since that is stored in a
9806     * content provider or other persistent storage), the currently selected
9807     * item in a list view.
9808     *
9809     * @return Returns a Parcelable object containing the view's current dynamic
9810     *         state, or null if there is nothing interesting to save. The
9811     *         default implementation returns null.
9812     * @see #onRestoreInstanceState(android.os.Parcelable)
9813     * @see #saveHierarchyState(android.util.SparseArray)
9814     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9815     * @see #setSaveEnabled(boolean)
9816     */
9817    protected Parcelable onSaveInstanceState() {
9818        mPrivateFlags |= SAVE_STATE_CALLED;
9819        return BaseSavedState.EMPTY_STATE;
9820    }
9821
9822    /**
9823     * Restore this view hierarchy's frozen state from the given container.
9824     *
9825     * @param container The SparseArray which holds previously frozen states.
9826     *
9827     * @see #saveHierarchyState(android.util.SparseArray)
9828     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9829     * @see #onRestoreInstanceState(android.os.Parcelable)
9830     */
9831    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9832        dispatchRestoreInstanceState(container);
9833    }
9834
9835    /**
9836     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9837     * state for this view and its children. May be overridden to modify how restoring
9838     * happens to a view's children; for example, some views may want to not store state
9839     * for their children.
9840     *
9841     * @param container The SparseArray which holds previously saved state.
9842     *
9843     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9844     * @see #restoreHierarchyState(android.util.SparseArray)
9845     * @see #onRestoreInstanceState(android.os.Parcelable)
9846     */
9847    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9848        if (mID != NO_ID) {
9849            Parcelable state = container.get(mID);
9850            if (state != null) {
9851                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9852                // + ": " + state);
9853                mPrivateFlags &= ~SAVE_STATE_CALLED;
9854                onRestoreInstanceState(state);
9855                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9856                    throw new IllegalStateException(
9857                            "Derived class did not call super.onRestoreInstanceState()");
9858                }
9859            }
9860        }
9861    }
9862
9863    /**
9864     * Hook allowing a view to re-apply a representation of its internal state that had previously
9865     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9866     * null state.
9867     *
9868     * @param state The frozen state that had previously been returned by
9869     *        {@link #onSaveInstanceState}.
9870     *
9871     * @see #onSaveInstanceState()
9872     * @see #restoreHierarchyState(android.util.SparseArray)
9873     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9874     */
9875    protected void onRestoreInstanceState(Parcelable state) {
9876        mPrivateFlags |= SAVE_STATE_CALLED;
9877        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9878            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9879                    + "received " + state.getClass().toString() + " instead. This usually happens "
9880                    + "when two views of different type have the same id in the same hierarchy. "
9881                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9882                    + "other views do not use the same id.");
9883        }
9884    }
9885
9886    /**
9887     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9888     *
9889     * @return the drawing start time in milliseconds
9890     */
9891    public long getDrawingTime() {
9892        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9893    }
9894
9895    /**
9896     * <p>Enables or disables the duplication of the parent's state into this view. When
9897     * duplication is enabled, this view gets its drawable state from its parent rather
9898     * than from its own internal properties.</p>
9899     *
9900     * <p>Note: in the current implementation, setting this property to true after the
9901     * view was added to a ViewGroup might have no effect at all. This property should
9902     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9903     *
9904     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9905     * property is enabled, an exception will be thrown.</p>
9906     *
9907     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9908     * parent, these states should not be affected by this method.</p>
9909     *
9910     * @param enabled True to enable duplication of the parent's drawable state, false
9911     *                to disable it.
9912     *
9913     * @see #getDrawableState()
9914     * @see #isDuplicateParentStateEnabled()
9915     */
9916    public void setDuplicateParentStateEnabled(boolean enabled) {
9917        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9918    }
9919
9920    /**
9921     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9922     *
9923     * @return True if this view's drawable state is duplicated from the parent,
9924     *         false otherwise
9925     *
9926     * @see #getDrawableState()
9927     * @see #setDuplicateParentStateEnabled(boolean)
9928     */
9929    public boolean isDuplicateParentStateEnabled() {
9930        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9931    }
9932
9933    /**
9934     * <p>Specifies the type of layer backing this view. The layer can be
9935     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9936     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9937     *
9938     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9939     * instance that controls how the layer is composed on screen. The following
9940     * properties of the paint are taken into account when composing the layer:</p>
9941     * <ul>
9942     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9943     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9944     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9945     * </ul>
9946     *
9947     * <p>If this view has an alpha value set to < 1.0 by calling
9948     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9949     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9950     * equivalent to setting a hardware layer on this view and providing a paint with
9951     * the desired alpha value.<p>
9952     *
9953     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9954     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9955     * for more information on when and how to use layers.</p>
9956     *
9957     * @param layerType The ype of layer to use with this view, must be one of
9958     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9959     *        {@link #LAYER_TYPE_HARDWARE}
9960     * @param paint The paint used to compose the layer. This argument is optional
9961     *        and can be null. It is ignored when the layer type is
9962     *        {@link #LAYER_TYPE_NONE}
9963     *
9964     * @see #getLayerType()
9965     * @see #LAYER_TYPE_NONE
9966     * @see #LAYER_TYPE_SOFTWARE
9967     * @see #LAYER_TYPE_HARDWARE
9968     * @see #setAlpha(float)
9969     *
9970     * @attr ref android.R.styleable#View_layerType
9971     */
9972    public void setLayerType(int layerType, Paint paint) {
9973        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9974            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9975                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9976        }
9977
9978        if (layerType == mLayerType) {
9979            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9980                mLayerPaint = paint == null ? new Paint() : paint;
9981                invalidateParentCaches();
9982                invalidate(true);
9983            }
9984            return;
9985        }
9986
9987        // Destroy any previous software drawing cache if needed
9988        switch (mLayerType) {
9989            case LAYER_TYPE_HARDWARE:
9990                destroyLayer();
9991                // fall through - unaccelerated views may use software layer mechanism instead
9992            case LAYER_TYPE_SOFTWARE:
9993                destroyDrawingCache();
9994                break;
9995            default:
9996                break;
9997        }
9998
9999        mLayerType = layerType;
10000        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10001        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10002        mLocalDirtyRect = layerDisabled ? null : new Rect();
10003
10004        invalidateParentCaches();
10005        invalidate(true);
10006    }
10007
10008    /**
10009     * Indicates whether this view has a static layer. A view with layer type
10010     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10011     * dynamic.
10012     */
10013    boolean hasStaticLayer() {
10014        return mLayerType == LAYER_TYPE_NONE;
10015    }
10016
10017    /**
10018     * Indicates what type of layer is currently associated with this view. By default
10019     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10020     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10021     * for more information on the different types of layers.
10022     *
10023     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10024     *         {@link #LAYER_TYPE_HARDWARE}
10025     *
10026     * @see #setLayerType(int, android.graphics.Paint)
10027     * @see #buildLayer()
10028     * @see #LAYER_TYPE_NONE
10029     * @see #LAYER_TYPE_SOFTWARE
10030     * @see #LAYER_TYPE_HARDWARE
10031     */
10032    public int getLayerType() {
10033        return mLayerType;
10034    }
10035
10036    /**
10037     * Forces this view's layer to be created and this view to be rendered
10038     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10039     * invoking this method will have no effect.
10040     *
10041     * This method can for instance be used to render a view into its layer before
10042     * starting an animation. If this view is complex, rendering into the layer
10043     * before starting the animation will avoid skipping frames.
10044     *
10045     * @throws IllegalStateException If this view is not attached to a window
10046     *
10047     * @see #setLayerType(int, android.graphics.Paint)
10048     */
10049    public void buildLayer() {
10050        if (mLayerType == LAYER_TYPE_NONE) return;
10051
10052        if (mAttachInfo == null) {
10053            throw new IllegalStateException("This view must be attached to a window first");
10054        }
10055
10056        switch (mLayerType) {
10057            case LAYER_TYPE_HARDWARE:
10058                getHardwareLayer();
10059                break;
10060            case LAYER_TYPE_SOFTWARE:
10061                buildDrawingCache(true);
10062                break;
10063        }
10064    }
10065
10066    /**
10067     * <p>Returns a hardware layer that can be used to draw this view again
10068     * without executing its draw method.</p>
10069     *
10070     * @return A HardwareLayer ready to render, or null if an error occurred.
10071     */
10072    HardwareLayer getHardwareLayer() {
10073        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10074                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10075            return null;
10076        }
10077
10078        final int width = mRight - mLeft;
10079        final int height = mBottom - mTop;
10080
10081        if (width == 0 || height == 0) {
10082            return null;
10083        }
10084
10085        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10086            if (mHardwareLayer == null) {
10087                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10088                        width, height, isOpaque());
10089                mLocalDirtyRect.setEmpty();
10090            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10091                mHardwareLayer.resize(width, height);
10092                mLocalDirtyRect.setEmpty();
10093            }
10094
10095            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10096            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10097            mAttachInfo.mHardwareCanvas = canvas;
10098            try {
10099                canvas.setViewport(width, height);
10100                canvas.onPreDraw(mLocalDirtyRect);
10101                mLocalDirtyRect.setEmpty();
10102
10103                final int restoreCount = canvas.save();
10104
10105                computeScroll();
10106                canvas.translate(-mScrollX, -mScrollY);
10107
10108                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10109
10110                // Fast path for layouts with no backgrounds
10111                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10112                    mPrivateFlags &= ~DIRTY_MASK;
10113                    dispatchDraw(canvas);
10114                } else {
10115                    draw(canvas);
10116                }
10117
10118                canvas.restoreToCount(restoreCount);
10119            } finally {
10120                canvas.onPostDraw();
10121                mHardwareLayer.end(currentCanvas);
10122                mAttachInfo.mHardwareCanvas = currentCanvas;
10123            }
10124        }
10125
10126        return mHardwareLayer;
10127    }
10128
10129    boolean destroyLayer() {
10130        if (mHardwareLayer != null) {
10131            mHardwareLayer.destroy();
10132            mHardwareLayer = null;
10133            return true;
10134        }
10135        return false;
10136    }
10137
10138    /**
10139     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10140     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10141     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10142     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10143     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10144     * null.</p>
10145     *
10146     * <p>Enabling the drawing cache is similar to
10147     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10148     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10149     * drawing cache has no effect on rendering because the system uses a different mechanism
10150     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10151     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10152     * for information on how to enable software and hardware layers.</p>
10153     *
10154     * <p>This API can be used to manually generate
10155     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10156     * {@link #getDrawingCache()}.</p>
10157     *
10158     * @param enabled true to enable the drawing cache, false otherwise
10159     *
10160     * @see #isDrawingCacheEnabled()
10161     * @see #getDrawingCache()
10162     * @see #buildDrawingCache()
10163     * @see #setLayerType(int, android.graphics.Paint)
10164     */
10165    public void setDrawingCacheEnabled(boolean enabled) {
10166        mCachingFailed = false;
10167        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10168    }
10169
10170    /**
10171     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10172     *
10173     * @return true if the drawing cache is enabled
10174     *
10175     * @see #setDrawingCacheEnabled(boolean)
10176     * @see #getDrawingCache()
10177     */
10178    @ViewDebug.ExportedProperty(category = "drawing")
10179    public boolean isDrawingCacheEnabled() {
10180        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10181    }
10182
10183    /**
10184     * Debugging utility which recursively outputs the dirty state of a view and its
10185     * descendants.
10186     *
10187     * @hide
10188     */
10189    @SuppressWarnings({"UnusedDeclaration"})
10190    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10191        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10192                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10193                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10194                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10195        if (clear) {
10196            mPrivateFlags &= clearMask;
10197        }
10198        if (this instanceof ViewGroup) {
10199            ViewGroup parent = (ViewGroup) this;
10200            final int count = parent.getChildCount();
10201            for (int i = 0; i < count; i++) {
10202                final View child = parent.getChildAt(i);
10203                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10204            }
10205        }
10206    }
10207
10208    /**
10209     * This method is used by ViewGroup to cause its children to restore or recreate their
10210     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10211     * to recreate its own display list, which would happen if it went through the normal
10212     * draw/dispatchDraw mechanisms.
10213     *
10214     * @hide
10215     */
10216    protected void dispatchGetDisplayList() {}
10217
10218    /**
10219     * A view that is not attached or hardware accelerated cannot create a display list.
10220     * This method checks these conditions and returns the appropriate result.
10221     *
10222     * @return true if view has the ability to create a display list, false otherwise.
10223     *
10224     * @hide
10225     */
10226    public boolean canHaveDisplayList() {
10227        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10228    }
10229
10230    /**
10231     * <p>Returns a display list that can be used to draw this view again
10232     * without executing its draw method.</p>
10233     *
10234     * @return A DisplayList ready to replay, or null if caching is not enabled.
10235     *
10236     * @hide
10237     */
10238    public DisplayList getDisplayList() {
10239        if (!canHaveDisplayList()) {
10240            return null;
10241        }
10242
10243        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10244                mDisplayList == null || !mDisplayList.isValid() ||
10245                mRecreateDisplayList)) {
10246            // Don't need to recreate the display list, just need to tell our
10247            // children to restore/recreate theirs
10248            if (mDisplayList != null && mDisplayList.isValid() &&
10249                    !mRecreateDisplayList) {
10250                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10251                mPrivateFlags &= ~DIRTY_MASK;
10252                dispatchGetDisplayList();
10253
10254                return mDisplayList;
10255            }
10256
10257            // If we got here, we're recreating it. Mark it as such to ensure that
10258            // we copy in child display lists into ours in drawChild()
10259            mRecreateDisplayList = true;
10260            if (mDisplayList == null) {
10261                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
10262                // If we're creating a new display list, make sure our parent gets invalidated
10263                // since they will need to recreate their display list to account for this
10264                // new child display list.
10265                invalidateParentCaches();
10266            }
10267
10268            final HardwareCanvas canvas = mDisplayList.start();
10269            int restoreCount = 0;
10270            try {
10271                int width = mRight - mLeft;
10272                int height = mBottom - mTop;
10273
10274                canvas.setViewport(width, height);
10275                // The dirty rect should always be null for a display list
10276                canvas.onPreDraw(null);
10277
10278                computeScroll();
10279
10280                restoreCount = canvas.save();
10281                canvas.translate(-mScrollX, -mScrollY);
10282                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10283                mPrivateFlags &= ~DIRTY_MASK;
10284
10285                // Fast path for layouts with no backgrounds
10286                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10287                    dispatchDraw(canvas);
10288                } else {
10289                    draw(canvas);
10290                }
10291            } finally {
10292                canvas.restoreToCount(restoreCount);
10293                canvas.onPostDraw();
10294
10295                mDisplayList.end();
10296            }
10297        } else {
10298            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10299            mPrivateFlags &= ~DIRTY_MASK;
10300        }
10301
10302        return mDisplayList;
10303    }
10304
10305    /**
10306     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10307     *
10308     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10309     *
10310     * @see #getDrawingCache(boolean)
10311     */
10312    public Bitmap getDrawingCache() {
10313        return getDrawingCache(false);
10314    }
10315
10316    /**
10317     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10318     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10319     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10320     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10321     * request the drawing cache by calling this method and draw it on screen if the
10322     * returned bitmap is not null.</p>
10323     *
10324     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10325     * this method will create a bitmap of the same size as this view. Because this bitmap
10326     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10327     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10328     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10329     * size than the view. This implies that your application must be able to handle this
10330     * size.</p>
10331     *
10332     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10333     *        the current density of the screen when the application is in compatibility
10334     *        mode.
10335     *
10336     * @return A bitmap representing this view or null if cache is disabled.
10337     *
10338     * @see #setDrawingCacheEnabled(boolean)
10339     * @see #isDrawingCacheEnabled()
10340     * @see #buildDrawingCache(boolean)
10341     * @see #destroyDrawingCache()
10342     */
10343    public Bitmap getDrawingCache(boolean autoScale) {
10344        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10345            return null;
10346        }
10347        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10348            buildDrawingCache(autoScale);
10349        }
10350        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10351    }
10352
10353    /**
10354     * <p>Frees the resources used by the drawing cache. If you call
10355     * {@link #buildDrawingCache()} manually without calling
10356     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10357     * should cleanup the cache with this method afterwards.</p>
10358     *
10359     * @see #setDrawingCacheEnabled(boolean)
10360     * @see #buildDrawingCache()
10361     * @see #getDrawingCache()
10362     */
10363    public void destroyDrawingCache() {
10364        if (mDrawingCache != null) {
10365            mDrawingCache.recycle();
10366            mDrawingCache = null;
10367        }
10368        if (mUnscaledDrawingCache != null) {
10369            mUnscaledDrawingCache.recycle();
10370            mUnscaledDrawingCache = null;
10371        }
10372    }
10373
10374    /**
10375     * Setting a solid background color for the drawing cache's bitmaps will improve
10376     * performance and memory usage. Note, though that this should only be used if this
10377     * view will always be drawn on top of a solid color.
10378     *
10379     * @param color The background color to use for the drawing cache's bitmap
10380     *
10381     * @see #setDrawingCacheEnabled(boolean)
10382     * @see #buildDrawingCache()
10383     * @see #getDrawingCache()
10384     */
10385    public void setDrawingCacheBackgroundColor(int color) {
10386        if (color != mDrawingCacheBackgroundColor) {
10387            mDrawingCacheBackgroundColor = color;
10388            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10389        }
10390    }
10391
10392    /**
10393     * @see #setDrawingCacheBackgroundColor(int)
10394     *
10395     * @return The background color to used for the drawing cache's bitmap
10396     */
10397    public int getDrawingCacheBackgroundColor() {
10398        return mDrawingCacheBackgroundColor;
10399    }
10400
10401    /**
10402     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10403     *
10404     * @see #buildDrawingCache(boolean)
10405     */
10406    public void buildDrawingCache() {
10407        buildDrawingCache(false);
10408    }
10409
10410    /**
10411     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10412     *
10413     * <p>If you call {@link #buildDrawingCache()} manually without calling
10414     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10415     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10416     *
10417     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10418     * this method will create a bitmap of the same size as this view. Because this bitmap
10419     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10420     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10421     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10422     * size than the view. This implies that your application must be able to handle this
10423     * size.</p>
10424     *
10425     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10426     * you do not need the drawing cache bitmap, calling this method will increase memory
10427     * usage and cause the view to be rendered in software once, thus negatively impacting
10428     * performance.</p>
10429     *
10430     * @see #getDrawingCache()
10431     * @see #destroyDrawingCache()
10432     */
10433    public void buildDrawingCache(boolean autoScale) {
10434        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10435                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10436            mCachingFailed = false;
10437
10438            if (ViewDebug.TRACE_HIERARCHY) {
10439                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10440            }
10441
10442            int width = mRight - mLeft;
10443            int height = mBottom - mTop;
10444
10445            final AttachInfo attachInfo = mAttachInfo;
10446            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10447
10448            if (autoScale && scalingRequired) {
10449                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10450                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10451            }
10452
10453            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10454            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10455            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10456
10457            if (width <= 0 || height <= 0 ||
10458                     // Projected bitmap size in bytes
10459                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10460                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10461                destroyDrawingCache();
10462                mCachingFailed = true;
10463                return;
10464            }
10465
10466            boolean clear = true;
10467            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10468
10469            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10470                Bitmap.Config quality;
10471                if (!opaque) {
10472                    // Never pick ARGB_4444 because it looks awful
10473                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10474                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10475                        case DRAWING_CACHE_QUALITY_AUTO:
10476                            quality = Bitmap.Config.ARGB_8888;
10477                            break;
10478                        case DRAWING_CACHE_QUALITY_LOW:
10479                            quality = Bitmap.Config.ARGB_8888;
10480                            break;
10481                        case DRAWING_CACHE_QUALITY_HIGH:
10482                            quality = Bitmap.Config.ARGB_8888;
10483                            break;
10484                        default:
10485                            quality = Bitmap.Config.ARGB_8888;
10486                            break;
10487                    }
10488                } else {
10489                    // Optimization for translucent windows
10490                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10491                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10492                }
10493
10494                // Try to cleanup memory
10495                if (bitmap != null) bitmap.recycle();
10496
10497                try {
10498                    bitmap = Bitmap.createBitmap(width, height, quality);
10499                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10500                    if (autoScale) {
10501                        mDrawingCache = bitmap;
10502                    } else {
10503                        mUnscaledDrawingCache = bitmap;
10504                    }
10505                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10506                } catch (OutOfMemoryError e) {
10507                    // If there is not enough memory to create the bitmap cache, just
10508                    // ignore the issue as bitmap caches are not required to draw the
10509                    // view hierarchy
10510                    if (autoScale) {
10511                        mDrawingCache = null;
10512                    } else {
10513                        mUnscaledDrawingCache = null;
10514                    }
10515                    mCachingFailed = true;
10516                    return;
10517                }
10518
10519                clear = drawingCacheBackgroundColor != 0;
10520            }
10521
10522            Canvas canvas;
10523            if (attachInfo != null) {
10524                canvas = attachInfo.mCanvas;
10525                if (canvas == null) {
10526                    canvas = new Canvas();
10527                }
10528                canvas.setBitmap(bitmap);
10529                // Temporarily clobber the cached Canvas in case one of our children
10530                // is also using a drawing cache. Without this, the children would
10531                // steal the canvas by attaching their own bitmap to it and bad, bad
10532                // thing would happen (invisible views, corrupted drawings, etc.)
10533                attachInfo.mCanvas = null;
10534            } else {
10535                // This case should hopefully never or seldom happen
10536                canvas = new Canvas(bitmap);
10537            }
10538
10539            if (clear) {
10540                bitmap.eraseColor(drawingCacheBackgroundColor);
10541            }
10542
10543            computeScroll();
10544            final int restoreCount = canvas.save();
10545
10546            if (autoScale && scalingRequired) {
10547                final float scale = attachInfo.mApplicationScale;
10548                canvas.scale(scale, scale);
10549            }
10550
10551            canvas.translate(-mScrollX, -mScrollY);
10552
10553            mPrivateFlags |= DRAWN;
10554            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10555                    mLayerType != LAYER_TYPE_NONE) {
10556                mPrivateFlags |= DRAWING_CACHE_VALID;
10557            }
10558
10559            // Fast path for layouts with no backgrounds
10560            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10561                if (ViewDebug.TRACE_HIERARCHY) {
10562                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10563                }
10564                mPrivateFlags &= ~DIRTY_MASK;
10565                dispatchDraw(canvas);
10566            } else {
10567                draw(canvas);
10568            }
10569
10570            canvas.restoreToCount(restoreCount);
10571            canvas.setBitmap(null);
10572
10573            if (attachInfo != null) {
10574                // Restore the cached Canvas for our siblings
10575                attachInfo.mCanvas = canvas;
10576            }
10577        }
10578    }
10579
10580    /**
10581     * Create a snapshot of the view into a bitmap.  We should probably make
10582     * some form of this public, but should think about the API.
10583     */
10584    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10585        int width = mRight - mLeft;
10586        int height = mBottom - mTop;
10587
10588        final AttachInfo attachInfo = mAttachInfo;
10589        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10590        width = (int) ((width * scale) + 0.5f);
10591        height = (int) ((height * scale) + 0.5f);
10592
10593        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10594        if (bitmap == null) {
10595            throw new OutOfMemoryError();
10596        }
10597
10598        Resources resources = getResources();
10599        if (resources != null) {
10600            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10601        }
10602
10603        Canvas canvas;
10604        if (attachInfo != null) {
10605            canvas = attachInfo.mCanvas;
10606            if (canvas == null) {
10607                canvas = new Canvas();
10608            }
10609            canvas.setBitmap(bitmap);
10610            // Temporarily clobber the cached Canvas in case one of our children
10611            // is also using a drawing cache. Without this, the children would
10612            // steal the canvas by attaching their own bitmap to it and bad, bad
10613            // things would happen (invisible views, corrupted drawings, etc.)
10614            attachInfo.mCanvas = null;
10615        } else {
10616            // This case should hopefully never or seldom happen
10617            canvas = new Canvas(bitmap);
10618        }
10619
10620        if ((backgroundColor & 0xff000000) != 0) {
10621            bitmap.eraseColor(backgroundColor);
10622        }
10623
10624        computeScroll();
10625        final int restoreCount = canvas.save();
10626        canvas.scale(scale, scale);
10627        canvas.translate(-mScrollX, -mScrollY);
10628
10629        // Temporarily remove the dirty mask
10630        int flags = mPrivateFlags;
10631        mPrivateFlags &= ~DIRTY_MASK;
10632
10633        // Fast path for layouts with no backgrounds
10634        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10635            dispatchDraw(canvas);
10636        } else {
10637            draw(canvas);
10638        }
10639
10640        mPrivateFlags = flags;
10641
10642        canvas.restoreToCount(restoreCount);
10643        canvas.setBitmap(null);
10644
10645        if (attachInfo != null) {
10646            // Restore the cached Canvas for our siblings
10647            attachInfo.mCanvas = canvas;
10648        }
10649
10650        return bitmap;
10651    }
10652
10653    /**
10654     * Indicates whether this View is currently in edit mode. A View is usually
10655     * in edit mode when displayed within a developer tool. For instance, if
10656     * this View is being drawn by a visual user interface builder, this method
10657     * should return true.
10658     *
10659     * Subclasses should check the return value of this method to provide
10660     * different behaviors if their normal behavior might interfere with the
10661     * host environment. For instance: the class spawns a thread in its
10662     * constructor, the drawing code relies on device-specific features, etc.
10663     *
10664     * This method is usually checked in the drawing code of custom widgets.
10665     *
10666     * @return True if this View is in edit mode, false otherwise.
10667     */
10668    public boolean isInEditMode() {
10669        return false;
10670    }
10671
10672    /**
10673     * If the View draws content inside its padding and enables fading edges,
10674     * it needs to support padding offsets. Padding offsets are added to the
10675     * fading edges to extend the length of the fade so that it covers pixels
10676     * drawn inside the padding.
10677     *
10678     * Subclasses of this class should override this method if they need
10679     * to draw content inside the padding.
10680     *
10681     * @return True if padding offset must be applied, false otherwise.
10682     *
10683     * @see #getLeftPaddingOffset()
10684     * @see #getRightPaddingOffset()
10685     * @see #getTopPaddingOffset()
10686     * @see #getBottomPaddingOffset()
10687     *
10688     * @since CURRENT
10689     */
10690    protected boolean isPaddingOffsetRequired() {
10691        return false;
10692    }
10693
10694    /**
10695     * Amount by which to extend the left fading region. Called only when
10696     * {@link #isPaddingOffsetRequired()} returns true.
10697     *
10698     * @return The left padding offset in pixels.
10699     *
10700     * @see #isPaddingOffsetRequired()
10701     *
10702     * @since CURRENT
10703     */
10704    protected int getLeftPaddingOffset() {
10705        return 0;
10706    }
10707
10708    /**
10709     * Amount by which to extend the right fading region. Called only when
10710     * {@link #isPaddingOffsetRequired()} returns true.
10711     *
10712     * @return The right padding offset in pixels.
10713     *
10714     * @see #isPaddingOffsetRequired()
10715     *
10716     * @since CURRENT
10717     */
10718    protected int getRightPaddingOffset() {
10719        return 0;
10720    }
10721
10722    /**
10723     * Amount by which to extend the top fading region. Called only when
10724     * {@link #isPaddingOffsetRequired()} returns true.
10725     *
10726     * @return The top padding offset in pixels.
10727     *
10728     * @see #isPaddingOffsetRequired()
10729     *
10730     * @since CURRENT
10731     */
10732    protected int getTopPaddingOffset() {
10733        return 0;
10734    }
10735
10736    /**
10737     * Amount by which to extend the bottom fading region. Called only when
10738     * {@link #isPaddingOffsetRequired()} returns true.
10739     *
10740     * @return The bottom padding offset in pixels.
10741     *
10742     * @see #isPaddingOffsetRequired()
10743     *
10744     * @since CURRENT
10745     */
10746    protected int getBottomPaddingOffset() {
10747        return 0;
10748    }
10749
10750    /**
10751     * @hide
10752     * @param offsetRequired
10753     */
10754    protected int getFadeTop(boolean offsetRequired) {
10755        int top = mPaddingTop;
10756        if (offsetRequired) top += getTopPaddingOffset();
10757        return top;
10758    }
10759
10760    /**
10761     * @hide
10762     * @param offsetRequired
10763     */
10764    protected int getFadeHeight(boolean offsetRequired) {
10765        int padding = mPaddingTop;
10766        if (offsetRequired) padding += getTopPaddingOffset();
10767        return mBottom - mTop - mPaddingBottom - padding;
10768    }
10769
10770    /**
10771     * <p>Indicates whether this view is attached to an hardware accelerated
10772     * window or not.</p>
10773     *
10774     * <p>Even if this method returns true, it does not mean that every call
10775     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10776     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10777     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10778     * window is hardware accelerated,
10779     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10780     * return false, and this method will return true.</p>
10781     *
10782     * @return True if the view is attached to a window and the window is
10783     *         hardware accelerated; false in any other case.
10784     */
10785    public boolean isHardwareAccelerated() {
10786        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10787    }
10788
10789    /**
10790     * Manually render this view (and all of its children) to the given Canvas.
10791     * The view must have already done a full layout before this function is
10792     * called.  When implementing a view, implement
10793     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10794     * If you do need to override this method, call the superclass version.
10795     *
10796     * @param canvas The Canvas to which the View is rendered.
10797     */
10798    public void draw(Canvas canvas) {
10799        if (ViewDebug.TRACE_HIERARCHY) {
10800            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10801        }
10802
10803        final int privateFlags = mPrivateFlags;
10804        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10805                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10806        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10807
10808        /*
10809         * Draw traversal performs several drawing steps which must be executed
10810         * in the appropriate order:
10811         *
10812         *      1. Draw the background
10813         *      2. If necessary, save the canvas' layers to prepare for fading
10814         *      3. Draw view's content
10815         *      4. Draw children
10816         *      5. If necessary, draw the fading edges and restore layers
10817         *      6. Draw decorations (scrollbars for instance)
10818         */
10819
10820        // Step 1, draw the background, if needed
10821        int saveCount;
10822
10823        if (!dirtyOpaque) {
10824            final Drawable background = mBGDrawable;
10825            if (background != null) {
10826                final int scrollX = mScrollX;
10827                final int scrollY = mScrollY;
10828
10829                if (mBackgroundSizeChanged) {
10830                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10831                    mBackgroundSizeChanged = false;
10832                }
10833
10834                if ((scrollX | scrollY) == 0) {
10835                    background.draw(canvas);
10836                } else {
10837                    canvas.translate(scrollX, scrollY);
10838                    background.draw(canvas);
10839                    canvas.translate(-scrollX, -scrollY);
10840                }
10841            }
10842        }
10843
10844        // skip step 2 & 5 if possible (common case)
10845        final int viewFlags = mViewFlags;
10846        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10847        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10848        if (!verticalEdges && !horizontalEdges) {
10849            // Step 3, draw the content
10850            if (!dirtyOpaque) onDraw(canvas);
10851
10852            // Step 4, draw the children
10853            dispatchDraw(canvas);
10854
10855            // Step 6, draw decorations (scrollbars)
10856            onDrawScrollBars(canvas);
10857
10858            // we're done...
10859            return;
10860        }
10861
10862        /*
10863         * Here we do the full fledged routine...
10864         * (this is an uncommon case where speed matters less,
10865         * this is why we repeat some of the tests that have been
10866         * done above)
10867         */
10868
10869        boolean drawTop = false;
10870        boolean drawBottom = false;
10871        boolean drawLeft = false;
10872        boolean drawRight = false;
10873
10874        float topFadeStrength = 0.0f;
10875        float bottomFadeStrength = 0.0f;
10876        float leftFadeStrength = 0.0f;
10877        float rightFadeStrength = 0.0f;
10878
10879        // Step 2, save the canvas' layers
10880        int paddingLeft = mPaddingLeft;
10881
10882        final boolean offsetRequired = isPaddingOffsetRequired();
10883        if (offsetRequired) {
10884            paddingLeft += getLeftPaddingOffset();
10885        }
10886
10887        int left = mScrollX + paddingLeft;
10888        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
10889        int top = mScrollY + getFadeTop(offsetRequired);
10890        int bottom = top + getFadeHeight(offsetRequired);
10891
10892        if (offsetRequired) {
10893            right += getRightPaddingOffset();
10894            bottom += getBottomPaddingOffset();
10895        }
10896
10897        final ScrollabilityCache scrollabilityCache = mScrollCache;
10898        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
10899        int length = (int) fadeHeight;
10900
10901        // clip the fade length if top and bottom fades overlap
10902        // overlapping fades produce odd-looking artifacts
10903        if (verticalEdges && (top + length > bottom - length)) {
10904            length = (bottom - top) / 2;
10905        }
10906
10907        // also clip horizontal fades if necessary
10908        if (horizontalEdges && (left + length > right - length)) {
10909            length = (right - left) / 2;
10910        }
10911
10912        if (verticalEdges) {
10913            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
10914            drawTop = topFadeStrength * fadeHeight > 1.0f;
10915            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
10916            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
10917        }
10918
10919        if (horizontalEdges) {
10920            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
10921            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
10922            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
10923            drawRight = rightFadeStrength * fadeHeight > 1.0f;
10924        }
10925
10926        saveCount = canvas.getSaveCount();
10927
10928        int solidColor = getSolidColor();
10929        if (solidColor == 0) {
10930            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
10931
10932            if (drawTop) {
10933                canvas.saveLayer(left, top, right, top + length, null, flags);
10934            }
10935
10936            if (drawBottom) {
10937                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
10938            }
10939
10940            if (drawLeft) {
10941                canvas.saveLayer(left, top, left + length, bottom, null, flags);
10942            }
10943
10944            if (drawRight) {
10945                canvas.saveLayer(right - length, top, right, bottom, null, flags);
10946            }
10947        } else {
10948            scrollabilityCache.setFadeColor(solidColor);
10949        }
10950
10951        // Step 3, draw the content
10952        if (!dirtyOpaque) onDraw(canvas);
10953
10954        // Step 4, draw the children
10955        dispatchDraw(canvas);
10956
10957        // Step 5, draw the fade effect and restore layers
10958        final Paint p = scrollabilityCache.paint;
10959        final Matrix matrix = scrollabilityCache.matrix;
10960        final Shader fade = scrollabilityCache.shader;
10961
10962        if (drawTop) {
10963            matrix.setScale(1, fadeHeight * topFadeStrength);
10964            matrix.postTranslate(left, top);
10965            fade.setLocalMatrix(matrix);
10966            canvas.drawRect(left, top, right, top + length, p);
10967        }
10968
10969        if (drawBottom) {
10970            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10971            matrix.postRotate(180);
10972            matrix.postTranslate(left, bottom);
10973            fade.setLocalMatrix(matrix);
10974            canvas.drawRect(left, bottom - length, right, bottom, p);
10975        }
10976
10977        if (drawLeft) {
10978            matrix.setScale(1, fadeHeight * leftFadeStrength);
10979            matrix.postRotate(-90);
10980            matrix.postTranslate(left, top);
10981            fade.setLocalMatrix(matrix);
10982            canvas.drawRect(left, top, left + length, bottom, p);
10983        }
10984
10985        if (drawRight) {
10986            matrix.setScale(1, fadeHeight * rightFadeStrength);
10987            matrix.postRotate(90);
10988            matrix.postTranslate(right, top);
10989            fade.setLocalMatrix(matrix);
10990            canvas.drawRect(right - length, top, right, bottom, p);
10991        }
10992
10993        canvas.restoreToCount(saveCount);
10994
10995        // Step 6, draw decorations (scrollbars)
10996        onDrawScrollBars(canvas);
10997    }
10998
10999    /**
11000     * Override this if your view is known to always be drawn on top of a solid color background,
11001     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11002     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11003     * should be set to 0xFF.
11004     *
11005     * @see #setVerticalFadingEdgeEnabled(boolean)
11006     * @see #setHorizontalFadingEdgeEnabled(boolean)
11007     *
11008     * @return The known solid color background for this view, or 0 if the color may vary
11009     */
11010    @ViewDebug.ExportedProperty(category = "drawing")
11011    public int getSolidColor() {
11012        return 0;
11013    }
11014
11015    /**
11016     * Build a human readable string representation of the specified view flags.
11017     *
11018     * @param flags the view flags to convert to a string
11019     * @return a String representing the supplied flags
11020     */
11021    private static String printFlags(int flags) {
11022        String output = "";
11023        int numFlags = 0;
11024        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11025            output += "TAKES_FOCUS";
11026            numFlags++;
11027        }
11028
11029        switch (flags & VISIBILITY_MASK) {
11030        case INVISIBLE:
11031            if (numFlags > 0) {
11032                output += " ";
11033            }
11034            output += "INVISIBLE";
11035            // USELESS HERE numFlags++;
11036            break;
11037        case GONE:
11038            if (numFlags > 0) {
11039                output += " ";
11040            }
11041            output += "GONE";
11042            // USELESS HERE numFlags++;
11043            break;
11044        default:
11045            break;
11046        }
11047        return output;
11048    }
11049
11050    /**
11051     * Build a human readable string representation of the specified private
11052     * view flags.
11053     *
11054     * @param privateFlags the private view flags to convert to a string
11055     * @return a String representing the supplied flags
11056     */
11057    private static String printPrivateFlags(int privateFlags) {
11058        String output = "";
11059        int numFlags = 0;
11060
11061        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11062            output += "WANTS_FOCUS";
11063            numFlags++;
11064        }
11065
11066        if ((privateFlags & FOCUSED) == FOCUSED) {
11067            if (numFlags > 0) {
11068                output += " ";
11069            }
11070            output += "FOCUSED";
11071            numFlags++;
11072        }
11073
11074        if ((privateFlags & SELECTED) == SELECTED) {
11075            if (numFlags > 0) {
11076                output += " ";
11077            }
11078            output += "SELECTED";
11079            numFlags++;
11080        }
11081
11082        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11083            if (numFlags > 0) {
11084                output += " ";
11085            }
11086            output += "IS_ROOT_NAMESPACE";
11087            numFlags++;
11088        }
11089
11090        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11091            if (numFlags > 0) {
11092                output += " ";
11093            }
11094            output += "HAS_BOUNDS";
11095            numFlags++;
11096        }
11097
11098        if ((privateFlags & DRAWN) == DRAWN) {
11099            if (numFlags > 0) {
11100                output += " ";
11101            }
11102            output += "DRAWN";
11103            // USELESS HERE numFlags++;
11104        }
11105        return output;
11106    }
11107
11108    /**
11109     * <p>Indicates whether or not this view's layout will be requested during
11110     * the next hierarchy layout pass.</p>
11111     *
11112     * @return true if the layout will be forced during next layout pass
11113     */
11114    public boolean isLayoutRequested() {
11115        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11116    }
11117
11118    /**
11119     * Assign a size and position to a view and all of its
11120     * descendants
11121     *
11122     * <p>This is the second phase of the layout mechanism.
11123     * (The first is measuring). In this phase, each parent calls
11124     * layout on all of its children to position them.
11125     * This is typically done using the child measurements
11126     * that were stored in the measure pass().</p>
11127     *
11128     * <p>Derived classes should not override this method.
11129     * Derived classes with children should override
11130     * onLayout. In that method, they should
11131     * call layout on each of their children.</p>
11132     *
11133     * @param l Left position, relative to parent
11134     * @param t Top position, relative to parent
11135     * @param r Right position, relative to parent
11136     * @param b Bottom position, relative to parent
11137     */
11138    @SuppressWarnings({"unchecked"})
11139    public void layout(int l, int t, int r, int b) {
11140        int oldL = mLeft;
11141        int oldT = mTop;
11142        int oldB = mBottom;
11143        int oldR = mRight;
11144        boolean changed = setFrame(l, t, r, b);
11145        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11146            if (ViewDebug.TRACE_HIERARCHY) {
11147                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11148            }
11149
11150            onLayout(changed, l, t, r, b);
11151            mPrivateFlags &= ~LAYOUT_REQUIRED;
11152
11153            if (mOnLayoutChangeListeners != null) {
11154                ArrayList<OnLayoutChangeListener> listenersCopy =
11155                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
11156                int numListeners = listenersCopy.size();
11157                for (int i = 0; i < numListeners; ++i) {
11158                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11159                }
11160            }
11161        }
11162        mPrivateFlags &= ~FORCE_LAYOUT;
11163    }
11164
11165    /**
11166     * Called from layout when this view should
11167     * assign a size and position to each of its children.
11168     *
11169     * Derived classes with children should override
11170     * this method and call layout on each of
11171     * their children.
11172     * @param changed This is a new size or position for this view
11173     * @param left Left position, relative to parent
11174     * @param top Top position, relative to parent
11175     * @param right Right position, relative to parent
11176     * @param bottom Bottom position, relative to parent
11177     */
11178    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11179    }
11180
11181    /**
11182     * Assign a size and position to this view.
11183     *
11184     * This is called from layout.
11185     *
11186     * @param left Left position, relative to parent
11187     * @param top Top position, relative to parent
11188     * @param right Right position, relative to parent
11189     * @param bottom Bottom position, relative to parent
11190     * @return true if the new size and position are different than the
11191     *         previous ones
11192     * {@hide}
11193     */
11194    protected boolean setFrame(int left, int top, int right, int bottom) {
11195        boolean changed = false;
11196
11197        if (DBG) {
11198            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11199                    + right + "," + bottom + ")");
11200        }
11201
11202        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11203            changed = true;
11204
11205            // Remember our drawn bit
11206            int drawn = mPrivateFlags & DRAWN;
11207
11208            int oldWidth = mRight - mLeft;
11209            int oldHeight = mBottom - mTop;
11210            int newWidth = right - left;
11211            int newHeight = bottom - top;
11212            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11213
11214            // Invalidate our old position
11215            invalidate(sizeChanged);
11216
11217            mLeft = left;
11218            mTop = top;
11219            mRight = right;
11220            mBottom = bottom;
11221
11222            mPrivateFlags |= HAS_BOUNDS;
11223
11224
11225            if (sizeChanged) {
11226                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11227                    // A change in dimension means an auto-centered pivot point changes, too
11228                    if (mTransformationInfo != null) {
11229                        mTransformationInfo.mMatrixDirty = true;
11230                    }
11231                }
11232                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11233            }
11234
11235            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11236                // If we are visible, force the DRAWN bit to on so that
11237                // this invalidate will go through (at least to our parent).
11238                // This is because someone may have invalidated this view
11239                // before this call to setFrame came in, thereby clearing
11240                // the DRAWN bit.
11241                mPrivateFlags |= DRAWN;
11242                invalidate(sizeChanged);
11243                // parent display list may need to be recreated based on a change in the bounds
11244                // of any child
11245                invalidateParentCaches();
11246            }
11247
11248            // Reset drawn bit to original value (invalidate turns it off)
11249            mPrivateFlags |= drawn;
11250
11251            mBackgroundSizeChanged = true;
11252        }
11253        return changed;
11254    }
11255
11256    /**
11257     * Finalize inflating a view from XML.  This is called as the last phase
11258     * of inflation, after all child views have been added.
11259     *
11260     * <p>Even if the subclass overrides onFinishInflate, they should always be
11261     * sure to call the super method, so that we get called.
11262     */
11263    protected void onFinishInflate() {
11264    }
11265
11266    /**
11267     * Returns the resources associated with this view.
11268     *
11269     * @return Resources object.
11270     */
11271    public Resources getResources() {
11272        return mResources;
11273    }
11274
11275    /**
11276     * Invalidates the specified Drawable.
11277     *
11278     * @param drawable the drawable to invalidate
11279     */
11280    public void invalidateDrawable(Drawable drawable) {
11281        if (verifyDrawable(drawable)) {
11282            final Rect dirty = drawable.getBounds();
11283            final int scrollX = mScrollX;
11284            final int scrollY = mScrollY;
11285
11286            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11287                    dirty.right + scrollX, dirty.bottom + scrollY);
11288        }
11289    }
11290
11291    /**
11292     * Schedules an action on a drawable to occur at a specified time.
11293     *
11294     * @param who the recipient of the action
11295     * @param what the action to run on the drawable
11296     * @param when the time at which the action must occur. Uses the
11297     *        {@link SystemClock#uptimeMillis} timebase.
11298     */
11299    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11300        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11301            mAttachInfo.mHandler.postAtTime(what, who, when);
11302        }
11303    }
11304
11305    /**
11306     * Cancels a scheduled action on a drawable.
11307     *
11308     * @param who the recipient of the action
11309     * @param what the action to cancel
11310     */
11311    public void unscheduleDrawable(Drawable who, Runnable what) {
11312        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11313            mAttachInfo.mHandler.removeCallbacks(what, who);
11314        }
11315    }
11316
11317    /**
11318     * Unschedule any events associated with the given Drawable.  This can be
11319     * used when selecting a new Drawable into a view, so that the previous
11320     * one is completely unscheduled.
11321     *
11322     * @param who The Drawable to unschedule.
11323     *
11324     * @see #drawableStateChanged
11325     */
11326    public void unscheduleDrawable(Drawable who) {
11327        if (mAttachInfo != null) {
11328            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11329        }
11330    }
11331
11332    /**
11333    * Return the layout direction of a given Drawable.
11334    *
11335    * @param who the Drawable to query
11336    *
11337    * @hide
11338    */
11339    public int getResolvedLayoutDirection(Drawable who) {
11340        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11341    }
11342
11343    /**
11344     * If your view subclass is displaying its own Drawable objects, it should
11345     * override this function and return true for any Drawable it is
11346     * displaying.  This allows animations for those drawables to be
11347     * scheduled.
11348     *
11349     * <p>Be sure to call through to the super class when overriding this
11350     * function.
11351     *
11352     * @param who The Drawable to verify.  Return true if it is one you are
11353     *            displaying, else return the result of calling through to the
11354     *            super class.
11355     *
11356     * @return boolean If true than the Drawable is being displayed in the
11357     *         view; else false and it is not allowed to animate.
11358     *
11359     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11360     * @see #drawableStateChanged()
11361     */
11362    protected boolean verifyDrawable(Drawable who) {
11363        return who == mBGDrawable;
11364    }
11365
11366    /**
11367     * This function is called whenever the state of the view changes in such
11368     * a way that it impacts the state of drawables being shown.
11369     *
11370     * <p>Be sure to call through to the superclass when overriding this
11371     * function.
11372     *
11373     * @see Drawable#setState(int[])
11374     */
11375    protected void drawableStateChanged() {
11376        Drawable d = mBGDrawable;
11377        if (d != null && d.isStateful()) {
11378            d.setState(getDrawableState());
11379        }
11380    }
11381
11382    /**
11383     * Call this to force a view to update its drawable state. This will cause
11384     * drawableStateChanged to be called on this view. Views that are interested
11385     * in the new state should call getDrawableState.
11386     *
11387     * @see #drawableStateChanged
11388     * @see #getDrawableState
11389     */
11390    public void refreshDrawableState() {
11391        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11392        drawableStateChanged();
11393
11394        ViewParent parent = mParent;
11395        if (parent != null) {
11396            parent.childDrawableStateChanged(this);
11397        }
11398    }
11399
11400    /**
11401     * Return an array of resource IDs of the drawable states representing the
11402     * current state of the view.
11403     *
11404     * @return The current drawable state
11405     *
11406     * @see Drawable#setState(int[])
11407     * @see #drawableStateChanged()
11408     * @see #onCreateDrawableState(int)
11409     */
11410    public final int[] getDrawableState() {
11411        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11412            return mDrawableState;
11413        } else {
11414            mDrawableState = onCreateDrawableState(0);
11415            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11416            return mDrawableState;
11417        }
11418    }
11419
11420    /**
11421     * Generate the new {@link android.graphics.drawable.Drawable} state for
11422     * this view. This is called by the view
11423     * system when the cached Drawable state is determined to be invalid.  To
11424     * retrieve the current state, you should use {@link #getDrawableState}.
11425     *
11426     * @param extraSpace if non-zero, this is the number of extra entries you
11427     * would like in the returned array in which you can place your own
11428     * states.
11429     *
11430     * @return Returns an array holding the current {@link Drawable} state of
11431     * the view.
11432     *
11433     * @see #mergeDrawableStates(int[], int[])
11434     */
11435    protected int[] onCreateDrawableState(int extraSpace) {
11436        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11437                mParent instanceof View) {
11438            return ((View) mParent).onCreateDrawableState(extraSpace);
11439        }
11440
11441        int[] drawableState;
11442
11443        int privateFlags = mPrivateFlags;
11444
11445        int viewStateIndex = 0;
11446        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11447        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11448        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11449        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11450        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11451        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11452        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11453                HardwareRenderer.isAvailable()) {
11454            // This is set if HW acceleration is requested, even if the current
11455            // process doesn't allow it.  This is just to allow app preview
11456            // windows to better match their app.
11457            viewStateIndex |= VIEW_STATE_ACCELERATED;
11458        }
11459        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11460
11461        final int privateFlags2 = mPrivateFlags2;
11462        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11463        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11464
11465        drawableState = VIEW_STATE_SETS[viewStateIndex];
11466
11467        //noinspection ConstantIfStatement
11468        if (false) {
11469            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11470            Log.i("View", toString()
11471                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11472                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11473                    + " fo=" + hasFocus()
11474                    + " sl=" + ((privateFlags & SELECTED) != 0)
11475                    + " wf=" + hasWindowFocus()
11476                    + ": " + Arrays.toString(drawableState));
11477        }
11478
11479        if (extraSpace == 0) {
11480            return drawableState;
11481        }
11482
11483        final int[] fullState;
11484        if (drawableState != null) {
11485            fullState = new int[drawableState.length + extraSpace];
11486            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11487        } else {
11488            fullState = new int[extraSpace];
11489        }
11490
11491        return fullState;
11492    }
11493
11494    /**
11495     * Merge your own state values in <var>additionalState</var> into the base
11496     * state values <var>baseState</var> that were returned by
11497     * {@link #onCreateDrawableState(int)}.
11498     *
11499     * @param baseState The base state values returned by
11500     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11501     * own additional state values.
11502     *
11503     * @param additionalState The additional state values you would like
11504     * added to <var>baseState</var>; this array is not modified.
11505     *
11506     * @return As a convenience, the <var>baseState</var> array you originally
11507     * passed into the function is returned.
11508     *
11509     * @see #onCreateDrawableState(int)
11510     */
11511    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11512        final int N = baseState.length;
11513        int i = N - 1;
11514        while (i >= 0 && baseState[i] == 0) {
11515            i--;
11516        }
11517        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11518        return baseState;
11519    }
11520
11521    /**
11522     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11523     * on all Drawable objects associated with this view.
11524     */
11525    public void jumpDrawablesToCurrentState() {
11526        if (mBGDrawable != null) {
11527            mBGDrawable.jumpToCurrentState();
11528        }
11529    }
11530
11531    /**
11532     * Sets the background color for this view.
11533     * @param color the color of the background
11534     */
11535    @RemotableViewMethod
11536    public void setBackgroundColor(int color) {
11537        if (mBGDrawable instanceof ColorDrawable) {
11538            ((ColorDrawable) mBGDrawable).setColor(color);
11539        } else {
11540            setBackgroundDrawable(new ColorDrawable(color));
11541        }
11542    }
11543
11544    /**
11545     * Set the background to a given resource. The resource should refer to
11546     * a Drawable object or 0 to remove the background.
11547     * @param resid The identifier of the resource.
11548     * @attr ref android.R.styleable#View_background
11549     */
11550    @RemotableViewMethod
11551    public void setBackgroundResource(int resid) {
11552        if (resid != 0 && resid == mBackgroundResource) {
11553            return;
11554        }
11555
11556        Drawable d= null;
11557        if (resid != 0) {
11558            d = mResources.getDrawable(resid);
11559        }
11560        setBackgroundDrawable(d);
11561
11562        mBackgroundResource = resid;
11563    }
11564
11565    /**
11566     * Set the background to a given Drawable, or remove the background. If the
11567     * background has padding, this View's padding is set to the background's
11568     * padding. However, when a background is removed, this View's padding isn't
11569     * touched. If setting the padding is desired, please use
11570     * {@link #setPadding(int, int, int, int)}.
11571     *
11572     * @param d The Drawable to use as the background, or null to remove the
11573     *        background
11574     */
11575    public void setBackgroundDrawable(Drawable d) {
11576        if (d == mBGDrawable) {
11577            return;
11578        }
11579
11580        boolean requestLayout = false;
11581
11582        mBackgroundResource = 0;
11583
11584        /*
11585         * Regardless of whether we're setting a new background or not, we want
11586         * to clear the previous drawable.
11587         */
11588        if (mBGDrawable != null) {
11589            mBGDrawable.setCallback(null);
11590            unscheduleDrawable(mBGDrawable);
11591        }
11592
11593        if (d != null) {
11594            Rect padding = sThreadLocal.get();
11595            if (padding == null) {
11596                padding = new Rect();
11597                sThreadLocal.set(padding);
11598            }
11599            if (d.getPadding(padding)) {
11600                switch (d.getResolvedLayoutDirectionSelf()) {
11601                    case LAYOUT_DIRECTION_RTL:
11602                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11603                        break;
11604                    case LAYOUT_DIRECTION_LTR:
11605                    default:
11606                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11607                }
11608            }
11609
11610            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11611            // if it has a different minimum size, we should layout again
11612            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11613                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11614                requestLayout = true;
11615            }
11616
11617            d.setCallback(this);
11618            if (d.isStateful()) {
11619                d.setState(getDrawableState());
11620            }
11621            d.setVisible(getVisibility() == VISIBLE, false);
11622            mBGDrawable = d;
11623
11624            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11625                mPrivateFlags &= ~SKIP_DRAW;
11626                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11627                requestLayout = true;
11628            }
11629        } else {
11630            /* Remove the background */
11631            mBGDrawable = null;
11632
11633            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11634                /*
11635                 * This view ONLY drew the background before and we're removing
11636                 * the background, so now it won't draw anything
11637                 * (hence we SKIP_DRAW)
11638                 */
11639                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11640                mPrivateFlags |= SKIP_DRAW;
11641            }
11642
11643            /*
11644             * When the background is set, we try to apply its padding to this
11645             * View. When the background is removed, we don't touch this View's
11646             * padding. This is noted in the Javadocs. Hence, we don't need to
11647             * requestLayout(), the invalidate() below is sufficient.
11648             */
11649
11650            // The old background's minimum size could have affected this
11651            // View's layout, so let's requestLayout
11652            requestLayout = true;
11653        }
11654
11655        computeOpaqueFlags();
11656
11657        if (requestLayout) {
11658            requestLayout();
11659        }
11660
11661        mBackgroundSizeChanged = true;
11662        invalidate(true);
11663    }
11664
11665    /**
11666     * Gets the background drawable
11667     * @return The drawable used as the background for this view, if any.
11668     */
11669    public Drawable getBackground() {
11670        return mBGDrawable;
11671    }
11672
11673    /**
11674     * Sets the padding. The view may add on the space required to display
11675     * the scrollbars, depending on the style and visibility of the scrollbars.
11676     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11677     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11678     * from the values set in this call.
11679     *
11680     * @attr ref android.R.styleable#View_padding
11681     * @attr ref android.R.styleable#View_paddingBottom
11682     * @attr ref android.R.styleable#View_paddingLeft
11683     * @attr ref android.R.styleable#View_paddingRight
11684     * @attr ref android.R.styleable#View_paddingTop
11685     * @param left the left padding in pixels
11686     * @param top the top padding in pixels
11687     * @param right the right padding in pixels
11688     * @param bottom the bottom padding in pixels
11689     */
11690    public void setPadding(int left, int top, int right, int bottom) {
11691        boolean changed = false;
11692
11693        mUserPaddingRelative = false;
11694
11695        mUserPaddingLeft = left;
11696        mUserPaddingRight = right;
11697        mUserPaddingBottom = bottom;
11698
11699        final int viewFlags = mViewFlags;
11700
11701        // Common case is there are no scroll bars.
11702        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11703            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11704                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11705                        ? 0 : getVerticalScrollbarWidth();
11706                switch (mVerticalScrollbarPosition) {
11707                    case SCROLLBAR_POSITION_DEFAULT:
11708                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11709                            left += offset;
11710                        } else {
11711                            right += offset;
11712                        }
11713                        break;
11714                    case SCROLLBAR_POSITION_RIGHT:
11715                        right += offset;
11716                        break;
11717                    case SCROLLBAR_POSITION_LEFT:
11718                        left += offset;
11719                        break;
11720                }
11721            }
11722            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11723                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11724                        ? 0 : getHorizontalScrollbarHeight();
11725            }
11726        }
11727
11728        if (mPaddingLeft != left) {
11729            changed = true;
11730            mPaddingLeft = left;
11731        }
11732        if (mPaddingTop != top) {
11733            changed = true;
11734            mPaddingTop = top;
11735        }
11736        if (mPaddingRight != right) {
11737            changed = true;
11738            mPaddingRight = right;
11739        }
11740        if (mPaddingBottom != bottom) {
11741            changed = true;
11742            mPaddingBottom = bottom;
11743        }
11744
11745        if (changed) {
11746            requestLayout();
11747        }
11748    }
11749
11750    /**
11751     * Sets the relative padding. The view may add on the space required to display
11752     * the scrollbars, depending on the style and visibility of the scrollbars.
11753     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11754     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11755     * from the values set in this call.
11756     *
11757     * @attr ref android.R.styleable#View_padding
11758     * @attr ref android.R.styleable#View_paddingBottom
11759     * @attr ref android.R.styleable#View_paddingStart
11760     * @attr ref android.R.styleable#View_paddingEnd
11761     * @attr ref android.R.styleable#View_paddingTop
11762     * @param start the start padding in pixels
11763     * @param top the top padding in pixels
11764     * @param end the end padding in pixels
11765     * @param bottom the bottom padding in pixels
11766     *
11767     * @hide
11768     */
11769    public void setPaddingRelative(int start, int top, int end, int bottom) {
11770        mUserPaddingRelative = true;
11771
11772        mUserPaddingStart = start;
11773        mUserPaddingEnd = end;
11774
11775        switch(getResolvedLayoutDirection()) {
11776            case LAYOUT_DIRECTION_RTL:
11777                setPadding(end, top, start, bottom);
11778                break;
11779            case LAYOUT_DIRECTION_LTR:
11780            default:
11781                setPadding(start, top, end, bottom);
11782        }
11783    }
11784
11785    /**
11786     * Returns the top padding of this view.
11787     *
11788     * @return the top padding in pixels
11789     */
11790    public int getPaddingTop() {
11791        return mPaddingTop;
11792    }
11793
11794    /**
11795     * Returns the bottom padding of this view. If there are inset and enabled
11796     * scrollbars, this value may include the space required to display the
11797     * scrollbars as well.
11798     *
11799     * @return the bottom padding in pixels
11800     */
11801    public int getPaddingBottom() {
11802        return mPaddingBottom;
11803    }
11804
11805    /**
11806     * Returns the left padding of this view. If there are inset and enabled
11807     * scrollbars, this value may include the space required to display the
11808     * scrollbars as well.
11809     *
11810     * @return the left padding in pixels
11811     */
11812    public int getPaddingLeft() {
11813        return mPaddingLeft;
11814    }
11815
11816    /**
11817     * Returns the start padding of this view. If there are inset and enabled
11818     * scrollbars, this value may include the space required to display the
11819     * scrollbars as well.
11820     *
11821     * @return the start padding in pixels
11822     *
11823     * @hide
11824     */
11825    public int getPaddingStart() {
11826        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11827                mPaddingRight : mPaddingLeft;
11828    }
11829
11830    /**
11831     * Returns the right padding of this view. If there are inset and enabled
11832     * scrollbars, this value may include the space required to display the
11833     * scrollbars as well.
11834     *
11835     * @return the right padding in pixels
11836     */
11837    public int getPaddingRight() {
11838        return mPaddingRight;
11839    }
11840
11841    /**
11842     * Returns the end padding of this view. If there are inset and enabled
11843     * scrollbars, this value may include the space required to display the
11844     * scrollbars as well.
11845     *
11846     * @return the end padding in pixels
11847     *
11848     * @hide
11849     */
11850    public int getPaddingEnd() {
11851        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11852                mPaddingLeft : mPaddingRight;
11853    }
11854
11855    /**
11856     * Return if the padding as been set thru relative values
11857     * {@link #setPaddingRelative(int, int, int, int)} or thru
11858     * @attr ref android.R.styleable#View_paddingStart or
11859     * @attr ref android.R.styleable#View_paddingEnd
11860     *
11861     * @return true if the padding is relative or false if it is not.
11862     *
11863     * @hide
11864     */
11865    public boolean isPaddingRelative() {
11866        return mUserPaddingRelative;
11867    }
11868
11869    /**
11870     * Changes the selection state of this view. A view can be selected or not.
11871     * Note that selection is not the same as focus. Views are typically
11872     * selected in the context of an AdapterView like ListView or GridView;
11873     * the selected view is the view that is highlighted.
11874     *
11875     * @param selected true if the view must be selected, false otherwise
11876     */
11877    public void setSelected(boolean selected) {
11878        if (((mPrivateFlags & SELECTED) != 0) != selected) {
11879            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
11880            if (!selected) resetPressedState();
11881            invalidate(true);
11882            refreshDrawableState();
11883            dispatchSetSelected(selected);
11884        }
11885    }
11886
11887    /**
11888     * Dispatch setSelected to all of this View's children.
11889     *
11890     * @see #setSelected(boolean)
11891     *
11892     * @param selected The new selected state
11893     */
11894    protected void dispatchSetSelected(boolean selected) {
11895    }
11896
11897    /**
11898     * Indicates the selection state of this view.
11899     *
11900     * @return true if the view is selected, false otherwise
11901     */
11902    @ViewDebug.ExportedProperty
11903    public boolean isSelected() {
11904        return (mPrivateFlags & SELECTED) != 0;
11905    }
11906
11907    /**
11908     * Changes the activated state of this view. A view can be activated or not.
11909     * Note that activation is not the same as selection.  Selection is
11910     * a transient property, representing the view (hierarchy) the user is
11911     * currently interacting with.  Activation is a longer-term state that the
11912     * user can move views in and out of.  For example, in a list view with
11913     * single or multiple selection enabled, the views in the current selection
11914     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
11915     * here.)  The activated state is propagated down to children of the view it
11916     * is set on.
11917     *
11918     * @param activated true if the view must be activated, false otherwise
11919     */
11920    public void setActivated(boolean activated) {
11921        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
11922            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
11923            invalidate(true);
11924            refreshDrawableState();
11925            dispatchSetActivated(activated);
11926        }
11927    }
11928
11929    /**
11930     * Dispatch setActivated to all of this View's children.
11931     *
11932     * @see #setActivated(boolean)
11933     *
11934     * @param activated The new activated state
11935     */
11936    protected void dispatchSetActivated(boolean activated) {
11937    }
11938
11939    /**
11940     * Indicates the activation state of this view.
11941     *
11942     * @return true if the view is activated, false otherwise
11943     */
11944    @ViewDebug.ExportedProperty
11945    public boolean isActivated() {
11946        return (mPrivateFlags & ACTIVATED) != 0;
11947    }
11948
11949    /**
11950     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
11951     * observer can be used to get notifications when global events, like
11952     * layout, happen.
11953     *
11954     * The returned ViewTreeObserver observer is not guaranteed to remain
11955     * valid for the lifetime of this View. If the caller of this method keeps
11956     * a long-lived reference to ViewTreeObserver, it should always check for
11957     * the return value of {@link ViewTreeObserver#isAlive()}.
11958     *
11959     * @return The ViewTreeObserver for this view's hierarchy.
11960     */
11961    public ViewTreeObserver getViewTreeObserver() {
11962        if (mAttachInfo != null) {
11963            return mAttachInfo.mTreeObserver;
11964        }
11965        if (mFloatingTreeObserver == null) {
11966            mFloatingTreeObserver = new ViewTreeObserver();
11967        }
11968        return mFloatingTreeObserver;
11969    }
11970
11971    /**
11972     * <p>Finds the topmost view in the current view hierarchy.</p>
11973     *
11974     * @return the topmost view containing this view
11975     */
11976    public View getRootView() {
11977        if (mAttachInfo != null) {
11978            final View v = mAttachInfo.mRootView;
11979            if (v != null) {
11980                return v;
11981            }
11982        }
11983
11984        View parent = this;
11985
11986        while (parent.mParent != null && parent.mParent instanceof View) {
11987            parent = (View) parent.mParent;
11988        }
11989
11990        return parent;
11991    }
11992
11993    /**
11994     * <p>Computes the coordinates of this view on the screen. The argument
11995     * must be an array of two integers. After the method returns, the array
11996     * contains the x and y location in that order.</p>
11997     *
11998     * @param location an array of two integers in which to hold the coordinates
11999     */
12000    public void getLocationOnScreen(int[] location) {
12001        getLocationInWindow(location);
12002
12003        final AttachInfo info = mAttachInfo;
12004        if (info != null) {
12005            location[0] += info.mWindowLeft;
12006            location[1] += info.mWindowTop;
12007        }
12008    }
12009
12010    /**
12011     * <p>Computes the coordinates of this view in its window. The argument
12012     * must be an array of two integers. After the method returns, the array
12013     * contains the x and y location in that order.</p>
12014     *
12015     * @param location an array of two integers in which to hold the coordinates
12016     */
12017    public void getLocationInWindow(int[] location) {
12018        if (location == null || location.length < 2) {
12019            throw new IllegalArgumentException("location must be an array of "
12020                    + "two integers");
12021        }
12022
12023        location[0] = mLeft;
12024        location[1] = mTop;
12025        if (mTransformationInfo != null) {
12026            location[0] += (int) (mTransformationInfo.mTranslationX + 0.5f);
12027            location[1] += (int) (mTransformationInfo.mTranslationY + 0.5f);
12028        }
12029
12030        ViewParent viewParent = mParent;
12031        while (viewParent instanceof View) {
12032            final View view = (View)viewParent;
12033            location[0] += view.mLeft - view.mScrollX;
12034            location[1] += view.mTop - view.mScrollY;
12035            if (view.mTransformationInfo != null) {
12036                location[0] += (int) (view.mTransformationInfo.mTranslationX + 0.5f);
12037                location[1] += (int) (view.mTransformationInfo.mTranslationY + 0.5f);
12038            }
12039            viewParent = view.mParent;
12040        }
12041
12042        if (viewParent instanceof ViewRootImpl) {
12043            // *cough*
12044            final ViewRootImpl vr = (ViewRootImpl)viewParent;
12045            location[1] -= vr.mCurScrollY;
12046        }
12047    }
12048
12049    /**
12050     * {@hide}
12051     * @param id the id of the view to be found
12052     * @return the view of the specified id, null if cannot be found
12053     */
12054    protected View findViewTraversal(int id) {
12055        if (id == mID) {
12056            return this;
12057        }
12058        return null;
12059    }
12060
12061    /**
12062     * {@hide}
12063     * @param tag the tag of the view to be found
12064     * @return the view of specified tag, null if cannot be found
12065     */
12066    protected View findViewWithTagTraversal(Object tag) {
12067        if (tag != null && tag.equals(mTag)) {
12068            return this;
12069        }
12070        return null;
12071    }
12072
12073    /**
12074     * {@hide}
12075     * @param predicate The predicate to evaluate.
12076     * @param childToSkip If not null, ignores this child during the recursive traversal.
12077     * @return The first view that matches the predicate or null.
12078     */
12079    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12080        if (predicate.apply(this)) {
12081            return this;
12082        }
12083        return null;
12084    }
12085
12086    /**
12087     * Look for a child view with the given id.  If this view has the given
12088     * id, return this view.
12089     *
12090     * @param id The id to search for.
12091     * @return The view that has the given id in the hierarchy or null
12092     */
12093    public final View findViewById(int id) {
12094        if (id < 0) {
12095            return null;
12096        }
12097        return findViewTraversal(id);
12098    }
12099
12100    /**
12101     * Finds a view by its unuque and stable accessibility id.
12102     *
12103     * @param accessibilityId The searched accessibility id.
12104     * @return The found view.
12105     */
12106    final View findViewByAccessibilityId(int accessibilityId) {
12107        if (accessibilityId < 0) {
12108            return null;
12109        }
12110        return findViewByAccessibilityIdTraversal(accessibilityId);
12111    }
12112
12113    /**
12114     * Performs the traversal to find a view by its unuque and stable accessibility id.
12115     *
12116     * <strong>Note:</strong>This method does not stop at the root namespace
12117     * boundary since the user can touch the screen at an arbitrary location
12118     * potentially crossing the root namespace bounday which will send an
12119     * accessibility event to accessibility services and they should be able
12120     * to obtain the event source. Also accessibility ids are guaranteed to be
12121     * unique in the window.
12122     *
12123     * @param accessibilityId The accessibility id.
12124     * @return The found view.
12125     */
12126    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12127        if (getAccessibilityViewId() == accessibilityId) {
12128            return this;
12129        }
12130        return null;
12131    }
12132
12133    /**
12134     * Look for a child view with the given tag.  If this view has the given
12135     * tag, return this view.
12136     *
12137     * @param tag The tag to search for, using "tag.equals(getTag())".
12138     * @return The View that has the given tag in the hierarchy or null
12139     */
12140    public final View findViewWithTag(Object tag) {
12141        if (tag == null) {
12142            return null;
12143        }
12144        return findViewWithTagTraversal(tag);
12145    }
12146
12147    /**
12148     * {@hide}
12149     * Look for a child view that matches the specified predicate.
12150     * If this view matches the predicate, return this view.
12151     *
12152     * @param predicate The predicate to evaluate.
12153     * @return The first view that matches the predicate or null.
12154     */
12155    public final View findViewByPredicate(Predicate<View> predicate) {
12156        return findViewByPredicateTraversal(predicate, null);
12157    }
12158
12159    /**
12160     * {@hide}
12161     * Look for a child view that matches the specified predicate,
12162     * starting with the specified view and its descendents and then
12163     * recusively searching the ancestors and siblings of that view
12164     * until this view is reached.
12165     *
12166     * This method is useful in cases where the predicate does not match
12167     * a single unique view (perhaps multiple views use the same id)
12168     * and we are trying to find the view that is "closest" in scope to the
12169     * starting view.
12170     *
12171     * @param start The view to start from.
12172     * @param predicate The predicate to evaluate.
12173     * @return The first view that matches the predicate or null.
12174     */
12175    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12176        View childToSkip = null;
12177        for (;;) {
12178            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12179            if (view != null || start == this) {
12180                return view;
12181            }
12182
12183            ViewParent parent = start.getParent();
12184            if (parent == null || !(parent instanceof View)) {
12185                return null;
12186            }
12187
12188            childToSkip = start;
12189            start = (View) parent;
12190        }
12191    }
12192
12193    /**
12194     * Sets the identifier for this view. The identifier does not have to be
12195     * unique in this view's hierarchy. The identifier should be a positive
12196     * number.
12197     *
12198     * @see #NO_ID
12199     * @see #getId()
12200     * @see #findViewById(int)
12201     *
12202     * @param id a number used to identify the view
12203     *
12204     * @attr ref android.R.styleable#View_id
12205     */
12206    public void setId(int id) {
12207        mID = id;
12208    }
12209
12210    /**
12211     * {@hide}
12212     *
12213     * @param isRoot true if the view belongs to the root namespace, false
12214     *        otherwise
12215     */
12216    public void setIsRootNamespace(boolean isRoot) {
12217        if (isRoot) {
12218            mPrivateFlags |= IS_ROOT_NAMESPACE;
12219        } else {
12220            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12221        }
12222    }
12223
12224    /**
12225     * {@hide}
12226     *
12227     * @return true if the view belongs to the root namespace, false otherwise
12228     */
12229    public boolean isRootNamespace() {
12230        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12231    }
12232
12233    /**
12234     * Returns this view's identifier.
12235     *
12236     * @return a positive integer used to identify the view or {@link #NO_ID}
12237     *         if the view has no ID
12238     *
12239     * @see #setId(int)
12240     * @see #findViewById(int)
12241     * @attr ref android.R.styleable#View_id
12242     */
12243    @ViewDebug.CapturedViewProperty
12244    public int getId() {
12245        return mID;
12246    }
12247
12248    /**
12249     * Returns this view's tag.
12250     *
12251     * @return the Object stored in this view as a tag
12252     *
12253     * @see #setTag(Object)
12254     * @see #getTag(int)
12255     */
12256    @ViewDebug.ExportedProperty
12257    public Object getTag() {
12258        return mTag;
12259    }
12260
12261    /**
12262     * Sets the tag associated with this view. A tag can be used to mark
12263     * a view in its hierarchy and does not have to be unique within the
12264     * hierarchy. Tags can also be used to store data within a view without
12265     * resorting to another data structure.
12266     *
12267     * @param tag an Object to tag the view with
12268     *
12269     * @see #getTag()
12270     * @see #setTag(int, Object)
12271     */
12272    public void setTag(final Object tag) {
12273        mTag = tag;
12274    }
12275
12276    /**
12277     * Returns the tag associated with this view and the specified key.
12278     *
12279     * @param key The key identifying the tag
12280     *
12281     * @return the Object stored in this view as a tag
12282     *
12283     * @see #setTag(int, Object)
12284     * @see #getTag()
12285     */
12286    public Object getTag(int key) {
12287        if (mKeyedTags != null) return mKeyedTags.get(key);
12288        return null;
12289    }
12290
12291    /**
12292     * Sets a tag associated with this view and a key. A tag can be used
12293     * to mark a view in its hierarchy and does not have to be unique within
12294     * the hierarchy. Tags can also be used to store data within a view
12295     * without resorting to another data structure.
12296     *
12297     * The specified key should be an id declared in the resources of the
12298     * application to ensure it is unique (see the <a
12299     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12300     * Keys identified as belonging to
12301     * the Android framework or not associated with any package will cause
12302     * an {@link IllegalArgumentException} to be thrown.
12303     *
12304     * @param key The key identifying the tag
12305     * @param tag An Object to tag the view with
12306     *
12307     * @throws IllegalArgumentException If they specified key is not valid
12308     *
12309     * @see #setTag(Object)
12310     * @see #getTag(int)
12311     */
12312    public void setTag(int key, final Object tag) {
12313        // If the package id is 0x00 or 0x01, it's either an undefined package
12314        // or a framework id
12315        if ((key >>> 24) < 2) {
12316            throw new IllegalArgumentException("The key must be an application-specific "
12317                    + "resource id.");
12318        }
12319
12320        setKeyedTag(key, tag);
12321    }
12322
12323    /**
12324     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12325     * framework id.
12326     *
12327     * @hide
12328     */
12329    public void setTagInternal(int key, Object tag) {
12330        if ((key >>> 24) != 0x1) {
12331            throw new IllegalArgumentException("The key must be a framework-specific "
12332                    + "resource id.");
12333        }
12334
12335        setKeyedTag(key, tag);
12336    }
12337
12338    private void setKeyedTag(int key, Object tag) {
12339        if (mKeyedTags == null) {
12340            mKeyedTags = new SparseArray<Object>();
12341        }
12342
12343        mKeyedTags.put(key, tag);
12344    }
12345
12346    /**
12347     * @param consistency The type of consistency. See ViewDebug for more information.
12348     *
12349     * @hide
12350     */
12351    protected boolean dispatchConsistencyCheck(int consistency) {
12352        return onConsistencyCheck(consistency);
12353    }
12354
12355    /**
12356     * Method that subclasses should implement to check their consistency. The type of
12357     * consistency check is indicated by the bit field passed as a parameter.
12358     *
12359     * @param consistency The type of consistency. See ViewDebug for more information.
12360     *
12361     * @throws IllegalStateException if the view is in an inconsistent state.
12362     *
12363     * @hide
12364     */
12365    protected boolean onConsistencyCheck(int consistency) {
12366        boolean result = true;
12367
12368        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12369        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12370
12371        if (checkLayout) {
12372            if (getParent() == null) {
12373                result = false;
12374                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12375                        "View " + this + " does not have a parent.");
12376            }
12377
12378            if (mAttachInfo == null) {
12379                result = false;
12380                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12381                        "View " + this + " is not attached to a window.");
12382            }
12383        }
12384
12385        if (checkDrawing) {
12386            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12387            // from their draw() method
12388
12389            if ((mPrivateFlags & DRAWN) != DRAWN &&
12390                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12391                result = false;
12392                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12393                        "View " + this + " was invalidated but its drawing cache is valid.");
12394            }
12395        }
12396
12397        return result;
12398    }
12399
12400    /**
12401     * Prints information about this view in the log output, with the tag
12402     * {@link #VIEW_LOG_TAG}.
12403     *
12404     * @hide
12405     */
12406    public void debug() {
12407        debug(0);
12408    }
12409
12410    /**
12411     * Prints information about this view in the log output, with the tag
12412     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12413     * indentation defined by the <code>depth</code>.
12414     *
12415     * @param depth the indentation level
12416     *
12417     * @hide
12418     */
12419    protected void debug(int depth) {
12420        String output = debugIndent(depth - 1);
12421
12422        output += "+ " + this;
12423        int id = getId();
12424        if (id != -1) {
12425            output += " (id=" + id + ")";
12426        }
12427        Object tag = getTag();
12428        if (tag != null) {
12429            output += " (tag=" + tag + ")";
12430        }
12431        Log.d(VIEW_LOG_TAG, output);
12432
12433        if ((mPrivateFlags & FOCUSED) != 0) {
12434            output = debugIndent(depth) + " FOCUSED";
12435            Log.d(VIEW_LOG_TAG, output);
12436        }
12437
12438        output = debugIndent(depth);
12439        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12440                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12441                + "} ";
12442        Log.d(VIEW_LOG_TAG, output);
12443
12444        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12445                || mPaddingBottom != 0) {
12446            output = debugIndent(depth);
12447            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12448                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12449            Log.d(VIEW_LOG_TAG, output);
12450        }
12451
12452        output = debugIndent(depth);
12453        output += "mMeasureWidth=" + mMeasuredWidth +
12454                " mMeasureHeight=" + mMeasuredHeight;
12455        Log.d(VIEW_LOG_TAG, output);
12456
12457        output = debugIndent(depth);
12458        if (mLayoutParams == null) {
12459            output += "BAD! no layout params";
12460        } else {
12461            output = mLayoutParams.debug(output);
12462        }
12463        Log.d(VIEW_LOG_TAG, output);
12464
12465        output = debugIndent(depth);
12466        output += "flags={";
12467        output += View.printFlags(mViewFlags);
12468        output += "}";
12469        Log.d(VIEW_LOG_TAG, output);
12470
12471        output = debugIndent(depth);
12472        output += "privateFlags={";
12473        output += View.printPrivateFlags(mPrivateFlags);
12474        output += "}";
12475        Log.d(VIEW_LOG_TAG, output);
12476    }
12477
12478    /**
12479     * Creates an string of whitespaces used for indentation.
12480     *
12481     * @param depth the indentation level
12482     * @return a String containing (depth * 2 + 3) * 2 white spaces
12483     *
12484     * @hide
12485     */
12486    protected static String debugIndent(int depth) {
12487        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12488        for (int i = 0; i < (depth * 2) + 3; i++) {
12489            spaces.append(' ').append(' ');
12490        }
12491        return spaces.toString();
12492    }
12493
12494    /**
12495     * <p>Return the offset of the widget's text baseline from the widget's top
12496     * boundary. If this widget does not support baseline alignment, this
12497     * method returns -1. </p>
12498     *
12499     * @return the offset of the baseline within the widget's bounds or -1
12500     *         if baseline alignment is not supported
12501     */
12502    @ViewDebug.ExportedProperty(category = "layout")
12503    public int getBaseline() {
12504        return -1;
12505    }
12506
12507    /**
12508     * Call this when something has changed which has invalidated the
12509     * layout of this view. This will schedule a layout pass of the view
12510     * tree.
12511     */
12512    public void requestLayout() {
12513        if (ViewDebug.TRACE_HIERARCHY) {
12514            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12515        }
12516
12517        mPrivateFlags |= FORCE_LAYOUT;
12518        mPrivateFlags |= INVALIDATED;
12519
12520        if (mParent != null) {
12521            if (mLayoutParams != null) {
12522                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12523            }
12524            if (!mParent.isLayoutRequested()) {
12525                mParent.requestLayout();
12526            }
12527        }
12528    }
12529
12530    /**
12531     * Forces this view to be laid out during the next layout pass.
12532     * This method does not call requestLayout() or forceLayout()
12533     * on the parent.
12534     */
12535    public void forceLayout() {
12536        mPrivateFlags |= FORCE_LAYOUT;
12537        mPrivateFlags |= INVALIDATED;
12538    }
12539
12540    /**
12541     * <p>
12542     * This is called to find out how big a view should be. The parent
12543     * supplies constraint information in the width and height parameters.
12544     * </p>
12545     *
12546     * <p>
12547     * The actual mesurement work of a view is performed in
12548     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12549     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12550     * </p>
12551     *
12552     *
12553     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12554     *        parent
12555     * @param heightMeasureSpec Vertical space requirements as imposed by the
12556     *        parent
12557     *
12558     * @see #onMeasure(int, int)
12559     */
12560    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12561        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12562                widthMeasureSpec != mOldWidthMeasureSpec ||
12563                heightMeasureSpec != mOldHeightMeasureSpec) {
12564
12565            // first clears the measured dimension flag
12566            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12567
12568            if (ViewDebug.TRACE_HIERARCHY) {
12569                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12570            }
12571
12572            // measure ourselves, this should set the measured dimension flag back
12573            onMeasure(widthMeasureSpec, heightMeasureSpec);
12574
12575            // flag not set, setMeasuredDimension() was not invoked, we raise
12576            // an exception to warn the developer
12577            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12578                throw new IllegalStateException("onMeasure() did not set the"
12579                        + " measured dimension by calling"
12580                        + " setMeasuredDimension()");
12581            }
12582
12583            mPrivateFlags |= LAYOUT_REQUIRED;
12584        }
12585
12586        mOldWidthMeasureSpec = widthMeasureSpec;
12587        mOldHeightMeasureSpec = heightMeasureSpec;
12588    }
12589
12590    /**
12591     * <p>
12592     * Measure the view and its content to determine the measured width and the
12593     * measured height. This method is invoked by {@link #measure(int, int)} and
12594     * should be overriden by subclasses to provide accurate and efficient
12595     * measurement of their contents.
12596     * </p>
12597     *
12598     * <p>
12599     * <strong>CONTRACT:</strong> When overriding this method, you
12600     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12601     * measured width and height of this view. Failure to do so will trigger an
12602     * <code>IllegalStateException</code>, thrown by
12603     * {@link #measure(int, int)}. Calling the superclass'
12604     * {@link #onMeasure(int, int)} is a valid use.
12605     * </p>
12606     *
12607     * <p>
12608     * The base class implementation of measure defaults to the background size,
12609     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12610     * override {@link #onMeasure(int, int)} to provide better measurements of
12611     * their content.
12612     * </p>
12613     *
12614     * <p>
12615     * If this method is overridden, it is the subclass's responsibility to make
12616     * sure the measured height and width are at least the view's minimum height
12617     * and width ({@link #getSuggestedMinimumHeight()} and
12618     * {@link #getSuggestedMinimumWidth()}).
12619     * </p>
12620     *
12621     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12622     *                         The requirements are encoded with
12623     *                         {@link android.view.View.MeasureSpec}.
12624     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12625     *                         The requirements are encoded with
12626     *                         {@link android.view.View.MeasureSpec}.
12627     *
12628     * @see #getMeasuredWidth()
12629     * @see #getMeasuredHeight()
12630     * @see #setMeasuredDimension(int, int)
12631     * @see #getSuggestedMinimumHeight()
12632     * @see #getSuggestedMinimumWidth()
12633     * @see android.view.View.MeasureSpec#getMode(int)
12634     * @see android.view.View.MeasureSpec#getSize(int)
12635     */
12636    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12637        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12638                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12639    }
12640
12641    /**
12642     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12643     * measured width and measured height. Failing to do so will trigger an
12644     * exception at measurement time.</p>
12645     *
12646     * @param measuredWidth The measured width of this view.  May be a complex
12647     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12648     * {@link #MEASURED_STATE_TOO_SMALL}.
12649     * @param measuredHeight The measured height of this view.  May be a complex
12650     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12651     * {@link #MEASURED_STATE_TOO_SMALL}.
12652     */
12653    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12654        mMeasuredWidth = measuredWidth;
12655        mMeasuredHeight = measuredHeight;
12656
12657        mPrivateFlags |= MEASURED_DIMENSION_SET;
12658    }
12659
12660    /**
12661     * Merge two states as returned by {@link #getMeasuredState()}.
12662     * @param curState The current state as returned from a view or the result
12663     * of combining multiple views.
12664     * @param newState The new view state to combine.
12665     * @return Returns a new integer reflecting the combination of the two
12666     * states.
12667     */
12668    public static int combineMeasuredStates(int curState, int newState) {
12669        return curState | newState;
12670    }
12671
12672    /**
12673     * Version of {@link #resolveSizeAndState(int, int, int)}
12674     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12675     */
12676    public static int resolveSize(int size, int measureSpec) {
12677        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12678    }
12679
12680    /**
12681     * Utility to reconcile a desired size and state, with constraints imposed
12682     * by a MeasureSpec.  Will take the desired size, unless a different size
12683     * is imposed by the constraints.  The returned value is a compound integer,
12684     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12685     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12686     * size is smaller than the size the view wants to be.
12687     *
12688     * @param size How big the view wants to be
12689     * @param measureSpec Constraints imposed by the parent
12690     * @return Size information bit mask as defined by
12691     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12692     */
12693    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12694        int result = size;
12695        int specMode = MeasureSpec.getMode(measureSpec);
12696        int specSize =  MeasureSpec.getSize(measureSpec);
12697        switch (specMode) {
12698        case MeasureSpec.UNSPECIFIED:
12699            result = size;
12700            break;
12701        case MeasureSpec.AT_MOST:
12702            if (specSize < size) {
12703                result = specSize | MEASURED_STATE_TOO_SMALL;
12704            } else {
12705                result = size;
12706            }
12707            break;
12708        case MeasureSpec.EXACTLY:
12709            result = specSize;
12710            break;
12711        }
12712        return result | (childMeasuredState&MEASURED_STATE_MASK);
12713    }
12714
12715    /**
12716     * Utility to return a default size. Uses the supplied size if the
12717     * MeasureSpec imposed no constraints. Will get larger if allowed
12718     * by the MeasureSpec.
12719     *
12720     * @param size Default size for this view
12721     * @param measureSpec Constraints imposed by the parent
12722     * @return The size this view should be.
12723     */
12724    public static int getDefaultSize(int size, int measureSpec) {
12725        int result = size;
12726        int specMode = MeasureSpec.getMode(measureSpec);
12727        int specSize = MeasureSpec.getSize(measureSpec);
12728
12729        switch (specMode) {
12730        case MeasureSpec.UNSPECIFIED:
12731            result = size;
12732            break;
12733        case MeasureSpec.AT_MOST:
12734        case MeasureSpec.EXACTLY:
12735            result = specSize;
12736            break;
12737        }
12738        return result;
12739    }
12740
12741    /**
12742     * Returns the suggested minimum height that the view should use. This
12743     * returns the maximum of the view's minimum height
12744     * and the background's minimum height
12745     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12746     * <p>
12747     * When being used in {@link #onMeasure(int, int)}, the caller should still
12748     * ensure the returned height is within the requirements of the parent.
12749     *
12750     * @return The suggested minimum height of the view.
12751     */
12752    protected int getSuggestedMinimumHeight() {
12753        int suggestedMinHeight = mMinHeight;
12754
12755        if (mBGDrawable != null) {
12756            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12757            if (suggestedMinHeight < bgMinHeight) {
12758                suggestedMinHeight = bgMinHeight;
12759            }
12760        }
12761
12762        return suggestedMinHeight;
12763    }
12764
12765    /**
12766     * Returns the suggested minimum width that the view should use. This
12767     * returns the maximum of the view's minimum width)
12768     * and the background's minimum width
12769     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12770     * <p>
12771     * When being used in {@link #onMeasure(int, int)}, the caller should still
12772     * ensure the returned width is within the requirements of the parent.
12773     *
12774     * @return The suggested minimum width of the view.
12775     */
12776    protected int getSuggestedMinimumWidth() {
12777        int suggestedMinWidth = mMinWidth;
12778
12779        if (mBGDrawable != null) {
12780            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12781            if (suggestedMinWidth < bgMinWidth) {
12782                suggestedMinWidth = bgMinWidth;
12783            }
12784        }
12785
12786        return suggestedMinWidth;
12787    }
12788
12789    /**
12790     * Sets the minimum height of the view. It is not guaranteed the view will
12791     * be able to achieve this minimum height (for example, if its parent layout
12792     * constrains it with less available height).
12793     *
12794     * @param minHeight The minimum height the view will try to be.
12795     */
12796    public void setMinimumHeight(int minHeight) {
12797        mMinHeight = minHeight;
12798    }
12799
12800    /**
12801     * Sets the minimum width of the view. It is not guaranteed the view will
12802     * be able to achieve this minimum width (for example, if its parent layout
12803     * constrains it with less available width).
12804     *
12805     * @param minWidth The minimum width the view will try to be.
12806     */
12807    public void setMinimumWidth(int minWidth) {
12808        mMinWidth = minWidth;
12809    }
12810
12811    /**
12812     * Get the animation currently associated with this view.
12813     *
12814     * @return The animation that is currently playing or
12815     *         scheduled to play for this view.
12816     */
12817    public Animation getAnimation() {
12818        return mCurrentAnimation;
12819    }
12820
12821    /**
12822     * Start the specified animation now.
12823     *
12824     * @param animation the animation to start now
12825     */
12826    public void startAnimation(Animation animation) {
12827        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12828        setAnimation(animation);
12829        invalidateParentCaches();
12830        invalidate(true);
12831    }
12832
12833    /**
12834     * Cancels any animations for this view.
12835     */
12836    public void clearAnimation() {
12837        if (mCurrentAnimation != null) {
12838            mCurrentAnimation.detach();
12839        }
12840        mCurrentAnimation = null;
12841        invalidateParentIfNeeded();
12842    }
12843
12844    /**
12845     * Sets the next animation to play for this view.
12846     * If you want the animation to play immediately, use
12847     * startAnimation. This method provides allows fine-grained
12848     * control over the start time and invalidation, but you
12849     * must make sure that 1) the animation has a start time set, and
12850     * 2) the view will be invalidated when the animation is supposed to
12851     * start.
12852     *
12853     * @param animation The next animation, or null.
12854     */
12855    public void setAnimation(Animation animation) {
12856        mCurrentAnimation = animation;
12857        if (animation != null) {
12858            animation.reset();
12859        }
12860    }
12861
12862    /**
12863     * Invoked by a parent ViewGroup to notify the start of the animation
12864     * currently associated with this view. If you override this method,
12865     * always call super.onAnimationStart();
12866     *
12867     * @see #setAnimation(android.view.animation.Animation)
12868     * @see #getAnimation()
12869     */
12870    protected void onAnimationStart() {
12871        mPrivateFlags |= ANIMATION_STARTED;
12872    }
12873
12874    /**
12875     * Invoked by a parent ViewGroup to notify the end of the animation
12876     * currently associated with this view. If you override this method,
12877     * always call super.onAnimationEnd();
12878     *
12879     * @see #setAnimation(android.view.animation.Animation)
12880     * @see #getAnimation()
12881     */
12882    protected void onAnimationEnd() {
12883        mPrivateFlags &= ~ANIMATION_STARTED;
12884    }
12885
12886    /**
12887     * Invoked if there is a Transform that involves alpha. Subclass that can
12888     * draw themselves with the specified alpha should return true, and then
12889     * respect that alpha when their onDraw() is called. If this returns false
12890     * then the view may be redirected to draw into an offscreen buffer to
12891     * fulfill the request, which will look fine, but may be slower than if the
12892     * subclass handles it internally. The default implementation returns false.
12893     *
12894     * @param alpha The alpha (0..255) to apply to the view's drawing
12895     * @return true if the view can draw with the specified alpha.
12896     */
12897    protected boolean onSetAlpha(int alpha) {
12898        return false;
12899    }
12900
12901    /**
12902     * This is used by the RootView to perform an optimization when
12903     * the view hierarchy contains one or several SurfaceView.
12904     * SurfaceView is always considered transparent, but its children are not,
12905     * therefore all View objects remove themselves from the global transparent
12906     * region (passed as a parameter to this function).
12907     *
12908     * @param region The transparent region for this ViewAncestor (window).
12909     *
12910     * @return Returns true if the effective visibility of the view at this
12911     * point is opaque, regardless of the transparent region; returns false
12912     * if it is possible for underlying windows to be seen behind the view.
12913     *
12914     * {@hide}
12915     */
12916    public boolean gatherTransparentRegion(Region region) {
12917        final AttachInfo attachInfo = mAttachInfo;
12918        if (region != null && attachInfo != null) {
12919            final int pflags = mPrivateFlags;
12920            if ((pflags & SKIP_DRAW) == 0) {
12921                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
12922                // remove it from the transparent region.
12923                final int[] location = attachInfo.mTransparentLocation;
12924                getLocationInWindow(location);
12925                region.op(location[0], location[1], location[0] + mRight - mLeft,
12926                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
12927            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
12928                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
12929                // exists, so we remove the background drawable's non-transparent
12930                // parts from this transparent region.
12931                applyDrawableToTransparentRegion(mBGDrawable, region);
12932            }
12933        }
12934        return true;
12935    }
12936
12937    /**
12938     * Play a sound effect for this view.
12939     *
12940     * <p>The framework will play sound effects for some built in actions, such as
12941     * clicking, but you may wish to play these effects in your widget,
12942     * for instance, for internal navigation.
12943     *
12944     * <p>The sound effect will only be played if sound effects are enabled by the user, and
12945     * {@link #isSoundEffectsEnabled()} is true.
12946     *
12947     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
12948     */
12949    public void playSoundEffect(int soundConstant) {
12950        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
12951            return;
12952        }
12953        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
12954    }
12955
12956    /**
12957     * BZZZTT!!1!
12958     *
12959     * <p>Provide haptic feedback to the user for this view.
12960     *
12961     * <p>The framework will provide haptic feedback for some built in actions,
12962     * such as long presses, but you may wish to provide feedback for your
12963     * own widget.
12964     *
12965     * <p>The feedback will only be performed if
12966     * {@link #isHapticFeedbackEnabled()} is true.
12967     *
12968     * @param feedbackConstant One of the constants defined in
12969     * {@link HapticFeedbackConstants}
12970     */
12971    public boolean performHapticFeedback(int feedbackConstant) {
12972        return performHapticFeedback(feedbackConstant, 0);
12973    }
12974
12975    /**
12976     * BZZZTT!!1!
12977     *
12978     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
12979     *
12980     * @param feedbackConstant One of the constants defined in
12981     * {@link HapticFeedbackConstants}
12982     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
12983     */
12984    public boolean performHapticFeedback(int feedbackConstant, int flags) {
12985        if (mAttachInfo == null) {
12986            return false;
12987        }
12988        //noinspection SimplifiableIfStatement
12989        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
12990                && !isHapticFeedbackEnabled()) {
12991            return false;
12992        }
12993        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
12994                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
12995    }
12996
12997    /**
12998     * Request that the visibility of the status bar be changed.
12999     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13000     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13001     */
13002    public void setSystemUiVisibility(int visibility) {
13003        if (visibility != mSystemUiVisibility) {
13004            mSystemUiVisibility = visibility;
13005            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13006                mParent.recomputeViewAttributes(this);
13007            }
13008        }
13009    }
13010
13011    /**
13012     * Returns the status bar visibility that this view has requested.
13013     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13014     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13015     */
13016    public int getSystemUiVisibility() {
13017        return mSystemUiVisibility;
13018    }
13019
13020    /**
13021     * Set a listener to receive callbacks when the visibility of the system bar changes.
13022     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13023     */
13024    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13025        mOnSystemUiVisibilityChangeListener = l;
13026        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13027            mParent.recomputeViewAttributes(this);
13028        }
13029    }
13030
13031    /**
13032     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13033     * the view hierarchy.
13034     */
13035    public void dispatchSystemUiVisibilityChanged(int visibility) {
13036        if (mOnSystemUiVisibilityChangeListener != null) {
13037            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13038                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13039        }
13040    }
13041
13042    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13043        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13044        if (val != mSystemUiVisibility) {
13045            setSystemUiVisibility(val);
13046        }
13047    }
13048
13049    /**
13050     * Creates an image that the system displays during the drag and drop
13051     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13052     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13053     * appearance as the given View. The default also positions the center of the drag shadow
13054     * directly under the touch point. If no View is provided (the constructor with no parameters
13055     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13056     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13057     * default is an invisible drag shadow.
13058     * <p>
13059     * You are not required to use the View you provide to the constructor as the basis of the
13060     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13061     * anything you want as the drag shadow.
13062     * </p>
13063     * <p>
13064     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13065     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13066     *  size and position of the drag shadow. It uses this data to construct a
13067     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13068     *  so that your application can draw the shadow image in the Canvas.
13069     * </p>
13070     */
13071    public static class DragShadowBuilder {
13072        private final WeakReference<View> mView;
13073
13074        /**
13075         * Constructs a shadow image builder based on a View. By default, the resulting drag
13076         * shadow will have the same appearance and dimensions as the View, with the touch point
13077         * over the center of the View.
13078         * @param view A View. Any View in scope can be used.
13079         */
13080        public DragShadowBuilder(View view) {
13081            mView = new WeakReference<View>(view);
13082        }
13083
13084        /**
13085         * Construct a shadow builder object with no associated View.  This
13086         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13087         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13088         * to supply the drag shadow's dimensions and appearance without
13089         * reference to any View object. If they are not overridden, then the result is an
13090         * invisible drag shadow.
13091         */
13092        public DragShadowBuilder() {
13093            mView = new WeakReference<View>(null);
13094        }
13095
13096        /**
13097         * Returns the View object that had been passed to the
13098         * {@link #View.DragShadowBuilder(View)}
13099         * constructor.  If that View parameter was {@code null} or if the
13100         * {@link #View.DragShadowBuilder()}
13101         * constructor was used to instantiate the builder object, this method will return
13102         * null.
13103         *
13104         * @return The View object associate with this builder object.
13105         */
13106        @SuppressWarnings({"JavadocReference"})
13107        final public View getView() {
13108            return mView.get();
13109        }
13110
13111        /**
13112         * Provides the metrics for the shadow image. These include the dimensions of
13113         * the shadow image, and the point within that shadow that should
13114         * be centered under the touch location while dragging.
13115         * <p>
13116         * The default implementation sets the dimensions of the shadow to be the
13117         * same as the dimensions of the View itself and centers the shadow under
13118         * the touch point.
13119         * </p>
13120         *
13121         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13122         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13123         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13124         * image.
13125         *
13126         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13127         * shadow image that should be underneath the touch point during the drag and drop
13128         * operation. Your application must set {@link android.graphics.Point#x} to the
13129         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13130         */
13131        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13132            final View view = mView.get();
13133            if (view != null) {
13134                shadowSize.set(view.getWidth(), view.getHeight());
13135                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13136            } else {
13137                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13138            }
13139        }
13140
13141        /**
13142         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13143         * based on the dimensions it received from the
13144         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13145         *
13146         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13147         */
13148        public void onDrawShadow(Canvas canvas) {
13149            final View view = mView.get();
13150            if (view != null) {
13151                view.draw(canvas);
13152            } else {
13153                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13154            }
13155        }
13156    }
13157
13158    /**
13159     * Starts a drag and drop operation. When your application calls this method, it passes a
13160     * {@link android.view.View.DragShadowBuilder} object to the system. The
13161     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13162     * to get metrics for the drag shadow, and then calls the object's
13163     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13164     * <p>
13165     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13166     *  drag events to all the View objects in your application that are currently visible. It does
13167     *  this either by calling the View object's drag listener (an implementation of
13168     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13169     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13170     *  Both are passed a {@link android.view.DragEvent} object that has a
13171     *  {@link android.view.DragEvent#getAction()} value of
13172     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13173     * </p>
13174     * <p>
13175     * Your application can invoke startDrag() on any attached View object. The View object does not
13176     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13177     * be related to the View the user selected for dragging.
13178     * </p>
13179     * @param data A {@link android.content.ClipData} object pointing to the data to be
13180     * transferred by the drag and drop operation.
13181     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13182     * drag shadow.
13183     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13184     * drop operation. This Object is put into every DragEvent object sent by the system during the
13185     * current drag.
13186     * <p>
13187     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13188     * to the target Views. For example, it can contain flags that differentiate between a
13189     * a copy operation and a move operation.
13190     * </p>
13191     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13192     * so the parameter should be set to 0.
13193     * @return {@code true} if the method completes successfully, or
13194     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13195     * do a drag, and so no drag operation is in progress.
13196     */
13197    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13198            Object myLocalState, int flags) {
13199        if (ViewDebug.DEBUG_DRAG) {
13200            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13201        }
13202        boolean okay = false;
13203
13204        Point shadowSize = new Point();
13205        Point shadowTouchPoint = new Point();
13206        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13207
13208        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13209                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13210            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13211        }
13212
13213        if (ViewDebug.DEBUG_DRAG) {
13214            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13215                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13216        }
13217        Surface surface = new Surface();
13218        try {
13219            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13220                    flags, shadowSize.x, shadowSize.y, surface);
13221            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13222                    + " surface=" + surface);
13223            if (token != null) {
13224                Canvas canvas = surface.lockCanvas(null);
13225                try {
13226                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13227                    shadowBuilder.onDrawShadow(canvas);
13228                } finally {
13229                    surface.unlockCanvasAndPost(canvas);
13230                }
13231
13232                final ViewRootImpl root = getViewRootImpl();
13233
13234                // Cache the local state object for delivery with DragEvents
13235                root.setLocalDragState(myLocalState);
13236
13237                // repurpose 'shadowSize' for the last touch point
13238                root.getLastTouchPoint(shadowSize);
13239
13240                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13241                        shadowSize.x, shadowSize.y,
13242                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13243                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13244
13245                // Off and running!  Release our local surface instance; the drag
13246                // shadow surface is now managed by the system process.
13247                surface.release();
13248            }
13249        } catch (Exception e) {
13250            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13251            surface.destroy();
13252        }
13253
13254        return okay;
13255    }
13256
13257    /**
13258     * Handles drag events sent by the system following a call to
13259     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13260     *<p>
13261     * When the system calls this method, it passes a
13262     * {@link android.view.DragEvent} object. A call to
13263     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13264     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13265     * operation.
13266     * @param event The {@link android.view.DragEvent} sent by the system.
13267     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13268     * in DragEvent, indicating the type of drag event represented by this object.
13269     * @return {@code true} if the method was successful, otherwise {@code false}.
13270     * <p>
13271     *  The method should return {@code true} in response to an action type of
13272     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13273     *  operation.
13274     * </p>
13275     * <p>
13276     *  The method should also return {@code true} in response to an action type of
13277     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13278     *  {@code false} if it didn't.
13279     * </p>
13280     */
13281    public boolean onDragEvent(DragEvent event) {
13282        return false;
13283    }
13284
13285    /**
13286     * Detects if this View is enabled and has a drag event listener.
13287     * If both are true, then it calls the drag event listener with the
13288     * {@link android.view.DragEvent} it received. If the drag event listener returns
13289     * {@code true}, then dispatchDragEvent() returns {@code true}.
13290     * <p>
13291     * For all other cases, the method calls the
13292     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13293     * method and returns its result.
13294     * </p>
13295     * <p>
13296     * This ensures that a drag event is always consumed, even if the View does not have a drag
13297     * event listener. However, if the View has a listener and the listener returns true, then
13298     * onDragEvent() is not called.
13299     * </p>
13300     */
13301    public boolean dispatchDragEvent(DragEvent event) {
13302        //noinspection SimplifiableIfStatement
13303        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13304                && mOnDragListener.onDrag(this, event)) {
13305            return true;
13306        }
13307        return onDragEvent(event);
13308    }
13309
13310    boolean canAcceptDrag() {
13311        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13312    }
13313
13314    /**
13315     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13316     * it is ever exposed at all.
13317     * @hide
13318     */
13319    public void onCloseSystemDialogs(String reason) {
13320    }
13321
13322    /**
13323     * Given a Drawable whose bounds have been set to draw into this view,
13324     * update a Region being computed for
13325     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13326     * that any non-transparent parts of the Drawable are removed from the
13327     * given transparent region.
13328     *
13329     * @param dr The Drawable whose transparency is to be applied to the region.
13330     * @param region A Region holding the current transparency information,
13331     * where any parts of the region that are set are considered to be
13332     * transparent.  On return, this region will be modified to have the
13333     * transparency information reduced by the corresponding parts of the
13334     * Drawable that are not transparent.
13335     * {@hide}
13336     */
13337    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13338        if (DBG) {
13339            Log.i("View", "Getting transparent region for: " + this);
13340        }
13341        final Region r = dr.getTransparentRegion();
13342        final Rect db = dr.getBounds();
13343        final AttachInfo attachInfo = mAttachInfo;
13344        if (r != null && attachInfo != null) {
13345            final int w = getRight()-getLeft();
13346            final int h = getBottom()-getTop();
13347            if (db.left > 0) {
13348                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13349                r.op(0, 0, db.left, h, Region.Op.UNION);
13350            }
13351            if (db.right < w) {
13352                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13353                r.op(db.right, 0, w, h, Region.Op.UNION);
13354            }
13355            if (db.top > 0) {
13356                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13357                r.op(0, 0, w, db.top, Region.Op.UNION);
13358            }
13359            if (db.bottom < h) {
13360                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13361                r.op(0, db.bottom, w, h, Region.Op.UNION);
13362            }
13363            final int[] location = attachInfo.mTransparentLocation;
13364            getLocationInWindow(location);
13365            r.translate(location[0], location[1]);
13366            region.op(r, Region.Op.INTERSECT);
13367        } else {
13368            region.op(db, Region.Op.DIFFERENCE);
13369        }
13370    }
13371
13372    private void checkForLongClick(int delayOffset) {
13373        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13374            mHasPerformedLongPress = false;
13375
13376            if (mPendingCheckForLongPress == null) {
13377                mPendingCheckForLongPress = new CheckForLongPress();
13378            }
13379            mPendingCheckForLongPress.rememberWindowAttachCount();
13380            postDelayed(mPendingCheckForLongPress,
13381                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13382        }
13383    }
13384
13385    /**
13386     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13387     * LayoutInflater} class, which provides a full range of options for view inflation.
13388     *
13389     * @param context The Context object for your activity or application.
13390     * @param resource The resource ID to inflate
13391     * @param root A view group that will be the parent.  Used to properly inflate the
13392     * layout_* parameters.
13393     * @see LayoutInflater
13394     */
13395    public static View inflate(Context context, int resource, ViewGroup root) {
13396        LayoutInflater factory = LayoutInflater.from(context);
13397        return factory.inflate(resource, root);
13398    }
13399
13400    /**
13401     * Scroll the view with standard behavior for scrolling beyond the normal
13402     * content boundaries. Views that call this method should override
13403     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13404     * results of an over-scroll operation.
13405     *
13406     * Views can use this method to handle any touch or fling-based scrolling.
13407     *
13408     * @param deltaX Change in X in pixels
13409     * @param deltaY Change in Y in pixels
13410     * @param scrollX Current X scroll value in pixels before applying deltaX
13411     * @param scrollY Current Y scroll value in pixels before applying deltaY
13412     * @param scrollRangeX Maximum content scroll range along the X axis
13413     * @param scrollRangeY Maximum content scroll range along the Y axis
13414     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13415     *          along the X axis.
13416     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13417     *          along the Y axis.
13418     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13419     * @return true if scrolling was clamped to an over-scroll boundary along either
13420     *          axis, false otherwise.
13421     */
13422    @SuppressWarnings({"UnusedParameters"})
13423    protected boolean overScrollBy(int deltaX, int deltaY,
13424            int scrollX, int scrollY,
13425            int scrollRangeX, int scrollRangeY,
13426            int maxOverScrollX, int maxOverScrollY,
13427            boolean isTouchEvent) {
13428        final int overScrollMode = mOverScrollMode;
13429        final boolean canScrollHorizontal =
13430                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13431        final boolean canScrollVertical =
13432                computeVerticalScrollRange() > computeVerticalScrollExtent();
13433        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13434                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13435        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13436                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13437
13438        int newScrollX = scrollX + deltaX;
13439        if (!overScrollHorizontal) {
13440            maxOverScrollX = 0;
13441        }
13442
13443        int newScrollY = scrollY + deltaY;
13444        if (!overScrollVertical) {
13445            maxOverScrollY = 0;
13446        }
13447
13448        // Clamp values if at the limits and record
13449        final int left = -maxOverScrollX;
13450        final int right = maxOverScrollX + scrollRangeX;
13451        final int top = -maxOverScrollY;
13452        final int bottom = maxOverScrollY + scrollRangeY;
13453
13454        boolean clampedX = false;
13455        if (newScrollX > right) {
13456            newScrollX = right;
13457            clampedX = true;
13458        } else if (newScrollX < left) {
13459            newScrollX = left;
13460            clampedX = true;
13461        }
13462
13463        boolean clampedY = false;
13464        if (newScrollY > bottom) {
13465            newScrollY = bottom;
13466            clampedY = true;
13467        } else if (newScrollY < top) {
13468            newScrollY = top;
13469            clampedY = true;
13470        }
13471
13472        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13473
13474        return clampedX || clampedY;
13475    }
13476
13477    /**
13478     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13479     * respond to the results of an over-scroll operation.
13480     *
13481     * @param scrollX New X scroll value in pixels
13482     * @param scrollY New Y scroll value in pixels
13483     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13484     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13485     */
13486    protected void onOverScrolled(int scrollX, int scrollY,
13487            boolean clampedX, boolean clampedY) {
13488        // Intentionally empty.
13489    }
13490
13491    /**
13492     * Returns the over-scroll mode for this view. The result will be
13493     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13494     * (allow over-scrolling only if the view content is larger than the container),
13495     * or {@link #OVER_SCROLL_NEVER}.
13496     *
13497     * @return This view's over-scroll mode.
13498     */
13499    public int getOverScrollMode() {
13500        return mOverScrollMode;
13501    }
13502
13503    /**
13504     * Set the over-scroll mode for this view. Valid over-scroll modes are
13505     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13506     * (allow over-scrolling only if the view content is larger than the container),
13507     * or {@link #OVER_SCROLL_NEVER}.
13508     *
13509     * Setting the over-scroll mode of a view will have an effect only if the
13510     * view is capable of scrolling.
13511     *
13512     * @param overScrollMode The new over-scroll mode for this view.
13513     */
13514    public void setOverScrollMode(int overScrollMode) {
13515        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13516                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13517                overScrollMode != OVER_SCROLL_NEVER) {
13518            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13519        }
13520        mOverScrollMode = overScrollMode;
13521    }
13522
13523    /**
13524     * Gets a scale factor that determines the distance the view should scroll
13525     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13526     * @return The vertical scroll scale factor.
13527     * @hide
13528     */
13529    protected float getVerticalScrollFactor() {
13530        if (mVerticalScrollFactor == 0) {
13531            TypedValue outValue = new TypedValue();
13532            if (!mContext.getTheme().resolveAttribute(
13533                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13534                throw new IllegalStateException(
13535                        "Expected theme to define listPreferredItemHeight.");
13536            }
13537            mVerticalScrollFactor = outValue.getDimension(
13538                    mContext.getResources().getDisplayMetrics());
13539        }
13540        return mVerticalScrollFactor;
13541    }
13542
13543    /**
13544     * Gets a scale factor that determines the distance the view should scroll
13545     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13546     * @return The horizontal scroll scale factor.
13547     * @hide
13548     */
13549    protected float getHorizontalScrollFactor() {
13550        // TODO: Should use something else.
13551        return getVerticalScrollFactor();
13552    }
13553
13554    /**
13555     * Return the value specifying the text direction or policy that was set with
13556     * {@link #setTextDirection(int)}.
13557     *
13558     * @return the defined text direction. It can be one of:
13559     *
13560     * {@link #TEXT_DIRECTION_INHERIT},
13561     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13562     * {@link #TEXT_DIRECTION_ANY_RTL},
13563     * {@link #TEXT_DIRECTION_LTR},
13564     * {@link #TEXT_DIRECTION_RTL},
13565     *
13566     * @hide
13567     */
13568    public int getTextDirection() {
13569        return mTextDirection;
13570    }
13571
13572    /**
13573     * Set the text direction.
13574     *
13575     * @param textDirection the direction to set. Should be one of:
13576     *
13577     * {@link #TEXT_DIRECTION_INHERIT},
13578     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13579     * {@link #TEXT_DIRECTION_ANY_RTL},
13580     * {@link #TEXT_DIRECTION_LTR},
13581     * {@link #TEXT_DIRECTION_RTL},
13582     *
13583     * @hide
13584     */
13585    public void setTextDirection(int textDirection) {
13586        if (textDirection != mTextDirection) {
13587            mTextDirection = textDirection;
13588            resetResolvedTextDirection();
13589            requestLayout();
13590        }
13591    }
13592
13593    /**
13594     * Return the resolved text direction.
13595     *
13596     * @return the resolved text direction. Return one of:
13597     *
13598     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13599     * {@link #TEXT_DIRECTION_ANY_RTL},
13600     * {@link #TEXT_DIRECTION_LTR},
13601     * {@link #TEXT_DIRECTION_RTL},
13602     *
13603     * @hide
13604     */
13605    public int getResolvedTextDirection() {
13606        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13607            resolveTextDirection();
13608        }
13609        return mResolvedTextDirection;
13610    }
13611
13612    /**
13613     * Resolve the text direction.
13614     *
13615     * @hide
13616     */
13617    protected void resolveTextDirection() {
13618        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13619            mResolvedTextDirection = mTextDirection;
13620            return;
13621        }
13622        if (mParent != null && mParent instanceof ViewGroup) {
13623            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13624            return;
13625        }
13626        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13627    }
13628
13629    /**
13630     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13631     *
13632     * @hide
13633     */
13634    protected void resetResolvedTextDirection() {
13635        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13636    }
13637
13638    //
13639    // Properties
13640    //
13641    /**
13642     * A Property wrapper around the <code>alpha</code> functionality handled by the
13643     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13644     */
13645    public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13646        @Override
13647        public void setValue(View object, float value) {
13648            object.setAlpha(value);
13649        }
13650
13651        @Override
13652        public Float get(View object) {
13653            return object.getAlpha();
13654        }
13655    };
13656
13657    /**
13658     * A Property wrapper around the <code>translationX</code> functionality handled by the
13659     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13660     */
13661    public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13662        @Override
13663        public void setValue(View object, float value) {
13664            object.setTranslationX(value);
13665        }
13666
13667                @Override
13668        public Float get(View object) {
13669            return object.getTranslationX();
13670        }
13671    };
13672
13673    /**
13674     * A Property wrapper around the <code>translationY</code> functionality handled by the
13675     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13676     */
13677    public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13678        @Override
13679        public void setValue(View object, float value) {
13680            object.setTranslationY(value);
13681        }
13682
13683        @Override
13684        public Float get(View object) {
13685            return object.getTranslationY();
13686        }
13687    };
13688
13689    /**
13690     * A Property wrapper around the <code>x</code> functionality handled by the
13691     * {@link View#setX(float)} and {@link View#getX()} methods.
13692     */
13693    public static Property<View, Float> X = new FloatProperty<View>("x") {
13694        @Override
13695        public void setValue(View object, float value) {
13696            object.setX(value);
13697        }
13698
13699        @Override
13700        public Float get(View object) {
13701            return object.getX();
13702        }
13703    };
13704
13705    /**
13706     * A Property wrapper around the <code>y</code> functionality handled by the
13707     * {@link View#setY(float)} and {@link View#getY()} methods.
13708     */
13709    public static Property<View, Float> Y = new FloatProperty<View>("y") {
13710        @Override
13711        public void setValue(View object, float value) {
13712            object.setY(value);
13713        }
13714
13715        @Override
13716        public Float get(View object) {
13717            return object.getY();
13718        }
13719    };
13720
13721    /**
13722     * A Property wrapper around the <code>rotation</code> functionality handled by the
13723     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13724     */
13725    public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13726        @Override
13727        public void setValue(View object, float value) {
13728            object.setRotation(value);
13729        }
13730
13731        @Override
13732        public Float get(View object) {
13733            return object.getRotation();
13734        }
13735    };
13736
13737    /**
13738     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13739     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13740     */
13741    public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13742        @Override
13743        public void setValue(View object, float value) {
13744            object.setRotationX(value);
13745        }
13746
13747        @Override
13748        public Float get(View object) {
13749            return object.getRotationX();
13750        }
13751    };
13752
13753    /**
13754     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13755     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13756     */
13757    public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13758        @Override
13759        public void setValue(View object, float value) {
13760            object.setRotationY(value);
13761        }
13762
13763        @Override
13764        public Float get(View object) {
13765            return object.getRotationY();
13766        }
13767    };
13768
13769    /**
13770     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13771     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13772     */
13773    public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13774        @Override
13775        public void setValue(View object, float value) {
13776            object.setScaleX(value);
13777        }
13778
13779        @Override
13780        public Float get(View object) {
13781            return object.getScaleX();
13782        }
13783    };
13784
13785    /**
13786     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13787     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13788     */
13789    public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13790        @Override
13791        public void setValue(View object, float value) {
13792            object.setScaleY(value);
13793        }
13794
13795        @Override
13796        public Float get(View object) {
13797            return object.getScaleY();
13798        }
13799    };
13800
13801    /**
13802     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13803     * Each MeasureSpec represents a requirement for either the width or the height.
13804     * A MeasureSpec is comprised of a size and a mode. There are three possible
13805     * modes:
13806     * <dl>
13807     * <dt>UNSPECIFIED</dt>
13808     * <dd>
13809     * The parent has not imposed any constraint on the child. It can be whatever size
13810     * it wants.
13811     * </dd>
13812     *
13813     * <dt>EXACTLY</dt>
13814     * <dd>
13815     * The parent has determined an exact size for the child. The child is going to be
13816     * given those bounds regardless of how big it wants to be.
13817     * </dd>
13818     *
13819     * <dt>AT_MOST</dt>
13820     * <dd>
13821     * The child can be as large as it wants up to the specified size.
13822     * </dd>
13823     * </dl>
13824     *
13825     * MeasureSpecs are implemented as ints to reduce object allocation. This class
13826     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
13827     */
13828    public static class MeasureSpec {
13829        private static final int MODE_SHIFT = 30;
13830        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
13831
13832        /**
13833         * Measure specification mode: The parent has not imposed any constraint
13834         * on the child. It can be whatever size it wants.
13835         */
13836        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
13837
13838        /**
13839         * Measure specification mode: The parent has determined an exact size
13840         * for the child. The child is going to be given those bounds regardless
13841         * of how big it wants to be.
13842         */
13843        public static final int EXACTLY     = 1 << MODE_SHIFT;
13844
13845        /**
13846         * Measure specification mode: The child can be as large as it wants up
13847         * to the specified size.
13848         */
13849        public static final int AT_MOST     = 2 << MODE_SHIFT;
13850
13851        /**
13852         * Creates a measure specification based on the supplied size and mode.
13853         *
13854         * The mode must always be one of the following:
13855         * <ul>
13856         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
13857         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
13858         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
13859         * </ul>
13860         *
13861         * @param size the size of the measure specification
13862         * @param mode the mode of the measure specification
13863         * @return the measure specification based on size and mode
13864         */
13865        public static int makeMeasureSpec(int size, int mode) {
13866            return size + mode;
13867        }
13868
13869        /**
13870         * Extracts the mode from the supplied measure specification.
13871         *
13872         * @param measureSpec the measure specification to extract the mode from
13873         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
13874         *         {@link android.view.View.MeasureSpec#AT_MOST} or
13875         *         {@link android.view.View.MeasureSpec#EXACTLY}
13876         */
13877        public static int getMode(int measureSpec) {
13878            return (measureSpec & MODE_MASK);
13879        }
13880
13881        /**
13882         * Extracts the size from the supplied measure specification.
13883         *
13884         * @param measureSpec the measure specification to extract the size from
13885         * @return the size in pixels defined in the supplied measure specification
13886         */
13887        public static int getSize(int measureSpec) {
13888            return (measureSpec & ~MODE_MASK);
13889        }
13890
13891        /**
13892         * Returns a String representation of the specified measure
13893         * specification.
13894         *
13895         * @param measureSpec the measure specification to convert to a String
13896         * @return a String with the following format: "MeasureSpec: MODE SIZE"
13897         */
13898        public static String toString(int measureSpec) {
13899            int mode = getMode(measureSpec);
13900            int size = getSize(measureSpec);
13901
13902            StringBuilder sb = new StringBuilder("MeasureSpec: ");
13903
13904            if (mode == UNSPECIFIED)
13905                sb.append("UNSPECIFIED ");
13906            else if (mode == EXACTLY)
13907                sb.append("EXACTLY ");
13908            else if (mode == AT_MOST)
13909                sb.append("AT_MOST ");
13910            else
13911                sb.append(mode).append(" ");
13912
13913            sb.append(size);
13914            return sb.toString();
13915        }
13916    }
13917
13918    class CheckForLongPress implements Runnable {
13919
13920        private int mOriginalWindowAttachCount;
13921
13922        public void run() {
13923            if (isPressed() && (mParent != null)
13924                    && mOriginalWindowAttachCount == mWindowAttachCount) {
13925                if (performLongClick()) {
13926                    mHasPerformedLongPress = true;
13927                }
13928            }
13929        }
13930
13931        public void rememberWindowAttachCount() {
13932            mOriginalWindowAttachCount = mWindowAttachCount;
13933        }
13934    }
13935
13936    private final class CheckForTap implements Runnable {
13937        public void run() {
13938            mPrivateFlags &= ~PREPRESSED;
13939            mPrivateFlags |= PRESSED;
13940            refreshDrawableState();
13941            checkForLongClick(ViewConfiguration.getTapTimeout());
13942        }
13943    }
13944
13945    private final class PerformClick implements Runnable {
13946        public void run() {
13947            performClick();
13948        }
13949    }
13950
13951    /** @hide */
13952    public void hackTurnOffWindowResizeAnim(boolean off) {
13953        mAttachInfo.mTurnOffWindowResizeAnim = off;
13954    }
13955
13956    /**
13957     * This method returns a ViewPropertyAnimator object, which can be used to animate
13958     * specific properties on this View.
13959     *
13960     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
13961     */
13962    public ViewPropertyAnimator animate() {
13963        if (mAnimator == null) {
13964            mAnimator = new ViewPropertyAnimator(this);
13965        }
13966        return mAnimator;
13967    }
13968
13969    /**
13970     * Interface definition for a callback to be invoked when a key event is
13971     * dispatched to this view. The callback will be invoked before the key
13972     * event is given to the view.
13973     */
13974    public interface OnKeyListener {
13975        /**
13976         * Called when a key is dispatched to a view. This allows listeners to
13977         * get a chance to respond before the target view.
13978         *
13979         * @param v The view the key has been dispatched to.
13980         * @param keyCode The code for the physical key that was pressed
13981         * @param event The KeyEvent object containing full information about
13982         *        the event.
13983         * @return True if the listener has consumed the event, false otherwise.
13984         */
13985        boolean onKey(View v, int keyCode, KeyEvent event);
13986    }
13987
13988    /**
13989     * Interface definition for a callback to be invoked when a touch event is
13990     * dispatched to this view. The callback will be invoked before the touch
13991     * event is given to the view.
13992     */
13993    public interface OnTouchListener {
13994        /**
13995         * Called when a touch event is dispatched to a view. This allows listeners to
13996         * get a chance to respond before the target view.
13997         *
13998         * @param v The view the touch event has been dispatched to.
13999         * @param event The MotionEvent object containing full information about
14000         *        the event.
14001         * @return True if the listener has consumed the event, false otherwise.
14002         */
14003        boolean onTouch(View v, MotionEvent event);
14004    }
14005
14006    /**
14007     * Interface definition for a callback to be invoked when a hover event is
14008     * dispatched to this view. The callback will be invoked before the hover
14009     * event is given to the view.
14010     */
14011    public interface OnHoverListener {
14012        /**
14013         * Called when a hover event is dispatched to a view. This allows listeners to
14014         * get a chance to respond before the target view.
14015         *
14016         * @param v The view the hover event has been dispatched to.
14017         * @param event The MotionEvent object containing full information about
14018         *        the event.
14019         * @return True if the listener has consumed the event, false otherwise.
14020         */
14021        boolean onHover(View v, MotionEvent event);
14022    }
14023
14024    /**
14025     * Interface definition for a callback to be invoked when a generic motion event is
14026     * dispatched to this view. The callback will be invoked before the generic motion
14027     * event is given to the view.
14028     */
14029    public interface OnGenericMotionListener {
14030        /**
14031         * Called when a generic motion event is dispatched to a view. This allows listeners to
14032         * get a chance to respond before the target view.
14033         *
14034         * @param v The view the generic motion event has been dispatched to.
14035         * @param event The MotionEvent object containing full information about
14036         *        the event.
14037         * @return True if the listener has consumed the event, false otherwise.
14038         */
14039        boolean onGenericMotion(View v, MotionEvent event);
14040    }
14041
14042    /**
14043     * Interface definition for a callback to be invoked when a view has been clicked and held.
14044     */
14045    public interface OnLongClickListener {
14046        /**
14047         * Called when a view has been clicked and held.
14048         *
14049         * @param v The view that was clicked and held.
14050         *
14051         * @return true if the callback consumed the long click, false otherwise.
14052         */
14053        boolean onLongClick(View v);
14054    }
14055
14056    /**
14057     * Interface definition for a callback to be invoked when a drag is being dispatched
14058     * to this view.  The callback will be invoked before the hosting view's own
14059     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14060     * onDrag(event) behavior, it should return 'false' from this callback.
14061     */
14062    public interface OnDragListener {
14063        /**
14064         * Called when a drag event is dispatched to a view. This allows listeners
14065         * to get a chance to override base View behavior.
14066         *
14067         * @param v The View that received the drag event.
14068         * @param event The {@link android.view.DragEvent} object for the drag event.
14069         * @return {@code true} if the drag event was handled successfully, or {@code false}
14070         * if the drag event was not handled. Note that {@code false} will trigger the View
14071         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14072         */
14073        boolean onDrag(View v, DragEvent event);
14074    }
14075
14076    /**
14077     * Interface definition for a callback to be invoked when the focus state of
14078     * a view changed.
14079     */
14080    public interface OnFocusChangeListener {
14081        /**
14082         * Called when the focus state of a view has changed.
14083         *
14084         * @param v The view whose state has changed.
14085         * @param hasFocus The new focus state of v.
14086         */
14087        void onFocusChange(View v, boolean hasFocus);
14088    }
14089
14090    /**
14091     * Interface definition for a callback to be invoked when a view is clicked.
14092     */
14093    public interface OnClickListener {
14094        /**
14095         * Called when a view has been clicked.
14096         *
14097         * @param v The view that was clicked.
14098         */
14099        void onClick(View v);
14100    }
14101
14102    /**
14103     * Interface definition for a callback to be invoked when the context menu
14104     * for this view is being built.
14105     */
14106    public interface OnCreateContextMenuListener {
14107        /**
14108         * Called when the context menu for this view is being built. It is not
14109         * safe to hold onto the menu after this method returns.
14110         *
14111         * @param menu The context menu that is being built
14112         * @param v The view for which the context menu is being built
14113         * @param menuInfo Extra information about the item for which the
14114         *            context menu should be shown. This information will vary
14115         *            depending on the class of v.
14116         */
14117        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14118    }
14119
14120    /**
14121     * Interface definition for a callback to be invoked when the status bar changes
14122     * visibility.  This reports <strong>global</strong> changes to the system UI
14123     * state, not just what the application is requesting.
14124     *
14125     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14126     */
14127    public interface OnSystemUiVisibilityChangeListener {
14128        /**
14129         * Called when the status bar changes visibility because of a call to
14130         * {@link View#setSystemUiVisibility(int)}.
14131         *
14132         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14133         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
14134         * <strong>global</strong> state of the UI visibility flags, not what your
14135         * app is currently applying.
14136         */
14137        public void onSystemUiVisibilityChange(int visibility);
14138    }
14139
14140    /**
14141     * Interface definition for a callback to be invoked when this view is attached
14142     * or detached from its window.
14143     */
14144    public interface OnAttachStateChangeListener {
14145        /**
14146         * Called when the view is attached to a window.
14147         * @param v The view that was attached
14148         */
14149        public void onViewAttachedToWindow(View v);
14150        /**
14151         * Called when the view is detached from a window.
14152         * @param v The view that was detached
14153         */
14154        public void onViewDetachedFromWindow(View v);
14155    }
14156
14157    private final class UnsetPressedState implements Runnable {
14158        public void run() {
14159            setPressed(false);
14160        }
14161    }
14162
14163    /**
14164     * Base class for derived classes that want to save and restore their own
14165     * state in {@link android.view.View#onSaveInstanceState()}.
14166     */
14167    public static class BaseSavedState extends AbsSavedState {
14168        /**
14169         * Constructor used when reading from a parcel. Reads the state of the superclass.
14170         *
14171         * @param source
14172         */
14173        public BaseSavedState(Parcel source) {
14174            super(source);
14175        }
14176
14177        /**
14178         * Constructor called by derived classes when creating their SavedState objects
14179         *
14180         * @param superState The state of the superclass of this view
14181         */
14182        public BaseSavedState(Parcelable superState) {
14183            super(superState);
14184        }
14185
14186        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14187                new Parcelable.Creator<BaseSavedState>() {
14188            public BaseSavedState createFromParcel(Parcel in) {
14189                return new BaseSavedState(in);
14190            }
14191
14192            public BaseSavedState[] newArray(int size) {
14193                return new BaseSavedState[size];
14194            }
14195        };
14196    }
14197
14198    /**
14199     * A set of information given to a view when it is attached to its parent
14200     * window.
14201     */
14202    static class AttachInfo {
14203        interface Callbacks {
14204            void playSoundEffect(int effectId);
14205            boolean performHapticFeedback(int effectId, boolean always);
14206        }
14207
14208        /**
14209         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14210         * to a Handler. This class contains the target (View) to invalidate and
14211         * the coordinates of the dirty rectangle.
14212         *
14213         * For performance purposes, this class also implements a pool of up to
14214         * POOL_LIMIT objects that get reused. This reduces memory allocations
14215         * whenever possible.
14216         */
14217        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14218            private static final int POOL_LIMIT = 10;
14219            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14220                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14221                        public InvalidateInfo newInstance() {
14222                            return new InvalidateInfo();
14223                        }
14224
14225                        public void onAcquired(InvalidateInfo element) {
14226                        }
14227
14228                        public void onReleased(InvalidateInfo element) {
14229                            element.target = null;
14230                        }
14231                    }, POOL_LIMIT)
14232            );
14233
14234            private InvalidateInfo mNext;
14235            private boolean mIsPooled;
14236
14237            View target;
14238
14239            int left;
14240            int top;
14241            int right;
14242            int bottom;
14243
14244            public void setNextPoolable(InvalidateInfo element) {
14245                mNext = element;
14246            }
14247
14248            public InvalidateInfo getNextPoolable() {
14249                return mNext;
14250            }
14251
14252            static InvalidateInfo acquire() {
14253                return sPool.acquire();
14254            }
14255
14256            void release() {
14257                sPool.release(this);
14258            }
14259
14260            public boolean isPooled() {
14261                return mIsPooled;
14262            }
14263
14264            public void setPooled(boolean isPooled) {
14265                mIsPooled = isPooled;
14266            }
14267        }
14268
14269        final IWindowSession mSession;
14270
14271        final IWindow mWindow;
14272
14273        final IBinder mWindowToken;
14274
14275        final Callbacks mRootCallbacks;
14276
14277        HardwareCanvas mHardwareCanvas;
14278
14279        /**
14280         * The top view of the hierarchy.
14281         */
14282        View mRootView;
14283
14284        IBinder mPanelParentWindowToken;
14285        Surface mSurface;
14286
14287        boolean mHardwareAccelerated;
14288        boolean mHardwareAccelerationRequested;
14289        HardwareRenderer mHardwareRenderer;
14290
14291        /**
14292         * Scale factor used by the compatibility mode
14293         */
14294        float mApplicationScale;
14295
14296        /**
14297         * Indicates whether the application is in compatibility mode
14298         */
14299        boolean mScalingRequired;
14300
14301        /**
14302         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14303         */
14304        boolean mTurnOffWindowResizeAnim;
14305
14306        /**
14307         * Left position of this view's window
14308         */
14309        int mWindowLeft;
14310
14311        /**
14312         * Top position of this view's window
14313         */
14314        int mWindowTop;
14315
14316        /**
14317         * Indicates whether views need to use 32-bit drawing caches
14318         */
14319        boolean mUse32BitDrawingCache;
14320
14321        /**
14322         * For windows that are full-screen but using insets to layout inside
14323         * of the screen decorations, these are the current insets for the
14324         * content of the window.
14325         */
14326        final Rect mContentInsets = new Rect();
14327
14328        /**
14329         * For windows that are full-screen but using insets to layout inside
14330         * of the screen decorations, these are the current insets for the
14331         * actual visible parts of the window.
14332         */
14333        final Rect mVisibleInsets = new Rect();
14334
14335        /**
14336         * The internal insets given by this window.  This value is
14337         * supplied by the client (through
14338         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14339         * be given to the window manager when changed to be used in laying
14340         * out windows behind it.
14341         */
14342        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14343                = new ViewTreeObserver.InternalInsetsInfo();
14344
14345        /**
14346         * All views in the window's hierarchy that serve as scroll containers,
14347         * used to determine if the window can be resized or must be panned
14348         * to adjust for a soft input area.
14349         */
14350        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14351
14352        final KeyEvent.DispatcherState mKeyDispatchState
14353                = new KeyEvent.DispatcherState();
14354
14355        /**
14356         * Indicates whether the view's window currently has the focus.
14357         */
14358        boolean mHasWindowFocus;
14359
14360        /**
14361         * The current visibility of the window.
14362         */
14363        int mWindowVisibility;
14364
14365        /**
14366         * Indicates the time at which drawing started to occur.
14367         */
14368        long mDrawingTime;
14369
14370        /**
14371         * Indicates whether or not ignoring the DIRTY_MASK flags.
14372         */
14373        boolean mIgnoreDirtyState;
14374
14375        /**
14376         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14377         * to avoid clearing that flag prematurely.
14378         */
14379        boolean mSetIgnoreDirtyState = false;
14380
14381        /**
14382         * Indicates whether the view's window is currently in touch mode.
14383         */
14384        boolean mInTouchMode;
14385
14386        /**
14387         * Indicates that ViewAncestor should trigger a global layout change
14388         * the next time it performs a traversal
14389         */
14390        boolean mRecomputeGlobalAttributes;
14391
14392        /**
14393         * Always report new attributes at next traversal.
14394         */
14395        boolean mForceReportNewAttributes;
14396
14397        /**
14398         * Set during a traveral if any views want to keep the screen on.
14399         */
14400        boolean mKeepScreenOn;
14401
14402        /**
14403         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14404         */
14405        int mSystemUiVisibility;
14406
14407        /**
14408         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14409         * attached.
14410         */
14411        boolean mHasSystemUiListeners;
14412
14413        /**
14414         * Set if the visibility of any views has changed.
14415         */
14416        boolean mViewVisibilityChanged;
14417
14418        /**
14419         * Set to true if a view has been scrolled.
14420         */
14421        boolean mViewScrollChanged;
14422
14423        /**
14424         * Global to the view hierarchy used as a temporary for dealing with
14425         * x/y points in the transparent region computations.
14426         */
14427        final int[] mTransparentLocation = new int[2];
14428
14429        /**
14430         * Global to the view hierarchy used as a temporary for dealing with
14431         * x/y points in the ViewGroup.invalidateChild implementation.
14432         */
14433        final int[] mInvalidateChildLocation = new int[2];
14434
14435
14436        /**
14437         * Global to the view hierarchy used as a temporary for dealing with
14438         * x/y location when view is transformed.
14439         */
14440        final float[] mTmpTransformLocation = new float[2];
14441
14442        /**
14443         * The view tree observer used to dispatch global events like
14444         * layout, pre-draw, touch mode change, etc.
14445         */
14446        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14447
14448        /**
14449         * A Canvas used by the view hierarchy to perform bitmap caching.
14450         */
14451        Canvas mCanvas;
14452
14453        /**
14454         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14455         * handler can be used to pump events in the UI events queue.
14456         */
14457        final Handler mHandler;
14458
14459        /**
14460         * Identifier for messages requesting the view to be invalidated.
14461         * Such messages should be sent to {@link #mHandler}.
14462         */
14463        static final int INVALIDATE_MSG = 0x1;
14464
14465        /**
14466         * Identifier for messages requesting the view to invalidate a region.
14467         * Such messages should be sent to {@link #mHandler}.
14468         */
14469        static final int INVALIDATE_RECT_MSG = 0x2;
14470
14471        /**
14472         * Temporary for use in computing invalidate rectangles while
14473         * calling up the hierarchy.
14474         */
14475        final Rect mTmpInvalRect = new Rect();
14476
14477        /**
14478         * Temporary for use in computing hit areas with transformed views
14479         */
14480        final RectF mTmpTransformRect = new RectF();
14481
14482        /**
14483         * Temporary list for use in collecting focusable descendents of a view.
14484         */
14485        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14486
14487        /**
14488         * The id of the window for accessibility purposes.
14489         */
14490        int mAccessibilityWindowId = View.NO_ID;
14491
14492        /**
14493         * Creates a new set of attachment information with the specified
14494         * events handler and thread.
14495         *
14496         * @param handler the events handler the view must use
14497         */
14498        AttachInfo(IWindowSession session, IWindow window,
14499                Handler handler, Callbacks effectPlayer) {
14500            mSession = session;
14501            mWindow = window;
14502            mWindowToken = window.asBinder();
14503            mHandler = handler;
14504            mRootCallbacks = effectPlayer;
14505        }
14506    }
14507
14508    /**
14509     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14510     * is supported. This avoids keeping too many unused fields in most
14511     * instances of View.</p>
14512     */
14513    private static class ScrollabilityCache implements Runnable {
14514
14515        /**
14516         * Scrollbars are not visible
14517         */
14518        public static final int OFF = 0;
14519
14520        /**
14521         * Scrollbars are visible
14522         */
14523        public static final int ON = 1;
14524
14525        /**
14526         * Scrollbars are fading away
14527         */
14528        public static final int FADING = 2;
14529
14530        public boolean fadeScrollBars;
14531
14532        public int fadingEdgeLength;
14533        public int scrollBarDefaultDelayBeforeFade;
14534        public int scrollBarFadeDuration;
14535
14536        public int scrollBarSize;
14537        public ScrollBarDrawable scrollBar;
14538        public float[] interpolatorValues;
14539        public View host;
14540
14541        public final Paint paint;
14542        public final Matrix matrix;
14543        public Shader shader;
14544
14545        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14546
14547        private static final float[] OPAQUE = { 255 };
14548        private static final float[] TRANSPARENT = { 0.0f };
14549
14550        /**
14551         * When fading should start. This time moves into the future every time
14552         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14553         */
14554        public long fadeStartTime;
14555
14556
14557        /**
14558         * The current state of the scrollbars: ON, OFF, or FADING
14559         */
14560        public int state = OFF;
14561
14562        private int mLastColor;
14563
14564        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14565            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14566            scrollBarSize = configuration.getScaledScrollBarSize();
14567            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14568            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14569
14570            paint = new Paint();
14571            matrix = new Matrix();
14572            // use use a height of 1, and then wack the matrix each time we
14573            // actually use it.
14574            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14575
14576            paint.setShader(shader);
14577            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14578            this.host = host;
14579        }
14580
14581        public void setFadeColor(int color) {
14582            if (color != 0 && color != mLastColor) {
14583                mLastColor = color;
14584                color |= 0xFF000000;
14585
14586                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14587                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14588
14589                paint.setShader(shader);
14590                // Restore the default transfer mode (src_over)
14591                paint.setXfermode(null);
14592            }
14593        }
14594
14595        public void run() {
14596            long now = AnimationUtils.currentAnimationTimeMillis();
14597            if (now >= fadeStartTime) {
14598
14599                // the animation fades the scrollbars out by changing
14600                // the opacity (alpha) from fully opaque to fully
14601                // transparent
14602                int nextFrame = (int) now;
14603                int framesCount = 0;
14604
14605                Interpolator interpolator = scrollBarInterpolator;
14606
14607                // Start opaque
14608                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14609
14610                // End transparent
14611                nextFrame += scrollBarFadeDuration;
14612                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14613
14614                state = FADING;
14615
14616                // Kick off the fade animation
14617                host.invalidate(true);
14618            }
14619        }
14620    }
14621
14622    /**
14623     * Resuable callback for sending
14624     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14625     */
14626    private class SendViewScrolledAccessibilityEvent implements Runnable {
14627        public volatile boolean mIsPending;
14628
14629        public void run() {
14630            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14631            mIsPending = false;
14632        }
14633    }
14634
14635    /**
14636     * <p>
14637     * This class represents a delegate that can be registered in a {@link View}
14638     * to enhance accessibility support via composition rather via inheritance.
14639     * It is specifically targeted to widget developers that extend basic View
14640     * classes i.e. classes in package android.view, that would like their
14641     * applications to be backwards compatible.
14642     * </p>
14643     * <p>
14644     * A scenario in which a developer would like to use an accessibility delegate
14645     * is overriding a method introduced in a later API version then the minimal API
14646     * version supported by the application. For example, the method
14647     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
14648     * in API version 4 when the accessibility APIs were first introduced. If a
14649     * developer would like his application to run on API version 4 devices (assuming
14650     * all other APIs used by the application are version 4 or lower) and take advantage
14651     * of this method, instead of overriding the method which would break the application's
14652     * backwards compatibility, he can override the corresponding method in this
14653     * delegate and register the delegate in the target View if the API version of
14654     * the system is high enough i.e. the API version is same or higher to the API
14655     * version that introduced
14656     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
14657     * </p>
14658     * <p>
14659     * Here is an example implementation:
14660     * </p>
14661     * <code><pre><p>
14662     * if (Build.VERSION.SDK_INT >= 14) {
14663     *     // If the API version is equal of higher than the version in
14664     *     // which onInitializeAccessibilityNodeInfo was introduced we
14665     *     // register a delegate with a customized implementation.
14666     *     View view = findViewById(R.id.view_id);
14667     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
14668     *         public void onInitializeAccessibilityNodeInfo(View host,
14669     *                 AccessibilityNodeInfo info) {
14670     *             // Let the default implementation populate the info.
14671     *             super.onInitializeAccessibilityNodeInfo(host, info);
14672     *             // Set some other information.
14673     *             info.setEnabled(host.isEnabled());
14674     *         }
14675     *     });
14676     * }
14677     * </code></pre></p>
14678     * <p>
14679     * This delegate contains methods that correspond to the accessibility methods
14680     * in View. If a delegate has been specified the implementation in View hands
14681     * off handling to the corresponding method in this delegate. The default
14682     * implementation the delegate methods behaves exactly as the corresponding
14683     * method in View for the case of no accessibility delegate been set. Hence,
14684     * to customize the behavior of a View method, clients can override only the
14685     * corresponding delegate method without altering the behavior of the rest
14686     * accessibility related methods of the host view.
14687     * </p>
14688     */
14689    public static class AccessibilityDelegate {
14690
14691        /**
14692         * Sends an accessibility event of the given type. If accessibility is not
14693         * enabled this method has no effect.
14694         * <p>
14695         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
14696         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
14697         * been set.
14698         * </p>
14699         *
14700         * @param host The View hosting the delegate.
14701         * @param eventType The type of the event to send.
14702         *
14703         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
14704         */
14705        public void sendAccessibilityEvent(View host, int eventType) {
14706            host.sendAccessibilityEventInternal(eventType);
14707        }
14708
14709        /**
14710         * Sends an accessibility event. This method behaves exactly as
14711         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
14712         * empty {@link AccessibilityEvent} and does not perform a check whether
14713         * accessibility is enabled.
14714         * <p>
14715         * The default implementation behaves as
14716         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14717         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
14718         * the case of no accessibility delegate been set.
14719         * </p>
14720         *
14721         * @param host The View hosting the delegate.
14722         * @param event The event to send.
14723         *
14724         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14725         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14726         */
14727        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
14728            host.sendAccessibilityEventUncheckedInternal(event);
14729        }
14730
14731        /**
14732         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
14733         * to its children for adding their text content to the event.
14734         * <p>
14735         * The default implementation behaves as
14736         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14737         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
14738         * the case of no accessibility delegate been set.
14739         * </p>
14740         *
14741         * @param host The View hosting the delegate.
14742         * @param event The event.
14743         * @return True if the event population was completed.
14744         *
14745         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14746         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14747         */
14748        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14749            return host.dispatchPopulateAccessibilityEventInternal(event);
14750        }
14751
14752        /**
14753         * Gives a chance to the host View to populate the accessibility event with its
14754         * text content.
14755         * <p>
14756         * The default implementation behaves as
14757         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
14758         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
14759         * the case of no accessibility delegate been set.
14760         * </p>
14761         *
14762         * @param host The View hosting the delegate.
14763         * @param event The accessibility event which to populate.
14764         *
14765         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
14766         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
14767         */
14768        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14769            host.onPopulateAccessibilityEventInternal(event);
14770        }
14771
14772        /**
14773         * Initializes an {@link AccessibilityEvent} with information about the
14774         * the host View which is the event source.
14775         * <p>
14776         * The default implementation behaves as
14777         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
14778         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
14779         * the case of no accessibility delegate been set.
14780         * </p>
14781         *
14782         * @param host The View hosting the delegate.
14783         * @param event The event to initialize.
14784         *
14785         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
14786         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
14787         */
14788        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
14789            host.onInitializeAccessibilityEventInternal(event);
14790        }
14791
14792        /**
14793         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
14794         * <p>
14795         * The default implementation behaves as
14796         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14797         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
14798         * the case of no accessibility delegate been set.
14799         * </p>
14800         *
14801         * @param host The View hosting the delegate.
14802         * @param info The instance to initialize.
14803         *
14804         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14805         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14806         */
14807        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
14808            host.onInitializeAccessibilityNodeInfoInternal(info);
14809        }
14810
14811        /**
14812         * Called when a child of the host View has requested sending an
14813         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
14814         * to augment the event.
14815         * <p>
14816         * The default implementation behaves as
14817         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14818         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
14819         * the case of no accessibility delegate been set.
14820         * </p>
14821         *
14822         * @param host The View hosting the delegate.
14823         * @param child The child which requests sending the event.
14824         * @param event The event to be sent.
14825         * @return True if the event should be sent
14826         *
14827         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14828         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14829         */
14830        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
14831                AccessibilityEvent event) {
14832            return host.onRequestSendAccessibilityEventInternal(child, event);
14833        }
14834    }
14835}
14836