View.java revision 12df3cf156885a421beccfa6b6e20fd1a188847a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.text.TextUtils;
49import android.util.AttributeSet;
50import android.util.FloatProperty;
51import android.util.LocaleUtil;
52import android.util.Log;
53import android.util.Pool;
54import android.util.Poolable;
55import android.util.PoolableManager;
56import android.util.Pools;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.accessibility.AccessibilityNodeProvider;
66import android.view.animation.Animation;
67import android.view.animation.AnimationUtils;
68import android.view.inputmethod.EditorInfo;
69import android.view.inputmethod.InputConnection;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.ScrollBarDrawable;
72
73import static android.os.Build.VERSION_CODES.*;
74
75import com.android.internal.R;
76import com.android.internal.util.Predicate;
77import com.android.internal.view.menu.MenuBuilder;
78
79import java.lang.ref.WeakReference;
80import java.lang.reflect.InvocationTargetException;
81import java.lang.reflect.Method;
82import java.util.ArrayList;
83import java.util.Arrays;
84import java.util.Locale;
85import java.util.concurrent.CopyOnWriteArrayList;
86
87/**
88 * <p>
89 * This class represents the basic building block for user interface components. A View
90 * occupies a rectangular area on the screen and is responsible for drawing and
91 * event handling. View is the base class for <em>widgets</em>, which are
92 * used to create interactive UI components (buttons, text fields, etc.). The
93 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
94 * are invisible containers that hold other Views (or other ViewGroups) and define
95 * their layout properties.
96 * </p>
97 *
98 * <div class="special reference">
99 * <h3>Developer Guides</h3>
100 * <p>For information about using this class to develop your application's user interface,
101 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
102 * </div>
103 *
104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
129 * Other view subclasses offer more specialized listeners. For example, a Button
130 * exposes a listener to notify clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility(int)}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 *     <thead>
152 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 *     </thead>
154 *
155 *     <tbody>
156 *     <tr>
157 *         <td rowspan="2">Creation</td>
158 *         <td>Constructors</td>
159 *         <td>There is a form of the constructor that are called when the view
160 *         is created from code and a form that is called when the view is
161 *         inflated from a layout file. The second form should parse and apply
162 *         any attributes defined in the layout file.
163 *         </td>
164 *     </tr>
165 *     <tr>
166 *         <td><code>{@link #onFinishInflate()}</code></td>
167 *         <td>Called after a view and all of its children has been inflated
168 *         from XML.</td>
169 *     </tr>
170 *
171 *     <tr>
172 *         <td rowspan="3">Layout</td>
173 *         <td><code>{@link #onMeasure(int, int)}</code></td>
174 *         <td>Called to determine the size requirements for this view and all
175 *         of its children.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
180 *         <td>Called when this view should assign a size and position to all
181 *         of its children.
182 *         </td>
183 *     </tr>
184 *     <tr>
185 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
186 *         <td>Called when the size of this view has changed.
187 *         </td>
188 *     </tr>
189 *
190 *     <tr>
191 *         <td>Drawing</td>
192 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
193 *         <td>Called when the view should render its content.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="4">Event processing</td>
199 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
200 *         <td>Called when a new key event occurs.
201 *         </td>
202 *     </tr>
203 *     <tr>
204 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
205 *         <td>Called when a key up event occurs.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
210 *         <td>Called when a trackball motion event occurs.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
215 *         <td>Called when a touch screen motion event occurs.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td rowspan="2">Focus</td>
221 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
222 *         <td>Called when the view gains or loses focus.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
228 *         <td>Called when the window containing the view gains or loses focus.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="3">Attaching</td>
234 *         <td><code>{@link #onAttachedToWindow()}</code></td>
235 *         <td>Called when the view is attached to a window.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onDetachedFromWindow}</code></td>
241 *         <td>Called when the view is detached from its window.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
247 *         <td>Called when the visibility of the window containing the view
248 *         has changed.
249 *         </td>
250 *     </tr>
251 *     </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
264 * &lt;Button
265 *     android:id="@+id/my_button"
266 *     android:layout_width="wrap_content"
267 *     android:layout_height="wrap_content"
268 *     android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 *      Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
385 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
430 * Note that the framework will not draw views that are not in the invalid region.
431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input.  If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view.  This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode.  From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 * <p>
547 * Starting with Android 3.0, the preferred way of animating views is to use the
548 * {@link android.animation} package APIs.
549 * </p>
550 *
551 * <a name="Security"></a>
552 * <h3>Security</h3>
553 * <p>
554 * Sometimes it is essential that an application be able to verify that an action
555 * is being performed with the full knowledge and consent of the user, such as
556 * granting a permission request, making a purchase or clicking on an advertisement.
557 * Unfortunately, a malicious application could try to spoof the user into
558 * performing these actions, unaware, by concealing the intended purpose of the view.
559 * As a remedy, the framework offers a touch filtering mechanism that can be used to
560 * improve the security of views that provide access to sensitive functionality.
561 * </p><p>
562 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
563 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
564 * will discard touches that are received whenever the view's window is obscured by
565 * another visible window.  As a result, the view will not receive touches whenever a
566 * toast, dialog or other window appears above the view's window.
567 * </p><p>
568 * For more fine-grained control over security, consider overriding the
569 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
570 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
571 * </p>
572 *
573 * @attr ref android.R.styleable#View_alpha
574 * @attr ref android.R.styleable#View_background
575 * @attr ref android.R.styleable#View_clickable
576 * @attr ref android.R.styleable#View_contentDescription
577 * @attr ref android.R.styleable#View_drawingCacheQuality
578 * @attr ref android.R.styleable#View_duplicateParentState
579 * @attr ref android.R.styleable#View_id
580 * @attr ref android.R.styleable#View_requiresFadingEdge
581 * @attr ref android.R.styleable#View_fadingEdgeLength
582 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
583 * @attr ref android.R.styleable#View_fitsSystemWindows
584 * @attr ref android.R.styleable#View_isScrollContainer
585 * @attr ref android.R.styleable#View_focusable
586 * @attr ref android.R.styleable#View_focusableInTouchMode
587 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
588 * @attr ref android.R.styleable#View_keepScreenOn
589 * @attr ref android.R.styleable#View_layerType
590 * @attr ref android.R.styleable#View_longClickable
591 * @attr ref android.R.styleable#View_minHeight
592 * @attr ref android.R.styleable#View_minWidth
593 * @attr ref android.R.styleable#View_nextFocusDown
594 * @attr ref android.R.styleable#View_nextFocusLeft
595 * @attr ref android.R.styleable#View_nextFocusRight
596 * @attr ref android.R.styleable#View_nextFocusUp
597 * @attr ref android.R.styleable#View_onClick
598 * @attr ref android.R.styleable#View_padding
599 * @attr ref android.R.styleable#View_paddingBottom
600 * @attr ref android.R.styleable#View_paddingLeft
601 * @attr ref android.R.styleable#View_paddingRight
602 * @attr ref android.R.styleable#View_paddingTop
603 * @attr ref android.R.styleable#View_saveEnabled
604 * @attr ref android.R.styleable#View_rotation
605 * @attr ref android.R.styleable#View_rotationX
606 * @attr ref android.R.styleable#View_rotationY
607 * @attr ref android.R.styleable#View_scaleX
608 * @attr ref android.R.styleable#View_scaleY
609 * @attr ref android.R.styleable#View_scrollX
610 * @attr ref android.R.styleable#View_scrollY
611 * @attr ref android.R.styleable#View_scrollbarSize
612 * @attr ref android.R.styleable#View_scrollbarStyle
613 * @attr ref android.R.styleable#View_scrollbars
614 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
615 * @attr ref android.R.styleable#View_scrollbarFadeDuration
616 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
617 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
618 * @attr ref android.R.styleable#View_scrollbarThumbVertical
619 * @attr ref android.R.styleable#View_scrollbarTrackVertical
620 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
621 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
622 * @attr ref android.R.styleable#View_soundEffectsEnabled
623 * @attr ref android.R.styleable#View_tag
624 * @attr ref android.R.styleable#View_transformPivotX
625 * @attr ref android.R.styleable#View_transformPivotY
626 * @attr ref android.R.styleable#View_translationX
627 * @attr ref android.R.styleable#View_translationY
628 * @attr ref android.R.styleable#View_visibility
629 *
630 * @see android.view.ViewGroup
631 */
632public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
633        AccessibilityEventSource {
634    private static final boolean DBG = false;
635
636    /**
637     * The logging tag used by this class with android.util.Log.
638     */
639    protected static final String VIEW_LOG_TAG = "View";
640
641    /**
642     * Used to mark a View that has no ID.
643     */
644    public static final int NO_ID = -1;
645
646    /**
647     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
648     * calling setFlags.
649     */
650    private static final int NOT_FOCUSABLE = 0x00000000;
651
652    /**
653     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
654     * setFlags.
655     */
656    private static final int FOCUSABLE = 0x00000001;
657
658    /**
659     * Mask for use with setFlags indicating bits used for focus.
660     */
661    private static final int FOCUSABLE_MASK = 0x00000001;
662
663    /**
664     * This view will adjust its padding to fit sytem windows (e.g. status bar)
665     */
666    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
667
668    /**
669     * This view is visible.
670     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
671     * android:visibility}.
672     */
673    public static final int VISIBLE = 0x00000000;
674
675    /**
676     * This view is invisible, but it still takes up space for layout purposes.
677     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
678     * android:visibility}.
679     */
680    public static final int INVISIBLE = 0x00000004;
681
682    /**
683     * This view is invisible, and it doesn't take any space for layout
684     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
685     * android:visibility}.
686     */
687    public static final int GONE = 0x00000008;
688
689    /**
690     * Mask for use with setFlags indicating bits used for visibility.
691     * {@hide}
692     */
693    static final int VISIBILITY_MASK = 0x0000000C;
694
695    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
696
697    /**
698     * This view is enabled. Intrepretation varies by subclass.
699     * Use with ENABLED_MASK when calling setFlags.
700     * {@hide}
701     */
702    static final int ENABLED = 0x00000000;
703
704    /**
705     * This view is disabled. Intrepretation varies by subclass.
706     * Use with ENABLED_MASK when calling setFlags.
707     * {@hide}
708     */
709    static final int DISABLED = 0x00000020;
710
711   /**
712    * Mask for use with setFlags indicating bits used for indicating whether
713    * this view is enabled
714    * {@hide}
715    */
716    static final int ENABLED_MASK = 0x00000020;
717
718    /**
719     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
720     * called and further optimizations will be performed. It is okay to have
721     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
722     * {@hide}
723     */
724    static final int WILL_NOT_DRAW = 0x00000080;
725
726    /**
727     * Mask for use with setFlags indicating bits used for indicating whether
728     * this view is will draw
729     * {@hide}
730     */
731    static final int DRAW_MASK = 0x00000080;
732
733    /**
734     * <p>This view doesn't show scrollbars.</p>
735     * {@hide}
736     */
737    static final int SCROLLBARS_NONE = 0x00000000;
738
739    /**
740     * <p>This view shows horizontal scrollbars.</p>
741     * {@hide}
742     */
743    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
744
745    /**
746     * <p>This view shows vertical scrollbars.</p>
747     * {@hide}
748     */
749    static final int SCROLLBARS_VERTICAL = 0x00000200;
750
751    /**
752     * <p>Mask for use with setFlags indicating bits used for indicating which
753     * scrollbars are enabled.</p>
754     * {@hide}
755     */
756    static final int SCROLLBARS_MASK = 0x00000300;
757
758    /**
759     * Indicates that the view should filter touches when its window is obscured.
760     * Refer to the class comments for more information about this security feature.
761     * {@hide}
762     */
763    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
764
765    // note flag value 0x00000800 is now available for next flags...
766
767    /**
768     * <p>This view doesn't show fading edges.</p>
769     * {@hide}
770     */
771    static final int FADING_EDGE_NONE = 0x00000000;
772
773    /**
774     * <p>This view shows horizontal fading edges.</p>
775     * {@hide}
776     */
777    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
778
779    /**
780     * <p>This view shows vertical fading edges.</p>
781     * {@hide}
782     */
783    static final int FADING_EDGE_VERTICAL = 0x00002000;
784
785    /**
786     * <p>Mask for use with setFlags indicating bits used for indicating which
787     * fading edges are enabled.</p>
788     * {@hide}
789     */
790    static final int FADING_EDGE_MASK = 0x00003000;
791
792    /**
793     * <p>Indicates this view can be clicked. When clickable, a View reacts
794     * to clicks by notifying the OnClickListener.<p>
795     * {@hide}
796     */
797    static final int CLICKABLE = 0x00004000;
798
799    /**
800     * <p>Indicates this view is caching its drawing into a bitmap.</p>
801     * {@hide}
802     */
803    static final int DRAWING_CACHE_ENABLED = 0x00008000;
804
805    /**
806     * <p>Indicates that no icicle should be saved for this view.<p>
807     * {@hide}
808     */
809    static final int SAVE_DISABLED = 0x000010000;
810
811    /**
812     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
813     * property.</p>
814     * {@hide}
815     */
816    static final int SAVE_DISABLED_MASK = 0x000010000;
817
818    /**
819     * <p>Indicates that no drawing cache should ever be created for this view.<p>
820     * {@hide}
821     */
822    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
823
824    /**
825     * <p>Indicates this view can take / keep focus when int touch mode.</p>
826     * {@hide}
827     */
828    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
829
830    /**
831     * <p>Enables low quality mode for the drawing cache.</p>
832     */
833    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
834
835    /**
836     * <p>Enables high quality mode for the drawing cache.</p>
837     */
838    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
839
840    /**
841     * <p>Enables automatic quality mode for the drawing cache.</p>
842     */
843    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
844
845    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
846            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
847    };
848
849    /**
850     * <p>Mask for use with setFlags indicating bits used for the cache
851     * quality property.</p>
852     * {@hide}
853     */
854    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
855
856    /**
857     * <p>
858     * Indicates this view can be long clicked. When long clickable, a View
859     * reacts to long clicks by notifying the OnLongClickListener or showing a
860     * context menu.
861     * </p>
862     * {@hide}
863     */
864    static final int LONG_CLICKABLE = 0x00200000;
865
866    /**
867     * <p>Indicates that this view gets its drawable states from its direct parent
868     * and ignores its original internal states.</p>
869     *
870     * @hide
871     */
872    static final int DUPLICATE_PARENT_STATE = 0x00400000;
873
874    /**
875     * The scrollbar style to display the scrollbars inside the content area,
876     * without increasing the padding. The scrollbars will be overlaid with
877     * translucency on the view's content.
878     */
879    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
880
881    /**
882     * The scrollbar style to display the scrollbars inside the padded area,
883     * increasing the padding of the view. The scrollbars will not overlap the
884     * content area of the view.
885     */
886    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
887
888    /**
889     * The scrollbar style to display the scrollbars at the edge of the view,
890     * without increasing the padding. The scrollbars will be overlaid with
891     * translucency.
892     */
893    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
894
895    /**
896     * The scrollbar style to display the scrollbars at the edge of the view,
897     * increasing the padding of the view. The scrollbars will only overlap the
898     * background, if any.
899     */
900    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
901
902    /**
903     * Mask to check if the scrollbar style is overlay or inset.
904     * {@hide}
905     */
906    static final int SCROLLBARS_INSET_MASK = 0x01000000;
907
908    /**
909     * Mask to check if the scrollbar style is inside or outside.
910     * {@hide}
911     */
912    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
913
914    /**
915     * Mask for scrollbar style.
916     * {@hide}
917     */
918    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
919
920    /**
921     * View flag indicating that the screen should remain on while the
922     * window containing this view is visible to the user.  This effectively
923     * takes care of automatically setting the WindowManager's
924     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
925     */
926    public static final int KEEP_SCREEN_ON = 0x04000000;
927
928    /**
929     * View flag indicating whether this view should have sound effects enabled
930     * for events such as clicking and touching.
931     */
932    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
933
934    /**
935     * View flag indicating whether this view should have haptic feedback
936     * enabled for events such as long presses.
937     */
938    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
939
940    /**
941     * <p>Indicates that the view hierarchy should stop saving state when
942     * it reaches this view.  If state saving is initiated immediately at
943     * the view, it will be allowed.
944     * {@hide}
945     */
946    static final int PARENT_SAVE_DISABLED = 0x20000000;
947
948    /**
949     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
950     * {@hide}
951     */
952    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
953
954    /**
955     * Horizontal direction of this view is from Left to Right.
956     * Use with {@link #setLayoutDirection}.
957     * {@hide}
958     */
959    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
960
961    /**
962     * Horizontal direction of this view is from Right to Left.
963     * Use with {@link #setLayoutDirection}.
964     * {@hide}
965     */
966    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
967
968    /**
969     * Horizontal direction of this view is inherited from its parent.
970     * Use with {@link #setLayoutDirection}.
971     * {@hide}
972     */
973    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
974
975    /**
976     * Horizontal direction of this view is from deduced from the default language
977     * script for the locale. Use with {@link #setLayoutDirection}.
978     * {@hide}
979     */
980    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
981
982    /**
983     * Mask for use with setFlags indicating bits used for horizontalDirection.
984     * {@hide}
985     */
986    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
987
988    /*
989     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
990     * flag value.
991     * {@hide}
992     */
993    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
994        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
995
996    /**
997     * Default horizontalDirection.
998     * {@hide}
999     */
1000    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1001
1002    /**
1003     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1004     * should add all focusable Views regardless if they are focusable in touch mode.
1005     */
1006    public static final int FOCUSABLES_ALL = 0x00000000;
1007
1008    /**
1009     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1010     * should add only Views focusable in touch mode.
1011     */
1012    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1013
1014    /**
1015     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1016     * item.
1017     */
1018    public static final int FOCUS_BACKWARD = 0x00000001;
1019
1020    /**
1021     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1022     * item.
1023     */
1024    public static final int FOCUS_FORWARD = 0x00000002;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus to the left.
1028     */
1029    public static final int FOCUS_LEFT = 0x00000011;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move focus up.
1033     */
1034    public static final int FOCUS_UP = 0x00000021;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus to the right.
1038     */
1039    public static final int FOCUS_RIGHT = 0x00000042;
1040
1041    /**
1042     * Use with {@link #focusSearch(int)}. Move focus down.
1043     */
1044    public static final int FOCUS_DOWN = 0x00000082;
1045
1046    /**
1047     * Bits of {@link #getMeasuredWidthAndState()} and
1048     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1049     */
1050    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1051
1052    /**
1053     * Bits of {@link #getMeasuredWidthAndState()} and
1054     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1055     */
1056    public static final int MEASURED_STATE_MASK = 0xff000000;
1057
1058    /**
1059     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1060     * for functions that combine both width and height into a single int,
1061     * such as {@link #getMeasuredState()} and the childState argument of
1062     * {@link #resolveSizeAndState(int, int, int)}.
1063     */
1064    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1065
1066    /**
1067     * Bit of {@link #getMeasuredWidthAndState()} and
1068     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1069     * is smaller that the space the view would like to have.
1070     */
1071    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1072
1073    /**
1074     * Base View state sets
1075     */
1076    // Singles
1077    /**
1078     * Indicates the view has no states set. States are used with
1079     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1080     * view depending on its state.
1081     *
1082     * @see android.graphics.drawable.Drawable
1083     * @see #getDrawableState()
1084     */
1085    protected static final int[] EMPTY_STATE_SET;
1086    /**
1087     * Indicates the view is enabled. States are used with
1088     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1089     * view depending on its state.
1090     *
1091     * @see android.graphics.drawable.Drawable
1092     * @see #getDrawableState()
1093     */
1094    protected static final int[] ENABLED_STATE_SET;
1095    /**
1096     * Indicates the view is focused. States are used with
1097     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1098     * view depending on its state.
1099     *
1100     * @see android.graphics.drawable.Drawable
1101     * @see #getDrawableState()
1102     */
1103    protected static final int[] FOCUSED_STATE_SET;
1104    /**
1105     * Indicates the view is selected. States are used with
1106     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1107     * view depending on its state.
1108     *
1109     * @see android.graphics.drawable.Drawable
1110     * @see #getDrawableState()
1111     */
1112    protected static final int[] SELECTED_STATE_SET;
1113    /**
1114     * Indicates the view is pressed. States are used with
1115     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1116     * view depending on its state.
1117     *
1118     * @see android.graphics.drawable.Drawable
1119     * @see #getDrawableState()
1120     * @hide
1121     */
1122    protected static final int[] PRESSED_STATE_SET;
1123    /**
1124     * Indicates the view's window has focus. States are used with
1125     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1126     * view depending on its state.
1127     *
1128     * @see android.graphics.drawable.Drawable
1129     * @see #getDrawableState()
1130     */
1131    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1132    // Doubles
1133    /**
1134     * Indicates the view is enabled and has the focus.
1135     *
1136     * @see #ENABLED_STATE_SET
1137     * @see #FOCUSED_STATE_SET
1138     */
1139    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1140    /**
1141     * Indicates the view is enabled and selected.
1142     *
1143     * @see #ENABLED_STATE_SET
1144     * @see #SELECTED_STATE_SET
1145     */
1146    protected static final int[] ENABLED_SELECTED_STATE_SET;
1147    /**
1148     * Indicates the view is enabled and that its window has focus.
1149     *
1150     * @see #ENABLED_STATE_SET
1151     * @see #WINDOW_FOCUSED_STATE_SET
1152     */
1153    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1154    /**
1155     * Indicates the view is focused and selected.
1156     *
1157     * @see #FOCUSED_STATE_SET
1158     * @see #SELECTED_STATE_SET
1159     */
1160    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1161    /**
1162     * Indicates the view has the focus and that its window has the focus.
1163     *
1164     * @see #FOCUSED_STATE_SET
1165     * @see #WINDOW_FOCUSED_STATE_SET
1166     */
1167    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1168    /**
1169     * Indicates the view is selected and that its window has the focus.
1170     *
1171     * @see #SELECTED_STATE_SET
1172     * @see #WINDOW_FOCUSED_STATE_SET
1173     */
1174    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1175    // Triples
1176    /**
1177     * Indicates the view is enabled, focused and selected.
1178     *
1179     * @see #ENABLED_STATE_SET
1180     * @see #FOCUSED_STATE_SET
1181     * @see #SELECTED_STATE_SET
1182     */
1183    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1184    /**
1185     * Indicates the view is enabled, focused and its window has the focus.
1186     *
1187     * @see #ENABLED_STATE_SET
1188     * @see #FOCUSED_STATE_SET
1189     * @see #WINDOW_FOCUSED_STATE_SET
1190     */
1191    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1192    /**
1193     * Indicates the view is enabled, selected and its window has the focus.
1194     *
1195     * @see #ENABLED_STATE_SET
1196     * @see #SELECTED_STATE_SET
1197     * @see #WINDOW_FOCUSED_STATE_SET
1198     */
1199    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1200    /**
1201     * Indicates the view is focused, selected and its window has the focus.
1202     *
1203     * @see #FOCUSED_STATE_SET
1204     * @see #SELECTED_STATE_SET
1205     * @see #WINDOW_FOCUSED_STATE_SET
1206     */
1207    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1208    /**
1209     * Indicates the view is enabled, focused, selected and its window
1210     * has the focus.
1211     *
1212     * @see #ENABLED_STATE_SET
1213     * @see #FOCUSED_STATE_SET
1214     * @see #SELECTED_STATE_SET
1215     * @see #WINDOW_FOCUSED_STATE_SET
1216     */
1217    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1218    /**
1219     * Indicates the view is pressed and its window has the focus.
1220     *
1221     * @see #PRESSED_STATE_SET
1222     * @see #WINDOW_FOCUSED_STATE_SET
1223     */
1224    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1225    /**
1226     * Indicates the view is pressed and selected.
1227     *
1228     * @see #PRESSED_STATE_SET
1229     * @see #SELECTED_STATE_SET
1230     */
1231    protected static final int[] PRESSED_SELECTED_STATE_SET;
1232    /**
1233     * Indicates the view is pressed, selected and its window has the focus.
1234     *
1235     * @see #PRESSED_STATE_SET
1236     * @see #SELECTED_STATE_SET
1237     * @see #WINDOW_FOCUSED_STATE_SET
1238     */
1239    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1240    /**
1241     * Indicates the view is pressed and focused.
1242     *
1243     * @see #PRESSED_STATE_SET
1244     * @see #FOCUSED_STATE_SET
1245     */
1246    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1247    /**
1248     * Indicates the view is pressed, focused and its window has the focus.
1249     *
1250     * @see #PRESSED_STATE_SET
1251     * @see #FOCUSED_STATE_SET
1252     * @see #WINDOW_FOCUSED_STATE_SET
1253     */
1254    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1255    /**
1256     * Indicates the view is pressed, focused and selected.
1257     *
1258     * @see #PRESSED_STATE_SET
1259     * @see #SELECTED_STATE_SET
1260     * @see #FOCUSED_STATE_SET
1261     */
1262    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1263    /**
1264     * Indicates the view is pressed, focused, selected and its window has the focus.
1265     *
1266     * @see #PRESSED_STATE_SET
1267     * @see #FOCUSED_STATE_SET
1268     * @see #SELECTED_STATE_SET
1269     * @see #WINDOW_FOCUSED_STATE_SET
1270     */
1271    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1272    /**
1273     * Indicates the view is pressed and enabled.
1274     *
1275     * @see #PRESSED_STATE_SET
1276     * @see #ENABLED_STATE_SET
1277     */
1278    protected static final int[] PRESSED_ENABLED_STATE_SET;
1279    /**
1280     * Indicates the view is pressed, enabled and its window has the focus.
1281     *
1282     * @see #PRESSED_STATE_SET
1283     * @see #ENABLED_STATE_SET
1284     * @see #WINDOW_FOCUSED_STATE_SET
1285     */
1286    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1287    /**
1288     * Indicates the view is pressed, enabled and selected.
1289     *
1290     * @see #PRESSED_STATE_SET
1291     * @see #ENABLED_STATE_SET
1292     * @see #SELECTED_STATE_SET
1293     */
1294    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1295    /**
1296     * Indicates the view is pressed, enabled, selected and its window has the
1297     * focus.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #ENABLED_STATE_SET
1301     * @see #SELECTED_STATE_SET
1302     * @see #WINDOW_FOCUSED_STATE_SET
1303     */
1304    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1305    /**
1306     * Indicates the view is pressed, enabled and focused.
1307     *
1308     * @see #PRESSED_STATE_SET
1309     * @see #ENABLED_STATE_SET
1310     * @see #FOCUSED_STATE_SET
1311     */
1312    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1313    /**
1314     * Indicates the view is pressed, enabled, focused and its window has the
1315     * focus.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #ENABLED_STATE_SET
1319     * @see #FOCUSED_STATE_SET
1320     * @see #WINDOW_FOCUSED_STATE_SET
1321     */
1322    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1323    /**
1324     * Indicates the view is pressed, enabled, focused and selected.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #ENABLED_STATE_SET
1328     * @see #SELECTED_STATE_SET
1329     * @see #FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, focused, selected and its window
1334     * has the focus.
1335     *
1336     * @see #PRESSED_STATE_SET
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     * @see #FOCUSED_STATE_SET
1340     * @see #WINDOW_FOCUSED_STATE_SET
1341     */
1342    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1343
1344    /**
1345     * The order here is very important to {@link #getDrawableState()}
1346     */
1347    private static final int[][] VIEW_STATE_SETS;
1348
1349    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1350    static final int VIEW_STATE_SELECTED = 1 << 1;
1351    static final int VIEW_STATE_FOCUSED = 1 << 2;
1352    static final int VIEW_STATE_ENABLED = 1 << 3;
1353    static final int VIEW_STATE_PRESSED = 1 << 4;
1354    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1355    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1356    static final int VIEW_STATE_HOVERED = 1 << 7;
1357    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1358    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1359
1360    static final int[] VIEW_STATE_IDS = new int[] {
1361        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1362        R.attr.state_selected,          VIEW_STATE_SELECTED,
1363        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1364        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1365        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1366        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1367        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1368        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1369        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1370        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1371    };
1372
1373    static {
1374        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1375            throw new IllegalStateException(
1376                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1377        }
1378        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1379        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1380            int viewState = R.styleable.ViewDrawableStates[i];
1381            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1382                if (VIEW_STATE_IDS[j] == viewState) {
1383                    orderedIds[i * 2] = viewState;
1384                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1385                }
1386            }
1387        }
1388        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1389        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1390        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1391            int numBits = Integer.bitCount(i);
1392            int[] set = new int[numBits];
1393            int pos = 0;
1394            for (int j = 0; j < orderedIds.length; j += 2) {
1395                if ((i & orderedIds[j+1]) != 0) {
1396                    set[pos++] = orderedIds[j];
1397                }
1398            }
1399            VIEW_STATE_SETS[i] = set;
1400        }
1401
1402        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1403        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1404        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1405        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1406                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1407        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1408        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1410        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1412        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1414                | VIEW_STATE_FOCUSED];
1415        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1416        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1418        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1420        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1421                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1422                | VIEW_STATE_ENABLED];
1423        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1425        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1427                | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1430                | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1433                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1434
1435        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1436        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1438        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1439                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1440        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1441                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1442                | VIEW_STATE_PRESSED];
1443        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1445        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1447                | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1450                | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1453                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1454        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1456        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1458                | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1461                | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1464                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1473                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1476                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1477                | VIEW_STATE_PRESSED];
1478    }
1479
1480    /**
1481     * Accessibility event types that are dispatched for text population.
1482     */
1483    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1484            AccessibilityEvent.TYPE_VIEW_CLICKED
1485            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1486            | AccessibilityEvent.TYPE_VIEW_SELECTED
1487            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1488            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1489            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1490            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1491            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1492            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1493
1494    /**
1495     * Temporary Rect currently for use in setBackground().  This will probably
1496     * be extended in the future to hold our own class with more than just
1497     * a Rect. :)
1498     */
1499    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1500
1501    /**
1502     * Map used to store views' tags.
1503     */
1504    private SparseArray<Object> mKeyedTags;
1505
1506    /**
1507     * The next available accessiiblity id.
1508     */
1509    private static int sNextAccessibilityViewId;
1510
1511    /**
1512     * The animation currently associated with this view.
1513     * @hide
1514     */
1515    protected Animation mCurrentAnimation = null;
1516
1517    /**
1518     * Width as measured during measure pass.
1519     * {@hide}
1520     */
1521    @ViewDebug.ExportedProperty(category = "measurement")
1522    int mMeasuredWidth;
1523
1524    /**
1525     * Height as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredHeight;
1530
1531    /**
1532     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1533     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1534     * its display list. This flag, used only when hw accelerated, allows us to clear the
1535     * flag while retaining this information until it's needed (at getDisplayList() time and
1536     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1537     *
1538     * {@hide}
1539     */
1540    boolean mRecreateDisplayList = false;
1541
1542    /**
1543     * The view's identifier.
1544     * {@hide}
1545     *
1546     * @see #setId(int)
1547     * @see #getId()
1548     */
1549    @ViewDebug.ExportedProperty(resolveId = true)
1550    int mID = NO_ID;
1551
1552    /**
1553     * The stable ID of this view for accessibility purposes.
1554     */
1555    int mAccessibilityViewId = NO_ID;
1556
1557    /**
1558     * The view's tag.
1559     * {@hide}
1560     *
1561     * @see #setTag(Object)
1562     * @see #getTag()
1563     */
1564    protected Object mTag;
1565
1566    // for mPrivateFlags:
1567    /** {@hide} */
1568    static final int WANTS_FOCUS                    = 0x00000001;
1569    /** {@hide} */
1570    static final int FOCUSED                        = 0x00000002;
1571    /** {@hide} */
1572    static final int SELECTED                       = 0x00000004;
1573    /** {@hide} */
1574    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1575    /** {@hide} */
1576    static final int HAS_BOUNDS                     = 0x00000010;
1577    /** {@hide} */
1578    static final int DRAWN                          = 0x00000020;
1579    /**
1580     * When this flag is set, this view is running an animation on behalf of its
1581     * children and should therefore not cancel invalidate requests, even if they
1582     * lie outside of this view's bounds.
1583     *
1584     * {@hide}
1585     */
1586    static final int DRAW_ANIMATION                 = 0x00000040;
1587    /** {@hide} */
1588    static final int SKIP_DRAW                      = 0x00000080;
1589    /** {@hide} */
1590    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1591    /** {@hide} */
1592    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1593    /** {@hide} */
1594    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1595    /** {@hide} */
1596    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1597    /** {@hide} */
1598    static final int FORCE_LAYOUT                   = 0x00001000;
1599    /** {@hide} */
1600    static final int LAYOUT_REQUIRED                = 0x00002000;
1601
1602    private static final int PRESSED                = 0x00004000;
1603
1604    /** {@hide} */
1605    static final int DRAWING_CACHE_VALID            = 0x00008000;
1606    /**
1607     * Flag used to indicate that this view should be drawn once more (and only once
1608     * more) after its animation has completed.
1609     * {@hide}
1610     */
1611    static final int ANIMATION_STARTED              = 0x00010000;
1612
1613    private static final int SAVE_STATE_CALLED      = 0x00020000;
1614
1615    /**
1616     * Indicates that the View returned true when onSetAlpha() was called and that
1617     * the alpha must be restored.
1618     * {@hide}
1619     */
1620    static final int ALPHA_SET                      = 0x00040000;
1621
1622    /**
1623     * Set by {@link #setScrollContainer(boolean)}.
1624     */
1625    static final int SCROLL_CONTAINER               = 0x00080000;
1626
1627    /**
1628     * Set by {@link #setScrollContainer(boolean)}.
1629     */
1630    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1631
1632    /**
1633     * View flag indicating whether this view was invalidated (fully or partially.)
1634     *
1635     * @hide
1636     */
1637    static final int DIRTY                          = 0x00200000;
1638
1639    /**
1640     * View flag indicating whether this view was invalidated by an opaque
1641     * invalidate request.
1642     *
1643     * @hide
1644     */
1645    static final int DIRTY_OPAQUE                   = 0x00400000;
1646
1647    /**
1648     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1649     *
1650     * @hide
1651     */
1652    static final int DIRTY_MASK                     = 0x00600000;
1653
1654    /**
1655     * Indicates whether the background is opaque.
1656     *
1657     * @hide
1658     */
1659    static final int OPAQUE_BACKGROUND              = 0x00800000;
1660
1661    /**
1662     * Indicates whether the scrollbars are opaque.
1663     *
1664     * @hide
1665     */
1666    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1667
1668    /**
1669     * Indicates whether the view is opaque.
1670     *
1671     * @hide
1672     */
1673    static final int OPAQUE_MASK                    = 0x01800000;
1674
1675    /**
1676     * Indicates a prepressed state;
1677     * the short time between ACTION_DOWN and recognizing
1678     * a 'real' press. Prepressed is used to recognize quick taps
1679     * even when they are shorter than ViewConfiguration.getTapTimeout().
1680     *
1681     * @hide
1682     */
1683    private static final int PREPRESSED             = 0x02000000;
1684
1685    /**
1686     * Indicates whether the view is temporarily detached.
1687     *
1688     * @hide
1689     */
1690    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1691
1692    /**
1693     * Indicates that we should awaken scroll bars once attached
1694     *
1695     * @hide
1696     */
1697    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1698
1699    /**
1700     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1701     * @hide
1702     */
1703    private static final int HOVERED              = 0x10000000;
1704
1705    /**
1706     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1707     * for transform operations
1708     *
1709     * @hide
1710     */
1711    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1712
1713    /** {@hide} */
1714    static final int ACTIVATED                    = 0x40000000;
1715
1716    /**
1717     * Indicates that this view was specifically invalidated, not just dirtied because some
1718     * child view was invalidated. The flag is used to determine when we need to recreate
1719     * a view's display list (as opposed to just returning a reference to its existing
1720     * display list).
1721     *
1722     * @hide
1723     */
1724    static final int INVALIDATED                  = 0x80000000;
1725
1726    /* Masks for mPrivateFlags2 */
1727
1728    /**
1729     * Indicates that this view has reported that it can accept the current drag's content.
1730     * Cleared when the drag operation concludes.
1731     * @hide
1732     */
1733    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1734
1735    /**
1736     * Indicates that this view is currently directly under the drag location in a
1737     * drag-and-drop operation involving content that it can accept.  Cleared when
1738     * the drag exits the view, or when the drag operation concludes.
1739     * @hide
1740     */
1741    static final int DRAG_HOVERED                 = 0x00000002;
1742
1743    /**
1744     * Indicates whether the view layout direction has been resolved and drawn to the
1745     * right-to-left direction.
1746     *
1747     * @hide
1748     */
1749    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1750
1751    /**
1752     * Indicates whether the view layout direction has been resolved.
1753     *
1754     * @hide
1755     */
1756    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1757
1758
1759    /* End of masks for mPrivateFlags2 */
1760
1761    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1762
1763    /**
1764     * Always allow a user to over-scroll this view, provided it is a
1765     * view that can scroll.
1766     *
1767     * @see #getOverScrollMode()
1768     * @see #setOverScrollMode(int)
1769     */
1770    public static final int OVER_SCROLL_ALWAYS = 0;
1771
1772    /**
1773     * Allow a user to over-scroll this view only if the content is large
1774     * enough to meaningfully scroll, provided it is a view that can scroll.
1775     *
1776     * @see #getOverScrollMode()
1777     * @see #setOverScrollMode(int)
1778     */
1779    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1780
1781    /**
1782     * Never allow a user to over-scroll this view.
1783     *
1784     * @see #getOverScrollMode()
1785     * @see #setOverScrollMode(int)
1786     */
1787    public static final int OVER_SCROLL_NEVER = 2;
1788
1789    /**
1790     * View has requested the system UI (status bar) to be visible (the default).
1791     *
1792     * @see #setSystemUiVisibility(int)
1793     */
1794    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1795
1796    /**
1797     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1798     *
1799     * This is for use in games, book readers, video players, or any other "immersive" application
1800     * where the usual system chrome is deemed too distracting.
1801     *
1802     * In low profile mode, the status bar and/or navigation icons may dim.
1803     *
1804     * @see #setSystemUiVisibility(int)
1805     */
1806    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1807
1808    /**
1809     * View has requested that the system navigation be temporarily hidden.
1810     *
1811     * This is an even less obtrusive state than that called for by
1812     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1813     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1814     * those to disappear. This is useful (in conjunction with the
1815     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1816     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1817     * window flags) for displaying content using every last pixel on the display.
1818     *
1819     * There is a limitation: because navigation controls are so important, the least user
1820     * interaction will cause them to reappear immediately.
1821     *
1822     * @see #setSystemUiVisibility(int)
1823     */
1824    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1825
1826    /**
1827     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1828     */
1829    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1830
1831    /**
1832     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1833     */
1834    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1835
1836    /**
1837     * @hide
1838     *
1839     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1840     * out of the public fields to keep the undefined bits out of the developer's way.
1841     *
1842     * Flag to make the status bar not expandable.  Unless you also
1843     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1844     */
1845    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1846
1847    /**
1848     * @hide
1849     *
1850     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1851     * out of the public fields to keep the undefined bits out of the developer's way.
1852     *
1853     * Flag to hide notification icons and scrolling ticker text.
1854     */
1855    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1856
1857    /**
1858     * @hide
1859     *
1860     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1861     * out of the public fields to keep the undefined bits out of the developer's way.
1862     *
1863     * Flag to disable incoming notification alerts.  This will not block
1864     * icons, but it will block sound, vibrating and other visual or aural notifications.
1865     */
1866    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1867
1868    /**
1869     * @hide
1870     *
1871     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1872     * out of the public fields to keep the undefined bits out of the developer's way.
1873     *
1874     * Flag to hide only the scrolling ticker.  Note that
1875     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1876     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1877     */
1878    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1879
1880    /**
1881     * @hide
1882     *
1883     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1884     * out of the public fields to keep the undefined bits out of the developer's way.
1885     *
1886     * Flag to hide the center system info area.
1887     */
1888    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1889
1890    /**
1891     * @hide
1892     *
1893     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1894     * out of the public fields to keep the undefined bits out of the developer's way.
1895     *
1896     * Flag to hide only the home button.  Don't use this
1897     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1898     */
1899    public static final int STATUS_BAR_DISABLE_HOME = 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     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1927     * out of the public fields to keep the undefined bits out of the developer's way.
1928     *
1929     * Flag to hide only the recent apps button. Don't use this
1930     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1931     */
1932    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
1933
1934    /**
1935     * @hide
1936     *
1937     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
1938     *
1939     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
1940     */
1941    @Deprecated
1942    public static final int STATUS_BAR_DISABLE_NAVIGATION =
1943            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
1944
1945    /**
1946     * @hide
1947     */
1948    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1949
1950    /**
1951     * These are the system UI flags that can be cleared by events outside
1952     * of an application.  Currently this is just the ability to tap on the
1953     * screen while hiding the navigation bar to have it return.
1954     * @hide
1955     */
1956    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1957            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1958
1959    /**
1960     * Find views that render the specified text.
1961     *
1962     * @see #findViewsWithText(ArrayList, CharSequence, int)
1963     */
1964    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1965
1966    /**
1967     * Find find views that contain the specified content description.
1968     *
1969     * @see #findViewsWithText(ArrayList, CharSequence, int)
1970     */
1971    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1972
1973    /**
1974     * Find views that contain {@link AccessibilityNodeProvider}. Such
1975     * a View is a root of virtual view hierarchy and may contain the searched
1976     * text. If this flag is set Views with providers are automatically
1977     * added and it is a responsibility of the client to call the APIs of
1978     * the provider to determine whether the virtual tree rooted at this View
1979     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
1980     * represeting the virtual views with this text.
1981     *
1982     * @see #findViewsWithText(ArrayList, CharSequence, int)
1983     *
1984     * @hide
1985     */
1986    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
1987
1988    /**
1989     * Controls the over-scroll mode for this view.
1990     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1991     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1992     * and {@link #OVER_SCROLL_NEVER}.
1993     */
1994    private int mOverScrollMode;
1995
1996    /**
1997     * The parent this view is attached to.
1998     * {@hide}
1999     *
2000     * @see #getParent()
2001     */
2002    protected ViewParent mParent;
2003
2004    /**
2005     * {@hide}
2006     */
2007    AttachInfo mAttachInfo;
2008
2009    /**
2010     * {@hide}
2011     */
2012    @ViewDebug.ExportedProperty(flagMapping = {
2013        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2014                name = "FORCE_LAYOUT"),
2015        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2016                name = "LAYOUT_REQUIRED"),
2017        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2018            name = "DRAWING_CACHE_INVALID", outputIf = false),
2019        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2020        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2021        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2022        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2023    })
2024    int mPrivateFlags;
2025    int mPrivateFlags2;
2026
2027    /**
2028     * This view's request for the visibility of the status bar.
2029     * @hide
2030     */
2031    @ViewDebug.ExportedProperty(flagMapping = {
2032        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2033                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2034                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2035        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2036                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2037                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2038        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2039                                equals = SYSTEM_UI_FLAG_VISIBLE,
2040                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2041    })
2042    int mSystemUiVisibility;
2043
2044    /**
2045     * Count of how many windows this view has been attached to.
2046     */
2047    int mWindowAttachCount;
2048
2049    /**
2050     * The layout parameters associated with this view and used by the parent
2051     * {@link android.view.ViewGroup} to determine how this view should be
2052     * laid out.
2053     * {@hide}
2054     */
2055    protected ViewGroup.LayoutParams mLayoutParams;
2056
2057    /**
2058     * The view flags hold various views states.
2059     * {@hide}
2060     */
2061    @ViewDebug.ExportedProperty
2062    int mViewFlags;
2063
2064    static class TransformationInfo {
2065        /**
2066         * The transform matrix for the View. This transform is calculated internally
2067         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2068         * is used by default. Do *not* use this variable directly; instead call
2069         * getMatrix(), which will automatically recalculate the matrix if necessary
2070         * to get the correct matrix based on the latest rotation and scale properties.
2071         */
2072        private final Matrix mMatrix = new Matrix();
2073
2074        /**
2075         * The transform matrix for the View. This transform is calculated internally
2076         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2077         * is used by default. Do *not* use this variable directly; instead call
2078         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2079         * to get the correct matrix based on the latest rotation and scale properties.
2080         */
2081        private Matrix mInverseMatrix;
2082
2083        /**
2084         * An internal variable that tracks whether we need to recalculate the
2085         * transform matrix, based on whether the rotation or scaleX/Y properties
2086         * have changed since the matrix was last calculated.
2087         */
2088        boolean mMatrixDirty = false;
2089
2090        /**
2091         * An internal variable that tracks whether we need to recalculate the
2092         * transform matrix, based on whether the rotation or scaleX/Y properties
2093         * have changed since the matrix was last calculated.
2094         */
2095        private boolean mInverseMatrixDirty = true;
2096
2097        /**
2098         * A variable that tracks whether we need to recalculate the
2099         * transform matrix, based on whether the rotation or scaleX/Y properties
2100         * have changed since the matrix was last calculated. This variable
2101         * is only valid after a call to updateMatrix() or to a function that
2102         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2103         */
2104        private boolean mMatrixIsIdentity = true;
2105
2106        /**
2107         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2108         */
2109        private Camera mCamera = null;
2110
2111        /**
2112         * This matrix is used when computing the matrix for 3D rotations.
2113         */
2114        private Matrix matrix3D = null;
2115
2116        /**
2117         * These prev values are used to recalculate a centered pivot point when necessary. The
2118         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2119         * set), so thes values are only used then as well.
2120         */
2121        private int mPrevWidth = -1;
2122        private int mPrevHeight = -1;
2123
2124        /**
2125         * The degrees rotation around the vertical axis through the pivot point.
2126         */
2127        @ViewDebug.ExportedProperty
2128        float mRotationY = 0f;
2129
2130        /**
2131         * The degrees rotation around the horizontal axis through the pivot point.
2132         */
2133        @ViewDebug.ExportedProperty
2134        float mRotationX = 0f;
2135
2136        /**
2137         * The degrees rotation around the pivot point.
2138         */
2139        @ViewDebug.ExportedProperty
2140        float mRotation = 0f;
2141
2142        /**
2143         * The amount of translation of the object away from its left property (post-layout).
2144         */
2145        @ViewDebug.ExportedProperty
2146        float mTranslationX = 0f;
2147
2148        /**
2149         * The amount of translation of the object away from its top property (post-layout).
2150         */
2151        @ViewDebug.ExportedProperty
2152        float mTranslationY = 0f;
2153
2154        /**
2155         * The amount of scale in the x direction around the pivot point. A
2156         * value of 1 means no scaling is applied.
2157         */
2158        @ViewDebug.ExportedProperty
2159        float mScaleX = 1f;
2160
2161        /**
2162         * The amount of scale in the y direction around the pivot point. A
2163         * value of 1 means no scaling is applied.
2164         */
2165        @ViewDebug.ExportedProperty
2166        float mScaleY = 1f;
2167
2168        /**
2169         * The amount of scale in the x direction around the pivot point. A
2170         * value of 1 means no scaling is applied.
2171         */
2172        @ViewDebug.ExportedProperty
2173        float mPivotX = 0f;
2174
2175        /**
2176         * The amount of scale in the y direction around the pivot point. A
2177         * value of 1 means no scaling is applied.
2178         */
2179        @ViewDebug.ExportedProperty
2180        float mPivotY = 0f;
2181
2182        /**
2183         * The opacity of the View. This is a value from 0 to 1, where 0 means
2184         * completely transparent and 1 means completely opaque.
2185         */
2186        @ViewDebug.ExportedProperty
2187        float mAlpha = 1f;
2188    }
2189
2190    TransformationInfo mTransformationInfo;
2191
2192    private boolean mLastIsOpaque;
2193
2194    /**
2195     * Convenience value to check for float values that are close enough to zero to be considered
2196     * zero.
2197     */
2198    private static final float NONZERO_EPSILON = .001f;
2199
2200    /**
2201     * The distance in pixels from the left edge of this view's parent
2202     * to the left edge of this view.
2203     * {@hide}
2204     */
2205    @ViewDebug.ExportedProperty(category = "layout")
2206    protected int mLeft;
2207    /**
2208     * The distance in pixels from the left edge of this view's parent
2209     * to the right edge of this view.
2210     * {@hide}
2211     */
2212    @ViewDebug.ExportedProperty(category = "layout")
2213    protected int mRight;
2214    /**
2215     * The distance in pixels from the top edge of this view's parent
2216     * to the top edge of this view.
2217     * {@hide}
2218     */
2219    @ViewDebug.ExportedProperty(category = "layout")
2220    protected int mTop;
2221    /**
2222     * The distance in pixels from the top edge of this view's parent
2223     * to the bottom edge of this view.
2224     * {@hide}
2225     */
2226    @ViewDebug.ExportedProperty(category = "layout")
2227    protected int mBottom;
2228
2229    /**
2230     * The offset, in pixels, by which the content of this view is scrolled
2231     * horizontally.
2232     * {@hide}
2233     */
2234    @ViewDebug.ExportedProperty(category = "scrolling")
2235    protected int mScrollX;
2236    /**
2237     * The offset, in pixels, by which the content of this view is scrolled
2238     * vertically.
2239     * {@hide}
2240     */
2241    @ViewDebug.ExportedProperty(category = "scrolling")
2242    protected int mScrollY;
2243
2244    /**
2245     * The left padding in pixels, that is the distance in pixels between the
2246     * left edge of this view and the left edge of its content.
2247     * {@hide}
2248     */
2249    @ViewDebug.ExportedProperty(category = "padding")
2250    protected int mPaddingLeft;
2251    /**
2252     * The right padding in pixels, that is the distance in pixels between the
2253     * right edge of this view and the right edge of its content.
2254     * {@hide}
2255     */
2256    @ViewDebug.ExportedProperty(category = "padding")
2257    protected int mPaddingRight;
2258    /**
2259     * The top padding in pixels, that is the distance in pixels between the
2260     * top edge of this view and the top edge of its content.
2261     * {@hide}
2262     */
2263    @ViewDebug.ExportedProperty(category = "padding")
2264    protected int mPaddingTop;
2265    /**
2266     * The bottom padding in pixels, that is the distance in pixels between the
2267     * bottom edge of this view and the bottom edge of its content.
2268     * {@hide}
2269     */
2270    @ViewDebug.ExportedProperty(category = "padding")
2271    protected int mPaddingBottom;
2272
2273    /**
2274     * Briefly describes the view and is primarily used for accessibility support.
2275     */
2276    private CharSequence mContentDescription;
2277
2278    /**
2279     * Cache the paddingRight set by the user to append to the scrollbar's size.
2280     *
2281     * @hide
2282     */
2283    @ViewDebug.ExportedProperty(category = "padding")
2284    protected int mUserPaddingRight;
2285
2286    /**
2287     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2288     *
2289     * @hide
2290     */
2291    @ViewDebug.ExportedProperty(category = "padding")
2292    protected int mUserPaddingBottom;
2293
2294    /**
2295     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2296     *
2297     * @hide
2298     */
2299    @ViewDebug.ExportedProperty(category = "padding")
2300    protected int mUserPaddingLeft;
2301
2302    /**
2303     * Cache if the user padding is relative.
2304     *
2305     */
2306    @ViewDebug.ExportedProperty(category = "padding")
2307    boolean mUserPaddingRelative;
2308
2309    /**
2310     * Cache the paddingStart set by the user to append to the scrollbar's size.
2311     *
2312     */
2313    @ViewDebug.ExportedProperty(category = "padding")
2314    int mUserPaddingStart;
2315
2316    /**
2317     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2318     *
2319     */
2320    @ViewDebug.ExportedProperty(category = "padding")
2321    int mUserPaddingEnd;
2322
2323    /**
2324     * @hide
2325     */
2326    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2327    /**
2328     * @hide
2329     */
2330    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2331
2332    private Drawable mBGDrawable;
2333
2334    private int mBackgroundResource;
2335    private boolean mBackgroundSizeChanged;
2336
2337    static class ListenerInfo {
2338        /**
2339         * Listener used to dispatch focus change events.
2340         * This field should be made private, so it is hidden from the SDK.
2341         * {@hide}
2342         */
2343        protected OnFocusChangeListener mOnFocusChangeListener;
2344
2345        /**
2346         * Listeners for layout change events.
2347         */
2348        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2349
2350        /**
2351         * Listeners for attach events.
2352         */
2353        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2354
2355        /**
2356         * Listener used to dispatch click events.
2357         * This field should be made private, so it is hidden from the SDK.
2358         * {@hide}
2359         */
2360        public OnClickListener mOnClickListener;
2361
2362        /**
2363         * Listener used to dispatch long click events.
2364         * This field should be made private, so it is hidden from the SDK.
2365         * {@hide}
2366         */
2367        protected OnLongClickListener mOnLongClickListener;
2368
2369        /**
2370         * Listener used to build the context menu.
2371         * This field should be made private, so it is hidden from the SDK.
2372         * {@hide}
2373         */
2374        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2375
2376        private OnKeyListener mOnKeyListener;
2377
2378        private OnTouchListener mOnTouchListener;
2379
2380        private OnHoverListener mOnHoverListener;
2381
2382        private OnGenericMotionListener mOnGenericMotionListener;
2383
2384        private OnDragListener mOnDragListener;
2385
2386        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2387    }
2388
2389    ListenerInfo mListenerInfo;
2390
2391    /**
2392     * The application environment this view lives in.
2393     * This field should be made private, so it is hidden from the SDK.
2394     * {@hide}
2395     */
2396    protected Context mContext;
2397
2398    private final Resources mResources;
2399
2400    private ScrollabilityCache mScrollCache;
2401
2402    private int[] mDrawableState = null;
2403
2404    /**
2405     * Set to true when drawing cache is enabled and cannot be created.
2406     *
2407     * @hide
2408     */
2409    public boolean mCachingFailed;
2410
2411    private Bitmap mDrawingCache;
2412    private Bitmap mUnscaledDrawingCache;
2413    private HardwareLayer mHardwareLayer;
2414    DisplayList mDisplayList;
2415
2416    /**
2417     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2418     * the user may specify which view to go to next.
2419     */
2420    private int mNextFocusLeftId = View.NO_ID;
2421
2422    /**
2423     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2424     * the user may specify which view to go to next.
2425     */
2426    private int mNextFocusRightId = View.NO_ID;
2427
2428    /**
2429     * When this view has focus and the next focus is {@link #FOCUS_UP},
2430     * the user may specify which view to go to next.
2431     */
2432    private int mNextFocusUpId = View.NO_ID;
2433
2434    /**
2435     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2436     * the user may specify which view to go to next.
2437     */
2438    private int mNextFocusDownId = View.NO_ID;
2439
2440    /**
2441     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2442     * the user may specify which view to go to next.
2443     */
2444    int mNextFocusForwardId = View.NO_ID;
2445
2446    private CheckForLongPress mPendingCheckForLongPress;
2447    private CheckForTap mPendingCheckForTap = null;
2448    private PerformClick mPerformClick;
2449    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2450
2451    private UnsetPressedState mUnsetPressedState;
2452
2453    /**
2454     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2455     * up event while a long press is invoked as soon as the long press duration is reached, so
2456     * a long press could be performed before the tap is checked, in which case the tap's action
2457     * should not be invoked.
2458     */
2459    private boolean mHasPerformedLongPress;
2460
2461    /**
2462     * The minimum height of the view. We'll try our best to have the height
2463     * of this view to at least this amount.
2464     */
2465    @ViewDebug.ExportedProperty(category = "measurement")
2466    private int mMinHeight;
2467
2468    /**
2469     * The minimum width of the view. We'll try our best to have the width
2470     * of this view to at least this amount.
2471     */
2472    @ViewDebug.ExportedProperty(category = "measurement")
2473    private int mMinWidth;
2474
2475    /**
2476     * The delegate to handle touch events that are physically in this view
2477     * but should be handled by another view.
2478     */
2479    private TouchDelegate mTouchDelegate = null;
2480
2481    /**
2482     * Solid color to use as a background when creating the drawing cache. Enables
2483     * the cache to use 16 bit bitmaps instead of 32 bit.
2484     */
2485    private int mDrawingCacheBackgroundColor = 0;
2486
2487    /**
2488     * Special tree observer used when mAttachInfo is null.
2489     */
2490    private ViewTreeObserver mFloatingTreeObserver;
2491
2492    /**
2493     * Cache the touch slop from the context that created the view.
2494     */
2495    private int mTouchSlop;
2496
2497    /**
2498     * Object that handles automatic animation of view properties.
2499     */
2500    private ViewPropertyAnimator mAnimator = null;
2501
2502    /**
2503     * Flag indicating that a drag can cross window boundaries.  When
2504     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2505     * with this flag set, all visible applications will be able to participate
2506     * in the drag operation and receive the dragged content.
2507     *
2508     * @hide
2509     */
2510    public static final int DRAG_FLAG_GLOBAL = 1;
2511
2512    /**
2513     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2514     */
2515    private float mVerticalScrollFactor;
2516
2517    /**
2518     * Position of the vertical scroll bar.
2519     */
2520    private int mVerticalScrollbarPosition;
2521
2522    /**
2523     * Position the scroll bar at the default position as determined by the system.
2524     */
2525    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2526
2527    /**
2528     * Position the scroll bar along the left edge.
2529     */
2530    public static final int SCROLLBAR_POSITION_LEFT = 1;
2531
2532    /**
2533     * Position the scroll bar along the right edge.
2534     */
2535    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2536
2537    /**
2538     * Indicates that the view does not have a layer.
2539     *
2540     * @see #getLayerType()
2541     * @see #setLayerType(int, android.graphics.Paint)
2542     * @see #LAYER_TYPE_SOFTWARE
2543     * @see #LAYER_TYPE_HARDWARE
2544     */
2545    public static final int LAYER_TYPE_NONE = 0;
2546
2547    /**
2548     * <p>Indicates that the view has a software layer. A software layer is backed
2549     * by a bitmap and causes the view to be rendered using Android's software
2550     * rendering pipeline, even if hardware acceleration is enabled.</p>
2551     *
2552     * <p>Software layers have various usages:</p>
2553     * <p>When the application is not using hardware acceleration, a software layer
2554     * is useful to apply a specific color filter and/or blending mode and/or
2555     * translucency to a view and all its children.</p>
2556     * <p>When the application is using hardware acceleration, a software layer
2557     * is useful to render drawing primitives not supported by the hardware
2558     * accelerated pipeline. It can also be used to cache a complex view tree
2559     * into a texture and reduce the complexity of drawing operations. For instance,
2560     * when animating a complex view tree with a translation, a software layer can
2561     * be used to render the view tree only once.</p>
2562     * <p>Software layers should be avoided when the affected view tree updates
2563     * often. Every update will require to re-render the software layer, which can
2564     * potentially be slow (particularly when hardware acceleration is turned on
2565     * since the layer will have to be uploaded into a hardware texture after every
2566     * update.)</p>
2567     *
2568     * @see #getLayerType()
2569     * @see #setLayerType(int, android.graphics.Paint)
2570     * @see #LAYER_TYPE_NONE
2571     * @see #LAYER_TYPE_HARDWARE
2572     */
2573    public static final int LAYER_TYPE_SOFTWARE = 1;
2574
2575    /**
2576     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2577     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2578     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2579     * rendering pipeline, but only if hardware acceleration is turned on for the
2580     * view hierarchy. When hardware acceleration is turned off, hardware layers
2581     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2582     *
2583     * <p>A hardware layer is useful to apply a specific color filter and/or
2584     * blending mode and/or translucency to a view and all its children.</p>
2585     * <p>A hardware layer can be used to cache a complex view tree into a
2586     * texture and reduce the complexity of drawing operations. For instance,
2587     * when animating a complex view tree with a translation, a hardware layer can
2588     * be used to render the view tree only once.</p>
2589     * <p>A hardware layer can also be used to increase the rendering quality when
2590     * rotation transformations are applied on a view. It can also be used to
2591     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2592     *
2593     * @see #getLayerType()
2594     * @see #setLayerType(int, android.graphics.Paint)
2595     * @see #LAYER_TYPE_NONE
2596     * @see #LAYER_TYPE_SOFTWARE
2597     */
2598    public static final int LAYER_TYPE_HARDWARE = 2;
2599
2600    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2601            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2602            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2603            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2604    })
2605    int mLayerType = LAYER_TYPE_NONE;
2606    Paint mLayerPaint;
2607    Rect mLocalDirtyRect;
2608
2609    /**
2610     * Set to true when the view is sending hover accessibility events because it
2611     * is the innermost hovered view.
2612     */
2613    private boolean mSendingHoverAccessibilityEvents;
2614
2615    /**
2616     * Delegate for injecting accessiblity functionality.
2617     */
2618    AccessibilityDelegate mAccessibilityDelegate;
2619
2620    /**
2621     * Text direction is inherited thru {@link ViewGroup}
2622     * @hide
2623     */
2624    public static final int TEXT_DIRECTION_INHERIT = 0;
2625
2626    /**
2627     * Text direction is using "first strong algorithm". The first strong directional character
2628     * determines the paragraph direction. If there is no strong directional character, the
2629     * paragraph direction is the view's resolved layout direction.
2630     *
2631     * @hide
2632     */
2633    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2634
2635    /**
2636     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2637     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2638     * If there are neither, the paragraph direction is the view's resolved layout direction.
2639     *
2640     * @hide
2641     */
2642    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2643
2644    /**
2645     * Text direction is forced to LTR.
2646     *
2647     * @hide
2648     */
2649    public static final int TEXT_DIRECTION_LTR = 3;
2650
2651    /**
2652     * Text direction is forced to RTL.
2653     *
2654     * @hide
2655     */
2656    public static final int TEXT_DIRECTION_RTL = 4;
2657
2658    /**
2659     * Text direction is coming from the system Locale.
2660     *
2661     * @hide
2662     */
2663    public static final int TEXT_DIRECTION_LOCALE = 5;
2664
2665    /**
2666     * Default text direction is inherited
2667     *
2668     * @hide
2669     */
2670    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2671
2672    /**
2673     * The text direction that has been defined by {@link #setTextDirection(int)}.
2674     *
2675     * {@hide}
2676     */
2677    @ViewDebug.ExportedProperty(category = "text", mapping = {
2678            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2679            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2680            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2681            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2682            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2683            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2684    })
2685    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2686
2687    /**
2688     * The resolved text direction.  This needs resolution if the value is
2689     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if it is
2690     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2691     * chain of the view.
2692     *
2693     * {@hide}
2694     */
2695    @ViewDebug.ExportedProperty(category = "text", mapping = {
2696            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2697            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2698            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2699            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2700            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2701            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2702    })
2703    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2704
2705    /**
2706     * Consistency verifier for debugging purposes.
2707     * @hide
2708     */
2709    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2710            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2711                    new InputEventConsistencyVerifier(this, 0) : null;
2712
2713    /**
2714     * Simple constructor to use when creating a view from code.
2715     *
2716     * @param context The Context the view is running in, through which it can
2717     *        access the current theme, resources, etc.
2718     */
2719    public View(Context context) {
2720        mContext = context;
2721        mResources = context != null ? context.getResources() : null;
2722        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2723        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2724        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2725        mUserPaddingStart = -1;
2726        mUserPaddingEnd = -1;
2727        mUserPaddingRelative = false;
2728    }
2729
2730    /**
2731     * Constructor that is called when inflating a view from XML. This is called
2732     * when a view is being constructed from an XML file, supplying attributes
2733     * that were specified in the XML file. This version uses a default style of
2734     * 0, so the only attribute values applied are those in the Context's Theme
2735     * and the given AttributeSet.
2736     *
2737     * <p>
2738     * The method onFinishInflate() will be called after all children have been
2739     * added.
2740     *
2741     * @param context The Context the view is running in, through which it can
2742     *        access the current theme, resources, etc.
2743     * @param attrs The attributes of the XML tag that is inflating the view.
2744     * @see #View(Context, AttributeSet, int)
2745     */
2746    public View(Context context, AttributeSet attrs) {
2747        this(context, attrs, 0);
2748    }
2749
2750    /**
2751     * Perform inflation from XML and apply a class-specific base style. This
2752     * constructor of View allows subclasses to use their own base style when
2753     * they are inflating. For example, a Button class's constructor would call
2754     * this version of the super class constructor and supply
2755     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2756     * the theme's button style to modify all of the base view attributes (in
2757     * particular its background) as well as the Button class's attributes.
2758     *
2759     * @param context The Context the view is running in, through which it can
2760     *        access the current theme, resources, etc.
2761     * @param attrs The attributes of the XML tag that is inflating the view.
2762     * @param defStyle The default style to apply to this view. If 0, no style
2763     *        will be applied (beyond what is included in the theme). This may
2764     *        either be an attribute resource, whose value will be retrieved
2765     *        from the current theme, or an explicit style resource.
2766     * @see #View(Context, AttributeSet)
2767     */
2768    public View(Context context, AttributeSet attrs, int defStyle) {
2769        this(context);
2770
2771        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2772                defStyle, 0);
2773
2774        Drawable background = null;
2775
2776        int leftPadding = -1;
2777        int topPadding = -1;
2778        int rightPadding = -1;
2779        int bottomPadding = -1;
2780        int startPadding = -1;
2781        int endPadding = -1;
2782
2783        int padding = -1;
2784
2785        int viewFlagValues = 0;
2786        int viewFlagMasks = 0;
2787
2788        boolean setScrollContainer = false;
2789
2790        int x = 0;
2791        int y = 0;
2792
2793        float tx = 0;
2794        float ty = 0;
2795        float rotation = 0;
2796        float rotationX = 0;
2797        float rotationY = 0;
2798        float sx = 1f;
2799        float sy = 1f;
2800        boolean transformSet = false;
2801
2802        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2803
2804        int overScrollMode = mOverScrollMode;
2805        final int N = a.getIndexCount();
2806        for (int i = 0; i < N; i++) {
2807            int attr = a.getIndex(i);
2808            switch (attr) {
2809                case com.android.internal.R.styleable.View_background:
2810                    background = a.getDrawable(attr);
2811                    break;
2812                case com.android.internal.R.styleable.View_padding:
2813                    padding = a.getDimensionPixelSize(attr, -1);
2814                    break;
2815                 case com.android.internal.R.styleable.View_paddingLeft:
2816                    leftPadding = a.getDimensionPixelSize(attr, -1);
2817                    break;
2818                case com.android.internal.R.styleable.View_paddingTop:
2819                    topPadding = a.getDimensionPixelSize(attr, -1);
2820                    break;
2821                case com.android.internal.R.styleable.View_paddingRight:
2822                    rightPadding = a.getDimensionPixelSize(attr, -1);
2823                    break;
2824                case com.android.internal.R.styleable.View_paddingBottom:
2825                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2826                    break;
2827                case com.android.internal.R.styleable.View_paddingStart:
2828                    startPadding = a.getDimensionPixelSize(attr, -1);
2829                    break;
2830                case com.android.internal.R.styleable.View_paddingEnd:
2831                    endPadding = a.getDimensionPixelSize(attr, -1);
2832                    break;
2833                case com.android.internal.R.styleable.View_scrollX:
2834                    x = a.getDimensionPixelOffset(attr, 0);
2835                    break;
2836                case com.android.internal.R.styleable.View_scrollY:
2837                    y = a.getDimensionPixelOffset(attr, 0);
2838                    break;
2839                case com.android.internal.R.styleable.View_alpha:
2840                    setAlpha(a.getFloat(attr, 1f));
2841                    break;
2842                case com.android.internal.R.styleable.View_transformPivotX:
2843                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2844                    break;
2845                case com.android.internal.R.styleable.View_transformPivotY:
2846                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2847                    break;
2848                case com.android.internal.R.styleable.View_translationX:
2849                    tx = a.getDimensionPixelOffset(attr, 0);
2850                    transformSet = true;
2851                    break;
2852                case com.android.internal.R.styleable.View_translationY:
2853                    ty = a.getDimensionPixelOffset(attr, 0);
2854                    transformSet = true;
2855                    break;
2856                case com.android.internal.R.styleable.View_rotation:
2857                    rotation = a.getFloat(attr, 0);
2858                    transformSet = true;
2859                    break;
2860                case com.android.internal.R.styleable.View_rotationX:
2861                    rotationX = a.getFloat(attr, 0);
2862                    transformSet = true;
2863                    break;
2864                case com.android.internal.R.styleable.View_rotationY:
2865                    rotationY = a.getFloat(attr, 0);
2866                    transformSet = true;
2867                    break;
2868                case com.android.internal.R.styleable.View_scaleX:
2869                    sx = a.getFloat(attr, 1f);
2870                    transformSet = true;
2871                    break;
2872                case com.android.internal.R.styleable.View_scaleY:
2873                    sy = a.getFloat(attr, 1f);
2874                    transformSet = true;
2875                    break;
2876                case com.android.internal.R.styleable.View_id:
2877                    mID = a.getResourceId(attr, NO_ID);
2878                    break;
2879                case com.android.internal.R.styleable.View_tag:
2880                    mTag = a.getText(attr);
2881                    break;
2882                case com.android.internal.R.styleable.View_fitsSystemWindows:
2883                    if (a.getBoolean(attr, false)) {
2884                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2885                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2886                    }
2887                    break;
2888                case com.android.internal.R.styleable.View_focusable:
2889                    if (a.getBoolean(attr, false)) {
2890                        viewFlagValues |= FOCUSABLE;
2891                        viewFlagMasks |= FOCUSABLE_MASK;
2892                    }
2893                    break;
2894                case com.android.internal.R.styleable.View_focusableInTouchMode:
2895                    if (a.getBoolean(attr, false)) {
2896                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2897                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2898                    }
2899                    break;
2900                case com.android.internal.R.styleable.View_clickable:
2901                    if (a.getBoolean(attr, false)) {
2902                        viewFlagValues |= CLICKABLE;
2903                        viewFlagMasks |= CLICKABLE;
2904                    }
2905                    break;
2906                case com.android.internal.R.styleable.View_longClickable:
2907                    if (a.getBoolean(attr, false)) {
2908                        viewFlagValues |= LONG_CLICKABLE;
2909                        viewFlagMasks |= LONG_CLICKABLE;
2910                    }
2911                    break;
2912                case com.android.internal.R.styleable.View_saveEnabled:
2913                    if (!a.getBoolean(attr, true)) {
2914                        viewFlagValues |= SAVE_DISABLED;
2915                        viewFlagMasks |= SAVE_DISABLED_MASK;
2916                    }
2917                    break;
2918                case com.android.internal.R.styleable.View_duplicateParentState:
2919                    if (a.getBoolean(attr, false)) {
2920                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2921                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2922                    }
2923                    break;
2924                case com.android.internal.R.styleable.View_visibility:
2925                    final int visibility = a.getInt(attr, 0);
2926                    if (visibility != 0) {
2927                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2928                        viewFlagMasks |= VISIBILITY_MASK;
2929                    }
2930                    break;
2931                case com.android.internal.R.styleable.View_layoutDirection:
2932                    // Clear any HORIZONTAL_DIRECTION flag already set
2933                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2934                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2935                    final int layoutDirection = a.getInt(attr, -1);
2936                    if (layoutDirection != -1) {
2937                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2938                    } else {
2939                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2940                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2941                    }
2942                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2943                    break;
2944                case com.android.internal.R.styleable.View_drawingCacheQuality:
2945                    final int cacheQuality = a.getInt(attr, 0);
2946                    if (cacheQuality != 0) {
2947                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2948                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2949                    }
2950                    break;
2951                case com.android.internal.R.styleable.View_contentDescription:
2952                    mContentDescription = a.getString(attr);
2953                    break;
2954                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2955                    if (!a.getBoolean(attr, true)) {
2956                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2957                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2958                    }
2959                    break;
2960                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2961                    if (!a.getBoolean(attr, true)) {
2962                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2963                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2964                    }
2965                    break;
2966                case R.styleable.View_scrollbars:
2967                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2968                    if (scrollbars != SCROLLBARS_NONE) {
2969                        viewFlagValues |= scrollbars;
2970                        viewFlagMasks |= SCROLLBARS_MASK;
2971                        initializeScrollbars(a);
2972                    }
2973                    break;
2974                //noinspection deprecation
2975                case R.styleable.View_fadingEdge:
2976                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2977                        // Ignore the attribute starting with ICS
2978                        break;
2979                    }
2980                    // With builds < ICS, fall through and apply fading edges
2981                case R.styleable.View_requiresFadingEdge:
2982                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2983                    if (fadingEdge != FADING_EDGE_NONE) {
2984                        viewFlagValues |= fadingEdge;
2985                        viewFlagMasks |= FADING_EDGE_MASK;
2986                        initializeFadingEdge(a);
2987                    }
2988                    break;
2989                case R.styleable.View_scrollbarStyle:
2990                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2991                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2992                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2993                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2994                    }
2995                    break;
2996                case R.styleable.View_isScrollContainer:
2997                    setScrollContainer = true;
2998                    if (a.getBoolean(attr, false)) {
2999                        setScrollContainer(true);
3000                    }
3001                    break;
3002                case com.android.internal.R.styleable.View_keepScreenOn:
3003                    if (a.getBoolean(attr, false)) {
3004                        viewFlagValues |= KEEP_SCREEN_ON;
3005                        viewFlagMasks |= KEEP_SCREEN_ON;
3006                    }
3007                    break;
3008                case R.styleable.View_filterTouchesWhenObscured:
3009                    if (a.getBoolean(attr, false)) {
3010                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3011                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3012                    }
3013                    break;
3014                case R.styleable.View_nextFocusLeft:
3015                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3016                    break;
3017                case R.styleable.View_nextFocusRight:
3018                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3019                    break;
3020                case R.styleable.View_nextFocusUp:
3021                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3022                    break;
3023                case R.styleable.View_nextFocusDown:
3024                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3025                    break;
3026                case R.styleable.View_nextFocusForward:
3027                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3028                    break;
3029                case R.styleable.View_minWidth:
3030                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3031                    break;
3032                case R.styleable.View_minHeight:
3033                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3034                    break;
3035                case R.styleable.View_onClick:
3036                    if (context.isRestricted()) {
3037                        throw new IllegalStateException("The android:onClick attribute cannot "
3038                                + "be used within a restricted context");
3039                    }
3040
3041                    final String handlerName = a.getString(attr);
3042                    if (handlerName != null) {
3043                        setOnClickListener(new OnClickListener() {
3044                            private Method mHandler;
3045
3046                            public void onClick(View v) {
3047                                if (mHandler == null) {
3048                                    try {
3049                                        mHandler = getContext().getClass().getMethod(handlerName,
3050                                                View.class);
3051                                    } catch (NoSuchMethodException e) {
3052                                        int id = getId();
3053                                        String idText = id == NO_ID ? "" : " with id '"
3054                                                + getContext().getResources().getResourceEntryName(
3055                                                    id) + "'";
3056                                        throw new IllegalStateException("Could not find a method " +
3057                                                handlerName + "(View) in the activity "
3058                                                + getContext().getClass() + " for onClick handler"
3059                                                + " on view " + View.this.getClass() + idText, e);
3060                                    }
3061                                }
3062
3063                                try {
3064                                    mHandler.invoke(getContext(), View.this);
3065                                } catch (IllegalAccessException e) {
3066                                    throw new IllegalStateException("Could not execute non "
3067                                            + "public method of the activity", e);
3068                                } catch (InvocationTargetException e) {
3069                                    throw new IllegalStateException("Could not execute "
3070                                            + "method of the activity", e);
3071                                }
3072                            }
3073                        });
3074                    }
3075                    break;
3076                case R.styleable.View_overScrollMode:
3077                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3078                    break;
3079                case R.styleable.View_verticalScrollbarPosition:
3080                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3081                    break;
3082                case R.styleable.View_layerType:
3083                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3084                    break;
3085                case R.styleable.View_textDirection:
3086                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3087                    break;
3088            }
3089        }
3090
3091        a.recycle();
3092
3093        setOverScrollMode(overScrollMode);
3094
3095        if (background != null) {
3096            setBackgroundDrawable(background);
3097        }
3098
3099        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3100
3101        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3102        // layout direction). Those cached values will be used later during padding resolution.
3103        mUserPaddingStart = startPadding;
3104        mUserPaddingEnd = endPadding;
3105
3106        if (padding >= 0) {
3107            leftPadding = padding;
3108            topPadding = padding;
3109            rightPadding = padding;
3110            bottomPadding = padding;
3111        }
3112
3113        // If the user specified the padding (either with android:padding or
3114        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3115        // use the default padding or the padding from the background drawable
3116        // (stored at this point in mPadding*)
3117        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3118                topPadding >= 0 ? topPadding : mPaddingTop,
3119                rightPadding >= 0 ? rightPadding : mPaddingRight,
3120                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3121
3122        if (viewFlagMasks != 0) {
3123            setFlags(viewFlagValues, viewFlagMasks);
3124        }
3125
3126        // Needs to be called after mViewFlags is set
3127        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3128            recomputePadding();
3129        }
3130
3131        if (x != 0 || y != 0) {
3132            scrollTo(x, y);
3133        }
3134
3135        if (transformSet) {
3136            setTranslationX(tx);
3137            setTranslationY(ty);
3138            setRotation(rotation);
3139            setRotationX(rotationX);
3140            setRotationY(rotationY);
3141            setScaleX(sx);
3142            setScaleY(sy);
3143        }
3144
3145        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3146            setScrollContainer(true);
3147        }
3148
3149        computeOpaqueFlags();
3150    }
3151
3152    /**
3153     * Non-public constructor for use in testing
3154     */
3155    View() {
3156        mResources = null;
3157    }
3158
3159    /**
3160     * <p>
3161     * Initializes the fading edges from a given set of styled attributes. This
3162     * method should be called by subclasses that need fading edges and when an
3163     * instance of these subclasses is created programmatically rather than
3164     * being inflated from XML. This method is automatically called when the XML
3165     * is inflated.
3166     * </p>
3167     *
3168     * @param a the styled attributes set to initialize the fading edges from
3169     */
3170    protected void initializeFadingEdge(TypedArray a) {
3171        initScrollCache();
3172
3173        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3174                R.styleable.View_fadingEdgeLength,
3175                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3176    }
3177
3178    /**
3179     * Returns the size of the vertical faded edges used to indicate that more
3180     * content in this view is visible.
3181     *
3182     * @return The size in pixels of the vertical faded edge or 0 if vertical
3183     *         faded edges are not enabled for this view.
3184     * @attr ref android.R.styleable#View_fadingEdgeLength
3185     */
3186    public int getVerticalFadingEdgeLength() {
3187        if (isVerticalFadingEdgeEnabled()) {
3188            ScrollabilityCache cache = mScrollCache;
3189            if (cache != null) {
3190                return cache.fadingEdgeLength;
3191            }
3192        }
3193        return 0;
3194    }
3195
3196    /**
3197     * Set the size of the faded edge used to indicate that more content in this
3198     * view is available.  Will not change whether the fading edge is enabled; use
3199     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3200     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3201     * for the vertical or horizontal fading edges.
3202     *
3203     * @param length The size in pixels of the faded edge used to indicate that more
3204     *        content in this view is visible.
3205     */
3206    public void setFadingEdgeLength(int length) {
3207        initScrollCache();
3208        mScrollCache.fadingEdgeLength = length;
3209    }
3210
3211    /**
3212     * Returns the size of the horizontal faded edges used to indicate that more
3213     * content in this view is visible.
3214     *
3215     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3216     *         faded edges are not enabled for this view.
3217     * @attr ref android.R.styleable#View_fadingEdgeLength
3218     */
3219    public int getHorizontalFadingEdgeLength() {
3220        if (isHorizontalFadingEdgeEnabled()) {
3221            ScrollabilityCache cache = mScrollCache;
3222            if (cache != null) {
3223                return cache.fadingEdgeLength;
3224            }
3225        }
3226        return 0;
3227    }
3228
3229    /**
3230     * Returns the width of the vertical scrollbar.
3231     *
3232     * @return The width in pixels of the vertical scrollbar or 0 if there
3233     *         is no vertical scrollbar.
3234     */
3235    public int getVerticalScrollbarWidth() {
3236        ScrollabilityCache cache = mScrollCache;
3237        if (cache != null) {
3238            ScrollBarDrawable scrollBar = cache.scrollBar;
3239            if (scrollBar != null) {
3240                int size = scrollBar.getSize(true);
3241                if (size <= 0) {
3242                    size = cache.scrollBarSize;
3243                }
3244                return size;
3245            }
3246            return 0;
3247        }
3248        return 0;
3249    }
3250
3251    /**
3252     * Returns the height of the horizontal scrollbar.
3253     *
3254     * @return The height in pixels of the horizontal scrollbar or 0 if
3255     *         there is no horizontal scrollbar.
3256     */
3257    protected int getHorizontalScrollbarHeight() {
3258        ScrollabilityCache cache = mScrollCache;
3259        if (cache != null) {
3260            ScrollBarDrawable scrollBar = cache.scrollBar;
3261            if (scrollBar != null) {
3262                int size = scrollBar.getSize(false);
3263                if (size <= 0) {
3264                    size = cache.scrollBarSize;
3265                }
3266                return size;
3267            }
3268            return 0;
3269        }
3270        return 0;
3271    }
3272
3273    /**
3274     * <p>
3275     * Initializes the scrollbars from a given set of styled attributes. This
3276     * method should be called by subclasses that need scrollbars and when an
3277     * instance of these subclasses is created programmatically rather than
3278     * being inflated from XML. This method is automatically called when the XML
3279     * is inflated.
3280     * </p>
3281     *
3282     * @param a the styled attributes set to initialize the scrollbars from
3283     */
3284    protected void initializeScrollbars(TypedArray a) {
3285        initScrollCache();
3286
3287        final ScrollabilityCache scrollabilityCache = mScrollCache;
3288
3289        if (scrollabilityCache.scrollBar == null) {
3290            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3291        }
3292
3293        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3294
3295        if (!fadeScrollbars) {
3296            scrollabilityCache.state = ScrollabilityCache.ON;
3297        }
3298        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3299
3300
3301        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3302                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3303                        .getScrollBarFadeDuration());
3304        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3305                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3306                ViewConfiguration.getScrollDefaultDelay());
3307
3308
3309        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3310                com.android.internal.R.styleable.View_scrollbarSize,
3311                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3312
3313        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3314        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3315
3316        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3317        if (thumb != null) {
3318            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3319        }
3320
3321        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3322                false);
3323        if (alwaysDraw) {
3324            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3325        }
3326
3327        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3328        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3329
3330        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3331        if (thumb != null) {
3332            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3333        }
3334
3335        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3336                false);
3337        if (alwaysDraw) {
3338            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3339        }
3340
3341        // Re-apply user/background padding so that scrollbar(s) get added
3342        resolvePadding();
3343    }
3344
3345    /**
3346     * <p>
3347     * Initalizes the scrollability cache if necessary.
3348     * </p>
3349     */
3350    private void initScrollCache() {
3351        if (mScrollCache == null) {
3352            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3353        }
3354    }
3355
3356    /**
3357     * Set the position of the vertical scroll bar. Should be one of
3358     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3359     * {@link #SCROLLBAR_POSITION_RIGHT}.
3360     *
3361     * @param position Where the vertical scroll bar should be positioned.
3362     */
3363    public void setVerticalScrollbarPosition(int position) {
3364        if (mVerticalScrollbarPosition != position) {
3365            mVerticalScrollbarPosition = position;
3366            computeOpaqueFlags();
3367            resolvePadding();
3368        }
3369    }
3370
3371    /**
3372     * @return The position where the vertical scroll bar will show, if applicable.
3373     * @see #setVerticalScrollbarPosition(int)
3374     */
3375    public int getVerticalScrollbarPosition() {
3376        return mVerticalScrollbarPosition;
3377    }
3378
3379    ListenerInfo getListenerInfo() {
3380        if (mListenerInfo != null) {
3381            return mListenerInfo;
3382        }
3383        mListenerInfo = new ListenerInfo();
3384        return mListenerInfo;
3385    }
3386
3387    /**
3388     * Register a callback to be invoked when focus of this view changed.
3389     *
3390     * @param l The callback that will run.
3391     */
3392    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3393        getListenerInfo().mOnFocusChangeListener = l;
3394    }
3395
3396    /**
3397     * Add a listener that will be called when the bounds of the view change due to
3398     * layout processing.
3399     *
3400     * @param listener The listener that will be called when layout bounds change.
3401     */
3402    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3403        ListenerInfo li = getListenerInfo();
3404        if (li.mOnLayoutChangeListeners == null) {
3405            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3406        }
3407        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3408            li.mOnLayoutChangeListeners.add(listener);
3409        }
3410    }
3411
3412    /**
3413     * Remove a listener for layout changes.
3414     *
3415     * @param listener The listener for layout bounds change.
3416     */
3417    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3418        ListenerInfo li = mListenerInfo;
3419        if (li == null || li.mOnLayoutChangeListeners == null) {
3420            return;
3421        }
3422        li.mOnLayoutChangeListeners.remove(listener);
3423    }
3424
3425    /**
3426     * Add a listener for attach state changes.
3427     *
3428     * This listener will be called whenever this view is attached or detached
3429     * from a window. Remove the listener using
3430     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3431     *
3432     * @param listener Listener to attach
3433     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3434     */
3435    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3436        ListenerInfo li = getListenerInfo();
3437        if (li.mOnAttachStateChangeListeners == null) {
3438            li.mOnAttachStateChangeListeners
3439                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3440        }
3441        li.mOnAttachStateChangeListeners.add(listener);
3442    }
3443
3444    /**
3445     * Remove a listener for attach state changes. The listener will receive no further
3446     * notification of window attach/detach events.
3447     *
3448     * @param listener Listener to remove
3449     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3450     */
3451    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3452        ListenerInfo li = mListenerInfo;
3453        if (li == null || li.mOnAttachStateChangeListeners == null) {
3454            return;
3455        }
3456        li.mOnAttachStateChangeListeners.remove(listener);
3457    }
3458
3459    /**
3460     * Returns the focus-change callback registered for this view.
3461     *
3462     * @return The callback, or null if one is not registered.
3463     */
3464    public OnFocusChangeListener getOnFocusChangeListener() {
3465        ListenerInfo li = mListenerInfo;
3466        return li != null ? li.mOnFocusChangeListener : null;
3467    }
3468
3469    /**
3470     * Register a callback to be invoked when this view is clicked. If this view is not
3471     * clickable, it becomes clickable.
3472     *
3473     * @param l The callback that will run
3474     *
3475     * @see #setClickable(boolean)
3476     */
3477    public void setOnClickListener(OnClickListener l) {
3478        if (!isClickable()) {
3479            setClickable(true);
3480        }
3481        getListenerInfo().mOnClickListener = l;
3482    }
3483
3484    /**
3485     * Return whether this view has an attached OnClickListener.  Returns
3486     * true if there is a listener, false if there is none.
3487     */
3488    public boolean hasOnClickListeners() {
3489        ListenerInfo li = mListenerInfo;
3490        return (li != null && li.mOnClickListener != null);
3491    }
3492
3493    /**
3494     * Register a callback to be invoked when this view is clicked and held. If this view is not
3495     * long clickable, it becomes long clickable.
3496     *
3497     * @param l The callback that will run
3498     *
3499     * @see #setLongClickable(boolean)
3500     */
3501    public void setOnLongClickListener(OnLongClickListener l) {
3502        if (!isLongClickable()) {
3503            setLongClickable(true);
3504        }
3505        getListenerInfo().mOnLongClickListener = l;
3506    }
3507
3508    /**
3509     * Register a callback to be invoked when the context menu for this view is
3510     * being built. If this view is not long clickable, it becomes long clickable.
3511     *
3512     * @param l The callback that will run
3513     *
3514     */
3515    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3516        if (!isLongClickable()) {
3517            setLongClickable(true);
3518        }
3519        getListenerInfo().mOnCreateContextMenuListener = l;
3520    }
3521
3522    /**
3523     * Call this view's OnClickListener, if it is defined.  Performs all normal
3524     * actions associated with clicking: reporting accessibility event, playing
3525     * a sound, etc.
3526     *
3527     * @return True there was an assigned OnClickListener that was called, false
3528     *         otherwise is returned.
3529     */
3530    public boolean performClick() {
3531        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3532
3533        ListenerInfo li = mListenerInfo;
3534        if (li != null && li.mOnClickListener != null) {
3535            playSoundEffect(SoundEffectConstants.CLICK);
3536            li.mOnClickListener.onClick(this);
3537            return true;
3538        }
3539
3540        return false;
3541    }
3542
3543    /**
3544     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3545     * this only calls the listener, and does not do any associated clicking
3546     * actions like reporting an accessibility event.
3547     *
3548     * @return True there was an assigned OnClickListener that was called, false
3549     *         otherwise is returned.
3550     */
3551    public boolean callOnClick() {
3552        ListenerInfo li = mListenerInfo;
3553        if (li != null && li.mOnClickListener != null) {
3554            li.mOnClickListener.onClick(this);
3555            return true;
3556        }
3557        return false;
3558    }
3559
3560    /**
3561     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3562     * OnLongClickListener did not consume the event.
3563     *
3564     * @return True if one of the above receivers consumed the event, false otherwise.
3565     */
3566    public boolean performLongClick() {
3567        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3568
3569        boolean handled = false;
3570        ListenerInfo li = mListenerInfo;
3571        if (li != null && li.mOnLongClickListener != null) {
3572            handled = li.mOnLongClickListener.onLongClick(View.this);
3573        }
3574        if (!handled) {
3575            handled = showContextMenu();
3576        }
3577        if (handled) {
3578            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3579        }
3580        return handled;
3581    }
3582
3583    /**
3584     * Performs button-related actions during a touch down event.
3585     *
3586     * @param event The event.
3587     * @return True if the down was consumed.
3588     *
3589     * @hide
3590     */
3591    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3592        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3593            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3594                return true;
3595            }
3596        }
3597        return false;
3598    }
3599
3600    /**
3601     * Bring up the context menu for this view.
3602     *
3603     * @return Whether a context menu was displayed.
3604     */
3605    public boolean showContextMenu() {
3606        return getParent().showContextMenuForChild(this);
3607    }
3608
3609    /**
3610     * Bring up the context menu for this view, referring to the item under the specified point.
3611     *
3612     * @param x The referenced x coordinate.
3613     * @param y The referenced y coordinate.
3614     * @param metaState The keyboard modifiers that were pressed.
3615     * @return Whether a context menu was displayed.
3616     *
3617     * @hide
3618     */
3619    public boolean showContextMenu(float x, float y, int metaState) {
3620        return showContextMenu();
3621    }
3622
3623    /**
3624     * Start an action mode.
3625     *
3626     * @param callback Callback that will control the lifecycle of the action mode
3627     * @return The new action mode if it is started, null otherwise
3628     *
3629     * @see ActionMode
3630     */
3631    public ActionMode startActionMode(ActionMode.Callback callback) {
3632        return getParent().startActionModeForChild(this, callback);
3633    }
3634
3635    /**
3636     * Register a callback to be invoked when a key is pressed in this view.
3637     * @param l the key listener to attach to this view
3638     */
3639    public void setOnKeyListener(OnKeyListener l) {
3640        getListenerInfo().mOnKeyListener = l;
3641    }
3642
3643    /**
3644     * Register a callback to be invoked when a touch event is sent to this view.
3645     * @param l the touch listener to attach to this view
3646     */
3647    public void setOnTouchListener(OnTouchListener l) {
3648        getListenerInfo().mOnTouchListener = l;
3649    }
3650
3651    /**
3652     * Register a callback to be invoked when a generic motion event is sent to this view.
3653     * @param l the generic motion listener to attach to this view
3654     */
3655    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3656        getListenerInfo().mOnGenericMotionListener = l;
3657    }
3658
3659    /**
3660     * Register a callback to be invoked when a hover event is sent to this view.
3661     * @param l the hover listener to attach to this view
3662     */
3663    public void setOnHoverListener(OnHoverListener l) {
3664        getListenerInfo().mOnHoverListener = l;
3665    }
3666
3667    /**
3668     * Register a drag event listener callback object for this View. The parameter is
3669     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3670     * View, the system calls the
3671     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3672     * @param l An implementation of {@link android.view.View.OnDragListener}.
3673     */
3674    public void setOnDragListener(OnDragListener l) {
3675        getListenerInfo().mOnDragListener = l;
3676    }
3677
3678    /**
3679     * Give this view focus. This will cause
3680     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3681     *
3682     * Note: this does not check whether this {@link View} should get focus, it just
3683     * gives it focus no matter what.  It should only be called internally by framework
3684     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3685     *
3686     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3687     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3688     *        focus moved when requestFocus() is called. It may not always
3689     *        apply, in which case use the default View.FOCUS_DOWN.
3690     * @param previouslyFocusedRect The rectangle of the view that had focus
3691     *        prior in this View's coordinate system.
3692     */
3693    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3694        if (DBG) {
3695            System.out.println(this + " requestFocus()");
3696        }
3697
3698        if ((mPrivateFlags & FOCUSED) == 0) {
3699            mPrivateFlags |= FOCUSED;
3700
3701            if (mParent != null) {
3702                mParent.requestChildFocus(this, this);
3703            }
3704
3705            onFocusChanged(true, direction, previouslyFocusedRect);
3706            refreshDrawableState();
3707        }
3708    }
3709
3710    /**
3711     * Request that a rectangle of this view be visible on the screen,
3712     * scrolling if necessary just enough.
3713     *
3714     * <p>A View should call this if it maintains some notion of which part
3715     * of its content is interesting.  For example, a text editing view
3716     * should call this when its cursor moves.
3717     *
3718     * @param rectangle The rectangle.
3719     * @return Whether any parent scrolled.
3720     */
3721    public boolean requestRectangleOnScreen(Rect rectangle) {
3722        return requestRectangleOnScreen(rectangle, false);
3723    }
3724
3725    /**
3726     * Request that a rectangle of this view be visible on the screen,
3727     * scrolling if necessary just enough.
3728     *
3729     * <p>A View should call this if it maintains some notion of which part
3730     * of its content is interesting.  For example, a text editing view
3731     * should call this when its cursor moves.
3732     *
3733     * <p>When <code>immediate</code> is set to true, scrolling will not be
3734     * animated.
3735     *
3736     * @param rectangle The rectangle.
3737     * @param immediate True to forbid animated scrolling, false otherwise
3738     * @return Whether any parent scrolled.
3739     */
3740    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3741        View child = this;
3742        ViewParent parent = mParent;
3743        boolean scrolled = false;
3744        while (parent != null) {
3745            scrolled |= parent.requestChildRectangleOnScreen(child,
3746                    rectangle, immediate);
3747
3748            // offset rect so next call has the rectangle in the
3749            // coordinate system of its direct child.
3750            rectangle.offset(child.getLeft(), child.getTop());
3751            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3752
3753            if (!(parent instanceof View)) {
3754                break;
3755            }
3756
3757            child = (View) parent;
3758            parent = child.getParent();
3759        }
3760        return scrolled;
3761    }
3762
3763    /**
3764     * Called when this view wants to give up focus. This will cause
3765     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3766     */
3767    public void clearFocus() {
3768        if (DBG) {
3769            System.out.println(this + " clearFocus()");
3770        }
3771
3772        if ((mPrivateFlags & FOCUSED) != 0) {
3773            // If this is the first focusable do not clear focus since the we
3774            // try to give it focus every time a view clears its focus. Hence,
3775            // the view that would gain focus already has it.
3776            View firstFocusable = getFirstFocusable();
3777            if (firstFocusable == this) {
3778                return;
3779            }
3780
3781            mPrivateFlags &= ~FOCUSED;
3782
3783            if (mParent != null) {
3784                mParent.clearChildFocus(this);
3785            }
3786
3787            onFocusChanged(false, 0, null);
3788            refreshDrawableState();
3789
3790            // The view cleared focus and invoked the callbacks, so  now is the
3791            // time to give focus to the the first focusable to ensure that the
3792            // gain focus is announced after clear focus.
3793            if (firstFocusable != null) {
3794                firstFocusable.requestFocus(FOCUS_FORWARD);
3795            }
3796        }
3797    }
3798
3799    private View getFirstFocusable() {
3800        ViewRootImpl viewRoot = getViewRootImpl();
3801        if (viewRoot != null) {
3802            return viewRoot.focusSearch(null, FOCUS_FORWARD);
3803        }
3804        return null;
3805    }
3806
3807    /**
3808     * Called to clear the focus of a view that is about to be removed.
3809     * Doesn't call clearChildFocus, which prevents this view from taking
3810     * focus again before it has been removed from the parent
3811     */
3812    void clearFocusForRemoval() {
3813        if ((mPrivateFlags & FOCUSED) != 0) {
3814            mPrivateFlags &= ~FOCUSED;
3815
3816            onFocusChanged(false, 0, null);
3817            refreshDrawableState();
3818        }
3819    }
3820
3821    /**
3822     * Called internally by the view system when a new view is getting focus.
3823     * This is what clears the old focus.
3824     */
3825    void unFocus() {
3826        if (DBG) {
3827            System.out.println(this + " unFocus()");
3828        }
3829
3830        if ((mPrivateFlags & FOCUSED) != 0) {
3831            mPrivateFlags &= ~FOCUSED;
3832
3833            onFocusChanged(false, 0, null);
3834            refreshDrawableState();
3835        }
3836    }
3837
3838    /**
3839     * Returns true if this view has focus iteself, or is the ancestor of the
3840     * view that has focus.
3841     *
3842     * @return True if this view has or contains focus, false otherwise.
3843     */
3844    @ViewDebug.ExportedProperty(category = "focus")
3845    public boolean hasFocus() {
3846        return (mPrivateFlags & FOCUSED) != 0;
3847    }
3848
3849    /**
3850     * Returns true if this view is focusable or if it contains a reachable View
3851     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3852     * is a View whose parents do not block descendants focus.
3853     *
3854     * Only {@link #VISIBLE} views are considered focusable.
3855     *
3856     * @return True if the view is focusable or if the view contains a focusable
3857     *         View, false otherwise.
3858     *
3859     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3860     */
3861    public boolean hasFocusable() {
3862        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3863    }
3864
3865    /**
3866     * Called by the view system when the focus state of this view changes.
3867     * When the focus change event is caused by directional navigation, direction
3868     * and previouslyFocusedRect provide insight into where the focus is coming from.
3869     * When overriding, be sure to call up through to the super class so that
3870     * the standard focus handling will occur.
3871     *
3872     * @param gainFocus True if the View has focus; false otherwise.
3873     * @param direction The direction focus has moved when requestFocus()
3874     *                  is called to give this view focus. Values are
3875     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3876     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3877     *                  It may not always apply, in which case use the default.
3878     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3879     *        system, of the previously focused view.  If applicable, this will be
3880     *        passed in as finer grained information about where the focus is coming
3881     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3882     */
3883    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3884        if (gainFocus) {
3885            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3886        }
3887
3888        InputMethodManager imm = InputMethodManager.peekInstance();
3889        if (!gainFocus) {
3890            if (isPressed()) {
3891                setPressed(false);
3892            }
3893            if (imm != null && mAttachInfo != null
3894                    && mAttachInfo.mHasWindowFocus) {
3895                imm.focusOut(this);
3896            }
3897            onFocusLost();
3898        } else if (imm != null && mAttachInfo != null
3899                && mAttachInfo.mHasWindowFocus) {
3900            imm.focusIn(this);
3901        }
3902
3903        invalidate(true);
3904        ListenerInfo li = mListenerInfo;
3905        if (li != null && li.mOnFocusChangeListener != null) {
3906            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3907        }
3908
3909        if (mAttachInfo != null) {
3910            mAttachInfo.mKeyDispatchState.reset(this);
3911        }
3912    }
3913
3914    /**
3915     * Sends an accessibility event of the given type. If accessiiblity is
3916     * not enabled this method has no effect. The default implementation calls
3917     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3918     * to populate information about the event source (this View), then calls
3919     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3920     * populate the text content of the event source including its descendants,
3921     * and last calls
3922     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3923     * on its parent to resuest sending of the event to interested parties.
3924     * <p>
3925     * If an {@link AccessibilityDelegate} has been specified via calling
3926     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3927     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3928     * responsible for handling this call.
3929     * </p>
3930     *
3931     * @param eventType The type of the event to send, as defined by several types from
3932     * {@link android.view.accessibility.AccessibilityEvent}, such as
3933     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3934     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3935     *
3936     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3937     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3938     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3939     * @see AccessibilityDelegate
3940     */
3941    public void sendAccessibilityEvent(int eventType) {
3942        if (mAccessibilityDelegate != null) {
3943            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3944        } else {
3945            sendAccessibilityEventInternal(eventType);
3946        }
3947    }
3948
3949    /**
3950     * @see #sendAccessibilityEvent(int)
3951     *
3952     * Note: Called from the default {@link AccessibilityDelegate}.
3953     */
3954    void sendAccessibilityEventInternal(int eventType) {
3955        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3956            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3957        }
3958    }
3959
3960    /**
3961     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3962     * takes as an argument an empty {@link AccessibilityEvent} and does not
3963     * perform a check whether accessibility is enabled.
3964     * <p>
3965     * If an {@link AccessibilityDelegate} has been specified via calling
3966     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3967     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3968     * is responsible for handling this call.
3969     * </p>
3970     *
3971     * @param event The event to send.
3972     *
3973     * @see #sendAccessibilityEvent(int)
3974     */
3975    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3976        if (mAccessibilityDelegate != null) {
3977           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3978        } else {
3979            sendAccessibilityEventUncheckedInternal(event);
3980        }
3981    }
3982
3983    /**
3984     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3985     *
3986     * Note: Called from the default {@link AccessibilityDelegate}.
3987     */
3988    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3989        if (!isShown()) {
3990            return;
3991        }
3992        onInitializeAccessibilityEvent(event);
3993        // Only a subset of accessibility events populates text content.
3994        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
3995            dispatchPopulateAccessibilityEvent(event);
3996        }
3997        // In the beginning we called #isShown(), so we know that getParent() is not null.
3998        getParent().requestSendAccessibilityEvent(this, event);
3999    }
4000
4001    /**
4002     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4003     * to its children for adding their text content to the event. Note that the
4004     * event text is populated in a separate dispatch path since we add to the
4005     * event not only the text of the source but also the text of all its descendants.
4006     * A typical implementation will call
4007     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4008     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4009     * on each child. Override this method if custom population of the event text
4010     * content is required.
4011     * <p>
4012     * If an {@link AccessibilityDelegate} has been specified via calling
4013     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4014     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4015     * is responsible for handling this call.
4016     * </p>
4017     * <p>
4018     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4019     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4020     * </p>
4021     *
4022     * @param event The event.
4023     *
4024     * @return True if the event population was completed.
4025     */
4026    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4027        if (mAccessibilityDelegate != null) {
4028            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4029        } else {
4030            return dispatchPopulateAccessibilityEventInternal(event);
4031        }
4032    }
4033
4034    /**
4035     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4036     *
4037     * Note: Called from the default {@link AccessibilityDelegate}.
4038     */
4039    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4040        onPopulateAccessibilityEvent(event);
4041        return false;
4042    }
4043
4044    /**
4045     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4046     * giving a chance to this View to populate the accessibility event with its
4047     * text content. While this method is free to modify event
4048     * attributes other than text content, doing so should normally be performed in
4049     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4050     * <p>
4051     * Example: Adding formatted date string to an accessibility event in addition
4052     *          to the text added by the super implementation:
4053     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4054     *     super.onPopulateAccessibilityEvent(event);
4055     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4056     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4057     *         mCurrentDate.getTimeInMillis(), flags);
4058     *     event.getText().add(selectedDateUtterance);
4059     * }</pre>
4060     * <p>
4061     * If an {@link AccessibilityDelegate} has been specified via calling
4062     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4063     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4064     * is responsible for handling this call.
4065     * </p>
4066     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4067     * information to the event, in case the default implementation has basic information to add.
4068     * </p>
4069     *
4070     * @param event The accessibility event which to populate.
4071     *
4072     * @see #sendAccessibilityEvent(int)
4073     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4074     */
4075    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4076        if (mAccessibilityDelegate != null) {
4077            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4078        } else {
4079            onPopulateAccessibilityEventInternal(event);
4080        }
4081    }
4082
4083    /**
4084     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4085     *
4086     * Note: Called from the default {@link AccessibilityDelegate}.
4087     */
4088    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4089
4090    }
4091
4092    /**
4093     * Initializes an {@link AccessibilityEvent} with information about
4094     * this View which is the event source. In other words, the source of
4095     * an accessibility event is the view whose state change triggered firing
4096     * the event.
4097     * <p>
4098     * Example: Setting the password property of an event in addition
4099     *          to properties set by the super implementation:
4100     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4101     *     super.onInitializeAccessibilityEvent(event);
4102     *     event.setPassword(true);
4103     * }</pre>
4104     * <p>
4105     * If an {@link AccessibilityDelegate} has been specified via calling
4106     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4107     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4108     * is responsible for handling this call.
4109     * </p>
4110     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4111     * information to the event, in case the default implementation has basic information to add.
4112     * </p>
4113     * @param event The event to initialize.
4114     *
4115     * @see #sendAccessibilityEvent(int)
4116     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4117     */
4118    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4119        if (mAccessibilityDelegate != null) {
4120            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4121        } else {
4122            onInitializeAccessibilityEventInternal(event);
4123        }
4124    }
4125
4126    /**
4127     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4128     *
4129     * Note: Called from the default {@link AccessibilityDelegate}.
4130     */
4131    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4132        event.setSource(this);
4133        event.setClassName(View.class.getName());
4134        event.setPackageName(getContext().getPackageName());
4135        event.setEnabled(isEnabled());
4136        event.setContentDescription(mContentDescription);
4137
4138        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4139            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4140            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4141                    FOCUSABLES_ALL);
4142            event.setItemCount(focusablesTempList.size());
4143            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4144            focusablesTempList.clear();
4145        }
4146    }
4147
4148    /**
4149     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4150     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4151     * This method is responsible for obtaining an accessibility node info from a
4152     * pool of reusable instances and calling
4153     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4154     * initialize the former.
4155     * <p>
4156     * Note: The client is responsible for recycling the obtained instance by calling
4157     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4158     * </p>
4159     *
4160     * @return A populated {@link AccessibilityNodeInfo}.
4161     *
4162     * @see AccessibilityNodeInfo
4163     */
4164    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4165        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4166        if (provider != null) {
4167            return provider.createAccessibilityNodeInfo(View.NO_ID);
4168        } else {
4169            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4170            onInitializeAccessibilityNodeInfo(info);
4171            return info;
4172        }
4173    }
4174
4175    /**
4176     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4177     * The base implementation sets:
4178     * <ul>
4179     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4180     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4181     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4182     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4183     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4184     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4185     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4186     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4187     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4188     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4189     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4190     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4191     * </ul>
4192     * <p>
4193     * Subclasses should override this method, call the super implementation,
4194     * and set additional attributes.
4195     * </p>
4196     * <p>
4197     * If an {@link AccessibilityDelegate} has been specified via calling
4198     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4199     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4200     * is responsible for handling this call.
4201     * </p>
4202     *
4203     * @param info The instance to initialize.
4204     */
4205    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4206        if (mAccessibilityDelegate != null) {
4207            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4208        } else {
4209            onInitializeAccessibilityNodeInfoInternal(info);
4210        }
4211    }
4212
4213    /**
4214     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4215     *
4216     * Note: Called from the default {@link AccessibilityDelegate}.
4217     */
4218    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4219        Rect bounds = mAttachInfo.mTmpInvalRect;
4220        getDrawingRect(bounds);
4221        info.setBoundsInParent(bounds);
4222
4223        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4224        getLocationOnScreen(locationOnScreen);
4225        bounds.offsetTo(0, 0);
4226        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4227        info.setBoundsInScreen(bounds);
4228
4229        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4230            ViewParent parent = getParent();
4231            if (parent instanceof View) {
4232                View parentView = (View) parent;
4233                info.setParent(parentView);
4234            }
4235        }
4236
4237        info.setPackageName(mContext.getPackageName());
4238        info.setClassName(View.class.getName());
4239        info.setContentDescription(getContentDescription());
4240
4241        info.setEnabled(isEnabled());
4242        info.setClickable(isClickable());
4243        info.setFocusable(isFocusable());
4244        info.setFocused(isFocused());
4245        info.setSelected(isSelected());
4246        info.setLongClickable(isLongClickable());
4247
4248        // TODO: These make sense only if we are in an AdapterView but all
4249        // views can be selected. Maybe from accessiiblity perspective
4250        // we should report as selectable view in an AdapterView.
4251        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4252        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4253
4254        if (isFocusable()) {
4255            if (isFocused()) {
4256                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4257            } else {
4258                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4259            }
4260        }
4261    }
4262
4263    /**
4264     * Sets a delegate for implementing accessibility support via compositon as
4265     * opposed to inheritance. The delegate's primary use is for implementing
4266     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4267     *
4268     * @param delegate The delegate instance.
4269     *
4270     * @see AccessibilityDelegate
4271     */
4272    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4273        mAccessibilityDelegate = delegate;
4274    }
4275
4276    /**
4277     * Gets the provider for managing a virtual view hierarchy rooted at this View
4278     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4279     * that explore the window content.
4280     * <p>
4281     * If this method returns an instance, this instance is responsible for managing
4282     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4283     * View including the one representing the View itself. Similarly the returned
4284     * instance is responsible for performing accessibility actions on any virtual
4285     * view or the root view itself.
4286     * </p>
4287     * <p>
4288     * If an {@link AccessibilityDelegate} has been specified via calling
4289     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4290     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4291     * is responsible for handling this call.
4292     * </p>
4293     *
4294     * @return The provider.
4295     *
4296     * @see AccessibilityNodeProvider
4297     */
4298    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4299        if (mAccessibilityDelegate != null) {
4300            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4301        } else {
4302            return null;
4303        }
4304    }
4305
4306    /**
4307     * Gets the unique identifier of this view on the screen for accessibility purposes.
4308     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4309     *
4310     * @return The view accessibility id.
4311     *
4312     * @hide
4313     */
4314    public int getAccessibilityViewId() {
4315        if (mAccessibilityViewId == NO_ID) {
4316            mAccessibilityViewId = sNextAccessibilityViewId++;
4317        }
4318        return mAccessibilityViewId;
4319    }
4320
4321    /**
4322     * Gets the unique identifier of the window in which this View reseides.
4323     *
4324     * @return The window accessibility id.
4325     *
4326     * @hide
4327     */
4328    public int getAccessibilityWindowId() {
4329        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4330    }
4331
4332    /**
4333     * Gets the {@link View} description. It briefly describes the view and is
4334     * primarily used for accessibility support. Set this property to enable
4335     * better accessibility support for your application. This is especially
4336     * true for views that do not have textual representation (For example,
4337     * ImageButton).
4338     *
4339     * @return The content descriptiopn.
4340     *
4341     * @attr ref android.R.styleable#View_contentDescription
4342     */
4343    public CharSequence getContentDescription() {
4344        return mContentDescription;
4345    }
4346
4347    /**
4348     * Sets the {@link View} description. It briefly describes the view and is
4349     * primarily used for accessibility support. Set this property to enable
4350     * better accessibility support for your application. This is especially
4351     * true for views that do not have textual representation (For example,
4352     * ImageButton).
4353     *
4354     * @param contentDescription The content description.
4355     *
4356     * @attr ref android.R.styleable#View_contentDescription
4357     */
4358    @RemotableViewMethod
4359    public void setContentDescription(CharSequence contentDescription) {
4360        mContentDescription = contentDescription;
4361    }
4362
4363    /**
4364     * Invoked whenever this view loses focus, either by losing window focus or by losing
4365     * focus within its window. This method can be used to clear any state tied to the
4366     * focus. For instance, if a button is held pressed with the trackball and the window
4367     * loses focus, this method can be used to cancel the press.
4368     *
4369     * Subclasses of View overriding this method should always call super.onFocusLost().
4370     *
4371     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4372     * @see #onWindowFocusChanged(boolean)
4373     *
4374     * @hide pending API council approval
4375     */
4376    protected void onFocusLost() {
4377        resetPressedState();
4378    }
4379
4380    private void resetPressedState() {
4381        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4382            return;
4383        }
4384
4385        if (isPressed()) {
4386            setPressed(false);
4387
4388            if (!mHasPerformedLongPress) {
4389                removeLongPressCallback();
4390            }
4391        }
4392    }
4393
4394    /**
4395     * Returns true if this view has focus
4396     *
4397     * @return True if this view has focus, false otherwise.
4398     */
4399    @ViewDebug.ExportedProperty(category = "focus")
4400    public boolean isFocused() {
4401        return (mPrivateFlags & FOCUSED) != 0;
4402    }
4403
4404    /**
4405     * Find the view in the hierarchy rooted at this view that currently has
4406     * focus.
4407     *
4408     * @return The view that currently has focus, or null if no focused view can
4409     *         be found.
4410     */
4411    public View findFocus() {
4412        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4413    }
4414
4415    /**
4416     * Change whether this view is one of the set of scrollable containers in
4417     * its window.  This will be used to determine whether the window can
4418     * resize or must pan when a soft input area is open -- scrollable
4419     * containers allow the window to use resize mode since the container
4420     * will appropriately shrink.
4421     */
4422    public void setScrollContainer(boolean isScrollContainer) {
4423        if (isScrollContainer) {
4424            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4425                mAttachInfo.mScrollContainers.add(this);
4426                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4427            }
4428            mPrivateFlags |= SCROLL_CONTAINER;
4429        } else {
4430            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4431                mAttachInfo.mScrollContainers.remove(this);
4432            }
4433            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4434        }
4435    }
4436
4437    /**
4438     * Returns the quality of the drawing cache.
4439     *
4440     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4441     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4442     *
4443     * @see #setDrawingCacheQuality(int)
4444     * @see #setDrawingCacheEnabled(boolean)
4445     * @see #isDrawingCacheEnabled()
4446     *
4447     * @attr ref android.R.styleable#View_drawingCacheQuality
4448     */
4449    public int getDrawingCacheQuality() {
4450        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4451    }
4452
4453    /**
4454     * Set the drawing cache quality of this view. This value is used only when the
4455     * drawing cache is enabled
4456     *
4457     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4458     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4459     *
4460     * @see #getDrawingCacheQuality()
4461     * @see #setDrawingCacheEnabled(boolean)
4462     * @see #isDrawingCacheEnabled()
4463     *
4464     * @attr ref android.R.styleable#View_drawingCacheQuality
4465     */
4466    public void setDrawingCacheQuality(int quality) {
4467        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4468    }
4469
4470    /**
4471     * Returns whether the screen should remain on, corresponding to the current
4472     * value of {@link #KEEP_SCREEN_ON}.
4473     *
4474     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4475     *
4476     * @see #setKeepScreenOn(boolean)
4477     *
4478     * @attr ref android.R.styleable#View_keepScreenOn
4479     */
4480    public boolean getKeepScreenOn() {
4481        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4482    }
4483
4484    /**
4485     * Controls whether the screen should remain on, modifying the
4486     * value of {@link #KEEP_SCREEN_ON}.
4487     *
4488     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4489     *
4490     * @see #getKeepScreenOn()
4491     *
4492     * @attr ref android.R.styleable#View_keepScreenOn
4493     */
4494    public void setKeepScreenOn(boolean keepScreenOn) {
4495        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4496    }
4497
4498    /**
4499     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4500     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4501     *
4502     * @attr ref android.R.styleable#View_nextFocusLeft
4503     */
4504    public int getNextFocusLeftId() {
4505        return mNextFocusLeftId;
4506    }
4507
4508    /**
4509     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4510     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4511     * decide automatically.
4512     *
4513     * @attr ref android.R.styleable#View_nextFocusLeft
4514     */
4515    public void setNextFocusLeftId(int nextFocusLeftId) {
4516        mNextFocusLeftId = nextFocusLeftId;
4517    }
4518
4519    /**
4520     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4521     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4522     *
4523     * @attr ref android.R.styleable#View_nextFocusRight
4524     */
4525    public int getNextFocusRightId() {
4526        return mNextFocusRightId;
4527    }
4528
4529    /**
4530     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4531     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4532     * decide automatically.
4533     *
4534     * @attr ref android.R.styleable#View_nextFocusRight
4535     */
4536    public void setNextFocusRightId(int nextFocusRightId) {
4537        mNextFocusRightId = nextFocusRightId;
4538    }
4539
4540    /**
4541     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4542     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4543     *
4544     * @attr ref android.R.styleable#View_nextFocusUp
4545     */
4546    public int getNextFocusUpId() {
4547        return mNextFocusUpId;
4548    }
4549
4550    /**
4551     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4552     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4553     * decide automatically.
4554     *
4555     * @attr ref android.R.styleable#View_nextFocusUp
4556     */
4557    public void setNextFocusUpId(int nextFocusUpId) {
4558        mNextFocusUpId = nextFocusUpId;
4559    }
4560
4561    /**
4562     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4563     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4564     *
4565     * @attr ref android.R.styleable#View_nextFocusDown
4566     */
4567    public int getNextFocusDownId() {
4568        return mNextFocusDownId;
4569    }
4570
4571    /**
4572     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4573     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4574     * decide automatically.
4575     *
4576     * @attr ref android.R.styleable#View_nextFocusDown
4577     */
4578    public void setNextFocusDownId(int nextFocusDownId) {
4579        mNextFocusDownId = nextFocusDownId;
4580    }
4581
4582    /**
4583     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4584     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4585     *
4586     * @attr ref android.R.styleable#View_nextFocusForward
4587     */
4588    public int getNextFocusForwardId() {
4589        return mNextFocusForwardId;
4590    }
4591
4592    /**
4593     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4594     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4595     * decide automatically.
4596     *
4597     * @attr ref android.R.styleable#View_nextFocusForward
4598     */
4599    public void setNextFocusForwardId(int nextFocusForwardId) {
4600        mNextFocusForwardId = nextFocusForwardId;
4601    }
4602
4603    /**
4604     * Returns the visibility of this view and all of its ancestors
4605     *
4606     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4607     */
4608    public boolean isShown() {
4609        View current = this;
4610        //noinspection ConstantConditions
4611        do {
4612            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4613                return false;
4614            }
4615            ViewParent parent = current.mParent;
4616            if (parent == null) {
4617                return false; // We are not attached to the view root
4618            }
4619            if (!(parent instanceof View)) {
4620                return true;
4621            }
4622            current = (View) parent;
4623        } while (current != null);
4624
4625        return false;
4626    }
4627
4628    /**
4629     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4630     * is set
4631     *
4632     * @param insets Insets for system windows
4633     *
4634     * @return True if this view applied the insets, false otherwise
4635     */
4636    protected boolean fitSystemWindows(Rect insets) {
4637        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4638            mPaddingLeft = insets.left;
4639            mPaddingTop = insets.top;
4640            mPaddingRight = insets.right;
4641            mPaddingBottom = insets.bottom;
4642            requestLayout();
4643            return true;
4644        }
4645        return false;
4646    }
4647
4648    /**
4649     * Set whether or not this view should account for system screen decorations
4650     * such as the status bar and inset its content. This allows this view to be
4651     * positioned in absolute screen coordinates and remain visible to the user.
4652     *
4653     * <p>This should only be used by top-level window decor views.
4654     *
4655     * @param fitSystemWindows true to inset content for system screen decorations, false for
4656     *                         default behavior.
4657     *
4658     * @attr ref android.R.styleable#View_fitsSystemWindows
4659     */
4660    public void setFitsSystemWindows(boolean fitSystemWindows) {
4661        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4662    }
4663
4664    /**
4665     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4666     * will account for system screen decorations such as the status bar and inset its
4667     * content. This allows the view to be positioned in absolute screen coordinates
4668     * and remain visible to the user.
4669     *
4670     * @return true if this view will adjust its content bounds for system screen decorations.
4671     *
4672     * @attr ref android.R.styleable#View_fitsSystemWindows
4673     */
4674    public boolean fitsSystemWindows() {
4675        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4676    }
4677
4678    /**
4679     * Returns the visibility status for this view.
4680     *
4681     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4682     * @attr ref android.R.styleable#View_visibility
4683     */
4684    @ViewDebug.ExportedProperty(mapping = {
4685        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4686        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4687        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4688    })
4689    public int getVisibility() {
4690        return mViewFlags & VISIBILITY_MASK;
4691    }
4692
4693    /**
4694     * Set the enabled state of this view.
4695     *
4696     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4697     * @attr ref android.R.styleable#View_visibility
4698     */
4699    @RemotableViewMethod
4700    public void setVisibility(int visibility) {
4701        setFlags(visibility, VISIBILITY_MASK);
4702        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4703    }
4704
4705    /**
4706     * Returns the enabled status for this view. The interpretation of the
4707     * enabled state varies by subclass.
4708     *
4709     * @return True if this view is enabled, false otherwise.
4710     */
4711    @ViewDebug.ExportedProperty
4712    public boolean isEnabled() {
4713        return (mViewFlags & ENABLED_MASK) == ENABLED;
4714    }
4715
4716    /**
4717     * Set the enabled state of this view. The interpretation of the enabled
4718     * state varies by subclass.
4719     *
4720     * @param enabled True if this view is enabled, false otherwise.
4721     */
4722    @RemotableViewMethod
4723    public void setEnabled(boolean enabled) {
4724        if (enabled == isEnabled()) return;
4725
4726        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4727
4728        /*
4729         * The View most likely has to change its appearance, so refresh
4730         * the drawable state.
4731         */
4732        refreshDrawableState();
4733
4734        // Invalidate too, since the default behavior for views is to be
4735        // be drawn at 50% alpha rather than to change the drawable.
4736        invalidate(true);
4737    }
4738
4739    /**
4740     * Set whether this view can receive the focus.
4741     *
4742     * Setting this to false will also ensure that this view is not focusable
4743     * in touch mode.
4744     *
4745     * @param focusable If true, this view can receive the focus.
4746     *
4747     * @see #setFocusableInTouchMode(boolean)
4748     * @attr ref android.R.styleable#View_focusable
4749     */
4750    public void setFocusable(boolean focusable) {
4751        if (!focusable) {
4752            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4753        }
4754        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4755    }
4756
4757    /**
4758     * Set whether this view can receive focus while in touch mode.
4759     *
4760     * Setting this to true will also ensure that this view is focusable.
4761     *
4762     * @param focusableInTouchMode If true, this view can receive the focus while
4763     *   in touch mode.
4764     *
4765     * @see #setFocusable(boolean)
4766     * @attr ref android.R.styleable#View_focusableInTouchMode
4767     */
4768    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4769        // Focusable in touch mode should always be set before the focusable flag
4770        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4771        // which, in touch mode, will not successfully request focus on this view
4772        // because the focusable in touch mode flag is not set
4773        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4774        if (focusableInTouchMode) {
4775            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4776        }
4777    }
4778
4779    /**
4780     * Set whether this view should have sound effects enabled for events such as
4781     * clicking and touching.
4782     *
4783     * <p>You may wish to disable sound effects for a view if you already play sounds,
4784     * for instance, a dial key that plays dtmf tones.
4785     *
4786     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4787     * @see #isSoundEffectsEnabled()
4788     * @see #playSoundEffect(int)
4789     * @attr ref android.R.styleable#View_soundEffectsEnabled
4790     */
4791    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4792        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4793    }
4794
4795    /**
4796     * @return whether this view should have sound effects enabled for events such as
4797     *     clicking and touching.
4798     *
4799     * @see #setSoundEffectsEnabled(boolean)
4800     * @see #playSoundEffect(int)
4801     * @attr ref android.R.styleable#View_soundEffectsEnabled
4802     */
4803    @ViewDebug.ExportedProperty
4804    public boolean isSoundEffectsEnabled() {
4805        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4806    }
4807
4808    /**
4809     * Set whether this view should have haptic feedback for events such as
4810     * long presses.
4811     *
4812     * <p>You may wish to disable haptic feedback if your view already controls
4813     * its own haptic feedback.
4814     *
4815     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4816     * @see #isHapticFeedbackEnabled()
4817     * @see #performHapticFeedback(int)
4818     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4819     */
4820    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4821        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4822    }
4823
4824    /**
4825     * @return whether this view should have haptic feedback enabled for events
4826     * long presses.
4827     *
4828     * @see #setHapticFeedbackEnabled(boolean)
4829     * @see #performHapticFeedback(int)
4830     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4831     */
4832    @ViewDebug.ExportedProperty
4833    public boolean isHapticFeedbackEnabled() {
4834        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4835    }
4836
4837    /**
4838     * Returns the layout direction for this view.
4839     *
4840     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4841     *   {@link #LAYOUT_DIRECTION_RTL},
4842     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4843     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4844     * @attr ref android.R.styleable#View_layoutDirection
4845     *
4846     * @hide
4847     */
4848    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4849        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4850        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4851        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4852        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4853    })
4854    public int getLayoutDirection() {
4855        return mViewFlags & LAYOUT_DIRECTION_MASK;
4856    }
4857
4858    /**
4859     * Set the layout direction for this view. This will propagate a reset of layout direction
4860     * resolution to the view's children and resolve layout direction for this view.
4861     *
4862     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4863     *   {@link #LAYOUT_DIRECTION_RTL},
4864     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4865     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4866     *
4867     * @attr ref android.R.styleable#View_layoutDirection
4868     *
4869     * @hide
4870     */
4871    @RemotableViewMethod
4872    public void setLayoutDirection(int layoutDirection) {
4873        if (getLayoutDirection() != layoutDirection) {
4874            resetResolvedLayoutDirection();
4875            // Setting the flag will also request a layout.
4876            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4877        }
4878    }
4879
4880    /**
4881     * Returns the resolved layout direction for this view.
4882     *
4883     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4884     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4885     *
4886     * @hide
4887     */
4888    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4889        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4890        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4891    })
4892    public int getResolvedLayoutDirection() {
4893        resolveLayoutDirectionIfNeeded();
4894        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4895                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4896    }
4897
4898    /**
4899     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4900     * layout attribute and/or the inherited value from the parent.</p>
4901     *
4902     * @return true if the layout is right-to-left.
4903     *
4904     * @hide
4905     */
4906    @ViewDebug.ExportedProperty(category = "layout")
4907    public boolean isLayoutRtl() {
4908        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4909    }
4910
4911    /**
4912     * If this view doesn't do any drawing on its own, set this flag to
4913     * allow further optimizations. By default, this flag is not set on
4914     * View, but could be set on some View subclasses such as ViewGroup.
4915     *
4916     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4917     * you should clear this flag.
4918     *
4919     * @param willNotDraw whether or not this View draw on its own
4920     */
4921    public void setWillNotDraw(boolean willNotDraw) {
4922        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4923    }
4924
4925    /**
4926     * Returns whether or not this View draws on its own.
4927     *
4928     * @return true if this view has nothing to draw, false otherwise
4929     */
4930    @ViewDebug.ExportedProperty(category = "drawing")
4931    public boolean willNotDraw() {
4932        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4933    }
4934
4935    /**
4936     * When a View's drawing cache is enabled, drawing is redirected to an
4937     * offscreen bitmap. Some views, like an ImageView, must be able to
4938     * bypass this mechanism if they already draw a single bitmap, to avoid
4939     * unnecessary usage of the memory.
4940     *
4941     * @param willNotCacheDrawing true if this view does not cache its
4942     *        drawing, false otherwise
4943     */
4944    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4945        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4946    }
4947
4948    /**
4949     * Returns whether or not this View can cache its drawing or not.
4950     *
4951     * @return true if this view does not cache its drawing, false otherwise
4952     */
4953    @ViewDebug.ExportedProperty(category = "drawing")
4954    public boolean willNotCacheDrawing() {
4955        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4956    }
4957
4958    /**
4959     * Indicates whether this view reacts to click events or not.
4960     *
4961     * @return true if the view is clickable, false otherwise
4962     *
4963     * @see #setClickable(boolean)
4964     * @attr ref android.R.styleable#View_clickable
4965     */
4966    @ViewDebug.ExportedProperty
4967    public boolean isClickable() {
4968        return (mViewFlags & CLICKABLE) == CLICKABLE;
4969    }
4970
4971    /**
4972     * Enables or disables click events for this view. When a view
4973     * is clickable it will change its state to "pressed" on every click.
4974     * Subclasses should set the view clickable to visually react to
4975     * user's clicks.
4976     *
4977     * @param clickable true to make the view clickable, false otherwise
4978     *
4979     * @see #isClickable()
4980     * @attr ref android.R.styleable#View_clickable
4981     */
4982    public void setClickable(boolean clickable) {
4983        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4984    }
4985
4986    /**
4987     * Indicates whether this view reacts to long click events or not.
4988     *
4989     * @return true if the view is long clickable, false otherwise
4990     *
4991     * @see #setLongClickable(boolean)
4992     * @attr ref android.R.styleable#View_longClickable
4993     */
4994    public boolean isLongClickable() {
4995        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4996    }
4997
4998    /**
4999     * Enables or disables long click events for this view. When a view is long
5000     * clickable it reacts to the user holding down the button for a longer
5001     * duration than a tap. This event can either launch the listener or a
5002     * context menu.
5003     *
5004     * @param longClickable true to make the view long clickable, false otherwise
5005     * @see #isLongClickable()
5006     * @attr ref android.R.styleable#View_longClickable
5007     */
5008    public void setLongClickable(boolean longClickable) {
5009        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5010    }
5011
5012    /**
5013     * Sets the pressed state for this view.
5014     *
5015     * @see #isClickable()
5016     * @see #setClickable(boolean)
5017     *
5018     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5019     *        the View's internal state from a previously set "pressed" state.
5020     */
5021    public void setPressed(boolean pressed) {
5022        if (pressed) {
5023            mPrivateFlags |= PRESSED;
5024        } else {
5025            mPrivateFlags &= ~PRESSED;
5026        }
5027        refreshDrawableState();
5028        dispatchSetPressed(pressed);
5029    }
5030
5031    /**
5032     * Dispatch setPressed to all of this View's children.
5033     *
5034     * @see #setPressed(boolean)
5035     *
5036     * @param pressed The new pressed state
5037     */
5038    protected void dispatchSetPressed(boolean pressed) {
5039    }
5040
5041    /**
5042     * Indicates whether the view is currently in pressed state. Unless
5043     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5044     * the pressed state.
5045     *
5046     * @see #setPressed(boolean)
5047     * @see #isClickable()
5048     * @see #setClickable(boolean)
5049     *
5050     * @return true if the view is currently pressed, false otherwise
5051     */
5052    public boolean isPressed() {
5053        return (mPrivateFlags & PRESSED) == PRESSED;
5054    }
5055
5056    /**
5057     * Indicates whether this view will save its state (that is,
5058     * whether its {@link #onSaveInstanceState} method will be called).
5059     *
5060     * @return Returns true if the view state saving is enabled, else false.
5061     *
5062     * @see #setSaveEnabled(boolean)
5063     * @attr ref android.R.styleable#View_saveEnabled
5064     */
5065    public boolean isSaveEnabled() {
5066        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5067    }
5068
5069    /**
5070     * Controls whether the saving of this view's state is
5071     * enabled (that is, whether its {@link #onSaveInstanceState} method
5072     * will be called).  Note that even if freezing is enabled, the
5073     * view still must have an id assigned to it (via {@link #setId(int)})
5074     * for its state to be saved.  This flag can only disable the
5075     * saving of this view; any child views may still have their state saved.
5076     *
5077     * @param enabled Set to false to <em>disable</em> state saving, or true
5078     * (the default) to allow it.
5079     *
5080     * @see #isSaveEnabled()
5081     * @see #setId(int)
5082     * @see #onSaveInstanceState()
5083     * @attr ref android.R.styleable#View_saveEnabled
5084     */
5085    public void setSaveEnabled(boolean enabled) {
5086        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5087    }
5088
5089    /**
5090     * Gets whether the framework should discard touches when the view's
5091     * window is obscured by another visible window.
5092     * Refer to the {@link View} security documentation for more details.
5093     *
5094     * @return True if touch filtering is enabled.
5095     *
5096     * @see #setFilterTouchesWhenObscured(boolean)
5097     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5098     */
5099    @ViewDebug.ExportedProperty
5100    public boolean getFilterTouchesWhenObscured() {
5101        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5102    }
5103
5104    /**
5105     * Sets whether the framework should discard touches when the view's
5106     * window is obscured by another visible window.
5107     * Refer to the {@link View} security documentation for more details.
5108     *
5109     * @param enabled True if touch filtering should be enabled.
5110     *
5111     * @see #getFilterTouchesWhenObscured
5112     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5113     */
5114    public void setFilterTouchesWhenObscured(boolean enabled) {
5115        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5116                FILTER_TOUCHES_WHEN_OBSCURED);
5117    }
5118
5119    /**
5120     * Indicates whether the entire hierarchy under this view will save its
5121     * state when a state saving traversal occurs from its parent.  The default
5122     * is true; if false, these views will not be saved unless
5123     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5124     *
5125     * @return Returns true if the view state saving from parent is enabled, else false.
5126     *
5127     * @see #setSaveFromParentEnabled(boolean)
5128     */
5129    public boolean isSaveFromParentEnabled() {
5130        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5131    }
5132
5133    /**
5134     * Controls whether the entire hierarchy under this view will save its
5135     * state when a state saving traversal occurs from its parent.  The default
5136     * is true; if false, these views will not be saved unless
5137     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5138     *
5139     * @param enabled Set to false to <em>disable</em> state saving, or true
5140     * (the default) to allow it.
5141     *
5142     * @see #isSaveFromParentEnabled()
5143     * @see #setId(int)
5144     * @see #onSaveInstanceState()
5145     */
5146    public void setSaveFromParentEnabled(boolean enabled) {
5147        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5148    }
5149
5150
5151    /**
5152     * Returns whether this View is able to take focus.
5153     *
5154     * @return True if this view can take focus, or false otherwise.
5155     * @attr ref android.R.styleable#View_focusable
5156     */
5157    @ViewDebug.ExportedProperty(category = "focus")
5158    public final boolean isFocusable() {
5159        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5160    }
5161
5162    /**
5163     * When a view is focusable, it may not want to take focus when in touch mode.
5164     * For example, a button would like focus when the user is navigating via a D-pad
5165     * so that the user can click on it, but once the user starts touching the screen,
5166     * the button shouldn't take focus
5167     * @return Whether the view is focusable in touch mode.
5168     * @attr ref android.R.styleable#View_focusableInTouchMode
5169     */
5170    @ViewDebug.ExportedProperty
5171    public final boolean isFocusableInTouchMode() {
5172        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5173    }
5174
5175    /**
5176     * Find the nearest view in the specified direction that can take focus.
5177     * This does not actually give focus to that view.
5178     *
5179     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5180     *
5181     * @return The nearest focusable in the specified direction, or null if none
5182     *         can be found.
5183     */
5184    public View focusSearch(int direction) {
5185        if (mParent != null) {
5186            return mParent.focusSearch(this, direction);
5187        } else {
5188            return null;
5189        }
5190    }
5191
5192    /**
5193     * This method is the last chance for the focused view and its ancestors to
5194     * respond to an arrow key. This is called when the focused view did not
5195     * consume the key internally, nor could the view system find a new view in
5196     * the requested direction to give focus to.
5197     *
5198     * @param focused The currently focused view.
5199     * @param direction The direction focus wants to move. One of FOCUS_UP,
5200     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5201     * @return True if the this view consumed this unhandled move.
5202     */
5203    public boolean dispatchUnhandledMove(View focused, int direction) {
5204        return false;
5205    }
5206
5207    /**
5208     * If a user manually specified the next view id for a particular direction,
5209     * use the root to look up the view.
5210     * @param root The root view of the hierarchy containing this view.
5211     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5212     * or FOCUS_BACKWARD.
5213     * @return The user specified next view, or null if there is none.
5214     */
5215    View findUserSetNextFocus(View root, int direction) {
5216        switch (direction) {
5217            case FOCUS_LEFT:
5218                if (mNextFocusLeftId == View.NO_ID) return null;
5219                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5220            case FOCUS_RIGHT:
5221                if (mNextFocusRightId == View.NO_ID) return null;
5222                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5223            case FOCUS_UP:
5224                if (mNextFocusUpId == View.NO_ID) return null;
5225                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5226            case FOCUS_DOWN:
5227                if (mNextFocusDownId == View.NO_ID) return null;
5228                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5229            case FOCUS_FORWARD:
5230                if (mNextFocusForwardId == View.NO_ID) return null;
5231                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5232            case FOCUS_BACKWARD: {
5233                final int id = mID;
5234                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5235                    @Override
5236                    public boolean apply(View t) {
5237                        return t.mNextFocusForwardId == id;
5238                    }
5239                });
5240            }
5241        }
5242        return null;
5243    }
5244
5245    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5246        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5247            @Override
5248            public boolean apply(View t) {
5249                return t.mID == childViewId;
5250            }
5251        });
5252
5253        if (result == null) {
5254            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5255                    + "by user for id " + childViewId);
5256        }
5257        return result;
5258    }
5259
5260    /**
5261     * Find and return all focusable views that are descendants of this view,
5262     * possibly including this view if it is focusable itself.
5263     *
5264     * @param direction The direction of the focus
5265     * @return A list of focusable views
5266     */
5267    public ArrayList<View> getFocusables(int direction) {
5268        ArrayList<View> result = new ArrayList<View>(24);
5269        addFocusables(result, direction);
5270        return result;
5271    }
5272
5273    /**
5274     * Add any focusable views that are descendants of this view (possibly
5275     * including this view if it is focusable itself) to views.  If we are in touch mode,
5276     * only add views that are also focusable in touch mode.
5277     *
5278     * @param views Focusable views found so far
5279     * @param direction The direction of the focus
5280     */
5281    public void addFocusables(ArrayList<View> views, int direction) {
5282        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5283    }
5284
5285    /**
5286     * Adds any focusable views that are descendants of this view (possibly
5287     * including this view if it is focusable itself) to views. This method
5288     * adds all focusable views regardless if we are in touch mode or
5289     * only views focusable in touch mode if we are in touch mode depending on
5290     * the focusable mode paramater.
5291     *
5292     * @param views Focusable views found so far or null if all we are interested is
5293     *        the number of focusables.
5294     * @param direction The direction of the focus.
5295     * @param focusableMode The type of focusables to be added.
5296     *
5297     * @see #FOCUSABLES_ALL
5298     * @see #FOCUSABLES_TOUCH_MODE
5299     */
5300    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5301        if (!isFocusable()) {
5302            return;
5303        }
5304
5305        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5306                isInTouchMode() && !isFocusableInTouchMode()) {
5307            return;
5308        }
5309
5310        if (views != null) {
5311            views.add(this);
5312        }
5313    }
5314
5315    /**
5316     * Finds the Views that contain given text. The containment is case insensitive.
5317     * The search is performed by either the text that the View renders or the content
5318     * description that describes the view for accessibility purposes and the view does
5319     * not render or both. Clients can specify how the search is to be performed via
5320     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5321     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5322     *
5323     * @param outViews The output list of matching Views.
5324     * @param searched The text to match against.
5325     *
5326     * @see #FIND_VIEWS_WITH_TEXT
5327     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5328     * @see #setContentDescription(CharSequence)
5329     */
5330    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5331        if (getAccessibilityNodeProvider() != null) {
5332            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5333                outViews.add(this);
5334            }
5335        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5336                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5337            String searchedLowerCase = searched.toString().toLowerCase();
5338            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5339            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5340                outViews.add(this);
5341            }
5342        }
5343    }
5344
5345    /**
5346     * Find and return all touchable views that are descendants of this view,
5347     * possibly including this view if it is touchable itself.
5348     *
5349     * @return A list of touchable views
5350     */
5351    public ArrayList<View> getTouchables() {
5352        ArrayList<View> result = new ArrayList<View>();
5353        addTouchables(result);
5354        return result;
5355    }
5356
5357    /**
5358     * Add any touchable views that are descendants of this view (possibly
5359     * including this view if it is touchable itself) to views.
5360     *
5361     * @param views Touchable views found so far
5362     */
5363    public void addTouchables(ArrayList<View> views) {
5364        final int viewFlags = mViewFlags;
5365
5366        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5367                && (viewFlags & ENABLED_MASK) == ENABLED) {
5368            views.add(this);
5369        }
5370    }
5371
5372    /**
5373     * Call this to try to give focus to a specific view or to one of its
5374     * descendants.
5375     *
5376     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5377     * false), or if it is focusable and it is not focusable in touch mode
5378     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5379     *
5380     * See also {@link #focusSearch(int)}, which is what you call to say that you
5381     * have focus, and you want your parent to look for the next one.
5382     *
5383     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5384     * {@link #FOCUS_DOWN} and <code>null</code>.
5385     *
5386     * @return Whether this view or one of its descendants actually took focus.
5387     */
5388    public final boolean requestFocus() {
5389        return requestFocus(View.FOCUS_DOWN);
5390    }
5391
5392
5393    /**
5394     * Call this to try to give focus to a specific view or to one of its
5395     * descendants and give it a hint about what direction focus is heading.
5396     *
5397     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5398     * false), or if it is focusable and it is not focusable in touch mode
5399     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5400     *
5401     * See also {@link #focusSearch(int)}, which is what you call to say that you
5402     * have focus, and you want your parent to look for the next one.
5403     *
5404     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5405     * <code>null</code> set for the previously focused rectangle.
5406     *
5407     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5408     * @return Whether this view or one of its descendants actually took focus.
5409     */
5410    public final boolean requestFocus(int direction) {
5411        return requestFocus(direction, null);
5412    }
5413
5414    /**
5415     * Call this to try to give focus to a specific view or to one of its descendants
5416     * and give it hints about the direction and a specific rectangle that the focus
5417     * is coming from.  The rectangle can help give larger views a finer grained hint
5418     * about where focus is coming from, and therefore, where to show selection, or
5419     * forward focus change internally.
5420     *
5421     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5422     * false), or if it is focusable and it is not focusable in touch mode
5423     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5424     *
5425     * A View will not take focus if it is not visible.
5426     *
5427     * A View will not take focus if one of its parents has
5428     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5429     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5430     *
5431     * See also {@link #focusSearch(int)}, which is what you call to say that you
5432     * have focus, and you want your parent to look for the next one.
5433     *
5434     * You may wish to override this method if your custom {@link View} has an internal
5435     * {@link View} that it wishes to forward the request to.
5436     *
5437     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5438     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5439     *        to give a finer grained hint about where focus is coming from.  May be null
5440     *        if there is no hint.
5441     * @return Whether this view or one of its descendants actually took focus.
5442     */
5443    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5444        // need to be focusable
5445        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5446                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5447            return false;
5448        }
5449
5450        // need to be focusable in touch mode if in touch mode
5451        if (isInTouchMode() &&
5452            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5453               return false;
5454        }
5455
5456        // need to not have any parents blocking us
5457        if (hasAncestorThatBlocksDescendantFocus()) {
5458            return false;
5459        }
5460
5461        handleFocusGainInternal(direction, previouslyFocusedRect);
5462        return true;
5463    }
5464
5465    /** Gets the ViewAncestor, or null if not attached. */
5466    /*package*/ ViewRootImpl getViewRootImpl() {
5467        View root = getRootView();
5468        return root != null ? (ViewRootImpl)root.getParent() : null;
5469    }
5470
5471    /**
5472     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5473     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5474     * touch mode to request focus when they are touched.
5475     *
5476     * @return Whether this view or one of its descendants actually took focus.
5477     *
5478     * @see #isInTouchMode()
5479     *
5480     */
5481    public final boolean requestFocusFromTouch() {
5482        // Leave touch mode if we need to
5483        if (isInTouchMode()) {
5484            ViewRootImpl viewRoot = getViewRootImpl();
5485            if (viewRoot != null) {
5486                viewRoot.ensureTouchMode(false);
5487            }
5488        }
5489        return requestFocus(View.FOCUS_DOWN);
5490    }
5491
5492    /**
5493     * @return Whether any ancestor of this view blocks descendant focus.
5494     */
5495    private boolean hasAncestorThatBlocksDescendantFocus() {
5496        ViewParent ancestor = mParent;
5497        while (ancestor instanceof ViewGroup) {
5498            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5499            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5500                return true;
5501            } else {
5502                ancestor = vgAncestor.getParent();
5503            }
5504        }
5505        return false;
5506    }
5507
5508    /**
5509     * @hide
5510     */
5511    public void dispatchStartTemporaryDetach() {
5512        onStartTemporaryDetach();
5513    }
5514
5515    /**
5516     * This is called when a container is going to temporarily detach a child, with
5517     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5518     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5519     * {@link #onDetachedFromWindow()} when the container is done.
5520     */
5521    public void onStartTemporaryDetach() {
5522        removeUnsetPressCallback();
5523        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5524    }
5525
5526    /**
5527     * @hide
5528     */
5529    public void dispatchFinishTemporaryDetach() {
5530        onFinishTemporaryDetach();
5531    }
5532
5533    /**
5534     * Called after {@link #onStartTemporaryDetach} when the container is done
5535     * changing the view.
5536     */
5537    public void onFinishTemporaryDetach() {
5538    }
5539
5540    /**
5541     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5542     * for this view's window.  Returns null if the view is not currently attached
5543     * to the window.  Normally you will not need to use this directly, but
5544     * just use the standard high-level event callbacks like
5545     * {@link #onKeyDown(int, KeyEvent)}.
5546     */
5547    public KeyEvent.DispatcherState getKeyDispatcherState() {
5548        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5549    }
5550
5551    /**
5552     * Dispatch a key event before it is processed by any input method
5553     * associated with the view hierarchy.  This can be used to intercept
5554     * key events in special situations before the IME consumes them; a
5555     * typical example would be handling the BACK key to update the application's
5556     * UI instead of allowing the IME to see it and close itself.
5557     *
5558     * @param event The key event to be dispatched.
5559     * @return True if the event was handled, false otherwise.
5560     */
5561    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5562        return onKeyPreIme(event.getKeyCode(), event);
5563    }
5564
5565    /**
5566     * Dispatch a key event to the next view on the focus path. This path runs
5567     * from the top of the view tree down to the currently focused view. If this
5568     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5569     * the next node down the focus path. This method also fires any key
5570     * listeners.
5571     *
5572     * @param event The key event to be dispatched.
5573     * @return True if the event was handled, false otherwise.
5574     */
5575    public boolean dispatchKeyEvent(KeyEvent event) {
5576        if (mInputEventConsistencyVerifier != null) {
5577            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5578        }
5579
5580        // Give any attached key listener a first crack at the event.
5581        //noinspection SimplifiableIfStatement
5582        ListenerInfo li = mListenerInfo;
5583        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5584                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5585            return true;
5586        }
5587
5588        if (event.dispatch(this, mAttachInfo != null
5589                ? mAttachInfo.mKeyDispatchState : null, this)) {
5590            return true;
5591        }
5592
5593        if (mInputEventConsistencyVerifier != null) {
5594            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5595        }
5596        return false;
5597    }
5598
5599    /**
5600     * Dispatches a key shortcut event.
5601     *
5602     * @param event The key event to be dispatched.
5603     * @return True if the event was handled by the view, false otherwise.
5604     */
5605    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5606        return onKeyShortcut(event.getKeyCode(), event);
5607    }
5608
5609    /**
5610     * Pass the touch screen motion event down to the target view, or this
5611     * view if it is the target.
5612     *
5613     * @param event The motion event to be dispatched.
5614     * @return True if the event was handled by the view, false otherwise.
5615     */
5616    public boolean dispatchTouchEvent(MotionEvent event) {
5617        if (mInputEventConsistencyVerifier != null) {
5618            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5619        }
5620
5621        if (onFilterTouchEventForSecurity(event)) {
5622            //noinspection SimplifiableIfStatement
5623            ListenerInfo li = mListenerInfo;
5624            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5625                    && li.mOnTouchListener.onTouch(this, event)) {
5626                return true;
5627            }
5628
5629            if (onTouchEvent(event)) {
5630                return true;
5631            }
5632        }
5633
5634        if (mInputEventConsistencyVerifier != null) {
5635            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5636        }
5637        return false;
5638    }
5639
5640    /**
5641     * Filter the touch event to apply security policies.
5642     *
5643     * @param event The motion event to be filtered.
5644     * @return True if the event should be dispatched, false if the event should be dropped.
5645     *
5646     * @see #getFilterTouchesWhenObscured
5647     */
5648    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5649        //noinspection RedundantIfStatement
5650        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5651                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5652            // Window is obscured, drop this touch.
5653            return false;
5654        }
5655        return true;
5656    }
5657
5658    /**
5659     * Pass a trackball motion event down to the focused view.
5660     *
5661     * @param event The motion event to be dispatched.
5662     * @return True if the event was handled by the view, false otherwise.
5663     */
5664    public boolean dispatchTrackballEvent(MotionEvent event) {
5665        if (mInputEventConsistencyVerifier != null) {
5666            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5667        }
5668
5669        return onTrackballEvent(event);
5670    }
5671
5672    /**
5673     * Dispatch a generic motion event.
5674     * <p>
5675     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5676     * are delivered to the view under the pointer.  All other generic motion events are
5677     * delivered to the focused view.  Hover events are handled specially and are delivered
5678     * to {@link #onHoverEvent(MotionEvent)}.
5679     * </p>
5680     *
5681     * @param event The motion event to be dispatched.
5682     * @return True if the event was handled by the view, false otherwise.
5683     */
5684    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5685        if (mInputEventConsistencyVerifier != null) {
5686            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5687        }
5688
5689        final int source = event.getSource();
5690        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5691            final int action = event.getAction();
5692            if (action == MotionEvent.ACTION_HOVER_ENTER
5693                    || action == MotionEvent.ACTION_HOVER_MOVE
5694                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5695                if (dispatchHoverEvent(event)) {
5696                    return true;
5697                }
5698            } else if (dispatchGenericPointerEvent(event)) {
5699                return true;
5700            }
5701        } else if (dispatchGenericFocusedEvent(event)) {
5702            return true;
5703        }
5704
5705        if (dispatchGenericMotionEventInternal(event)) {
5706            return true;
5707        }
5708
5709        if (mInputEventConsistencyVerifier != null) {
5710            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5711        }
5712        return false;
5713    }
5714
5715    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5716        //noinspection SimplifiableIfStatement
5717        ListenerInfo li = mListenerInfo;
5718        if (li != null && li.mOnGenericMotionListener != null
5719                && (mViewFlags & ENABLED_MASK) == ENABLED
5720                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5721            return true;
5722        }
5723
5724        if (onGenericMotionEvent(event)) {
5725            return true;
5726        }
5727
5728        if (mInputEventConsistencyVerifier != null) {
5729            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5730        }
5731        return false;
5732    }
5733
5734    /**
5735     * Dispatch a hover event.
5736     * <p>
5737     * Do not call this method directly.
5738     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5739     * </p>
5740     *
5741     * @param event The motion event to be dispatched.
5742     * @return True if the event was handled by the view, false otherwise.
5743     */
5744    protected boolean dispatchHoverEvent(MotionEvent event) {
5745        //noinspection SimplifiableIfStatement
5746        ListenerInfo li = mListenerInfo;
5747        if (li != null && li.mOnHoverListener != null
5748                && (mViewFlags & ENABLED_MASK) == ENABLED
5749                && li.mOnHoverListener.onHover(this, event)) {
5750            return true;
5751        }
5752
5753        return onHoverEvent(event);
5754    }
5755
5756    /**
5757     * Returns true if the view has a child to which it has recently sent
5758     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5759     * it does not have a hovered child, then it must be the innermost hovered view.
5760     * @hide
5761     */
5762    protected boolean hasHoveredChild() {
5763        return false;
5764    }
5765
5766    /**
5767     * Dispatch a generic motion event to the view under the first pointer.
5768     * <p>
5769     * Do not call this method directly.
5770     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5771     * </p>
5772     *
5773     * @param event The motion event to be dispatched.
5774     * @return True if the event was handled by the view, false otherwise.
5775     */
5776    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5777        return false;
5778    }
5779
5780    /**
5781     * Dispatch a generic motion event to the currently focused view.
5782     * <p>
5783     * Do not call this method directly.
5784     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5785     * </p>
5786     *
5787     * @param event The motion event to be dispatched.
5788     * @return True if the event was handled by the view, false otherwise.
5789     */
5790    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5791        return false;
5792    }
5793
5794    /**
5795     * Dispatch a pointer event.
5796     * <p>
5797     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5798     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5799     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5800     * and should not be expected to handle other pointing device features.
5801     * </p>
5802     *
5803     * @param event The motion event to be dispatched.
5804     * @return True if the event was handled by the view, false otherwise.
5805     * @hide
5806     */
5807    public final boolean dispatchPointerEvent(MotionEvent event) {
5808        if (event.isTouchEvent()) {
5809            return dispatchTouchEvent(event);
5810        } else {
5811            return dispatchGenericMotionEvent(event);
5812        }
5813    }
5814
5815    /**
5816     * Called when the window containing this view gains or loses window focus.
5817     * ViewGroups should override to route to their children.
5818     *
5819     * @param hasFocus True if the window containing this view now has focus,
5820     *        false otherwise.
5821     */
5822    public void dispatchWindowFocusChanged(boolean hasFocus) {
5823        onWindowFocusChanged(hasFocus);
5824    }
5825
5826    /**
5827     * Called when the window containing this view gains or loses focus.  Note
5828     * that this is separate from view focus: to receive key events, both
5829     * your view and its window must have focus.  If a window is displayed
5830     * on top of yours that takes input focus, then your own window will lose
5831     * focus but the view focus will remain unchanged.
5832     *
5833     * @param hasWindowFocus True if the window containing this view now has
5834     *        focus, false otherwise.
5835     */
5836    public void onWindowFocusChanged(boolean hasWindowFocus) {
5837        InputMethodManager imm = InputMethodManager.peekInstance();
5838        if (!hasWindowFocus) {
5839            if (isPressed()) {
5840                setPressed(false);
5841            }
5842            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5843                imm.focusOut(this);
5844            }
5845            removeLongPressCallback();
5846            removeTapCallback();
5847            onFocusLost();
5848        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5849            imm.focusIn(this);
5850        }
5851        refreshDrawableState();
5852    }
5853
5854    /**
5855     * Returns true if this view is in a window that currently has window focus.
5856     * Note that this is not the same as the view itself having focus.
5857     *
5858     * @return True if this view is in a window that currently has window focus.
5859     */
5860    public boolean hasWindowFocus() {
5861        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5862    }
5863
5864    /**
5865     * Dispatch a view visibility change down the view hierarchy.
5866     * ViewGroups should override to route to their children.
5867     * @param changedView The view whose visibility changed. Could be 'this' or
5868     * an ancestor view.
5869     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5870     * {@link #INVISIBLE} or {@link #GONE}.
5871     */
5872    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5873        onVisibilityChanged(changedView, visibility);
5874    }
5875
5876    /**
5877     * Called when the visibility of the view or an ancestor of the view is changed.
5878     * @param changedView The view whose visibility changed. Could be 'this' or
5879     * an ancestor view.
5880     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5881     * {@link #INVISIBLE} or {@link #GONE}.
5882     */
5883    protected void onVisibilityChanged(View changedView, int visibility) {
5884        if (visibility == VISIBLE) {
5885            if (mAttachInfo != null) {
5886                initialAwakenScrollBars();
5887            } else {
5888                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5889            }
5890        }
5891    }
5892
5893    /**
5894     * Dispatch a hint about whether this view is displayed. For instance, when
5895     * a View moves out of the screen, it might receives a display hint indicating
5896     * the view is not displayed. Applications should not <em>rely</em> on this hint
5897     * as there is no guarantee that they will receive one.
5898     *
5899     * @param hint A hint about whether or not this view is displayed:
5900     * {@link #VISIBLE} or {@link #INVISIBLE}.
5901     */
5902    public void dispatchDisplayHint(int hint) {
5903        onDisplayHint(hint);
5904    }
5905
5906    /**
5907     * Gives this view a hint about whether is displayed or not. For instance, when
5908     * a View moves out of the screen, it might receives a display hint indicating
5909     * the view is not displayed. Applications should not <em>rely</em> on this hint
5910     * as there is no guarantee that they will receive one.
5911     *
5912     * @param hint A hint about whether or not this view is displayed:
5913     * {@link #VISIBLE} or {@link #INVISIBLE}.
5914     */
5915    protected void onDisplayHint(int hint) {
5916    }
5917
5918    /**
5919     * Dispatch a window visibility change down the view hierarchy.
5920     * ViewGroups should override to route to their children.
5921     *
5922     * @param visibility The new visibility of the window.
5923     *
5924     * @see #onWindowVisibilityChanged(int)
5925     */
5926    public void dispatchWindowVisibilityChanged(int visibility) {
5927        onWindowVisibilityChanged(visibility);
5928    }
5929
5930    /**
5931     * Called when the window containing has change its visibility
5932     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5933     * that this tells you whether or not your window is being made visible
5934     * to the window manager; this does <em>not</em> tell you whether or not
5935     * your window is obscured by other windows on the screen, even if it
5936     * is itself visible.
5937     *
5938     * @param visibility The new visibility of the window.
5939     */
5940    protected void onWindowVisibilityChanged(int visibility) {
5941        if (visibility == VISIBLE) {
5942            initialAwakenScrollBars();
5943        }
5944    }
5945
5946    /**
5947     * Returns the current visibility of the window this view is attached to
5948     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5949     *
5950     * @return Returns the current visibility of the view's window.
5951     */
5952    public int getWindowVisibility() {
5953        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5954    }
5955
5956    /**
5957     * Retrieve the overall visible display size in which the window this view is
5958     * attached to has been positioned in.  This takes into account screen
5959     * decorations above the window, for both cases where the window itself
5960     * is being position inside of them or the window is being placed under
5961     * then and covered insets are used for the window to position its content
5962     * inside.  In effect, this tells you the available area where content can
5963     * be placed and remain visible to users.
5964     *
5965     * <p>This function requires an IPC back to the window manager to retrieve
5966     * the requested information, so should not be used in performance critical
5967     * code like drawing.
5968     *
5969     * @param outRect Filled in with the visible display frame.  If the view
5970     * is not attached to a window, this is simply the raw display size.
5971     */
5972    public void getWindowVisibleDisplayFrame(Rect outRect) {
5973        if (mAttachInfo != null) {
5974            try {
5975                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5976            } catch (RemoteException e) {
5977                return;
5978            }
5979            // XXX This is really broken, and probably all needs to be done
5980            // in the window manager, and we need to know more about whether
5981            // we want the area behind or in front of the IME.
5982            final Rect insets = mAttachInfo.mVisibleInsets;
5983            outRect.left += insets.left;
5984            outRect.top += insets.top;
5985            outRect.right -= insets.right;
5986            outRect.bottom -= insets.bottom;
5987            return;
5988        }
5989        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5990        d.getRectSize(outRect);
5991    }
5992
5993    /**
5994     * Dispatch a notification about a resource configuration change down
5995     * the view hierarchy.
5996     * ViewGroups should override to route to their children.
5997     *
5998     * @param newConfig The new resource configuration.
5999     *
6000     * @see #onConfigurationChanged(android.content.res.Configuration)
6001     */
6002    public void dispatchConfigurationChanged(Configuration newConfig) {
6003        onConfigurationChanged(newConfig);
6004    }
6005
6006    /**
6007     * Called when the current configuration of the resources being used
6008     * by the application have changed.  You can use this to decide when
6009     * to reload resources that can changed based on orientation and other
6010     * configuration characterstics.  You only need to use this if you are
6011     * not relying on the normal {@link android.app.Activity} mechanism of
6012     * recreating the activity instance upon a configuration change.
6013     *
6014     * @param newConfig The new resource configuration.
6015     */
6016    protected void onConfigurationChanged(Configuration newConfig) {
6017    }
6018
6019    /**
6020     * Private function to aggregate all per-view attributes in to the view
6021     * root.
6022     */
6023    void dispatchCollectViewAttributes(int visibility) {
6024        performCollectViewAttributes(visibility);
6025    }
6026
6027    void performCollectViewAttributes(int visibility) {
6028        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6029            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6030                mAttachInfo.mKeepScreenOn = true;
6031            }
6032            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6033            ListenerInfo li = mListenerInfo;
6034            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6035                mAttachInfo.mHasSystemUiListeners = true;
6036            }
6037        }
6038    }
6039
6040    void needGlobalAttributesUpdate(boolean force) {
6041        final AttachInfo ai = mAttachInfo;
6042        if (ai != null) {
6043            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6044                    || ai.mHasSystemUiListeners) {
6045                ai.mRecomputeGlobalAttributes = true;
6046            }
6047        }
6048    }
6049
6050    /**
6051     * Returns whether the device is currently in touch mode.  Touch mode is entered
6052     * once the user begins interacting with the device by touch, and affects various
6053     * things like whether focus is always visible to the user.
6054     *
6055     * @return Whether the device is in touch mode.
6056     */
6057    @ViewDebug.ExportedProperty
6058    public boolean isInTouchMode() {
6059        if (mAttachInfo != null) {
6060            return mAttachInfo.mInTouchMode;
6061        } else {
6062            return ViewRootImpl.isInTouchMode();
6063        }
6064    }
6065
6066    /**
6067     * Returns the context the view is running in, through which it can
6068     * access the current theme, resources, etc.
6069     *
6070     * @return The view's Context.
6071     */
6072    @ViewDebug.CapturedViewProperty
6073    public final Context getContext() {
6074        return mContext;
6075    }
6076
6077    /**
6078     * Handle a key event before it is processed by any input method
6079     * associated with the view hierarchy.  This can be used to intercept
6080     * key events in special situations before the IME consumes them; a
6081     * typical example would be handling the BACK key to update the application's
6082     * UI instead of allowing the IME to see it and close itself.
6083     *
6084     * @param keyCode The value in event.getKeyCode().
6085     * @param event Description of the key event.
6086     * @return If you handled the event, return true. If you want to allow the
6087     *         event to be handled by the next receiver, return false.
6088     */
6089    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6090        return false;
6091    }
6092
6093    /**
6094     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6095     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6096     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6097     * is released, if the view is enabled and clickable.
6098     *
6099     * @param keyCode A key code that represents the button pressed, from
6100     *                {@link android.view.KeyEvent}.
6101     * @param event   The KeyEvent object that defines the button action.
6102     */
6103    public boolean onKeyDown(int keyCode, KeyEvent event) {
6104        boolean result = false;
6105
6106        switch (keyCode) {
6107            case KeyEvent.KEYCODE_DPAD_CENTER:
6108            case KeyEvent.KEYCODE_ENTER: {
6109                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6110                    return true;
6111                }
6112                // Long clickable items don't necessarily have to be clickable
6113                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6114                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6115                        (event.getRepeatCount() == 0)) {
6116                    setPressed(true);
6117                    checkForLongClick(0);
6118                    return true;
6119                }
6120                break;
6121            }
6122        }
6123        return result;
6124    }
6125
6126    /**
6127     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6128     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6129     * the event).
6130     */
6131    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6132        return false;
6133    }
6134
6135    /**
6136     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6137     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6138     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6139     * {@link KeyEvent#KEYCODE_ENTER} is released.
6140     *
6141     * @param keyCode A key code that represents the button pressed, from
6142     *                {@link android.view.KeyEvent}.
6143     * @param event   The KeyEvent object that defines the button action.
6144     */
6145    public boolean onKeyUp(int keyCode, KeyEvent event) {
6146        boolean result = false;
6147
6148        switch (keyCode) {
6149            case KeyEvent.KEYCODE_DPAD_CENTER:
6150            case KeyEvent.KEYCODE_ENTER: {
6151                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6152                    return true;
6153                }
6154                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6155                    setPressed(false);
6156
6157                    if (!mHasPerformedLongPress) {
6158                        // This is a tap, so remove the longpress check
6159                        removeLongPressCallback();
6160
6161                        result = performClick();
6162                    }
6163                }
6164                break;
6165            }
6166        }
6167        return result;
6168    }
6169
6170    /**
6171     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6172     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6173     * the event).
6174     *
6175     * @param keyCode     A key code that represents the button pressed, from
6176     *                    {@link android.view.KeyEvent}.
6177     * @param repeatCount The number of times the action was made.
6178     * @param event       The KeyEvent object that defines the button action.
6179     */
6180    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6181        return false;
6182    }
6183
6184    /**
6185     * Called on the focused view when a key shortcut event is not handled.
6186     * Override this method to implement local key shortcuts for the View.
6187     * Key shortcuts can also be implemented by setting the
6188     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6189     *
6190     * @param keyCode The value in event.getKeyCode().
6191     * @param event Description of the key event.
6192     * @return If you handled the event, return true. If you want to allow the
6193     *         event to be handled by the next receiver, return false.
6194     */
6195    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6196        return false;
6197    }
6198
6199    /**
6200     * Check whether the called view is a text editor, in which case it
6201     * would make sense to automatically display a soft input window for
6202     * it.  Subclasses should override this if they implement
6203     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6204     * a call on that method would return a non-null InputConnection, and
6205     * they are really a first-class editor that the user would normally
6206     * start typing on when the go into a window containing your view.
6207     *
6208     * <p>The default implementation always returns false.  This does
6209     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6210     * will not be called or the user can not otherwise perform edits on your
6211     * view; it is just a hint to the system that this is not the primary
6212     * purpose of this view.
6213     *
6214     * @return Returns true if this view is a text editor, else false.
6215     */
6216    public boolean onCheckIsTextEditor() {
6217        return false;
6218    }
6219
6220    /**
6221     * Create a new InputConnection for an InputMethod to interact
6222     * with the view.  The default implementation returns null, since it doesn't
6223     * support input methods.  You can override this to implement such support.
6224     * This is only needed for views that take focus and text input.
6225     *
6226     * <p>When implementing this, you probably also want to implement
6227     * {@link #onCheckIsTextEditor()} to indicate you will return a
6228     * non-null InputConnection.
6229     *
6230     * @param outAttrs Fill in with attribute information about the connection.
6231     */
6232    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6233        return null;
6234    }
6235
6236    /**
6237     * Called by the {@link android.view.inputmethod.InputMethodManager}
6238     * when a view who is not the current
6239     * input connection target is trying to make a call on the manager.  The
6240     * default implementation returns false; you can override this to return
6241     * true for certain views if you are performing InputConnection proxying
6242     * to them.
6243     * @param view The View that is making the InputMethodManager call.
6244     * @return Return true to allow the call, false to reject.
6245     */
6246    public boolean checkInputConnectionProxy(View view) {
6247        return false;
6248    }
6249
6250    /**
6251     * Show the context menu for this view. It is not safe to hold on to the
6252     * menu after returning from this method.
6253     *
6254     * You should normally not overload this method. Overload
6255     * {@link #onCreateContextMenu(ContextMenu)} or define an
6256     * {@link OnCreateContextMenuListener} to add items to the context menu.
6257     *
6258     * @param menu The context menu to populate
6259     */
6260    public void createContextMenu(ContextMenu menu) {
6261        ContextMenuInfo menuInfo = getContextMenuInfo();
6262
6263        // Sets the current menu info so all items added to menu will have
6264        // my extra info set.
6265        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6266
6267        onCreateContextMenu(menu);
6268        ListenerInfo li = mListenerInfo;
6269        if (li != null && li.mOnCreateContextMenuListener != null) {
6270            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6271        }
6272
6273        // Clear the extra information so subsequent items that aren't mine don't
6274        // have my extra info.
6275        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6276
6277        if (mParent != null) {
6278            mParent.createContextMenu(menu);
6279        }
6280    }
6281
6282    /**
6283     * Views should implement this if they have extra information to associate
6284     * with the context menu. The return result is supplied as a parameter to
6285     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6286     * callback.
6287     *
6288     * @return Extra information about the item for which the context menu
6289     *         should be shown. This information will vary across different
6290     *         subclasses of View.
6291     */
6292    protected ContextMenuInfo getContextMenuInfo() {
6293        return null;
6294    }
6295
6296    /**
6297     * Views should implement this if the view itself is going to add items to
6298     * the context menu.
6299     *
6300     * @param menu the context menu to populate
6301     */
6302    protected void onCreateContextMenu(ContextMenu menu) {
6303    }
6304
6305    /**
6306     * Implement this method to handle trackball motion events.  The
6307     * <em>relative</em> movement of the trackball since the last event
6308     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6309     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6310     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6311     * they will often be fractional values, representing the more fine-grained
6312     * movement information available from a trackball).
6313     *
6314     * @param event The motion event.
6315     * @return True if the event was handled, false otherwise.
6316     */
6317    public boolean onTrackballEvent(MotionEvent event) {
6318        return false;
6319    }
6320
6321    /**
6322     * Implement this method to handle generic motion events.
6323     * <p>
6324     * Generic motion events describe joystick movements, mouse hovers, track pad
6325     * touches, scroll wheel movements and other input events.  The
6326     * {@link MotionEvent#getSource() source} of the motion event specifies
6327     * the class of input that was received.  Implementations of this method
6328     * must examine the bits in the source before processing the event.
6329     * The following code example shows how this is done.
6330     * </p><p>
6331     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6332     * are delivered to the view under the pointer.  All other generic motion events are
6333     * delivered to the focused view.
6334     * </p>
6335     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6336     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6337     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6338     *             // process the joystick movement...
6339     *             return true;
6340     *         }
6341     *     }
6342     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6343     *         switch (event.getAction()) {
6344     *             case MotionEvent.ACTION_HOVER_MOVE:
6345     *                 // process the mouse hover movement...
6346     *                 return true;
6347     *             case MotionEvent.ACTION_SCROLL:
6348     *                 // process the scroll wheel movement...
6349     *                 return true;
6350     *         }
6351     *     }
6352     *     return super.onGenericMotionEvent(event);
6353     * }</pre>
6354     *
6355     * @param event The generic motion event being processed.
6356     * @return True if the event was handled, false otherwise.
6357     */
6358    public boolean onGenericMotionEvent(MotionEvent event) {
6359        return false;
6360    }
6361
6362    /**
6363     * Implement this method to handle hover events.
6364     * <p>
6365     * This method is called whenever a pointer is hovering into, over, or out of the
6366     * bounds of a view and the view is not currently being touched.
6367     * Hover events are represented as pointer events with action
6368     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6369     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6370     * </p>
6371     * <ul>
6372     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6373     * when the pointer enters the bounds of the view.</li>
6374     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6375     * when the pointer has already entered the bounds of the view and has moved.</li>
6376     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6377     * when the pointer has exited the bounds of the view or when the pointer is
6378     * about to go down due to a button click, tap, or similar user action that
6379     * causes the view to be touched.</li>
6380     * </ul>
6381     * <p>
6382     * The view should implement this method to return true to indicate that it is
6383     * handling the hover event, such as by changing its drawable state.
6384     * </p><p>
6385     * The default implementation calls {@link #setHovered} to update the hovered state
6386     * of the view when a hover enter or hover exit event is received, if the view
6387     * is enabled and is clickable.  The default implementation also sends hover
6388     * accessibility events.
6389     * </p>
6390     *
6391     * @param event The motion event that describes the hover.
6392     * @return True if the view handled the hover event.
6393     *
6394     * @see #isHovered
6395     * @see #setHovered
6396     * @see #onHoverChanged
6397     */
6398    public boolean onHoverEvent(MotionEvent event) {
6399        // The root view may receive hover (or touch) events that are outside the bounds of
6400        // the window.  This code ensures that we only send accessibility events for
6401        // hovers that are actually within the bounds of the root view.
6402        final int action = event.getAction();
6403        if (!mSendingHoverAccessibilityEvents) {
6404            if ((action == MotionEvent.ACTION_HOVER_ENTER
6405                    || action == MotionEvent.ACTION_HOVER_MOVE)
6406                    && !hasHoveredChild()
6407                    && pointInView(event.getX(), event.getY())) {
6408                mSendingHoverAccessibilityEvents = true;
6409                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6410            }
6411        } else {
6412            if (action == MotionEvent.ACTION_HOVER_EXIT
6413                    || (action == MotionEvent.ACTION_HOVER_MOVE
6414                            && !pointInView(event.getX(), event.getY()))) {
6415                mSendingHoverAccessibilityEvents = false;
6416                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6417            }
6418        }
6419
6420        if (isHoverable()) {
6421            switch (action) {
6422                case MotionEvent.ACTION_HOVER_ENTER:
6423                    setHovered(true);
6424                    break;
6425                case MotionEvent.ACTION_HOVER_EXIT:
6426                    setHovered(false);
6427                    break;
6428            }
6429
6430            // Dispatch the event to onGenericMotionEvent before returning true.
6431            // This is to provide compatibility with existing applications that
6432            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6433            // break because of the new default handling for hoverable views
6434            // in onHoverEvent.
6435            // Note that onGenericMotionEvent will be called by default when
6436            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6437            dispatchGenericMotionEventInternal(event);
6438            return true;
6439        }
6440        return false;
6441    }
6442
6443    /**
6444     * Returns true if the view should handle {@link #onHoverEvent}
6445     * by calling {@link #setHovered} to change its hovered state.
6446     *
6447     * @return True if the view is hoverable.
6448     */
6449    private boolean isHoverable() {
6450        final int viewFlags = mViewFlags;
6451        //noinspection SimplifiableIfStatement
6452        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6453            return false;
6454        }
6455
6456        return (viewFlags & CLICKABLE) == CLICKABLE
6457                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6458    }
6459
6460    /**
6461     * Returns true if the view is currently hovered.
6462     *
6463     * @return True if the view is currently hovered.
6464     *
6465     * @see #setHovered
6466     * @see #onHoverChanged
6467     */
6468    @ViewDebug.ExportedProperty
6469    public boolean isHovered() {
6470        return (mPrivateFlags & HOVERED) != 0;
6471    }
6472
6473    /**
6474     * Sets whether the view is currently hovered.
6475     * <p>
6476     * Calling this method also changes the drawable state of the view.  This
6477     * enables the view to react to hover by using different drawable resources
6478     * to change its appearance.
6479     * </p><p>
6480     * The {@link #onHoverChanged} method is called when the hovered state changes.
6481     * </p>
6482     *
6483     * @param hovered True if the view is hovered.
6484     *
6485     * @see #isHovered
6486     * @see #onHoverChanged
6487     */
6488    public void setHovered(boolean hovered) {
6489        if (hovered) {
6490            if ((mPrivateFlags & HOVERED) == 0) {
6491                mPrivateFlags |= HOVERED;
6492                refreshDrawableState();
6493                onHoverChanged(true);
6494            }
6495        } else {
6496            if ((mPrivateFlags & HOVERED) != 0) {
6497                mPrivateFlags &= ~HOVERED;
6498                refreshDrawableState();
6499                onHoverChanged(false);
6500            }
6501        }
6502    }
6503
6504    /**
6505     * Implement this method to handle hover state changes.
6506     * <p>
6507     * This method is called whenever the hover state changes as a result of a
6508     * call to {@link #setHovered}.
6509     * </p>
6510     *
6511     * @param hovered The current hover state, as returned by {@link #isHovered}.
6512     *
6513     * @see #isHovered
6514     * @see #setHovered
6515     */
6516    public void onHoverChanged(boolean hovered) {
6517    }
6518
6519    /**
6520     * Implement this method to handle touch screen motion events.
6521     *
6522     * @param event The motion event.
6523     * @return True if the event was handled, false otherwise.
6524     */
6525    public boolean onTouchEvent(MotionEvent event) {
6526        final int viewFlags = mViewFlags;
6527
6528        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6529            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6530                mPrivateFlags &= ~PRESSED;
6531                refreshDrawableState();
6532            }
6533            // A disabled view that is clickable still consumes the touch
6534            // events, it just doesn't respond to them.
6535            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6536                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6537        }
6538
6539        if (mTouchDelegate != null) {
6540            if (mTouchDelegate.onTouchEvent(event)) {
6541                return true;
6542            }
6543        }
6544
6545        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6546                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6547            switch (event.getAction()) {
6548                case MotionEvent.ACTION_UP:
6549                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6550                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6551                        // take focus if we don't have it already and we should in
6552                        // touch mode.
6553                        boolean focusTaken = false;
6554                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6555                            focusTaken = requestFocus();
6556                        }
6557
6558                        if (prepressed) {
6559                            // The button is being released before we actually
6560                            // showed it as pressed.  Make it show the pressed
6561                            // state now (before scheduling the click) to ensure
6562                            // the user sees it.
6563                            mPrivateFlags |= PRESSED;
6564                            refreshDrawableState();
6565                       }
6566
6567                        if (!mHasPerformedLongPress) {
6568                            // This is a tap, so remove the longpress check
6569                            removeLongPressCallback();
6570
6571                            // Only perform take click actions if we were in the pressed state
6572                            if (!focusTaken) {
6573                                // Use a Runnable and post this rather than calling
6574                                // performClick directly. This lets other visual state
6575                                // of the view update before click actions start.
6576                                if (mPerformClick == null) {
6577                                    mPerformClick = new PerformClick();
6578                                }
6579                                if (!post(mPerformClick)) {
6580                                    performClick();
6581                                }
6582                            }
6583                        }
6584
6585                        if (mUnsetPressedState == null) {
6586                            mUnsetPressedState = new UnsetPressedState();
6587                        }
6588
6589                        if (prepressed) {
6590                            postDelayed(mUnsetPressedState,
6591                                    ViewConfiguration.getPressedStateDuration());
6592                        } else if (!post(mUnsetPressedState)) {
6593                            // If the post failed, unpress right now
6594                            mUnsetPressedState.run();
6595                        }
6596                        removeTapCallback();
6597                    }
6598                    break;
6599
6600                case MotionEvent.ACTION_DOWN:
6601                    mHasPerformedLongPress = false;
6602
6603                    if (performButtonActionOnTouchDown(event)) {
6604                        break;
6605                    }
6606
6607                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6608                    boolean isInScrollingContainer = isInScrollingContainer();
6609
6610                    // For views inside a scrolling container, delay the pressed feedback for
6611                    // a short period in case this is a scroll.
6612                    if (isInScrollingContainer) {
6613                        mPrivateFlags |= PREPRESSED;
6614                        if (mPendingCheckForTap == null) {
6615                            mPendingCheckForTap = new CheckForTap();
6616                        }
6617                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6618                    } else {
6619                        // Not inside a scrolling container, so show the feedback right away
6620                        mPrivateFlags |= PRESSED;
6621                        refreshDrawableState();
6622                        checkForLongClick(0);
6623                    }
6624                    break;
6625
6626                case MotionEvent.ACTION_CANCEL:
6627                    mPrivateFlags &= ~PRESSED;
6628                    refreshDrawableState();
6629                    removeTapCallback();
6630                    break;
6631
6632                case MotionEvent.ACTION_MOVE:
6633                    final int x = (int) event.getX();
6634                    final int y = (int) event.getY();
6635
6636                    // Be lenient about moving outside of buttons
6637                    if (!pointInView(x, y, mTouchSlop)) {
6638                        // Outside button
6639                        removeTapCallback();
6640                        if ((mPrivateFlags & PRESSED) != 0) {
6641                            // Remove any future long press/tap checks
6642                            removeLongPressCallback();
6643
6644                            // Need to switch from pressed to not pressed
6645                            mPrivateFlags &= ~PRESSED;
6646                            refreshDrawableState();
6647                        }
6648                    }
6649                    break;
6650            }
6651            return true;
6652        }
6653
6654        return false;
6655    }
6656
6657    /**
6658     * @hide
6659     */
6660    public boolean isInScrollingContainer() {
6661        ViewParent p = getParent();
6662        while (p != null && p instanceof ViewGroup) {
6663            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6664                return true;
6665            }
6666            p = p.getParent();
6667        }
6668        return false;
6669    }
6670
6671    /**
6672     * Remove the longpress detection timer.
6673     */
6674    private void removeLongPressCallback() {
6675        if (mPendingCheckForLongPress != null) {
6676          removeCallbacks(mPendingCheckForLongPress);
6677        }
6678    }
6679
6680    /**
6681     * Remove the pending click action
6682     */
6683    private void removePerformClickCallback() {
6684        if (mPerformClick != null) {
6685            removeCallbacks(mPerformClick);
6686        }
6687    }
6688
6689    /**
6690     * Remove the prepress detection timer.
6691     */
6692    private void removeUnsetPressCallback() {
6693        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6694            setPressed(false);
6695            removeCallbacks(mUnsetPressedState);
6696        }
6697    }
6698
6699    /**
6700     * Remove the tap detection timer.
6701     */
6702    private void removeTapCallback() {
6703        if (mPendingCheckForTap != null) {
6704            mPrivateFlags &= ~PREPRESSED;
6705            removeCallbacks(mPendingCheckForTap);
6706        }
6707    }
6708
6709    /**
6710     * Cancels a pending long press.  Your subclass can use this if you
6711     * want the context menu to come up if the user presses and holds
6712     * at the same place, but you don't want it to come up if they press
6713     * and then move around enough to cause scrolling.
6714     */
6715    public void cancelLongPress() {
6716        removeLongPressCallback();
6717
6718        /*
6719         * The prepressed state handled by the tap callback is a display
6720         * construct, but the tap callback will post a long press callback
6721         * less its own timeout. Remove it here.
6722         */
6723        removeTapCallback();
6724    }
6725
6726    /**
6727     * Remove the pending callback for sending a
6728     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6729     */
6730    private void removeSendViewScrolledAccessibilityEventCallback() {
6731        if (mSendViewScrolledAccessibilityEvent != null) {
6732            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6733        }
6734    }
6735
6736    /**
6737     * Sets the TouchDelegate for this View.
6738     */
6739    public void setTouchDelegate(TouchDelegate delegate) {
6740        mTouchDelegate = delegate;
6741    }
6742
6743    /**
6744     * Gets the TouchDelegate for this View.
6745     */
6746    public TouchDelegate getTouchDelegate() {
6747        return mTouchDelegate;
6748    }
6749
6750    /**
6751     * Set flags controlling behavior of this view.
6752     *
6753     * @param flags Constant indicating the value which should be set
6754     * @param mask Constant indicating the bit range that should be changed
6755     */
6756    void setFlags(int flags, int mask) {
6757        int old = mViewFlags;
6758        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6759
6760        int changed = mViewFlags ^ old;
6761        if (changed == 0) {
6762            return;
6763        }
6764        int privateFlags = mPrivateFlags;
6765
6766        /* Check if the FOCUSABLE bit has changed */
6767        if (((changed & FOCUSABLE_MASK) != 0) &&
6768                ((privateFlags & HAS_BOUNDS) !=0)) {
6769            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6770                    && ((privateFlags & FOCUSED) != 0)) {
6771                /* Give up focus if we are no longer focusable */
6772                clearFocus();
6773            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6774                    && ((privateFlags & FOCUSED) == 0)) {
6775                /*
6776                 * Tell the view system that we are now available to take focus
6777                 * if no one else already has it.
6778                 */
6779                if (mParent != null) mParent.focusableViewAvailable(this);
6780            }
6781        }
6782
6783        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6784            if ((changed & VISIBILITY_MASK) != 0) {
6785                /*
6786                 * If this view is becoming visible, invalidate it in case it changed while
6787                 * it was not visible. Marking it drawn ensures that the invalidation will
6788                 * go through.
6789                 */
6790                mPrivateFlags |= DRAWN;
6791                invalidate(true);
6792
6793                needGlobalAttributesUpdate(true);
6794
6795                // a view becoming visible is worth notifying the parent
6796                // about in case nothing has focus.  even if this specific view
6797                // isn't focusable, it may contain something that is, so let
6798                // the root view try to give this focus if nothing else does.
6799                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6800                    mParent.focusableViewAvailable(this);
6801                }
6802            }
6803        }
6804
6805        /* Check if the GONE bit has changed */
6806        if ((changed & GONE) != 0) {
6807            needGlobalAttributesUpdate(false);
6808            requestLayout();
6809
6810            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6811                if (hasFocus()) clearFocus();
6812                destroyDrawingCache();
6813                if (mParent instanceof View) {
6814                    // GONE views noop invalidation, so invalidate the parent
6815                    ((View) mParent).invalidate(true);
6816                }
6817                // Mark the view drawn to ensure that it gets invalidated properly the next
6818                // time it is visible and gets invalidated
6819                mPrivateFlags |= DRAWN;
6820            }
6821            if (mAttachInfo != null) {
6822                mAttachInfo.mViewVisibilityChanged = true;
6823            }
6824        }
6825
6826        /* Check if the VISIBLE bit has changed */
6827        if ((changed & INVISIBLE) != 0) {
6828            needGlobalAttributesUpdate(false);
6829            /*
6830             * If this view is becoming invisible, set the DRAWN flag so that
6831             * the next invalidate() will not be skipped.
6832             */
6833            mPrivateFlags |= DRAWN;
6834
6835            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6836                // root view becoming invisible shouldn't clear focus
6837                if (getRootView() != this) {
6838                    clearFocus();
6839                }
6840            }
6841            if (mAttachInfo != null) {
6842                mAttachInfo.mViewVisibilityChanged = true;
6843            }
6844        }
6845
6846        if ((changed & VISIBILITY_MASK) != 0) {
6847            if (mParent instanceof ViewGroup) {
6848                ((ViewGroup) mParent).onChildVisibilityChanged(this, (changed & VISIBILITY_MASK),
6849                        (flags & VISIBILITY_MASK));
6850                ((View) mParent).invalidate(true);
6851            } else if (mParent != null) {
6852                mParent.invalidateChild(this, null);
6853            }
6854            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6855        }
6856
6857        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6858            destroyDrawingCache();
6859        }
6860
6861        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6862            destroyDrawingCache();
6863            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6864            invalidateParentCaches();
6865        }
6866
6867        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6868            destroyDrawingCache();
6869            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6870        }
6871
6872        if ((changed & DRAW_MASK) != 0) {
6873            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6874                if (mBGDrawable != null) {
6875                    mPrivateFlags &= ~SKIP_DRAW;
6876                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6877                } else {
6878                    mPrivateFlags |= SKIP_DRAW;
6879                }
6880            } else {
6881                mPrivateFlags &= ~SKIP_DRAW;
6882            }
6883            requestLayout();
6884            invalidate(true);
6885        }
6886
6887        if ((changed & KEEP_SCREEN_ON) != 0) {
6888            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6889                mParent.recomputeViewAttributes(this);
6890            }
6891        }
6892
6893        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6894            requestLayout();
6895        }
6896    }
6897
6898    /**
6899     * Change the view's z order in the tree, so it's on top of other sibling
6900     * views
6901     */
6902    public void bringToFront() {
6903        if (mParent != null) {
6904            mParent.bringChildToFront(this);
6905        }
6906    }
6907
6908    /**
6909     * This is called in response to an internal scroll in this view (i.e., the
6910     * view scrolled its own contents). This is typically as a result of
6911     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6912     * called.
6913     *
6914     * @param l Current horizontal scroll origin.
6915     * @param t Current vertical scroll origin.
6916     * @param oldl Previous horizontal scroll origin.
6917     * @param oldt Previous vertical scroll origin.
6918     */
6919    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6920        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6921            postSendViewScrolledAccessibilityEventCallback();
6922        }
6923
6924        mBackgroundSizeChanged = true;
6925
6926        final AttachInfo ai = mAttachInfo;
6927        if (ai != null) {
6928            ai.mViewScrollChanged = true;
6929        }
6930    }
6931
6932    /**
6933     * Interface definition for a callback to be invoked when the layout bounds of a view
6934     * changes due to layout processing.
6935     */
6936    public interface OnLayoutChangeListener {
6937        /**
6938         * Called when the focus state of a view has changed.
6939         *
6940         * @param v The view whose state has changed.
6941         * @param left The new value of the view's left property.
6942         * @param top The new value of the view's top property.
6943         * @param right The new value of the view's right property.
6944         * @param bottom The new value of the view's bottom property.
6945         * @param oldLeft The previous value of the view's left property.
6946         * @param oldTop The previous value of the view's top property.
6947         * @param oldRight The previous value of the view's right property.
6948         * @param oldBottom The previous value of the view's bottom property.
6949         */
6950        void onLayoutChange(View v, int left, int top, int right, int bottom,
6951            int oldLeft, int oldTop, int oldRight, int oldBottom);
6952    }
6953
6954    /**
6955     * This is called during layout when the size of this view has changed. If
6956     * you were just added to the view hierarchy, you're called with the old
6957     * values of 0.
6958     *
6959     * @param w Current width of this view.
6960     * @param h Current height of this view.
6961     * @param oldw Old width of this view.
6962     * @param oldh Old height of this view.
6963     */
6964    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6965    }
6966
6967    /**
6968     * Called by draw to draw the child views. This may be overridden
6969     * by derived classes to gain control just before its children are drawn
6970     * (but after its own view has been drawn).
6971     * @param canvas the canvas on which to draw the view
6972     */
6973    protected void dispatchDraw(Canvas canvas) {
6974    }
6975
6976    /**
6977     * Gets the parent of this view. Note that the parent is a
6978     * ViewParent and not necessarily a View.
6979     *
6980     * @return Parent of this view.
6981     */
6982    public final ViewParent getParent() {
6983        return mParent;
6984    }
6985
6986    /**
6987     * Set the horizontal scrolled position of your view. This will cause a call to
6988     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6989     * invalidated.
6990     * @param value the x position to scroll to
6991     */
6992    public void setScrollX(int value) {
6993        scrollTo(value, mScrollY);
6994    }
6995
6996    /**
6997     * Set the vertical scrolled position of your view. This will cause a call to
6998     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6999     * invalidated.
7000     * @param value the y position to scroll to
7001     */
7002    public void setScrollY(int value) {
7003        scrollTo(mScrollX, value);
7004    }
7005
7006    /**
7007     * Return the scrolled left position of this view. This is the left edge of
7008     * the displayed part of your view. You do not need to draw any pixels
7009     * farther left, since those are outside of the frame of your view on
7010     * screen.
7011     *
7012     * @return The left edge of the displayed part of your view, in pixels.
7013     */
7014    public final int getScrollX() {
7015        return mScrollX;
7016    }
7017
7018    /**
7019     * Return the scrolled top position of this view. This is the top edge of
7020     * the displayed part of your view. You do not need to draw any pixels above
7021     * it, since those are outside of the frame of your view on screen.
7022     *
7023     * @return The top edge of the displayed part of your view, in pixels.
7024     */
7025    public final int getScrollY() {
7026        return mScrollY;
7027    }
7028
7029    /**
7030     * Return the width of the your view.
7031     *
7032     * @return The width of your view, in pixels.
7033     */
7034    @ViewDebug.ExportedProperty(category = "layout")
7035    public final int getWidth() {
7036        return mRight - mLeft;
7037    }
7038
7039    /**
7040     * Return the height of your view.
7041     *
7042     * @return The height of your view, in pixels.
7043     */
7044    @ViewDebug.ExportedProperty(category = "layout")
7045    public final int getHeight() {
7046        return mBottom - mTop;
7047    }
7048
7049    /**
7050     * Return the visible drawing bounds of your view. Fills in the output
7051     * rectangle with the values from getScrollX(), getScrollY(),
7052     * getWidth(), and getHeight().
7053     *
7054     * @param outRect The (scrolled) drawing bounds of the view.
7055     */
7056    public void getDrawingRect(Rect outRect) {
7057        outRect.left = mScrollX;
7058        outRect.top = mScrollY;
7059        outRect.right = mScrollX + (mRight - mLeft);
7060        outRect.bottom = mScrollY + (mBottom - mTop);
7061    }
7062
7063    /**
7064     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7065     * raw width component (that is the result is masked by
7066     * {@link #MEASURED_SIZE_MASK}).
7067     *
7068     * @return The raw measured width of this view.
7069     */
7070    public final int getMeasuredWidth() {
7071        return mMeasuredWidth & MEASURED_SIZE_MASK;
7072    }
7073
7074    /**
7075     * Return the full width measurement information for this view as computed
7076     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7077     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7078     * This should be used during measurement and layout calculations only. Use
7079     * {@link #getWidth()} to see how wide a view is after layout.
7080     *
7081     * @return The measured width of this view as a bit mask.
7082     */
7083    public final int getMeasuredWidthAndState() {
7084        return mMeasuredWidth;
7085    }
7086
7087    /**
7088     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7089     * raw width component (that is the result is masked by
7090     * {@link #MEASURED_SIZE_MASK}).
7091     *
7092     * @return The raw measured height of this view.
7093     */
7094    public final int getMeasuredHeight() {
7095        return mMeasuredHeight & MEASURED_SIZE_MASK;
7096    }
7097
7098    /**
7099     * Return the full height measurement information for this view as computed
7100     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7101     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7102     * This should be used during measurement and layout calculations only. Use
7103     * {@link #getHeight()} to see how wide a view is after layout.
7104     *
7105     * @return The measured width of this view as a bit mask.
7106     */
7107    public final int getMeasuredHeightAndState() {
7108        return mMeasuredHeight;
7109    }
7110
7111    /**
7112     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7113     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7114     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7115     * and the height component is at the shifted bits
7116     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7117     */
7118    public final int getMeasuredState() {
7119        return (mMeasuredWidth&MEASURED_STATE_MASK)
7120                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7121                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7122    }
7123
7124    /**
7125     * The transform matrix of this view, which is calculated based on the current
7126     * roation, scale, and pivot properties.
7127     *
7128     * @see #getRotation()
7129     * @see #getScaleX()
7130     * @see #getScaleY()
7131     * @see #getPivotX()
7132     * @see #getPivotY()
7133     * @return The current transform matrix for the view
7134     */
7135    public Matrix getMatrix() {
7136        if (mTransformationInfo != null) {
7137            updateMatrix();
7138            return mTransformationInfo.mMatrix;
7139        }
7140        return Matrix.IDENTITY_MATRIX;
7141    }
7142
7143    /**
7144     * Utility function to determine if the value is far enough away from zero to be
7145     * considered non-zero.
7146     * @param value A floating point value to check for zero-ness
7147     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7148     */
7149    private static boolean nonzero(float value) {
7150        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7151    }
7152
7153    /**
7154     * Returns true if the transform matrix is the identity matrix.
7155     * Recomputes the matrix if necessary.
7156     *
7157     * @return True if the transform matrix is the identity matrix, false otherwise.
7158     */
7159    final boolean hasIdentityMatrix() {
7160        if (mTransformationInfo != null) {
7161            updateMatrix();
7162            return mTransformationInfo.mMatrixIsIdentity;
7163        }
7164        return true;
7165    }
7166
7167    void ensureTransformationInfo() {
7168        if (mTransformationInfo == null) {
7169            mTransformationInfo = new TransformationInfo();
7170        }
7171    }
7172
7173    /**
7174     * Recomputes the transform matrix if necessary.
7175     */
7176    private void updateMatrix() {
7177        final TransformationInfo info = mTransformationInfo;
7178        if (info == null) {
7179            return;
7180        }
7181        if (info.mMatrixDirty) {
7182            // transform-related properties have changed since the last time someone
7183            // asked for the matrix; recalculate it with the current values
7184
7185            // Figure out if we need to update the pivot point
7186            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7187                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7188                    info.mPrevWidth = mRight - mLeft;
7189                    info.mPrevHeight = mBottom - mTop;
7190                    info.mPivotX = info.mPrevWidth / 2f;
7191                    info.mPivotY = info.mPrevHeight / 2f;
7192                }
7193            }
7194            info.mMatrix.reset();
7195            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7196                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7197                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7198                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7199            } else {
7200                if (info.mCamera == null) {
7201                    info.mCamera = new Camera();
7202                    info.matrix3D = new Matrix();
7203                }
7204                info.mCamera.save();
7205                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7206                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7207                info.mCamera.getMatrix(info.matrix3D);
7208                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7209                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7210                        info.mPivotY + info.mTranslationY);
7211                info.mMatrix.postConcat(info.matrix3D);
7212                info.mCamera.restore();
7213            }
7214            info.mMatrixDirty = false;
7215            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7216            info.mInverseMatrixDirty = true;
7217        }
7218    }
7219
7220    /**
7221     * Utility method to retrieve the inverse of the current mMatrix property.
7222     * We cache the matrix to avoid recalculating it when transform properties
7223     * have not changed.
7224     *
7225     * @return The inverse of the current matrix of this view.
7226     */
7227    final Matrix getInverseMatrix() {
7228        final TransformationInfo info = mTransformationInfo;
7229        if (info != null) {
7230            updateMatrix();
7231            if (info.mInverseMatrixDirty) {
7232                if (info.mInverseMatrix == null) {
7233                    info.mInverseMatrix = new Matrix();
7234                }
7235                info.mMatrix.invert(info.mInverseMatrix);
7236                info.mInverseMatrixDirty = false;
7237            }
7238            return info.mInverseMatrix;
7239        }
7240        return Matrix.IDENTITY_MATRIX;
7241    }
7242
7243    /**
7244     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7245     * views are drawn) from the camera to this view. The camera's distance
7246     * affects 3D transformations, for instance rotations around the X and Y
7247     * axis. If the rotationX or rotationY properties are changed and this view is
7248     * large (more than half the size of the screen), it is recommended to always
7249     * use a camera distance that's greater than the height (X axis rotation) or
7250     * the width (Y axis rotation) of this view.</p>
7251     *
7252     * <p>The distance of the camera from the view plane can have an affect on the
7253     * perspective distortion of the view when it is rotated around the x or y axis.
7254     * For example, a large distance will result in a large viewing angle, and there
7255     * will not be much perspective distortion of the view as it rotates. A short
7256     * distance may cause much more perspective distortion upon rotation, and can
7257     * also result in some drawing artifacts if the rotated view ends up partially
7258     * behind the camera (which is why the recommendation is to use a distance at
7259     * least as far as the size of the view, if the view is to be rotated.)</p>
7260     *
7261     * <p>The distance is expressed in "depth pixels." The default distance depends
7262     * on the screen density. For instance, on a medium density display, the
7263     * default distance is 1280. On a high density display, the default distance
7264     * is 1920.</p>
7265     *
7266     * <p>If you want to specify a distance that leads to visually consistent
7267     * results across various densities, use the following formula:</p>
7268     * <pre>
7269     * float scale = context.getResources().getDisplayMetrics().density;
7270     * view.setCameraDistance(distance * scale);
7271     * </pre>
7272     *
7273     * <p>The density scale factor of a high density display is 1.5,
7274     * and 1920 = 1280 * 1.5.</p>
7275     *
7276     * @param distance The distance in "depth pixels", if negative the opposite
7277     *        value is used
7278     *
7279     * @see #setRotationX(float)
7280     * @see #setRotationY(float)
7281     */
7282    public void setCameraDistance(float distance) {
7283        invalidateParentCaches();
7284        invalidate(false);
7285
7286        ensureTransformationInfo();
7287        final float dpi = mResources.getDisplayMetrics().densityDpi;
7288        final TransformationInfo info = mTransformationInfo;
7289        if (info.mCamera == null) {
7290            info.mCamera = new Camera();
7291            info.matrix3D = new Matrix();
7292        }
7293
7294        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7295        info.mMatrixDirty = true;
7296
7297        invalidate(false);
7298    }
7299
7300    /**
7301     * The degrees that the view is rotated around the pivot point.
7302     *
7303     * @see #setRotation(float)
7304     * @see #getPivotX()
7305     * @see #getPivotY()
7306     *
7307     * @return The degrees of rotation.
7308     */
7309    public float getRotation() {
7310        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7311    }
7312
7313    /**
7314     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7315     * result in clockwise rotation.
7316     *
7317     * @param rotation The degrees of rotation.
7318     *
7319     * @see #getRotation()
7320     * @see #getPivotX()
7321     * @see #getPivotY()
7322     * @see #setRotationX(float)
7323     * @see #setRotationY(float)
7324     *
7325     * @attr ref android.R.styleable#View_rotation
7326     */
7327    public void setRotation(float rotation) {
7328        ensureTransformationInfo();
7329        final TransformationInfo info = mTransformationInfo;
7330        if (info.mRotation != rotation) {
7331            invalidateParentCaches();
7332            // Double-invalidation is necessary to capture view's old and new areas
7333            invalidate(false);
7334            info.mRotation = rotation;
7335            info.mMatrixDirty = true;
7336            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7337            invalidate(false);
7338        }
7339    }
7340
7341    /**
7342     * The degrees that the view is rotated around the vertical axis through the pivot point.
7343     *
7344     * @see #getPivotX()
7345     * @see #getPivotY()
7346     * @see #setRotationY(float)
7347     *
7348     * @return The degrees of Y rotation.
7349     */
7350    public float getRotationY() {
7351        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7352    }
7353
7354    /**
7355     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7356     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7357     * down the y axis.
7358     *
7359     * When rotating large views, it is recommended to adjust the camera distance
7360     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7361     *
7362     * @param rotationY The degrees of Y rotation.
7363     *
7364     * @see #getRotationY()
7365     * @see #getPivotX()
7366     * @see #getPivotY()
7367     * @see #setRotation(float)
7368     * @see #setRotationX(float)
7369     * @see #setCameraDistance(float)
7370     *
7371     * @attr ref android.R.styleable#View_rotationY
7372     */
7373    public void setRotationY(float rotationY) {
7374        ensureTransformationInfo();
7375        final TransformationInfo info = mTransformationInfo;
7376        if (info.mRotationY != rotationY) {
7377            invalidateParentCaches();
7378            // Double-invalidation is necessary to capture view's old and new areas
7379            invalidate(false);
7380            info.mRotationY = rotationY;
7381            info.mMatrixDirty = true;
7382            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7383            invalidate(false);
7384        }
7385    }
7386
7387    /**
7388     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7389     *
7390     * @see #getPivotX()
7391     * @see #getPivotY()
7392     * @see #setRotationX(float)
7393     *
7394     * @return The degrees of X rotation.
7395     */
7396    public float getRotationX() {
7397        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7398    }
7399
7400    /**
7401     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7402     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7403     * x axis.
7404     *
7405     * When rotating large views, it is recommended to adjust the camera distance
7406     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7407     *
7408     * @param rotationX The degrees of X rotation.
7409     *
7410     * @see #getRotationX()
7411     * @see #getPivotX()
7412     * @see #getPivotY()
7413     * @see #setRotation(float)
7414     * @see #setRotationY(float)
7415     * @see #setCameraDistance(float)
7416     *
7417     * @attr ref android.R.styleable#View_rotationX
7418     */
7419    public void setRotationX(float rotationX) {
7420        ensureTransformationInfo();
7421        final TransformationInfo info = mTransformationInfo;
7422        if (info.mRotationX != rotationX) {
7423            invalidateParentCaches();
7424            // Double-invalidation is necessary to capture view's old and new areas
7425            invalidate(false);
7426            info.mRotationX = rotationX;
7427            info.mMatrixDirty = true;
7428            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7429            invalidate(false);
7430        }
7431    }
7432
7433    /**
7434     * The amount that the view is scaled in x around the pivot point, as a proportion of
7435     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7436     *
7437     * <p>By default, this is 1.0f.
7438     *
7439     * @see #getPivotX()
7440     * @see #getPivotY()
7441     * @return The scaling factor.
7442     */
7443    public float getScaleX() {
7444        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7445    }
7446
7447    /**
7448     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7449     * the view's unscaled width. A value of 1 means that no scaling is applied.
7450     *
7451     * @param scaleX The scaling factor.
7452     * @see #getPivotX()
7453     * @see #getPivotY()
7454     *
7455     * @attr ref android.R.styleable#View_scaleX
7456     */
7457    public void setScaleX(float scaleX) {
7458        ensureTransformationInfo();
7459        final TransformationInfo info = mTransformationInfo;
7460        if (info.mScaleX != scaleX) {
7461            invalidateParentCaches();
7462            // Double-invalidation is necessary to capture view's old and new areas
7463            invalidate(false);
7464            info.mScaleX = scaleX;
7465            info.mMatrixDirty = true;
7466            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7467            invalidate(false);
7468        }
7469    }
7470
7471    /**
7472     * The amount that the view is scaled in y around the pivot point, as a proportion of
7473     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7474     *
7475     * <p>By default, this is 1.0f.
7476     *
7477     * @see #getPivotX()
7478     * @see #getPivotY()
7479     * @return The scaling factor.
7480     */
7481    public float getScaleY() {
7482        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7483    }
7484
7485    /**
7486     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7487     * the view's unscaled width. A value of 1 means that no scaling is applied.
7488     *
7489     * @param scaleY The scaling factor.
7490     * @see #getPivotX()
7491     * @see #getPivotY()
7492     *
7493     * @attr ref android.R.styleable#View_scaleY
7494     */
7495    public void setScaleY(float scaleY) {
7496        ensureTransformationInfo();
7497        final TransformationInfo info = mTransformationInfo;
7498        if (info.mScaleY != scaleY) {
7499            invalidateParentCaches();
7500            // Double-invalidation is necessary to capture view's old and new areas
7501            invalidate(false);
7502            info.mScaleY = scaleY;
7503            info.mMatrixDirty = true;
7504            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7505            invalidate(false);
7506        }
7507    }
7508
7509    /**
7510     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7511     * and {@link #setScaleX(float) scaled}.
7512     *
7513     * @see #getRotation()
7514     * @see #getScaleX()
7515     * @see #getScaleY()
7516     * @see #getPivotY()
7517     * @return The x location of the pivot point.
7518     */
7519    public float getPivotX() {
7520        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7521    }
7522
7523    /**
7524     * Sets the x location of the point around which the view is
7525     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7526     * By default, the pivot point is centered on the object.
7527     * Setting this property disables this behavior and causes the view to use only the
7528     * explicitly set pivotX and pivotY values.
7529     *
7530     * @param pivotX The x location of the pivot point.
7531     * @see #getRotation()
7532     * @see #getScaleX()
7533     * @see #getScaleY()
7534     * @see #getPivotY()
7535     *
7536     * @attr ref android.R.styleable#View_transformPivotX
7537     */
7538    public void setPivotX(float pivotX) {
7539        ensureTransformationInfo();
7540        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7541        final TransformationInfo info = mTransformationInfo;
7542        if (info.mPivotX != pivotX) {
7543            invalidateParentCaches();
7544            // Double-invalidation is necessary to capture view's old and new areas
7545            invalidate(false);
7546            info.mPivotX = pivotX;
7547            info.mMatrixDirty = true;
7548            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7549            invalidate(false);
7550        }
7551    }
7552
7553    /**
7554     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7555     * and {@link #setScaleY(float) scaled}.
7556     *
7557     * @see #getRotation()
7558     * @see #getScaleX()
7559     * @see #getScaleY()
7560     * @see #getPivotY()
7561     * @return The y location of the pivot point.
7562     */
7563    public float getPivotY() {
7564        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7565    }
7566
7567    /**
7568     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7569     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7570     * Setting this property disables this behavior and causes the view to use only the
7571     * explicitly set pivotX and pivotY values.
7572     *
7573     * @param pivotY The y location of the pivot point.
7574     * @see #getRotation()
7575     * @see #getScaleX()
7576     * @see #getScaleY()
7577     * @see #getPivotY()
7578     *
7579     * @attr ref android.R.styleable#View_transformPivotY
7580     */
7581    public void setPivotY(float pivotY) {
7582        ensureTransformationInfo();
7583        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7584        final TransformationInfo info = mTransformationInfo;
7585        if (info.mPivotY != pivotY) {
7586            invalidateParentCaches();
7587            // Double-invalidation is necessary to capture view's old and new areas
7588            invalidate(false);
7589            info.mPivotY = pivotY;
7590            info.mMatrixDirty = true;
7591            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7592            invalidate(false);
7593        }
7594    }
7595
7596    /**
7597     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7598     * completely transparent and 1 means the view is completely opaque.
7599     *
7600     * <p>By default this is 1.0f.
7601     * @return The opacity of the view.
7602     */
7603    public float getAlpha() {
7604        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7605    }
7606
7607    /**
7608     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7609     * completely transparent and 1 means the view is completely opaque.</p>
7610     *
7611     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7612     * responsible for applying the opacity itself. Otherwise, calling this method is
7613     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7614     * setting a hardware layer.</p>
7615     *
7616     * @param alpha The opacity of the view.
7617     *
7618     * @see #setLayerType(int, android.graphics.Paint)
7619     *
7620     * @attr ref android.R.styleable#View_alpha
7621     */
7622    public void setAlpha(float alpha) {
7623        ensureTransformationInfo();
7624        if (mTransformationInfo.mAlpha != alpha) {
7625            mTransformationInfo.mAlpha = alpha;
7626            invalidateParentCaches();
7627            if (onSetAlpha((int) (alpha * 255))) {
7628                mPrivateFlags |= ALPHA_SET;
7629                // subclass is handling alpha - don't optimize rendering cache invalidation
7630                invalidate(true);
7631            } else {
7632                mPrivateFlags &= ~ALPHA_SET;
7633                invalidate(false);
7634            }
7635        }
7636    }
7637
7638    /**
7639     * Faster version of setAlpha() which performs the same steps except there are
7640     * no calls to invalidate(). The caller of this function should perform proper invalidation
7641     * on the parent and this object. The return value indicates whether the subclass handles
7642     * alpha (the return value for onSetAlpha()).
7643     *
7644     * @param alpha The new value for the alpha property
7645     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7646     *         the new value for the alpha property is different from the old value
7647     */
7648    boolean setAlphaNoInvalidation(float alpha) {
7649        ensureTransformationInfo();
7650        if (mTransformationInfo.mAlpha != alpha) {
7651            mTransformationInfo.mAlpha = alpha;
7652            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7653            if (subclassHandlesAlpha) {
7654                mPrivateFlags |= ALPHA_SET;
7655                return true;
7656            } else {
7657                mPrivateFlags &= ~ALPHA_SET;
7658            }
7659        }
7660        return false;
7661    }
7662
7663    /**
7664     * Top position of this view relative to its parent.
7665     *
7666     * @return The top of this view, in pixels.
7667     */
7668    @ViewDebug.CapturedViewProperty
7669    public final int getTop() {
7670        return mTop;
7671    }
7672
7673    /**
7674     * Sets the top position of this view relative to its parent. This method is meant to be called
7675     * by the layout system and should not generally be called otherwise, because the property
7676     * may be changed at any time by the layout.
7677     *
7678     * @param top The top of this view, in pixels.
7679     */
7680    public final void setTop(int top) {
7681        if (top != mTop) {
7682            updateMatrix();
7683            final boolean matrixIsIdentity = mTransformationInfo == null
7684                    || mTransformationInfo.mMatrixIsIdentity;
7685            if (matrixIsIdentity) {
7686                if (mAttachInfo != null) {
7687                    int minTop;
7688                    int yLoc;
7689                    if (top < mTop) {
7690                        minTop = top;
7691                        yLoc = top - mTop;
7692                    } else {
7693                        minTop = mTop;
7694                        yLoc = 0;
7695                    }
7696                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7697                }
7698            } else {
7699                // Double-invalidation is necessary to capture view's old and new areas
7700                invalidate(true);
7701            }
7702
7703            int width = mRight - mLeft;
7704            int oldHeight = mBottom - mTop;
7705
7706            mTop = top;
7707
7708            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7709
7710            if (!matrixIsIdentity) {
7711                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7712                    // A change in dimension means an auto-centered pivot point changes, too
7713                    mTransformationInfo.mMatrixDirty = true;
7714                }
7715                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7716                invalidate(true);
7717            }
7718            mBackgroundSizeChanged = true;
7719            invalidateParentIfNeeded();
7720        }
7721    }
7722
7723    /**
7724     * Bottom position of this view relative to its parent.
7725     *
7726     * @return The bottom of this view, in pixels.
7727     */
7728    @ViewDebug.CapturedViewProperty
7729    public final int getBottom() {
7730        return mBottom;
7731    }
7732
7733    /**
7734     * True if this view has changed since the last time being drawn.
7735     *
7736     * @return The dirty state of this view.
7737     */
7738    public boolean isDirty() {
7739        return (mPrivateFlags & DIRTY_MASK) != 0;
7740    }
7741
7742    /**
7743     * Sets the bottom position of this view relative to its parent. This method is meant to be
7744     * called by the layout system and should not generally be called otherwise, because the
7745     * property may be changed at any time by the layout.
7746     *
7747     * @param bottom The bottom of this view, in pixels.
7748     */
7749    public final void setBottom(int bottom) {
7750        if (bottom != mBottom) {
7751            updateMatrix();
7752            final boolean matrixIsIdentity = mTransformationInfo == null
7753                    || mTransformationInfo.mMatrixIsIdentity;
7754            if (matrixIsIdentity) {
7755                if (mAttachInfo != null) {
7756                    int maxBottom;
7757                    if (bottom < mBottom) {
7758                        maxBottom = mBottom;
7759                    } else {
7760                        maxBottom = bottom;
7761                    }
7762                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7763                }
7764            } else {
7765                // Double-invalidation is necessary to capture view's old and new areas
7766                invalidate(true);
7767            }
7768
7769            int width = mRight - mLeft;
7770            int oldHeight = mBottom - mTop;
7771
7772            mBottom = bottom;
7773
7774            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7775
7776            if (!matrixIsIdentity) {
7777                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7778                    // A change in dimension means an auto-centered pivot point changes, too
7779                    mTransformationInfo.mMatrixDirty = true;
7780                }
7781                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7782                invalidate(true);
7783            }
7784            mBackgroundSizeChanged = true;
7785            invalidateParentIfNeeded();
7786        }
7787    }
7788
7789    /**
7790     * Left position of this view relative to its parent.
7791     *
7792     * @return The left edge of this view, in pixels.
7793     */
7794    @ViewDebug.CapturedViewProperty
7795    public final int getLeft() {
7796        return mLeft;
7797    }
7798
7799    /**
7800     * Sets the left position of this view relative to its parent. This method is meant to be called
7801     * by the layout system and should not generally be called otherwise, because the property
7802     * may be changed at any time by the layout.
7803     *
7804     * @param left The bottom of this view, in pixels.
7805     */
7806    public final void setLeft(int left) {
7807        if (left != mLeft) {
7808            updateMatrix();
7809            final boolean matrixIsIdentity = mTransformationInfo == null
7810                    || mTransformationInfo.mMatrixIsIdentity;
7811            if (matrixIsIdentity) {
7812                if (mAttachInfo != null) {
7813                    int minLeft;
7814                    int xLoc;
7815                    if (left < mLeft) {
7816                        minLeft = left;
7817                        xLoc = left - mLeft;
7818                    } else {
7819                        minLeft = mLeft;
7820                        xLoc = 0;
7821                    }
7822                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7823                }
7824            } else {
7825                // Double-invalidation is necessary to capture view's old and new areas
7826                invalidate(true);
7827            }
7828
7829            int oldWidth = mRight - mLeft;
7830            int height = mBottom - mTop;
7831
7832            mLeft = left;
7833
7834            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7835
7836            if (!matrixIsIdentity) {
7837                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7838                    // A change in dimension means an auto-centered pivot point changes, too
7839                    mTransformationInfo.mMatrixDirty = true;
7840                }
7841                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7842                invalidate(true);
7843            }
7844            mBackgroundSizeChanged = true;
7845            invalidateParentIfNeeded();
7846        }
7847    }
7848
7849    /**
7850     * Right position of this view relative to its parent.
7851     *
7852     * @return The right edge of this view, in pixels.
7853     */
7854    @ViewDebug.CapturedViewProperty
7855    public final int getRight() {
7856        return mRight;
7857    }
7858
7859    /**
7860     * Sets the right position of this view relative to its parent. This method is meant to be called
7861     * by the layout system and should not generally be called otherwise, because the property
7862     * may be changed at any time by the layout.
7863     *
7864     * @param right The bottom of this view, in pixels.
7865     */
7866    public final void setRight(int right) {
7867        if (right != mRight) {
7868            updateMatrix();
7869            final boolean matrixIsIdentity = mTransformationInfo == null
7870                    || mTransformationInfo.mMatrixIsIdentity;
7871            if (matrixIsIdentity) {
7872                if (mAttachInfo != null) {
7873                    int maxRight;
7874                    if (right < mRight) {
7875                        maxRight = mRight;
7876                    } else {
7877                        maxRight = right;
7878                    }
7879                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7880                }
7881            } else {
7882                // Double-invalidation is necessary to capture view's old and new areas
7883                invalidate(true);
7884            }
7885
7886            int oldWidth = mRight - mLeft;
7887            int height = mBottom - mTop;
7888
7889            mRight = right;
7890
7891            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7892
7893            if (!matrixIsIdentity) {
7894                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7895                    // A change in dimension means an auto-centered pivot point changes, too
7896                    mTransformationInfo.mMatrixDirty = true;
7897                }
7898                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7899                invalidate(true);
7900            }
7901            mBackgroundSizeChanged = true;
7902            invalidateParentIfNeeded();
7903        }
7904    }
7905
7906    /**
7907     * The visual x position of this view, in pixels. This is equivalent to the
7908     * {@link #setTranslationX(float) translationX} property plus the current
7909     * {@link #getLeft() left} property.
7910     *
7911     * @return The visual x position of this view, in pixels.
7912     */
7913    public float getX() {
7914        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7915    }
7916
7917    /**
7918     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7919     * {@link #setTranslationX(float) translationX} property to be the difference between
7920     * the x value passed in and the current {@link #getLeft() left} property.
7921     *
7922     * @param x The visual x position of this view, in pixels.
7923     */
7924    public void setX(float x) {
7925        setTranslationX(x - mLeft);
7926    }
7927
7928    /**
7929     * The visual y position of this view, in pixels. This is equivalent to the
7930     * {@link #setTranslationY(float) translationY} property plus the current
7931     * {@link #getTop() top} property.
7932     *
7933     * @return The visual y position of this view, in pixels.
7934     */
7935    public float getY() {
7936        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7937    }
7938
7939    /**
7940     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7941     * {@link #setTranslationY(float) translationY} property to be the difference between
7942     * the y value passed in and the current {@link #getTop() top} property.
7943     *
7944     * @param y The visual y position of this view, in pixels.
7945     */
7946    public void setY(float y) {
7947        setTranslationY(y - mTop);
7948    }
7949
7950
7951    /**
7952     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7953     * This position is post-layout, in addition to wherever the object's
7954     * layout placed it.
7955     *
7956     * @return The horizontal position of this view relative to its left position, in pixels.
7957     */
7958    public float getTranslationX() {
7959        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7960    }
7961
7962    /**
7963     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7964     * This effectively positions the object post-layout, in addition to wherever the object's
7965     * layout placed it.
7966     *
7967     * @param translationX The horizontal position of this view relative to its left position,
7968     * in pixels.
7969     *
7970     * @attr ref android.R.styleable#View_translationX
7971     */
7972    public void setTranslationX(float translationX) {
7973        ensureTransformationInfo();
7974        final TransformationInfo info = mTransformationInfo;
7975        if (info.mTranslationX != translationX) {
7976            invalidateParentCaches();
7977            // Double-invalidation is necessary to capture view's old and new areas
7978            invalidate(false);
7979            info.mTranslationX = translationX;
7980            info.mMatrixDirty = true;
7981            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7982            invalidate(false);
7983        }
7984    }
7985
7986    /**
7987     * The horizontal location of this view relative to its {@link #getTop() top} position.
7988     * This position is post-layout, in addition to wherever the object's
7989     * layout placed it.
7990     *
7991     * @return The vertical position of this view relative to its top position,
7992     * in pixels.
7993     */
7994    public float getTranslationY() {
7995        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7996    }
7997
7998    /**
7999     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8000     * This effectively positions the object post-layout, in addition to wherever the object's
8001     * layout placed it.
8002     *
8003     * @param translationY The vertical position of this view relative to its top position,
8004     * in pixels.
8005     *
8006     * @attr ref android.R.styleable#View_translationY
8007     */
8008    public void setTranslationY(float translationY) {
8009        ensureTransformationInfo();
8010        final TransformationInfo info = mTransformationInfo;
8011        if (info.mTranslationY != translationY) {
8012            invalidateParentCaches();
8013            // Double-invalidation is necessary to capture view's old and new areas
8014            invalidate(false);
8015            info.mTranslationY = translationY;
8016            info.mMatrixDirty = true;
8017            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8018            invalidate(false);
8019        }
8020    }
8021
8022    /**
8023     * Hit rectangle in parent's coordinates
8024     *
8025     * @param outRect The hit rectangle of the view.
8026     */
8027    public void getHitRect(Rect outRect) {
8028        updateMatrix();
8029        final TransformationInfo info = mTransformationInfo;
8030        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8031            outRect.set(mLeft, mTop, mRight, mBottom);
8032        } else {
8033            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8034            tmpRect.set(-info.mPivotX, -info.mPivotY,
8035                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8036            info.mMatrix.mapRect(tmpRect);
8037            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8038                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8039        }
8040    }
8041
8042    /**
8043     * Determines whether the given point, in local coordinates is inside the view.
8044     */
8045    /*package*/ final boolean pointInView(float localX, float localY) {
8046        return localX >= 0 && localX < (mRight - mLeft)
8047                && localY >= 0 && localY < (mBottom - mTop);
8048    }
8049
8050    /**
8051     * Utility method to determine whether the given point, in local coordinates,
8052     * is inside the view, where the area of the view is expanded by the slop factor.
8053     * This method is called while processing touch-move events to determine if the event
8054     * is still within the view.
8055     */
8056    private boolean pointInView(float localX, float localY, float slop) {
8057        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8058                localY < ((mBottom - mTop) + slop);
8059    }
8060
8061    /**
8062     * When a view has focus and the user navigates away from it, the next view is searched for
8063     * starting from the rectangle filled in by this method.
8064     *
8065     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8066     * of the view.  However, if your view maintains some idea of internal selection,
8067     * such as a cursor, or a selected row or column, you should override this method and
8068     * fill in a more specific rectangle.
8069     *
8070     * @param r The rectangle to fill in, in this view's coordinates.
8071     */
8072    public void getFocusedRect(Rect r) {
8073        getDrawingRect(r);
8074    }
8075
8076    /**
8077     * If some part of this view is not clipped by any of its parents, then
8078     * return that area in r in global (root) coordinates. To convert r to local
8079     * coordinates (without taking possible View rotations into account), offset
8080     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8081     * If the view is completely clipped or translated out, return false.
8082     *
8083     * @param r If true is returned, r holds the global coordinates of the
8084     *        visible portion of this view.
8085     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8086     *        between this view and its root. globalOffet may be null.
8087     * @return true if r is non-empty (i.e. part of the view is visible at the
8088     *         root level.
8089     */
8090    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8091        int width = mRight - mLeft;
8092        int height = mBottom - mTop;
8093        if (width > 0 && height > 0) {
8094            r.set(0, 0, width, height);
8095            if (globalOffset != null) {
8096                globalOffset.set(-mScrollX, -mScrollY);
8097            }
8098            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8099        }
8100        return false;
8101    }
8102
8103    public final boolean getGlobalVisibleRect(Rect r) {
8104        return getGlobalVisibleRect(r, null);
8105    }
8106
8107    public final boolean getLocalVisibleRect(Rect r) {
8108        Point offset = new Point();
8109        if (getGlobalVisibleRect(r, offset)) {
8110            r.offset(-offset.x, -offset.y); // make r local
8111            return true;
8112        }
8113        return false;
8114    }
8115
8116    /**
8117     * Offset this view's vertical location by the specified number of pixels.
8118     *
8119     * @param offset the number of pixels to offset the view by
8120     */
8121    public void offsetTopAndBottom(int offset) {
8122        if (offset != 0) {
8123            updateMatrix();
8124            final boolean matrixIsIdentity = mTransformationInfo == null
8125                    || mTransformationInfo.mMatrixIsIdentity;
8126            if (matrixIsIdentity) {
8127                final ViewParent p = mParent;
8128                if (p != null && mAttachInfo != null) {
8129                    final Rect r = mAttachInfo.mTmpInvalRect;
8130                    int minTop;
8131                    int maxBottom;
8132                    int yLoc;
8133                    if (offset < 0) {
8134                        minTop = mTop + offset;
8135                        maxBottom = mBottom;
8136                        yLoc = offset;
8137                    } else {
8138                        minTop = mTop;
8139                        maxBottom = mBottom + offset;
8140                        yLoc = 0;
8141                    }
8142                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8143                    p.invalidateChild(this, r);
8144                }
8145            } else {
8146                invalidate(false);
8147            }
8148
8149            mTop += offset;
8150            mBottom += offset;
8151
8152            if (!matrixIsIdentity) {
8153                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8154                invalidate(false);
8155            }
8156            invalidateParentIfNeeded();
8157        }
8158    }
8159
8160    /**
8161     * Offset this view's horizontal location by the specified amount of pixels.
8162     *
8163     * @param offset the numer of pixels to offset the view by
8164     */
8165    public void offsetLeftAndRight(int offset) {
8166        if (offset != 0) {
8167            updateMatrix();
8168            final boolean matrixIsIdentity = mTransformationInfo == null
8169                    || mTransformationInfo.mMatrixIsIdentity;
8170            if (matrixIsIdentity) {
8171                final ViewParent p = mParent;
8172                if (p != null && mAttachInfo != null) {
8173                    final Rect r = mAttachInfo.mTmpInvalRect;
8174                    int minLeft;
8175                    int maxRight;
8176                    if (offset < 0) {
8177                        minLeft = mLeft + offset;
8178                        maxRight = mRight;
8179                    } else {
8180                        minLeft = mLeft;
8181                        maxRight = mRight + offset;
8182                    }
8183                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8184                    p.invalidateChild(this, r);
8185                }
8186            } else {
8187                invalidate(false);
8188            }
8189
8190            mLeft += offset;
8191            mRight += offset;
8192
8193            if (!matrixIsIdentity) {
8194                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8195                invalidate(false);
8196            }
8197            invalidateParentIfNeeded();
8198        }
8199    }
8200
8201    /**
8202     * Get the LayoutParams associated with this view. All views should have
8203     * layout parameters. These supply parameters to the <i>parent</i> of this
8204     * view specifying how it should be arranged. There are many subclasses of
8205     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8206     * of ViewGroup that are responsible for arranging their children.
8207     *
8208     * This method may return null if this View is not attached to a parent
8209     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8210     * was not invoked successfully. When a View is attached to a parent
8211     * ViewGroup, this method must not return null.
8212     *
8213     * @return The LayoutParams associated with this view, or null if no
8214     *         parameters have been set yet
8215     */
8216    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8217    public ViewGroup.LayoutParams getLayoutParams() {
8218        return mLayoutParams;
8219    }
8220
8221    /**
8222     * Set the layout parameters associated with this view. These supply
8223     * parameters to the <i>parent</i> of this view specifying how it should be
8224     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8225     * correspond to the different subclasses of ViewGroup that are responsible
8226     * for arranging their children.
8227     *
8228     * @param params The layout parameters for this view, cannot be null
8229     */
8230    public void setLayoutParams(ViewGroup.LayoutParams params) {
8231        if (params == null) {
8232            throw new NullPointerException("Layout parameters cannot be null");
8233        }
8234        mLayoutParams = params;
8235        requestLayout();
8236    }
8237
8238    /**
8239     * Set the scrolled position of your view. This will cause a call to
8240     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8241     * invalidated.
8242     * @param x the x position to scroll to
8243     * @param y the y position to scroll to
8244     */
8245    public void scrollTo(int x, int y) {
8246        if (mScrollX != x || mScrollY != y) {
8247            int oldX = mScrollX;
8248            int oldY = mScrollY;
8249            mScrollX = x;
8250            mScrollY = y;
8251            invalidateParentCaches();
8252            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8253            if (!awakenScrollBars()) {
8254                invalidate(true);
8255            }
8256        }
8257    }
8258
8259    /**
8260     * Move the scrolled position of your view. This will cause a call to
8261     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8262     * invalidated.
8263     * @param x the amount of pixels to scroll by horizontally
8264     * @param y the amount of pixels to scroll by vertically
8265     */
8266    public void scrollBy(int x, int y) {
8267        scrollTo(mScrollX + x, mScrollY + y);
8268    }
8269
8270    /**
8271     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8272     * animation to fade the scrollbars out after a default delay. If a subclass
8273     * provides animated scrolling, the start delay should equal the duration
8274     * of the scrolling animation.</p>
8275     *
8276     * <p>The animation starts only if at least one of the scrollbars is
8277     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8278     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8279     * this method returns true, and false otherwise. If the animation is
8280     * started, this method calls {@link #invalidate()}; in that case the
8281     * caller should not call {@link #invalidate()}.</p>
8282     *
8283     * <p>This method should be invoked every time a subclass directly updates
8284     * the scroll parameters.</p>
8285     *
8286     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8287     * and {@link #scrollTo(int, int)}.</p>
8288     *
8289     * @return true if the animation is played, false otherwise
8290     *
8291     * @see #awakenScrollBars(int)
8292     * @see #scrollBy(int, int)
8293     * @see #scrollTo(int, int)
8294     * @see #isHorizontalScrollBarEnabled()
8295     * @see #isVerticalScrollBarEnabled()
8296     * @see #setHorizontalScrollBarEnabled(boolean)
8297     * @see #setVerticalScrollBarEnabled(boolean)
8298     */
8299    protected boolean awakenScrollBars() {
8300        return mScrollCache != null &&
8301                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8302    }
8303
8304    /**
8305     * Trigger the scrollbars to draw.
8306     * This method differs from awakenScrollBars() only in its default duration.
8307     * initialAwakenScrollBars() will show the scroll bars for longer than
8308     * usual to give the user more of a chance to notice them.
8309     *
8310     * @return true if the animation is played, false otherwise.
8311     */
8312    private boolean initialAwakenScrollBars() {
8313        return mScrollCache != null &&
8314                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8315    }
8316
8317    /**
8318     * <p>
8319     * Trigger the scrollbars to draw. When invoked this method starts an
8320     * animation to fade the scrollbars out after a fixed delay. If a subclass
8321     * provides animated scrolling, the start delay should equal the duration of
8322     * the scrolling animation.
8323     * </p>
8324     *
8325     * <p>
8326     * The animation starts only if at least one of the scrollbars is enabled,
8327     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8328     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8329     * this method returns true, and false otherwise. If the animation is
8330     * started, this method calls {@link #invalidate()}; in that case the caller
8331     * should not call {@link #invalidate()}.
8332     * </p>
8333     *
8334     * <p>
8335     * This method should be invoked everytime a subclass directly updates the
8336     * scroll parameters.
8337     * </p>
8338     *
8339     * @param startDelay the delay, in milliseconds, after which the animation
8340     *        should start; when the delay is 0, the animation starts
8341     *        immediately
8342     * @return true if the animation is played, false otherwise
8343     *
8344     * @see #scrollBy(int, int)
8345     * @see #scrollTo(int, int)
8346     * @see #isHorizontalScrollBarEnabled()
8347     * @see #isVerticalScrollBarEnabled()
8348     * @see #setHorizontalScrollBarEnabled(boolean)
8349     * @see #setVerticalScrollBarEnabled(boolean)
8350     */
8351    protected boolean awakenScrollBars(int startDelay) {
8352        return awakenScrollBars(startDelay, true);
8353    }
8354
8355    /**
8356     * <p>
8357     * Trigger the scrollbars to draw. When invoked this method starts an
8358     * animation to fade the scrollbars out after a fixed delay. If a subclass
8359     * provides animated scrolling, the start delay should equal the duration of
8360     * the scrolling animation.
8361     * </p>
8362     *
8363     * <p>
8364     * The animation starts only if at least one of the scrollbars is enabled,
8365     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8366     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8367     * this method returns true, and false otherwise. If the animation is
8368     * started, this method calls {@link #invalidate()} if the invalidate parameter
8369     * is set to true; in that case the caller
8370     * should not call {@link #invalidate()}.
8371     * </p>
8372     *
8373     * <p>
8374     * This method should be invoked everytime a subclass directly updates the
8375     * scroll parameters.
8376     * </p>
8377     *
8378     * @param startDelay the delay, in milliseconds, after which the animation
8379     *        should start; when the delay is 0, the animation starts
8380     *        immediately
8381     *
8382     * @param invalidate Wheter this method should call invalidate
8383     *
8384     * @return true if the animation is played, false otherwise
8385     *
8386     * @see #scrollBy(int, int)
8387     * @see #scrollTo(int, int)
8388     * @see #isHorizontalScrollBarEnabled()
8389     * @see #isVerticalScrollBarEnabled()
8390     * @see #setHorizontalScrollBarEnabled(boolean)
8391     * @see #setVerticalScrollBarEnabled(boolean)
8392     */
8393    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8394        final ScrollabilityCache scrollCache = mScrollCache;
8395
8396        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8397            return false;
8398        }
8399
8400        if (scrollCache.scrollBar == null) {
8401            scrollCache.scrollBar = new ScrollBarDrawable();
8402        }
8403
8404        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8405
8406            if (invalidate) {
8407                // Invalidate to show the scrollbars
8408                invalidate(true);
8409            }
8410
8411            if (scrollCache.state == ScrollabilityCache.OFF) {
8412                // FIXME: this is copied from WindowManagerService.
8413                // We should get this value from the system when it
8414                // is possible to do so.
8415                final int KEY_REPEAT_FIRST_DELAY = 750;
8416                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8417            }
8418
8419            // Tell mScrollCache when we should start fading. This may
8420            // extend the fade start time if one was already scheduled
8421            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8422            scrollCache.fadeStartTime = fadeStartTime;
8423            scrollCache.state = ScrollabilityCache.ON;
8424
8425            // Schedule our fader to run, unscheduling any old ones first
8426            if (mAttachInfo != null) {
8427                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8428                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8429            }
8430
8431            return true;
8432        }
8433
8434        return false;
8435    }
8436
8437    /**
8438     * Do not invalidate views which are not visible and which are not running an animation. They
8439     * will not get drawn and they should not set dirty flags as if they will be drawn
8440     */
8441    private boolean skipInvalidate() {
8442        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8443                (!(mParent instanceof ViewGroup) ||
8444                        !((ViewGroup) mParent).isViewTransitioning(this));
8445    }
8446    /**
8447     * Mark the area defined by dirty as needing to be drawn. If the view is
8448     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8449     * in the future. This must be called from a UI thread. To call from a non-UI
8450     * thread, call {@link #postInvalidate()}.
8451     *
8452     * WARNING: This method is destructive to dirty.
8453     * @param dirty the rectangle representing the bounds of the dirty region
8454     */
8455    public void invalidate(Rect dirty) {
8456        if (ViewDebug.TRACE_HIERARCHY) {
8457            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8458        }
8459
8460        if (skipInvalidate()) {
8461            return;
8462        }
8463        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8464                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8465                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8466            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8467            mPrivateFlags |= INVALIDATED;
8468            mPrivateFlags |= DIRTY;
8469            final ViewParent p = mParent;
8470            final AttachInfo ai = mAttachInfo;
8471            //noinspection PointlessBooleanExpression,ConstantConditions
8472            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8473                if (p != null && ai != null && ai.mHardwareAccelerated) {
8474                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8475                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8476                    p.invalidateChild(this, null);
8477                    return;
8478                }
8479            }
8480            if (p != null && ai != null) {
8481                final int scrollX = mScrollX;
8482                final int scrollY = mScrollY;
8483                final Rect r = ai.mTmpInvalRect;
8484                r.set(dirty.left - scrollX, dirty.top - scrollY,
8485                        dirty.right - scrollX, dirty.bottom - scrollY);
8486                mParent.invalidateChild(this, r);
8487            }
8488        }
8489    }
8490
8491    /**
8492     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8493     * The coordinates of the dirty rect are relative to the view.
8494     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8495     * will be called at some point in the future. This must be called from
8496     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8497     * @param l the left position of the dirty region
8498     * @param t the top position of the dirty region
8499     * @param r the right position of the dirty region
8500     * @param b the bottom position of the dirty region
8501     */
8502    public void invalidate(int l, int t, int r, int b) {
8503        if (ViewDebug.TRACE_HIERARCHY) {
8504            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8505        }
8506
8507        if (skipInvalidate()) {
8508            return;
8509        }
8510        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8511                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8512                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8513            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8514            mPrivateFlags |= INVALIDATED;
8515            mPrivateFlags |= DIRTY;
8516            final ViewParent p = mParent;
8517            final AttachInfo ai = mAttachInfo;
8518            //noinspection PointlessBooleanExpression,ConstantConditions
8519            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8520                if (p != null && ai != null && ai.mHardwareAccelerated) {
8521                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8522                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8523                    p.invalidateChild(this, null);
8524                    return;
8525                }
8526            }
8527            if (p != null && ai != null && l < r && t < b) {
8528                final int scrollX = mScrollX;
8529                final int scrollY = mScrollY;
8530                final Rect tmpr = ai.mTmpInvalRect;
8531                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8532                p.invalidateChild(this, tmpr);
8533            }
8534        }
8535    }
8536
8537    /**
8538     * Invalidate the whole view. If the view is visible,
8539     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8540     * the future. This must be called from a UI thread. To call from a non-UI thread,
8541     * call {@link #postInvalidate()}.
8542     */
8543    public void invalidate() {
8544        invalidate(true);
8545    }
8546
8547    /**
8548     * This is where the invalidate() work actually happens. A full invalidate()
8549     * causes the drawing cache to be invalidated, but this function can be called with
8550     * invalidateCache set to false to skip that invalidation step for cases that do not
8551     * need it (for example, a component that remains at the same dimensions with the same
8552     * content).
8553     *
8554     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8555     * well. This is usually true for a full invalidate, but may be set to false if the
8556     * View's contents or dimensions have not changed.
8557     */
8558    void invalidate(boolean invalidateCache) {
8559        if (ViewDebug.TRACE_HIERARCHY) {
8560            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8561        }
8562
8563        if (skipInvalidate()) {
8564            return;
8565        }
8566        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8567                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8568                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8569            mLastIsOpaque = isOpaque();
8570            mPrivateFlags &= ~DRAWN;
8571            mPrivateFlags |= DIRTY;
8572            if (invalidateCache) {
8573                mPrivateFlags |= INVALIDATED;
8574                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8575            }
8576            final AttachInfo ai = mAttachInfo;
8577            final ViewParent p = mParent;
8578            //noinspection PointlessBooleanExpression,ConstantConditions
8579            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8580                if (p != null && ai != null && ai.mHardwareAccelerated) {
8581                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8582                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8583                    p.invalidateChild(this, null);
8584                    return;
8585                }
8586            }
8587
8588            if (p != null && ai != null) {
8589                final Rect r = ai.mTmpInvalRect;
8590                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8591                // Don't call invalidate -- we don't want to internally scroll
8592                // our own bounds
8593                p.invalidateChild(this, r);
8594            }
8595        }
8596    }
8597
8598    /**
8599     * Used to indicate that the parent of this view should clear its caches. This functionality
8600     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8601     * which is necessary when various parent-managed properties of the view change, such as
8602     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8603     * clears the parent caches and does not causes an invalidate event.
8604     *
8605     * @hide
8606     */
8607    protected void invalidateParentCaches() {
8608        if (mParent instanceof View) {
8609            ((View) mParent).mPrivateFlags |= INVALIDATED;
8610        }
8611    }
8612
8613    /**
8614     * Used to indicate that the parent of this view should be invalidated. This functionality
8615     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8616     * which is necessary when various parent-managed properties of the view change, such as
8617     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8618     * an invalidation event to the parent.
8619     *
8620     * @hide
8621     */
8622    protected void invalidateParentIfNeeded() {
8623        if (isHardwareAccelerated() && mParent instanceof View) {
8624            ((View) mParent).invalidate(true);
8625        }
8626    }
8627
8628    /**
8629     * Indicates whether this View is opaque. An opaque View guarantees that it will
8630     * draw all the pixels overlapping its bounds using a fully opaque color.
8631     *
8632     * Subclasses of View should override this method whenever possible to indicate
8633     * whether an instance is opaque. Opaque Views are treated in a special way by
8634     * the View hierarchy, possibly allowing it to perform optimizations during
8635     * invalidate/draw passes.
8636     *
8637     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8638     */
8639    @ViewDebug.ExportedProperty(category = "drawing")
8640    public boolean isOpaque() {
8641        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8642                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8643                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8644    }
8645
8646    /**
8647     * @hide
8648     */
8649    protected void computeOpaqueFlags() {
8650        // Opaque if:
8651        //   - Has a background
8652        //   - Background is opaque
8653        //   - Doesn't have scrollbars or scrollbars are inside overlay
8654
8655        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8656            mPrivateFlags |= OPAQUE_BACKGROUND;
8657        } else {
8658            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8659        }
8660
8661        final int flags = mViewFlags;
8662        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8663                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8664            mPrivateFlags |= OPAQUE_SCROLLBARS;
8665        } else {
8666            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8667        }
8668    }
8669
8670    /**
8671     * @hide
8672     */
8673    protected boolean hasOpaqueScrollbars() {
8674        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8675    }
8676
8677    /**
8678     * @return A handler associated with the thread running the View. This
8679     * handler can be used to pump events in the UI events queue.
8680     */
8681    public Handler getHandler() {
8682        if (mAttachInfo != null) {
8683            return mAttachInfo.mHandler;
8684        }
8685        return null;
8686    }
8687
8688    /**
8689     * <p>Causes the Runnable to be added to the message queue.
8690     * The runnable will be run on the user interface thread.</p>
8691     *
8692     * <p>This method can be invoked from outside of the UI thread
8693     * only when this View is attached to a window.</p>
8694     *
8695     * @param action The Runnable that will be executed.
8696     *
8697     * @return Returns true if the Runnable was successfully placed in to the
8698     *         message queue.  Returns false on failure, usually because the
8699     *         looper processing the message queue is exiting.
8700     */
8701    public boolean post(Runnable action) {
8702        Handler handler;
8703        AttachInfo attachInfo = mAttachInfo;
8704        if (attachInfo != null) {
8705            handler = attachInfo.mHandler;
8706        } else {
8707            // Assume that post will succeed later
8708            ViewRootImpl.getRunQueue().post(action);
8709            return true;
8710        }
8711
8712        return handler.post(action);
8713    }
8714
8715    /**
8716     * <p>Causes the Runnable to be added to the message queue, to be run
8717     * after the specified amount of time elapses.
8718     * The runnable will be run on the user interface thread.</p>
8719     *
8720     * <p>This method can be invoked from outside of the UI thread
8721     * only when this View is attached to a window.</p>
8722     *
8723     * @param action The Runnable that will be executed.
8724     * @param delayMillis The delay (in milliseconds) until the Runnable
8725     *        will be executed.
8726     *
8727     * @return true if the Runnable was successfully placed in to the
8728     *         message queue.  Returns false on failure, usually because the
8729     *         looper processing the message queue is exiting.  Note that a
8730     *         result of true does not mean the Runnable will be processed --
8731     *         if the looper is quit before the delivery time of the message
8732     *         occurs then the message will be dropped.
8733     */
8734    public boolean postDelayed(Runnable action, long delayMillis) {
8735        Handler handler;
8736        AttachInfo attachInfo = mAttachInfo;
8737        if (attachInfo != null) {
8738            handler = attachInfo.mHandler;
8739        } else {
8740            // Assume that post will succeed later
8741            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8742            return true;
8743        }
8744
8745        return handler.postDelayed(action, delayMillis);
8746    }
8747
8748    /**
8749     * <p>Removes the specified Runnable from the message queue.</p>
8750     *
8751     * <p>This method can be invoked from outside of the UI thread
8752     * only when this View is attached to a window.</p>
8753     *
8754     * @param action The Runnable to remove from the message handling queue
8755     *
8756     * @return true if this view could ask the Handler to remove the Runnable,
8757     *         false otherwise. When the returned value is true, the Runnable
8758     *         may or may not have been actually removed from the message queue
8759     *         (for instance, if the Runnable was not in the queue already.)
8760     */
8761    public boolean removeCallbacks(Runnable action) {
8762        Handler handler;
8763        AttachInfo attachInfo = mAttachInfo;
8764        if (attachInfo != null) {
8765            handler = attachInfo.mHandler;
8766        } else {
8767            // Assume that post will succeed later
8768            ViewRootImpl.getRunQueue().removeCallbacks(action);
8769            return true;
8770        }
8771
8772        handler.removeCallbacks(action);
8773        return true;
8774    }
8775
8776    /**
8777     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8778     * Use this to invalidate the View from a non-UI thread.</p>
8779     *
8780     * <p>This method can be invoked from outside of the UI thread
8781     * only when this View is attached to a window.</p>
8782     *
8783     * @see #invalidate()
8784     */
8785    public void postInvalidate() {
8786        postInvalidateDelayed(0);
8787    }
8788
8789    /**
8790     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8791     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8792     *
8793     * <p>This method can be invoked from outside of the UI thread
8794     * only when this View is attached to a window.</p>
8795     *
8796     * @param left The left coordinate of the rectangle to invalidate.
8797     * @param top The top coordinate of the rectangle to invalidate.
8798     * @param right The right coordinate of the rectangle to invalidate.
8799     * @param bottom The bottom coordinate of the rectangle to invalidate.
8800     *
8801     * @see #invalidate(int, int, int, int)
8802     * @see #invalidate(Rect)
8803     */
8804    public void postInvalidate(int left, int top, int right, int bottom) {
8805        postInvalidateDelayed(0, left, top, right, bottom);
8806    }
8807
8808    /**
8809     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8810     * loop. Waits for the specified amount of time.</p>
8811     *
8812     * <p>This method can be invoked from outside of the UI thread
8813     * only when this View is attached to a window.</p>
8814     *
8815     * @param delayMilliseconds the duration in milliseconds to delay the
8816     *         invalidation by
8817     */
8818    public void postInvalidateDelayed(long delayMilliseconds) {
8819        // We try only with the AttachInfo because there's no point in invalidating
8820        // if we are not attached to our window
8821        AttachInfo attachInfo = mAttachInfo;
8822        if (attachInfo != null) {
8823            Message msg = Message.obtain();
8824            msg.what = AttachInfo.INVALIDATE_MSG;
8825            msg.obj = this;
8826            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8827        }
8828    }
8829
8830    /**
8831     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8832     * through the event loop. Waits for the specified amount of time.</p>
8833     *
8834     * <p>This method can be invoked from outside of the UI thread
8835     * only when this View is attached to a window.</p>
8836     *
8837     * @param delayMilliseconds the duration in milliseconds to delay the
8838     *         invalidation by
8839     * @param left The left coordinate of the rectangle to invalidate.
8840     * @param top The top coordinate of the rectangle to invalidate.
8841     * @param right The right coordinate of the rectangle to invalidate.
8842     * @param bottom The bottom coordinate of the rectangle to invalidate.
8843     */
8844    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8845            int right, int bottom) {
8846
8847        // We try only with the AttachInfo because there's no point in invalidating
8848        // if we are not attached to our window
8849        AttachInfo attachInfo = mAttachInfo;
8850        if (attachInfo != null) {
8851            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8852            info.target = this;
8853            info.left = left;
8854            info.top = top;
8855            info.right = right;
8856            info.bottom = bottom;
8857
8858            final Message msg = Message.obtain();
8859            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8860            msg.obj = info;
8861            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8862        }
8863    }
8864
8865    /**
8866     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8867     * This event is sent at most once every
8868     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8869     */
8870    private void postSendViewScrolledAccessibilityEventCallback() {
8871        if (mSendViewScrolledAccessibilityEvent == null) {
8872            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8873        }
8874        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8875            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8876            postDelayed(mSendViewScrolledAccessibilityEvent,
8877                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8878        }
8879    }
8880
8881    /**
8882     * Called by a parent to request that a child update its values for mScrollX
8883     * and mScrollY if necessary. This will typically be done if the child is
8884     * animating a scroll using a {@link android.widget.Scroller Scroller}
8885     * object.
8886     */
8887    public void computeScroll() {
8888    }
8889
8890    /**
8891     * <p>Indicate whether the horizontal edges are faded when the view is
8892     * scrolled horizontally.</p>
8893     *
8894     * @return true if the horizontal edges should are faded on scroll, false
8895     *         otherwise
8896     *
8897     * @see #setHorizontalFadingEdgeEnabled(boolean)
8898     * @attr ref android.R.styleable#View_requiresFadingEdge
8899     */
8900    public boolean isHorizontalFadingEdgeEnabled() {
8901        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8902    }
8903
8904    /**
8905     * <p>Define whether the horizontal edges should be faded when this view
8906     * is scrolled horizontally.</p>
8907     *
8908     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8909     *                                    be faded when the view is scrolled
8910     *                                    horizontally
8911     *
8912     * @see #isHorizontalFadingEdgeEnabled()
8913     * @attr ref android.R.styleable#View_requiresFadingEdge
8914     */
8915    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8916        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8917            if (horizontalFadingEdgeEnabled) {
8918                initScrollCache();
8919            }
8920
8921            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8922        }
8923    }
8924
8925    /**
8926     * <p>Indicate whether the vertical edges are faded when the view is
8927     * scrolled horizontally.</p>
8928     *
8929     * @return true if the vertical edges should are faded on scroll, false
8930     *         otherwise
8931     *
8932     * @see #setVerticalFadingEdgeEnabled(boolean)
8933     * @attr ref android.R.styleable#View_requiresFadingEdge
8934     */
8935    public boolean isVerticalFadingEdgeEnabled() {
8936        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8937    }
8938
8939    /**
8940     * <p>Define whether the vertical edges should be faded when this view
8941     * is scrolled vertically.</p>
8942     *
8943     * @param verticalFadingEdgeEnabled true if the vertical edges should
8944     *                                  be faded when the view is scrolled
8945     *                                  vertically
8946     *
8947     * @see #isVerticalFadingEdgeEnabled()
8948     * @attr ref android.R.styleable#View_requiresFadingEdge
8949     */
8950    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8951        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8952            if (verticalFadingEdgeEnabled) {
8953                initScrollCache();
8954            }
8955
8956            mViewFlags ^= FADING_EDGE_VERTICAL;
8957        }
8958    }
8959
8960    /**
8961     * Returns the strength, or intensity, of the top faded edge. The strength is
8962     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8963     * returns 0.0 or 1.0 but no value in between.
8964     *
8965     * Subclasses should override this method to provide a smoother fade transition
8966     * when scrolling occurs.
8967     *
8968     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8969     */
8970    protected float getTopFadingEdgeStrength() {
8971        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8972    }
8973
8974    /**
8975     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8976     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8977     * returns 0.0 or 1.0 but no value in between.
8978     *
8979     * Subclasses should override this method to provide a smoother fade transition
8980     * when scrolling occurs.
8981     *
8982     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8983     */
8984    protected float getBottomFadingEdgeStrength() {
8985        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8986                computeVerticalScrollRange() ? 1.0f : 0.0f;
8987    }
8988
8989    /**
8990     * Returns the strength, or intensity, of the left faded edge. The strength is
8991     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8992     * returns 0.0 or 1.0 but no value in between.
8993     *
8994     * Subclasses should override this method to provide a smoother fade transition
8995     * when scrolling occurs.
8996     *
8997     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8998     */
8999    protected float getLeftFadingEdgeStrength() {
9000        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
9001    }
9002
9003    /**
9004     * Returns the strength, or intensity, of the right faded edge. The strength is
9005     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9006     * returns 0.0 or 1.0 but no value in between.
9007     *
9008     * Subclasses should override this method to provide a smoother fade transition
9009     * when scrolling occurs.
9010     *
9011     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9012     */
9013    protected float getRightFadingEdgeStrength() {
9014        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9015                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9016    }
9017
9018    /**
9019     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9020     * scrollbar is not drawn by default.</p>
9021     *
9022     * @return true if the horizontal scrollbar should be painted, false
9023     *         otherwise
9024     *
9025     * @see #setHorizontalScrollBarEnabled(boolean)
9026     */
9027    public boolean isHorizontalScrollBarEnabled() {
9028        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9029    }
9030
9031    /**
9032     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9033     * scrollbar is not drawn by default.</p>
9034     *
9035     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9036     *                                   be painted
9037     *
9038     * @see #isHorizontalScrollBarEnabled()
9039     */
9040    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9041        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9042            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9043            computeOpaqueFlags();
9044            resolvePadding();
9045        }
9046    }
9047
9048    /**
9049     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9050     * scrollbar is not drawn by default.</p>
9051     *
9052     * @return true if the vertical scrollbar should be painted, false
9053     *         otherwise
9054     *
9055     * @see #setVerticalScrollBarEnabled(boolean)
9056     */
9057    public boolean isVerticalScrollBarEnabled() {
9058        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9059    }
9060
9061    /**
9062     * <p>Define whether the vertical scrollbar should be drawn or not. The
9063     * scrollbar is not drawn by default.</p>
9064     *
9065     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9066     *                                 be painted
9067     *
9068     * @see #isVerticalScrollBarEnabled()
9069     */
9070    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9071        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9072            mViewFlags ^= SCROLLBARS_VERTICAL;
9073            computeOpaqueFlags();
9074            resolvePadding();
9075        }
9076    }
9077
9078    /**
9079     * @hide
9080     */
9081    protected void recomputePadding() {
9082        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9083    }
9084
9085    /**
9086     * Define whether scrollbars will fade when the view is not scrolling.
9087     *
9088     * @param fadeScrollbars wheter to enable fading
9089     *
9090     */
9091    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9092        initScrollCache();
9093        final ScrollabilityCache scrollabilityCache = mScrollCache;
9094        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9095        if (fadeScrollbars) {
9096            scrollabilityCache.state = ScrollabilityCache.OFF;
9097        } else {
9098            scrollabilityCache.state = ScrollabilityCache.ON;
9099        }
9100    }
9101
9102    /**
9103     *
9104     * Returns true if scrollbars will fade when this view is not scrolling
9105     *
9106     * @return true if scrollbar fading is enabled
9107     */
9108    public boolean isScrollbarFadingEnabled() {
9109        return mScrollCache != null && mScrollCache.fadeScrollBars;
9110    }
9111
9112    /**
9113     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9114     * inset. When inset, they add to the padding of the view. And the scrollbars
9115     * can be drawn inside the padding area or on the edge of the view. For example,
9116     * if a view has a background drawable and you want to draw the scrollbars
9117     * inside the padding specified by the drawable, you can use
9118     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9119     * appear at the edge of the view, ignoring the padding, then you can use
9120     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9121     * @param style the style of the scrollbars. Should be one of
9122     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9123     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9124     * @see #SCROLLBARS_INSIDE_OVERLAY
9125     * @see #SCROLLBARS_INSIDE_INSET
9126     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9127     * @see #SCROLLBARS_OUTSIDE_INSET
9128     */
9129    public void setScrollBarStyle(int style) {
9130        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9131            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9132            computeOpaqueFlags();
9133            resolvePadding();
9134        }
9135    }
9136
9137    /**
9138     * <p>Returns the current scrollbar style.</p>
9139     * @return the current scrollbar style
9140     * @see #SCROLLBARS_INSIDE_OVERLAY
9141     * @see #SCROLLBARS_INSIDE_INSET
9142     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9143     * @see #SCROLLBARS_OUTSIDE_INSET
9144     */
9145    @ViewDebug.ExportedProperty(mapping = {
9146            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9147            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9148            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9149            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9150    })
9151    public int getScrollBarStyle() {
9152        return mViewFlags & SCROLLBARS_STYLE_MASK;
9153    }
9154
9155    /**
9156     * <p>Compute the horizontal range that the horizontal scrollbar
9157     * represents.</p>
9158     *
9159     * <p>The range is expressed in arbitrary units that must be the same as the
9160     * units used by {@link #computeHorizontalScrollExtent()} and
9161     * {@link #computeHorizontalScrollOffset()}.</p>
9162     *
9163     * <p>The default range is the drawing width of this view.</p>
9164     *
9165     * @return the total horizontal range represented by the horizontal
9166     *         scrollbar
9167     *
9168     * @see #computeHorizontalScrollExtent()
9169     * @see #computeHorizontalScrollOffset()
9170     * @see android.widget.ScrollBarDrawable
9171     */
9172    protected int computeHorizontalScrollRange() {
9173        return getWidth();
9174    }
9175
9176    /**
9177     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9178     * within the horizontal range. This value is used to compute the position
9179     * of the thumb within the scrollbar's track.</p>
9180     *
9181     * <p>The range is expressed in arbitrary units that must be the same as the
9182     * units used by {@link #computeHorizontalScrollRange()} and
9183     * {@link #computeHorizontalScrollExtent()}.</p>
9184     *
9185     * <p>The default offset is the scroll offset of this view.</p>
9186     *
9187     * @return the horizontal offset of the scrollbar's thumb
9188     *
9189     * @see #computeHorizontalScrollRange()
9190     * @see #computeHorizontalScrollExtent()
9191     * @see android.widget.ScrollBarDrawable
9192     */
9193    protected int computeHorizontalScrollOffset() {
9194        return mScrollX;
9195    }
9196
9197    /**
9198     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9199     * within the horizontal range. This value is used to compute the length
9200     * of the thumb within the scrollbar's track.</p>
9201     *
9202     * <p>The range is expressed in arbitrary units that must be the same as the
9203     * units used by {@link #computeHorizontalScrollRange()} and
9204     * {@link #computeHorizontalScrollOffset()}.</p>
9205     *
9206     * <p>The default extent is the drawing width of this view.</p>
9207     *
9208     * @return the horizontal extent of the scrollbar's thumb
9209     *
9210     * @see #computeHorizontalScrollRange()
9211     * @see #computeHorizontalScrollOffset()
9212     * @see android.widget.ScrollBarDrawable
9213     */
9214    protected int computeHorizontalScrollExtent() {
9215        return getWidth();
9216    }
9217
9218    /**
9219     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9220     *
9221     * <p>The range is expressed in arbitrary units that must be the same as the
9222     * units used by {@link #computeVerticalScrollExtent()} and
9223     * {@link #computeVerticalScrollOffset()}.</p>
9224     *
9225     * @return the total vertical range represented by the vertical scrollbar
9226     *
9227     * <p>The default range is the drawing height of this view.</p>
9228     *
9229     * @see #computeVerticalScrollExtent()
9230     * @see #computeVerticalScrollOffset()
9231     * @see android.widget.ScrollBarDrawable
9232     */
9233    protected int computeVerticalScrollRange() {
9234        return getHeight();
9235    }
9236
9237    /**
9238     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9239     * within the horizontal range. This value is used to compute the position
9240     * of the thumb within the scrollbar's track.</p>
9241     *
9242     * <p>The range is expressed in arbitrary units that must be the same as the
9243     * units used by {@link #computeVerticalScrollRange()} and
9244     * {@link #computeVerticalScrollExtent()}.</p>
9245     *
9246     * <p>The default offset is the scroll offset of this view.</p>
9247     *
9248     * @return the vertical offset of the scrollbar's thumb
9249     *
9250     * @see #computeVerticalScrollRange()
9251     * @see #computeVerticalScrollExtent()
9252     * @see android.widget.ScrollBarDrawable
9253     */
9254    protected int computeVerticalScrollOffset() {
9255        return mScrollY;
9256    }
9257
9258    /**
9259     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9260     * within the vertical range. This value is used to compute the length
9261     * of the thumb within the scrollbar's track.</p>
9262     *
9263     * <p>The range is expressed in arbitrary units that must be the same as the
9264     * units used by {@link #computeVerticalScrollRange()} and
9265     * {@link #computeVerticalScrollOffset()}.</p>
9266     *
9267     * <p>The default extent is the drawing height of this view.</p>
9268     *
9269     * @return the vertical extent of the scrollbar's thumb
9270     *
9271     * @see #computeVerticalScrollRange()
9272     * @see #computeVerticalScrollOffset()
9273     * @see android.widget.ScrollBarDrawable
9274     */
9275    protected int computeVerticalScrollExtent() {
9276        return getHeight();
9277    }
9278
9279    /**
9280     * Check if this view can be scrolled horizontally in a certain direction.
9281     *
9282     * @param direction Negative to check scrolling left, positive to check scrolling right.
9283     * @return true if this view can be scrolled in the specified direction, false otherwise.
9284     */
9285    public boolean canScrollHorizontally(int direction) {
9286        final int offset = computeHorizontalScrollOffset();
9287        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9288        if (range == 0) return false;
9289        if (direction < 0) {
9290            return offset > 0;
9291        } else {
9292            return offset < range - 1;
9293        }
9294    }
9295
9296    /**
9297     * Check if this view can be scrolled vertically in a certain direction.
9298     *
9299     * @param direction Negative to check scrolling up, positive to check scrolling down.
9300     * @return true if this view can be scrolled in the specified direction, false otherwise.
9301     */
9302    public boolean canScrollVertically(int direction) {
9303        final int offset = computeVerticalScrollOffset();
9304        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9305        if (range == 0) return false;
9306        if (direction < 0) {
9307            return offset > 0;
9308        } else {
9309            return offset < range - 1;
9310        }
9311    }
9312
9313    /**
9314     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9315     * scrollbars are painted only if they have been awakened first.</p>
9316     *
9317     * @param canvas the canvas on which to draw the scrollbars
9318     *
9319     * @see #awakenScrollBars(int)
9320     */
9321    protected final void onDrawScrollBars(Canvas canvas) {
9322        // scrollbars are drawn only when the animation is running
9323        final ScrollabilityCache cache = mScrollCache;
9324        if (cache != null) {
9325
9326            int state = cache.state;
9327
9328            if (state == ScrollabilityCache.OFF) {
9329                return;
9330            }
9331
9332            boolean invalidate = false;
9333
9334            if (state == ScrollabilityCache.FADING) {
9335                // We're fading -- get our fade interpolation
9336                if (cache.interpolatorValues == null) {
9337                    cache.interpolatorValues = new float[1];
9338                }
9339
9340                float[] values = cache.interpolatorValues;
9341
9342                // Stops the animation if we're done
9343                if (cache.scrollBarInterpolator.timeToValues(values) ==
9344                        Interpolator.Result.FREEZE_END) {
9345                    cache.state = ScrollabilityCache.OFF;
9346                } else {
9347                    cache.scrollBar.setAlpha(Math.round(values[0]));
9348                }
9349
9350                // This will make the scroll bars inval themselves after
9351                // drawing. We only want this when we're fading so that
9352                // we prevent excessive redraws
9353                invalidate = true;
9354            } else {
9355                // We're just on -- but we may have been fading before so
9356                // reset alpha
9357                cache.scrollBar.setAlpha(255);
9358            }
9359
9360
9361            final int viewFlags = mViewFlags;
9362
9363            final boolean drawHorizontalScrollBar =
9364                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9365            final boolean drawVerticalScrollBar =
9366                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9367                && !isVerticalScrollBarHidden();
9368
9369            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9370                final int width = mRight - mLeft;
9371                final int height = mBottom - mTop;
9372
9373                final ScrollBarDrawable scrollBar = cache.scrollBar;
9374
9375                final int scrollX = mScrollX;
9376                final int scrollY = mScrollY;
9377                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9378
9379                int left, top, right, bottom;
9380
9381                if (drawHorizontalScrollBar) {
9382                    int size = scrollBar.getSize(false);
9383                    if (size <= 0) {
9384                        size = cache.scrollBarSize;
9385                    }
9386
9387                    scrollBar.setParameters(computeHorizontalScrollRange(),
9388                                            computeHorizontalScrollOffset(),
9389                                            computeHorizontalScrollExtent(), false);
9390                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9391                            getVerticalScrollbarWidth() : 0;
9392                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9393                    left = scrollX + (mPaddingLeft & inside);
9394                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9395                    bottom = top + size;
9396                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9397                    if (invalidate) {
9398                        invalidate(left, top, right, bottom);
9399                    }
9400                }
9401
9402                if (drawVerticalScrollBar) {
9403                    int size = scrollBar.getSize(true);
9404                    if (size <= 0) {
9405                        size = cache.scrollBarSize;
9406                    }
9407
9408                    scrollBar.setParameters(computeVerticalScrollRange(),
9409                                            computeVerticalScrollOffset(),
9410                                            computeVerticalScrollExtent(), true);
9411                    switch (mVerticalScrollbarPosition) {
9412                        default:
9413                        case SCROLLBAR_POSITION_DEFAULT:
9414                        case SCROLLBAR_POSITION_RIGHT:
9415                            left = scrollX + width - size - (mUserPaddingRight & inside);
9416                            break;
9417                        case SCROLLBAR_POSITION_LEFT:
9418                            left = scrollX + (mUserPaddingLeft & inside);
9419                            break;
9420                    }
9421                    top = scrollY + (mPaddingTop & inside);
9422                    right = left + size;
9423                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9424                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9425                    if (invalidate) {
9426                        invalidate(left, top, right, bottom);
9427                    }
9428                }
9429            }
9430        }
9431    }
9432
9433    /**
9434     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9435     * FastScroller is visible.
9436     * @return whether to temporarily hide the vertical scrollbar
9437     * @hide
9438     */
9439    protected boolean isVerticalScrollBarHidden() {
9440        return false;
9441    }
9442
9443    /**
9444     * <p>Draw the horizontal scrollbar if
9445     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9446     *
9447     * @param canvas the canvas on which to draw the scrollbar
9448     * @param scrollBar the scrollbar's drawable
9449     *
9450     * @see #isHorizontalScrollBarEnabled()
9451     * @see #computeHorizontalScrollRange()
9452     * @see #computeHorizontalScrollExtent()
9453     * @see #computeHorizontalScrollOffset()
9454     * @see android.widget.ScrollBarDrawable
9455     * @hide
9456     */
9457    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9458            int l, int t, int r, int b) {
9459        scrollBar.setBounds(l, t, r, b);
9460        scrollBar.draw(canvas);
9461    }
9462
9463    /**
9464     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9465     * returns true.</p>
9466     *
9467     * @param canvas the canvas on which to draw the scrollbar
9468     * @param scrollBar the scrollbar's drawable
9469     *
9470     * @see #isVerticalScrollBarEnabled()
9471     * @see #computeVerticalScrollRange()
9472     * @see #computeVerticalScrollExtent()
9473     * @see #computeVerticalScrollOffset()
9474     * @see android.widget.ScrollBarDrawable
9475     * @hide
9476     */
9477    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9478            int l, int t, int r, int b) {
9479        scrollBar.setBounds(l, t, r, b);
9480        scrollBar.draw(canvas);
9481    }
9482
9483    /**
9484     * Implement this to do your drawing.
9485     *
9486     * @param canvas the canvas on which the background will be drawn
9487     */
9488    protected void onDraw(Canvas canvas) {
9489    }
9490
9491    /*
9492     * Caller is responsible for calling requestLayout if necessary.
9493     * (This allows addViewInLayout to not request a new layout.)
9494     */
9495    void assignParent(ViewParent parent) {
9496        if (mParent == null) {
9497            mParent = parent;
9498        } else if (parent == null) {
9499            mParent = null;
9500        } else {
9501            throw new RuntimeException("view " + this + " being added, but"
9502                    + " it already has a parent");
9503        }
9504    }
9505
9506    /**
9507     * This is called when the view is attached to a window.  At this point it
9508     * has a Surface and will start drawing.  Note that this function is
9509     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9510     * however it may be called any time before the first onDraw -- including
9511     * before or after {@link #onMeasure(int, int)}.
9512     *
9513     * @see #onDetachedFromWindow()
9514     */
9515    protected void onAttachedToWindow() {
9516        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9517            mParent.requestTransparentRegion(this);
9518        }
9519        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9520            initialAwakenScrollBars();
9521            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9522        }
9523        jumpDrawablesToCurrentState();
9524        // Order is important here: LayoutDirection MUST be resolved before Padding
9525        // and TextDirection
9526        resolveLayoutDirectionIfNeeded();
9527        resolvePadding();
9528        resolveTextDirection();
9529        if (isFocused()) {
9530            InputMethodManager imm = InputMethodManager.peekInstance();
9531            imm.focusIn(this);
9532        }
9533    }
9534
9535    /**
9536     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9537     * that the parent directionality can and will be resolved before its children.
9538     */
9539    private void resolveLayoutDirectionIfNeeded() {
9540        // Do not resolve if it is not needed
9541        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9542
9543        // Clear any previous layout direction resolution
9544        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9545
9546        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9547        // TextDirectionHeuristic
9548        resetResolvedTextDirection();
9549
9550        // Set resolved depending on layout direction
9551        switch (getLayoutDirection()) {
9552            case LAYOUT_DIRECTION_INHERIT:
9553                // We cannot do the resolution if there is no parent
9554                if (mParent == null) return;
9555
9556                // If this is root view, no need to look at parent's layout dir.
9557                if (mParent instanceof ViewGroup) {
9558                    ViewGroup viewGroup = ((ViewGroup) mParent);
9559
9560                    // Check if the parent view group can resolve
9561                    if (! viewGroup.canResolveLayoutDirection()) {
9562                        return;
9563                    }
9564                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9565                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9566                    }
9567                }
9568                break;
9569            case LAYOUT_DIRECTION_RTL:
9570                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9571                break;
9572            case LAYOUT_DIRECTION_LOCALE:
9573                if(isLayoutDirectionRtl(Locale.getDefault())) {
9574                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9575                }
9576                break;
9577            default:
9578                // Nothing to do, LTR by default
9579        }
9580
9581        // Set to resolved
9582        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9583    }
9584
9585    /**
9586     * @hide
9587     */
9588    protected void resolvePadding() {
9589        // If the user specified the absolute padding (either with android:padding or
9590        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9591        // use the default padding or the padding from the background drawable
9592        // (stored at this point in mPadding*)
9593        switch (getResolvedLayoutDirection()) {
9594            case LAYOUT_DIRECTION_RTL:
9595                // Start user padding override Right user padding. Otherwise, if Right user
9596                // padding is not defined, use the default Right padding. If Right user padding
9597                // is defined, just use it.
9598                if (mUserPaddingStart >= 0) {
9599                    mUserPaddingRight = mUserPaddingStart;
9600                } else if (mUserPaddingRight < 0) {
9601                    mUserPaddingRight = mPaddingRight;
9602                }
9603                if (mUserPaddingEnd >= 0) {
9604                    mUserPaddingLeft = mUserPaddingEnd;
9605                } else if (mUserPaddingLeft < 0) {
9606                    mUserPaddingLeft = mPaddingLeft;
9607                }
9608                break;
9609            case LAYOUT_DIRECTION_LTR:
9610            default:
9611                // Start user padding override Left user padding. Otherwise, if Left user
9612                // padding is not defined, use the default left padding. If Left user padding
9613                // is defined, just use it.
9614                if (mUserPaddingStart >= 0) {
9615                    mUserPaddingLeft = mUserPaddingStart;
9616                } else if (mUserPaddingLeft < 0) {
9617                    mUserPaddingLeft = mPaddingLeft;
9618                }
9619                if (mUserPaddingEnd >= 0) {
9620                    mUserPaddingRight = mUserPaddingEnd;
9621                } else if (mUserPaddingRight < 0) {
9622                    mUserPaddingRight = mPaddingRight;
9623                }
9624        }
9625
9626        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9627
9628        recomputePadding();
9629    }
9630
9631    /**
9632     * Return true if layout direction resolution can be done
9633     *
9634     * @hide
9635     */
9636    protected boolean canResolveLayoutDirection() {
9637        switch (getLayoutDirection()) {
9638            case LAYOUT_DIRECTION_INHERIT:
9639                return (mParent != null);
9640            default:
9641                return true;
9642        }
9643    }
9644
9645    /**
9646     * Reset the resolved layout direction.
9647     *
9648     * Subclasses need to override this method to clear cached information that depends on the
9649     * resolved layout direction, or to inform child views that inherit their layout direction.
9650     * Overrides must also call the superclass implementation at the start of their implementation.
9651     *
9652     * @hide
9653     */
9654    protected void resetResolvedLayoutDirection() {
9655        // Reset the current View resolution
9656        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9657    }
9658
9659    /**
9660     * Check if a Locale is corresponding to a RTL script.
9661     *
9662     * @param locale Locale to check
9663     * @return true if a Locale is corresponding to a RTL script.
9664     *
9665     * @hide
9666     */
9667    protected static boolean isLayoutDirectionRtl(Locale locale) {
9668        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9669                LocaleUtil.getLayoutDirectionFromLocale(locale));
9670    }
9671
9672    /**
9673     * This is called when the view is detached from a window.  At this point it
9674     * no longer has a surface for drawing.
9675     *
9676     * @see #onAttachedToWindow()
9677     */
9678    protected void onDetachedFromWindow() {
9679        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9680
9681        removeUnsetPressCallback();
9682        removeLongPressCallback();
9683        removePerformClickCallback();
9684        removeSendViewScrolledAccessibilityEventCallback();
9685
9686        destroyDrawingCache();
9687
9688        destroyLayer();
9689
9690        if (mDisplayList != null) {
9691            mDisplayList.invalidate();
9692        }
9693
9694        if (mAttachInfo != null) {
9695            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9696        }
9697
9698        mCurrentAnimation = null;
9699
9700        resetResolvedLayoutDirection();
9701        resetResolvedTextDirection();
9702    }
9703
9704    /**
9705     * @return The number of times this view has been attached to a window
9706     */
9707    protected int getWindowAttachCount() {
9708        return mWindowAttachCount;
9709    }
9710
9711    /**
9712     * Retrieve a unique token identifying the window this view is attached to.
9713     * @return Return the window's token for use in
9714     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9715     */
9716    public IBinder getWindowToken() {
9717        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9718    }
9719
9720    /**
9721     * Retrieve a unique token identifying the top-level "real" window of
9722     * the window that this view is attached to.  That is, this is like
9723     * {@link #getWindowToken}, except if the window this view in is a panel
9724     * window (attached to another containing window), then the token of
9725     * the containing window is returned instead.
9726     *
9727     * @return Returns the associated window token, either
9728     * {@link #getWindowToken()} or the containing window's token.
9729     */
9730    public IBinder getApplicationWindowToken() {
9731        AttachInfo ai = mAttachInfo;
9732        if (ai != null) {
9733            IBinder appWindowToken = ai.mPanelParentWindowToken;
9734            if (appWindowToken == null) {
9735                appWindowToken = ai.mWindowToken;
9736            }
9737            return appWindowToken;
9738        }
9739        return null;
9740    }
9741
9742    /**
9743     * Retrieve private session object this view hierarchy is using to
9744     * communicate with the window manager.
9745     * @return the session object to communicate with the window manager
9746     */
9747    /*package*/ IWindowSession getWindowSession() {
9748        return mAttachInfo != null ? mAttachInfo.mSession : null;
9749    }
9750
9751    /**
9752     * @param info the {@link android.view.View.AttachInfo} to associated with
9753     *        this view
9754     */
9755    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9756        //System.out.println("Attached! " + this);
9757        mAttachInfo = info;
9758        mWindowAttachCount++;
9759        // We will need to evaluate the drawable state at least once.
9760        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9761        if (mFloatingTreeObserver != null) {
9762            info.mTreeObserver.merge(mFloatingTreeObserver);
9763            mFloatingTreeObserver = null;
9764        }
9765        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9766            mAttachInfo.mScrollContainers.add(this);
9767            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9768        }
9769        performCollectViewAttributes(visibility);
9770        onAttachedToWindow();
9771
9772        ListenerInfo li = mListenerInfo;
9773        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9774                li != null ? li.mOnAttachStateChangeListeners : null;
9775        if (listeners != null && listeners.size() > 0) {
9776            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9777            // perform the dispatching. The iterator is a safe guard against listeners that
9778            // could mutate the list by calling the various add/remove methods. This prevents
9779            // the array from being modified while we iterate it.
9780            for (OnAttachStateChangeListener listener : listeners) {
9781                listener.onViewAttachedToWindow(this);
9782            }
9783        }
9784
9785        int vis = info.mWindowVisibility;
9786        if (vis != GONE) {
9787            onWindowVisibilityChanged(vis);
9788        }
9789        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9790            // If nobody has evaluated the drawable state yet, then do it now.
9791            refreshDrawableState();
9792        }
9793    }
9794
9795    void dispatchDetachedFromWindow() {
9796        AttachInfo info = mAttachInfo;
9797        if (info != null) {
9798            int vis = info.mWindowVisibility;
9799            if (vis != GONE) {
9800                onWindowVisibilityChanged(GONE);
9801            }
9802        }
9803
9804        onDetachedFromWindow();
9805
9806        ListenerInfo li = mListenerInfo;
9807        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9808                li != null ? li.mOnAttachStateChangeListeners : null;
9809        if (listeners != null && listeners.size() > 0) {
9810            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9811            // perform the dispatching. The iterator is a safe guard against listeners that
9812            // could mutate the list by calling the various add/remove methods. This prevents
9813            // the array from being modified while we iterate it.
9814            for (OnAttachStateChangeListener listener : listeners) {
9815                listener.onViewDetachedFromWindow(this);
9816            }
9817        }
9818
9819        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9820            mAttachInfo.mScrollContainers.remove(this);
9821            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9822        }
9823
9824        mAttachInfo = null;
9825    }
9826
9827    /**
9828     * Store this view hierarchy's frozen state into the given container.
9829     *
9830     * @param container The SparseArray in which to save the view's state.
9831     *
9832     * @see #restoreHierarchyState(android.util.SparseArray)
9833     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9834     * @see #onSaveInstanceState()
9835     */
9836    public void saveHierarchyState(SparseArray<Parcelable> container) {
9837        dispatchSaveInstanceState(container);
9838    }
9839
9840    /**
9841     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9842     * this view and its children. May be overridden to modify how freezing happens to a
9843     * view's children; for example, some views may want to not store state for their children.
9844     *
9845     * @param container The SparseArray in which to save the view's state.
9846     *
9847     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9848     * @see #saveHierarchyState(android.util.SparseArray)
9849     * @see #onSaveInstanceState()
9850     */
9851    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9852        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9853            mPrivateFlags &= ~SAVE_STATE_CALLED;
9854            Parcelable state = onSaveInstanceState();
9855            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9856                throw new IllegalStateException(
9857                        "Derived class did not call super.onSaveInstanceState()");
9858            }
9859            if (state != null) {
9860                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9861                // + ": " + state);
9862                container.put(mID, state);
9863            }
9864        }
9865    }
9866
9867    /**
9868     * Hook allowing a view to generate a representation of its internal state
9869     * that can later be used to create a new instance with that same state.
9870     * This state should only contain information that is not persistent or can
9871     * not be reconstructed later. For example, you will never store your
9872     * current position on screen because that will be computed again when a
9873     * new instance of the view is placed in its view hierarchy.
9874     * <p>
9875     * Some examples of things you may store here: the current cursor position
9876     * in a text view (but usually not the text itself since that is stored in a
9877     * content provider or other persistent storage), the currently selected
9878     * item in a list view.
9879     *
9880     * @return Returns a Parcelable object containing the view's current dynamic
9881     *         state, or null if there is nothing interesting to save. The
9882     *         default implementation returns null.
9883     * @see #onRestoreInstanceState(android.os.Parcelable)
9884     * @see #saveHierarchyState(android.util.SparseArray)
9885     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9886     * @see #setSaveEnabled(boolean)
9887     */
9888    protected Parcelable onSaveInstanceState() {
9889        mPrivateFlags |= SAVE_STATE_CALLED;
9890        return BaseSavedState.EMPTY_STATE;
9891    }
9892
9893    /**
9894     * Restore this view hierarchy's frozen state from the given container.
9895     *
9896     * @param container The SparseArray which holds previously frozen states.
9897     *
9898     * @see #saveHierarchyState(android.util.SparseArray)
9899     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9900     * @see #onRestoreInstanceState(android.os.Parcelable)
9901     */
9902    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9903        dispatchRestoreInstanceState(container);
9904    }
9905
9906    /**
9907     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9908     * state for this view and its children. May be overridden to modify how restoring
9909     * happens to a view's children; for example, some views may want to not store state
9910     * for their children.
9911     *
9912     * @param container The SparseArray which holds previously saved state.
9913     *
9914     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9915     * @see #restoreHierarchyState(android.util.SparseArray)
9916     * @see #onRestoreInstanceState(android.os.Parcelable)
9917     */
9918    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9919        if (mID != NO_ID) {
9920            Parcelable state = container.get(mID);
9921            if (state != null) {
9922                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9923                // + ": " + state);
9924                mPrivateFlags &= ~SAVE_STATE_CALLED;
9925                onRestoreInstanceState(state);
9926                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9927                    throw new IllegalStateException(
9928                            "Derived class did not call super.onRestoreInstanceState()");
9929                }
9930            }
9931        }
9932    }
9933
9934    /**
9935     * Hook allowing a view to re-apply a representation of its internal state that had previously
9936     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9937     * null state.
9938     *
9939     * @param state The frozen state that had previously been returned by
9940     *        {@link #onSaveInstanceState}.
9941     *
9942     * @see #onSaveInstanceState()
9943     * @see #restoreHierarchyState(android.util.SparseArray)
9944     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9945     */
9946    protected void onRestoreInstanceState(Parcelable state) {
9947        mPrivateFlags |= SAVE_STATE_CALLED;
9948        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9949            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9950                    + "received " + state.getClass().toString() + " instead. This usually happens "
9951                    + "when two views of different type have the same id in the same hierarchy. "
9952                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9953                    + "other views do not use the same id.");
9954        }
9955    }
9956
9957    /**
9958     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9959     *
9960     * @return the drawing start time in milliseconds
9961     */
9962    public long getDrawingTime() {
9963        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9964    }
9965
9966    /**
9967     * <p>Enables or disables the duplication of the parent's state into this view. When
9968     * duplication is enabled, this view gets its drawable state from its parent rather
9969     * than from its own internal properties.</p>
9970     *
9971     * <p>Note: in the current implementation, setting this property to true after the
9972     * view was added to a ViewGroup might have no effect at all. This property should
9973     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9974     *
9975     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9976     * property is enabled, an exception will be thrown.</p>
9977     *
9978     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9979     * parent, these states should not be affected by this method.</p>
9980     *
9981     * @param enabled True to enable duplication of the parent's drawable state, false
9982     *                to disable it.
9983     *
9984     * @see #getDrawableState()
9985     * @see #isDuplicateParentStateEnabled()
9986     */
9987    public void setDuplicateParentStateEnabled(boolean enabled) {
9988        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9989    }
9990
9991    /**
9992     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9993     *
9994     * @return True if this view's drawable state is duplicated from the parent,
9995     *         false otherwise
9996     *
9997     * @see #getDrawableState()
9998     * @see #setDuplicateParentStateEnabled(boolean)
9999     */
10000    public boolean isDuplicateParentStateEnabled() {
10001        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10002    }
10003
10004    /**
10005     * <p>Specifies the type of layer backing this view. The layer can be
10006     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10007     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10008     *
10009     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10010     * instance that controls how the layer is composed on screen. The following
10011     * properties of the paint are taken into account when composing the layer:</p>
10012     * <ul>
10013     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10014     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10015     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10016     * </ul>
10017     *
10018     * <p>If this view has an alpha value set to < 1.0 by calling
10019     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10020     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10021     * equivalent to setting a hardware layer on this view and providing a paint with
10022     * the desired alpha value.<p>
10023     *
10024     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10025     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10026     * for more information on when and how to use layers.</p>
10027     *
10028     * @param layerType The ype of layer to use with this view, must be one of
10029     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10030     *        {@link #LAYER_TYPE_HARDWARE}
10031     * @param paint The paint used to compose the layer. This argument is optional
10032     *        and can be null. It is ignored when the layer type is
10033     *        {@link #LAYER_TYPE_NONE}
10034     *
10035     * @see #getLayerType()
10036     * @see #LAYER_TYPE_NONE
10037     * @see #LAYER_TYPE_SOFTWARE
10038     * @see #LAYER_TYPE_HARDWARE
10039     * @see #setAlpha(float)
10040     *
10041     * @attr ref android.R.styleable#View_layerType
10042     */
10043    public void setLayerType(int layerType, Paint paint) {
10044        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10045            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10046                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10047        }
10048
10049        if (layerType == mLayerType) {
10050            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10051                mLayerPaint = paint == null ? new Paint() : paint;
10052                invalidateParentCaches();
10053                invalidate(true);
10054            }
10055            return;
10056        }
10057
10058        // Destroy any previous software drawing cache if needed
10059        switch (mLayerType) {
10060            case LAYER_TYPE_HARDWARE:
10061                destroyLayer();
10062                // fall through - non-accelerated views may use software layer mechanism instead
10063            case LAYER_TYPE_SOFTWARE:
10064                destroyDrawingCache();
10065                break;
10066            default:
10067                break;
10068        }
10069
10070        mLayerType = layerType;
10071        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10072        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10073        mLocalDirtyRect = layerDisabled ? null : new Rect();
10074
10075        invalidateParentCaches();
10076        invalidate(true);
10077    }
10078
10079    /**
10080     * Indicates whether this view has a static layer. A view with layer type
10081     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10082     * dynamic.
10083     */
10084    boolean hasStaticLayer() {
10085        return mLayerType == LAYER_TYPE_NONE;
10086    }
10087
10088    /**
10089     * Indicates what type of layer is currently associated with this view. By default
10090     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10091     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10092     * for more information on the different types of layers.
10093     *
10094     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10095     *         {@link #LAYER_TYPE_HARDWARE}
10096     *
10097     * @see #setLayerType(int, android.graphics.Paint)
10098     * @see #buildLayer()
10099     * @see #LAYER_TYPE_NONE
10100     * @see #LAYER_TYPE_SOFTWARE
10101     * @see #LAYER_TYPE_HARDWARE
10102     */
10103    public int getLayerType() {
10104        return mLayerType;
10105    }
10106
10107    /**
10108     * Forces this view's layer to be created and this view to be rendered
10109     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10110     * invoking this method will have no effect.
10111     *
10112     * This method can for instance be used to render a view into its layer before
10113     * starting an animation. If this view is complex, rendering into the layer
10114     * before starting the animation will avoid skipping frames.
10115     *
10116     * @throws IllegalStateException If this view is not attached to a window
10117     *
10118     * @see #setLayerType(int, android.graphics.Paint)
10119     */
10120    public void buildLayer() {
10121        if (mLayerType == LAYER_TYPE_NONE) return;
10122
10123        if (mAttachInfo == null) {
10124            throw new IllegalStateException("This view must be attached to a window first");
10125        }
10126
10127        switch (mLayerType) {
10128            case LAYER_TYPE_HARDWARE:
10129                if (mAttachInfo.mHardwareRenderer != null &&
10130                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10131                        mAttachInfo.mHardwareRenderer.validate()) {
10132                    getHardwareLayer();
10133                }
10134                break;
10135            case LAYER_TYPE_SOFTWARE:
10136                buildDrawingCache(true);
10137                break;
10138        }
10139    }
10140
10141    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10142    void flushLayer() {
10143        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10144            mHardwareLayer.flush();
10145        }
10146    }
10147
10148    /**
10149     * <p>Returns a hardware layer that can be used to draw this view again
10150     * without executing its draw method.</p>
10151     *
10152     * @return A HardwareLayer ready to render, or null if an error occurred.
10153     */
10154    HardwareLayer getHardwareLayer() {
10155        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10156                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10157            return null;
10158        }
10159
10160        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10161
10162        final int width = mRight - mLeft;
10163        final int height = mBottom - mTop;
10164
10165        if (width == 0 || height == 0) {
10166            return null;
10167        }
10168
10169        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10170            if (mHardwareLayer == null) {
10171                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10172                        width, height, isOpaque());
10173                mLocalDirtyRect.setEmpty();
10174            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10175                mHardwareLayer.resize(width, height);
10176                mLocalDirtyRect.setEmpty();
10177            }
10178
10179            // The layer is not valid if the underlying GPU resources cannot be allocated
10180            if (!mHardwareLayer.isValid()) {
10181                return null;
10182            }
10183
10184            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10185            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10186
10187            // Make sure all the GPU resources have been properly allocated
10188            if (canvas == null) {
10189                mHardwareLayer.end(currentCanvas);
10190                return null;
10191            }
10192
10193            mAttachInfo.mHardwareCanvas = canvas;
10194            try {
10195                canvas.setViewport(width, height);
10196                canvas.onPreDraw(mLocalDirtyRect);
10197                mLocalDirtyRect.setEmpty();
10198
10199                final int restoreCount = canvas.save();
10200
10201                computeScroll();
10202                canvas.translate(-mScrollX, -mScrollY);
10203
10204                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10205
10206                // Fast path for layouts with no backgrounds
10207                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10208                    mPrivateFlags &= ~DIRTY_MASK;
10209                    dispatchDraw(canvas);
10210                } else {
10211                    draw(canvas);
10212                }
10213
10214                canvas.restoreToCount(restoreCount);
10215            } finally {
10216                canvas.onPostDraw();
10217                mHardwareLayer.end(currentCanvas);
10218                mAttachInfo.mHardwareCanvas = currentCanvas;
10219            }
10220        }
10221
10222        return mHardwareLayer;
10223    }
10224
10225    /**
10226     * Destroys this View's hardware layer if possible.
10227     *
10228     * @return True if the layer was destroyed, false otherwise.
10229     *
10230     * @see #setLayerType(int, android.graphics.Paint)
10231     * @see #LAYER_TYPE_HARDWARE
10232     */
10233    boolean destroyLayer() {
10234        if (mHardwareLayer != null) {
10235            AttachInfo info = mAttachInfo;
10236            if (info != null && info.mHardwareRenderer != null &&
10237                    info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) {
10238                mHardwareLayer.destroy();
10239                mHardwareLayer = null;
10240
10241                invalidate(true);
10242                invalidateParentCaches();
10243            }
10244            return true;
10245        }
10246        return false;
10247    }
10248
10249    /**
10250     * Destroys all hardware rendering resources. This method is invoked
10251     * when the system needs to reclaim resources. Upon execution of this
10252     * method, you should free any OpenGL resources created by the view.
10253     *
10254     * Note: you <strong>must</strong> call
10255     * <code>super.destroyHardwareResources()</code> when overriding
10256     * this method.
10257     *
10258     * @hide
10259     */
10260    protected void destroyHardwareResources() {
10261        destroyLayer();
10262    }
10263
10264    /**
10265     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10266     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10267     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10268     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10269     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10270     * null.</p>
10271     *
10272     * <p>Enabling the drawing cache is similar to
10273     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10274     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10275     * drawing cache has no effect on rendering because the system uses a different mechanism
10276     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10277     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10278     * for information on how to enable software and hardware layers.</p>
10279     *
10280     * <p>This API can be used to manually generate
10281     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10282     * {@link #getDrawingCache()}.</p>
10283     *
10284     * @param enabled true to enable the drawing cache, false otherwise
10285     *
10286     * @see #isDrawingCacheEnabled()
10287     * @see #getDrawingCache()
10288     * @see #buildDrawingCache()
10289     * @see #setLayerType(int, android.graphics.Paint)
10290     */
10291    public void setDrawingCacheEnabled(boolean enabled) {
10292        mCachingFailed = false;
10293        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10294    }
10295
10296    /**
10297     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10298     *
10299     * @return true if the drawing cache is enabled
10300     *
10301     * @see #setDrawingCacheEnabled(boolean)
10302     * @see #getDrawingCache()
10303     */
10304    @ViewDebug.ExportedProperty(category = "drawing")
10305    public boolean isDrawingCacheEnabled() {
10306        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10307    }
10308
10309    /**
10310     * Debugging utility which recursively outputs the dirty state of a view and its
10311     * descendants.
10312     *
10313     * @hide
10314     */
10315    @SuppressWarnings({"UnusedDeclaration"})
10316    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10317        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10318                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10319                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10320                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10321        if (clear) {
10322            mPrivateFlags &= clearMask;
10323        }
10324        if (this instanceof ViewGroup) {
10325            ViewGroup parent = (ViewGroup) this;
10326            final int count = parent.getChildCount();
10327            for (int i = 0; i < count; i++) {
10328                final View child = parent.getChildAt(i);
10329                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10330            }
10331        }
10332    }
10333
10334    /**
10335     * This method is used by ViewGroup to cause its children to restore or recreate their
10336     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10337     * to recreate its own display list, which would happen if it went through the normal
10338     * draw/dispatchDraw mechanisms.
10339     *
10340     * @hide
10341     */
10342    protected void dispatchGetDisplayList() {}
10343
10344    /**
10345     * A view that is not attached or hardware accelerated cannot create a display list.
10346     * This method checks these conditions and returns the appropriate result.
10347     *
10348     * @return true if view has the ability to create a display list, false otherwise.
10349     *
10350     * @hide
10351     */
10352    public boolean canHaveDisplayList() {
10353        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10354    }
10355
10356    /**
10357     * @return The HardwareRenderer associated with that view or null if hardware rendering
10358     * is not supported or this this has not been attached to a window.
10359     *
10360     * @hide
10361     */
10362    public HardwareRenderer getHardwareRenderer() {
10363        if (mAttachInfo != null) {
10364            return mAttachInfo.mHardwareRenderer;
10365        }
10366        return null;
10367    }
10368
10369    /**
10370     * <p>Returns a display list that can be used to draw this view again
10371     * without executing its draw method.</p>
10372     *
10373     * @return A DisplayList ready to replay, or null if caching is not enabled.
10374     *
10375     * @hide
10376     */
10377    public DisplayList getDisplayList() {
10378        if (!canHaveDisplayList()) {
10379            return null;
10380        }
10381
10382        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10383                mDisplayList == null || !mDisplayList.isValid() ||
10384                mRecreateDisplayList)) {
10385            // Don't need to recreate the display list, just need to tell our
10386            // children to restore/recreate theirs
10387            if (mDisplayList != null && mDisplayList.isValid() &&
10388                    !mRecreateDisplayList) {
10389                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10390                mPrivateFlags &= ~DIRTY_MASK;
10391                dispatchGetDisplayList();
10392
10393                return mDisplayList;
10394            }
10395
10396            // If we got here, we're recreating it. Mark it as such to ensure that
10397            // we copy in child display lists into ours in drawChild()
10398            mRecreateDisplayList = true;
10399            if (mDisplayList == null) {
10400                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
10401                // If we're creating a new display list, make sure our parent gets invalidated
10402                // since they will need to recreate their display list to account for this
10403                // new child display list.
10404                invalidateParentCaches();
10405            }
10406
10407            final HardwareCanvas canvas = mDisplayList.start();
10408            int restoreCount = 0;
10409            try {
10410                int width = mRight - mLeft;
10411                int height = mBottom - mTop;
10412
10413                canvas.setViewport(width, height);
10414                // The dirty rect should always be null for a display list
10415                canvas.onPreDraw(null);
10416
10417                computeScroll();
10418
10419                restoreCount = canvas.save();
10420                canvas.translate(-mScrollX, -mScrollY);
10421                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10422                mPrivateFlags &= ~DIRTY_MASK;
10423
10424                // Fast path for layouts with no backgrounds
10425                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10426                    dispatchDraw(canvas);
10427                } else {
10428                    draw(canvas);
10429                }
10430            } finally {
10431                canvas.restoreToCount(restoreCount);
10432                canvas.onPostDraw();
10433
10434                mDisplayList.end();
10435            }
10436        } else {
10437            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10438            mPrivateFlags &= ~DIRTY_MASK;
10439        }
10440
10441        return mDisplayList;
10442    }
10443
10444    /**
10445     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10446     *
10447     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10448     *
10449     * @see #getDrawingCache(boolean)
10450     */
10451    public Bitmap getDrawingCache() {
10452        return getDrawingCache(false);
10453    }
10454
10455    /**
10456     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10457     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10458     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10459     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10460     * request the drawing cache by calling this method and draw it on screen if the
10461     * returned bitmap is not null.</p>
10462     *
10463     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10464     * this method will create a bitmap of the same size as this view. Because this bitmap
10465     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10466     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10467     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10468     * size than the view. This implies that your application must be able to handle this
10469     * size.</p>
10470     *
10471     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10472     *        the current density of the screen when the application is in compatibility
10473     *        mode.
10474     *
10475     * @return A bitmap representing this view or null if cache is disabled.
10476     *
10477     * @see #setDrawingCacheEnabled(boolean)
10478     * @see #isDrawingCacheEnabled()
10479     * @see #buildDrawingCache(boolean)
10480     * @see #destroyDrawingCache()
10481     */
10482    public Bitmap getDrawingCache(boolean autoScale) {
10483        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10484            return null;
10485        }
10486        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10487            buildDrawingCache(autoScale);
10488        }
10489        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10490    }
10491
10492    /**
10493     * <p>Frees the resources used by the drawing cache. If you call
10494     * {@link #buildDrawingCache()} manually without calling
10495     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10496     * should cleanup the cache with this method afterwards.</p>
10497     *
10498     * @see #setDrawingCacheEnabled(boolean)
10499     * @see #buildDrawingCache()
10500     * @see #getDrawingCache()
10501     */
10502    public void destroyDrawingCache() {
10503        if (mDrawingCache != null) {
10504            mDrawingCache.recycle();
10505            mDrawingCache = null;
10506        }
10507        if (mUnscaledDrawingCache != null) {
10508            mUnscaledDrawingCache.recycle();
10509            mUnscaledDrawingCache = null;
10510        }
10511    }
10512
10513    /**
10514     * Setting a solid background color for the drawing cache's bitmaps will improve
10515     * performance and memory usage. Note, though that this should only be used if this
10516     * view will always be drawn on top of a solid color.
10517     *
10518     * @param color The background color to use for the drawing cache's bitmap
10519     *
10520     * @see #setDrawingCacheEnabled(boolean)
10521     * @see #buildDrawingCache()
10522     * @see #getDrawingCache()
10523     */
10524    public void setDrawingCacheBackgroundColor(int color) {
10525        if (color != mDrawingCacheBackgroundColor) {
10526            mDrawingCacheBackgroundColor = color;
10527            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10528        }
10529    }
10530
10531    /**
10532     * @see #setDrawingCacheBackgroundColor(int)
10533     *
10534     * @return The background color to used for the drawing cache's bitmap
10535     */
10536    public int getDrawingCacheBackgroundColor() {
10537        return mDrawingCacheBackgroundColor;
10538    }
10539
10540    /**
10541     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10542     *
10543     * @see #buildDrawingCache(boolean)
10544     */
10545    public void buildDrawingCache() {
10546        buildDrawingCache(false);
10547    }
10548
10549    /**
10550     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10551     *
10552     * <p>If you call {@link #buildDrawingCache()} manually without calling
10553     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10554     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10555     *
10556     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10557     * this method will create a bitmap of the same size as this view. Because this bitmap
10558     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10559     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10560     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10561     * size than the view. This implies that your application must be able to handle this
10562     * size.</p>
10563     *
10564     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10565     * you do not need the drawing cache bitmap, calling this method will increase memory
10566     * usage and cause the view to be rendered in software once, thus negatively impacting
10567     * performance.</p>
10568     *
10569     * @see #getDrawingCache()
10570     * @see #destroyDrawingCache()
10571     */
10572    public void buildDrawingCache(boolean autoScale) {
10573        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10574                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10575            mCachingFailed = false;
10576
10577            if (ViewDebug.TRACE_HIERARCHY) {
10578                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10579            }
10580
10581            int width = mRight - mLeft;
10582            int height = mBottom - mTop;
10583
10584            final AttachInfo attachInfo = mAttachInfo;
10585            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10586
10587            if (autoScale && scalingRequired) {
10588                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10589                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10590            }
10591
10592            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10593            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10594            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10595
10596            if (width <= 0 || height <= 0 ||
10597                     // Projected bitmap size in bytes
10598                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10599                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10600                destroyDrawingCache();
10601                mCachingFailed = true;
10602                return;
10603            }
10604
10605            boolean clear = true;
10606            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10607
10608            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10609                Bitmap.Config quality;
10610                if (!opaque) {
10611                    // Never pick ARGB_4444 because it looks awful
10612                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10613                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10614                        case DRAWING_CACHE_QUALITY_AUTO:
10615                            quality = Bitmap.Config.ARGB_8888;
10616                            break;
10617                        case DRAWING_CACHE_QUALITY_LOW:
10618                            quality = Bitmap.Config.ARGB_8888;
10619                            break;
10620                        case DRAWING_CACHE_QUALITY_HIGH:
10621                            quality = Bitmap.Config.ARGB_8888;
10622                            break;
10623                        default:
10624                            quality = Bitmap.Config.ARGB_8888;
10625                            break;
10626                    }
10627                } else {
10628                    // Optimization for translucent windows
10629                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10630                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10631                }
10632
10633                // Try to cleanup memory
10634                if (bitmap != null) bitmap.recycle();
10635
10636                try {
10637                    bitmap = Bitmap.createBitmap(width, height, quality);
10638                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10639                    if (autoScale) {
10640                        mDrawingCache = bitmap;
10641                    } else {
10642                        mUnscaledDrawingCache = bitmap;
10643                    }
10644                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10645                } catch (OutOfMemoryError e) {
10646                    // If there is not enough memory to create the bitmap cache, just
10647                    // ignore the issue as bitmap caches are not required to draw the
10648                    // view hierarchy
10649                    if (autoScale) {
10650                        mDrawingCache = null;
10651                    } else {
10652                        mUnscaledDrawingCache = null;
10653                    }
10654                    mCachingFailed = true;
10655                    return;
10656                }
10657
10658                clear = drawingCacheBackgroundColor != 0;
10659            }
10660
10661            Canvas canvas;
10662            if (attachInfo != null) {
10663                canvas = attachInfo.mCanvas;
10664                if (canvas == null) {
10665                    canvas = new Canvas();
10666                }
10667                canvas.setBitmap(bitmap);
10668                // Temporarily clobber the cached Canvas in case one of our children
10669                // is also using a drawing cache. Without this, the children would
10670                // steal the canvas by attaching their own bitmap to it and bad, bad
10671                // thing would happen (invisible views, corrupted drawings, etc.)
10672                attachInfo.mCanvas = null;
10673            } else {
10674                // This case should hopefully never or seldom happen
10675                canvas = new Canvas(bitmap);
10676            }
10677
10678            if (clear) {
10679                bitmap.eraseColor(drawingCacheBackgroundColor);
10680            }
10681
10682            computeScroll();
10683            final int restoreCount = canvas.save();
10684
10685            if (autoScale && scalingRequired) {
10686                final float scale = attachInfo.mApplicationScale;
10687                canvas.scale(scale, scale);
10688            }
10689
10690            canvas.translate(-mScrollX, -mScrollY);
10691
10692            mPrivateFlags |= DRAWN;
10693            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10694                    mLayerType != LAYER_TYPE_NONE) {
10695                mPrivateFlags |= DRAWING_CACHE_VALID;
10696            }
10697
10698            // Fast path for layouts with no backgrounds
10699            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10700                if (ViewDebug.TRACE_HIERARCHY) {
10701                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10702                }
10703                mPrivateFlags &= ~DIRTY_MASK;
10704                dispatchDraw(canvas);
10705            } else {
10706                draw(canvas);
10707            }
10708
10709            canvas.restoreToCount(restoreCount);
10710            canvas.setBitmap(null);
10711
10712            if (attachInfo != null) {
10713                // Restore the cached Canvas for our siblings
10714                attachInfo.mCanvas = canvas;
10715            }
10716        }
10717    }
10718
10719    /**
10720     * Create a snapshot of the view into a bitmap.  We should probably make
10721     * some form of this public, but should think about the API.
10722     */
10723    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10724        int width = mRight - mLeft;
10725        int height = mBottom - mTop;
10726
10727        final AttachInfo attachInfo = mAttachInfo;
10728        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10729        width = (int) ((width * scale) + 0.5f);
10730        height = (int) ((height * scale) + 0.5f);
10731
10732        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10733        if (bitmap == null) {
10734            throw new OutOfMemoryError();
10735        }
10736
10737        Resources resources = getResources();
10738        if (resources != null) {
10739            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10740        }
10741
10742        Canvas canvas;
10743        if (attachInfo != null) {
10744            canvas = attachInfo.mCanvas;
10745            if (canvas == null) {
10746                canvas = new Canvas();
10747            }
10748            canvas.setBitmap(bitmap);
10749            // Temporarily clobber the cached Canvas in case one of our children
10750            // is also using a drawing cache. Without this, the children would
10751            // steal the canvas by attaching their own bitmap to it and bad, bad
10752            // things would happen (invisible views, corrupted drawings, etc.)
10753            attachInfo.mCanvas = null;
10754        } else {
10755            // This case should hopefully never or seldom happen
10756            canvas = new Canvas(bitmap);
10757        }
10758
10759        if ((backgroundColor & 0xff000000) != 0) {
10760            bitmap.eraseColor(backgroundColor);
10761        }
10762
10763        computeScroll();
10764        final int restoreCount = canvas.save();
10765        canvas.scale(scale, scale);
10766        canvas.translate(-mScrollX, -mScrollY);
10767
10768        // Temporarily remove the dirty mask
10769        int flags = mPrivateFlags;
10770        mPrivateFlags &= ~DIRTY_MASK;
10771
10772        // Fast path for layouts with no backgrounds
10773        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10774            dispatchDraw(canvas);
10775        } else {
10776            draw(canvas);
10777        }
10778
10779        mPrivateFlags = flags;
10780
10781        canvas.restoreToCount(restoreCount);
10782        canvas.setBitmap(null);
10783
10784        if (attachInfo != null) {
10785            // Restore the cached Canvas for our siblings
10786            attachInfo.mCanvas = canvas;
10787        }
10788
10789        return bitmap;
10790    }
10791
10792    /**
10793     * Indicates whether this View is currently in edit mode. A View is usually
10794     * in edit mode when displayed within a developer tool. For instance, if
10795     * this View is being drawn by a visual user interface builder, this method
10796     * should return true.
10797     *
10798     * Subclasses should check the return value of this method to provide
10799     * different behaviors if their normal behavior might interfere with the
10800     * host environment. For instance: the class spawns a thread in its
10801     * constructor, the drawing code relies on device-specific features, etc.
10802     *
10803     * This method is usually checked in the drawing code of custom widgets.
10804     *
10805     * @return True if this View is in edit mode, false otherwise.
10806     */
10807    public boolean isInEditMode() {
10808        return false;
10809    }
10810
10811    /**
10812     * If the View draws content inside its padding and enables fading edges,
10813     * it needs to support padding offsets. Padding offsets are added to the
10814     * fading edges to extend the length of the fade so that it covers pixels
10815     * drawn inside the padding.
10816     *
10817     * Subclasses of this class should override this method if they need
10818     * to draw content inside the padding.
10819     *
10820     * @return True if padding offset must be applied, false otherwise.
10821     *
10822     * @see #getLeftPaddingOffset()
10823     * @see #getRightPaddingOffset()
10824     * @see #getTopPaddingOffset()
10825     * @see #getBottomPaddingOffset()
10826     *
10827     * @since CURRENT
10828     */
10829    protected boolean isPaddingOffsetRequired() {
10830        return false;
10831    }
10832
10833    /**
10834     * Amount by which to extend the left fading region. Called only when
10835     * {@link #isPaddingOffsetRequired()} returns true.
10836     *
10837     * @return The left padding offset in pixels.
10838     *
10839     * @see #isPaddingOffsetRequired()
10840     *
10841     * @since CURRENT
10842     */
10843    protected int getLeftPaddingOffset() {
10844        return 0;
10845    }
10846
10847    /**
10848     * Amount by which to extend the right fading region. Called only when
10849     * {@link #isPaddingOffsetRequired()} returns true.
10850     *
10851     * @return The right padding offset in pixels.
10852     *
10853     * @see #isPaddingOffsetRequired()
10854     *
10855     * @since CURRENT
10856     */
10857    protected int getRightPaddingOffset() {
10858        return 0;
10859    }
10860
10861    /**
10862     * Amount by which to extend the top fading region. Called only when
10863     * {@link #isPaddingOffsetRequired()} returns true.
10864     *
10865     * @return The top padding offset in pixels.
10866     *
10867     * @see #isPaddingOffsetRequired()
10868     *
10869     * @since CURRENT
10870     */
10871    protected int getTopPaddingOffset() {
10872        return 0;
10873    }
10874
10875    /**
10876     * Amount by which to extend the bottom fading region. Called only when
10877     * {@link #isPaddingOffsetRequired()} returns true.
10878     *
10879     * @return The bottom padding offset in pixels.
10880     *
10881     * @see #isPaddingOffsetRequired()
10882     *
10883     * @since CURRENT
10884     */
10885    protected int getBottomPaddingOffset() {
10886        return 0;
10887    }
10888
10889    /**
10890     * @hide
10891     * @param offsetRequired
10892     */
10893    protected int getFadeTop(boolean offsetRequired) {
10894        int top = mPaddingTop;
10895        if (offsetRequired) top += getTopPaddingOffset();
10896        return top;
10897    }
10898
10899    /**
10900     * @hide
10901     * @param offsetRequired
10902     */
10903    protected int getFadeHeight(boolean offsetRequired) {
10904        int padding = mPaddingTop;
10905        if (offsetRequired) padding += getTopPaddingOffset();
10906        return mBottom - mTop - mPaddingBottom - padding;
10907    }
10908
10909    /**
10910     * <p>Indicates whether this view is attached to an hardware accelerated
10911     * window or not.</p>
10912     *
10913     * <p>Even if this method returns true, it does not mean that every call
10914     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10915     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10916     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10917     * window is hardware accelerated,
10918     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10919     * return false, and this method will return true.</p>
10920     *
10921     * @return True if the view is attached to a window and the window is
10922     *         hardware accelerated; false in any other case.
10923     */
10924    public boolean isHardwareAccelerated() {
10925        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10926    }
10927
10928    /**
10929     * Manually render this view (and all of its children) to the given Canvas.
10930     * The view must have already done a full layout before this function is
10931     * called.  When implementing a view, implement
10932     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10933     * If you do need to override this method, call the superclass version.
10934     *
10935     * @param canvas The Canvas to which the View is rendered.
10936     */
10937    public void draw(Canvas canvas) {
10938        if (ViewDebug.TRACE_HIERARCHY) {
10939            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10940        }
10941
10942        final int privateFlags = mPrivateFlags;
10943        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10944                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10945        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10946
10947        /*
10948         * Draw traversal performs several drawing steps which must be executed
10949         * in the appropriate order:
10950         *
10951         *      1. Draw the background
10952         *      2. If necessary, save the canvas' layers to prepare for fading
10953         *      3. Draw view's content
10954         *      4. Draw children
10955         *      5. If necessary, draw the fading edges and restore layers
10956         *      6. Draw decorations (scrollbars for instance)
10957         */
10958
10959        // Step 1, draw the background, if needed
10960        int saveCount;
10961
10962        if (!dirtyOpaque) {
10963            final Drawable background = mBGDrawable;
10964            if (background != null) {
10965                final int scrollX = mScrollX;
10966                final int scrollY = mScrollY;
10967
10968                if (mBackgroundSizeChanged) {
10969                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10970                    mBackgroundSizeChanged = false;
10971                }
10972
10973                if ((scrollX | scrollY) == 0) {
10974                    background.draw(canvas);
10975                } else {
10976                    canvas.translate(scrollX, scrollY);
10977                    background.draw(canvas);
10978                    canvas.translate(-scrollX, -scrollY);
10979                }
10980            }
10981        }
10982
10983        // skip step 2 & 5 if possible (common case)
10984        final int viewFlags = mViewFlags;
10985        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10986        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10987        if (!verticalEdges && !horizontalEdges) {
10988            // Step 3, draw the content
10989            if (!dirtyOpaque) onDraw(canvas);
10990
10991            // Step 4, draw the children
10992            dispatchDraw(canvas);
10993
10994            // Step 6, draw decorations (scrollbars)
10995            onDrawScrollBars(canvas);
10996
10997            // we're done...
10998            return;
10999        }
11000
11001        /*
11002         * Here we do the full fledged routine...
11003         * (this is an uncommon case where speed matters less,
11004         * this is why we repeat some of the tests that have been
11005         * done above)
11006         */
11007
11008        boolean drawTop = false;
11009        boolean drawBottom = false;
11010        boolean drawLeft = false;
11011        boolean drawRight = false;
11012
11013        float topFadeStrength = 0.0f;
11014        float bottomFadeStrength = 0.0f;
11015        float leftFadeStrength = 0.0f;
11016        float rightFadeStrength = 0.0f;
11017
11018        // Step 2, save the canvas' layers
11019        int paddingLeft = mPaddingLeft;
11020
11021        final boolean offsetRequired = isPaddingOffsetRequired();
11022        if (offsetRequired) {
11023            paddingLeft += getLeftPaddingOffset();
11024        }
11025
11026        int left = mScrollX + paddingLeft;
11027        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11028        int top = mScrollY + getFadeTop(offsetRequired);
11029        int bottom = top + getFadeHeight(offsetRequired);
11030
11031        if (offsetRequired) {
11032            right += getRightPaddingOffset();
11033            bottom += getBottomPaddingOffset();
11034        }
11035
11036        final ScrollabilityCache scrollabilityCache = mScrollCache;
11037        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11038        int length = (int) fadeHeight;
11039
11040        // clip the fade length if top and bottom fades overlap
11041        // overlapping fades produce odd-looking artifacts
11042        if (verticalEdges && (top + length > bottom - length)) {
11043            length = (bottom - top) / 2;
11044        }
11045
11046        // also clip horizontal fades if necessary
11047        if (horizontalEdges && (left + length > right - length)) {
11048            length = (right - left) / 2;
11049        }
11050
11051        if (verticalEdges) {
11052            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11053            drawTop = topFadeStrength * fadeHeight > 1.0f;
11054            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11055            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11056        }
11057
11058        if (horizontalEdges) {
11059            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11060            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11061            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11062            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11063        }
11064
11065        saveCount = canvas.getSaveCount();
11066
11067        int solidColor = getSolidColor();
11068        if (solidColor == 0) {
11069            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11070
11071            if (drawTop) {
11072                canvas.saveLayer(left, top, right, top + length, null, flags);
11073            }
11074
11075            if (drawBottom) {
11076                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11077            }
11078
11079            if (drawLeft) {
11080                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11081            }
11082
11083            if (drawRight) {
11084                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11085            }
11086        } else {
11087            scrollabilityCache.setFadeColor(solidColor);
11088        }
11089
11090        // Step 3, draw the content
11091        if (!dirtyOpaque) onDraw(canvas);
11092
11093        // Step 4, draw the children
11094        dispatchDraw(canvas);
11095
11096        // Step 5, draw the fade effect and restore layers
11097        final Paint p = scrollabilityCache.paint;
11098        final Matrix matrix = scrollabilityCache.matrix;
11099        final Shader fade = scrollabilityCache.shader;
11100
11101        if (drawTop) {
11102            matrix.setScale(1, fadeHeight * topFadeStrength);
11103            matrix.postTranslate(left, top);
11104            fade.setLocalMatrix(matrix);
11105            canvas.drawRect(left, top, right, top + length, p);
11106        }
11107
11108        if (drawBottom) {
11109            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11110            matrix.postRotate(180);
11111            matrix.postTranslate(left, bottom);
11112            fade.setLocalMatrix(matrix);
11113            canvas.drawRect(left, bottom - length, right, bottom, p);
11114        }
11115
11116        if (drawLeft) {
11117            matrix.setScale(1, fadeHeight * leftFadeStrength);
11118            matrix.postRotate(-90);
11119            matrix.postTranslate(left, top);
11120            fade.setLocalMatrix(matrix);
11121            canvas.drawRect(left, top, left + length, bottom, p);
11122        }
11123
11124        if (drawRight) {
11125            matrix.setScale(1, fadeHeight * rightFadeStrength);
11126            matrix.postRotate(90);
11127            matrix.postTranslate(right, top);
11128            fade.setLocalMatrix(matrix);
11129            canvas.drawRect(right - length, top, right, bottom, p);
11130        }
11131
11132        canvas.restoreToCount(saveCount);
11133
11134        // Step 6, draw decorations (scrollbars)
11135        onDrawScrollBars(canvas);
11136    }
11137
11138    /**
11139     * Override this if your view is known to always be drawn on top of a solid color background,
11140     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11141     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11142     * should be set to 0xFF.
11143     *
11144     * @see #setVerticalFadingEdgeEnabled(boolean)
11145     * @see #setHorizontalFadingEdgeEnabled(boolean)
11146     *
11147     * @return The known solid color background for this view, or 0 if the color may vary
11148     */
11149    @ViewDebug.ExportedProperty(category = "drawing")
11150    public int getSolidColor() {
11151        return 0;
11152    }
11153
11154    /**
11155     * Build a human readable string representation of the specified view flags.
11156     *
11157     * @param flags the view flags to convert to a string
11158     * @return a String representing the supplied flags
11159     */
11160    private static String printFlags(int flags) {
11161        String output = "";
11162        int numFlags = 0;
11163        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11164            output += "TAKES_FOCUS";
11165            numFlags++;
11166        }
11167
11168        switch (flags & VISIBILITY_MASK) {
11169        case INVISIBLE:
11170            if (numFlags > 0) {
11171                output += " ";
11172            }
11173            output += "INVISIBLE";
11174            // USELESS HERE numFlags++;
11175            break;
11176        case GONE:
11177            if (numFlags > 0) {
11178                output += " ";
11179            }
11180            output += "GONE";
11181            // USELESS HERE numFlags++;
11182            break;
11183        default:
11184            break;
11185        }
11186        return output;
11187    }
11188
11189    /**
11190     * Build a human readable string representation of the specified private
11191     * view flags.
11192     *
11193     * @param privateFlags the private view flags to convert to a string
11194     * @return a String representing the supplied flags
11195     */
11196    private static String printPrivateFlags(int privateFlags) {
11197        String output = "";
11198        int numFlags = 0;
11199
11200        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11201            output += "WANTS_FOCUS";
11202            numFlags++;
11203        }
11204
11205        if ((privateFlags & FOCUSED) == FOCUSED) {
11206            if (numFlags > 0) {
11207                output += " ";
11208            }
11209            output += "FOCUSED";
11210            numFlags++;
11211        }
11212
11213        if ((privateFlags & SELECTED) == SELECTED) {
11214            if (numFlags > 0) {
11215                output += " ";
11216            }
11217            output += "SELECTED";
11218            numFlags++;
11219        }
11220
11221        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11222            if (numFlags > 0) {
11223                output += " ";
11224            }
11225            output += "IS_ROOT_NAMESPACE";
11226            numFlags++;
11227        }
11228
11229        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11230            if (numFlags > 0) {
11231                output += " ";
11232            }
11233            output += "HAS_BOUNDS";
11234            numFlags++;
11235        }
11236
11237        if ((privateFlags & DRAWN) == DRAWN) {
11238            if (numFlags > 0) {
11239                output += " ";
11240            }
11241            output += "DRAWN";
11242            // USELESS HERE numFlags++;
11243        }
11244        return output;
11245    }
11246
11247    /**
11248     * <p>Indicates whether or not this view's layout will be requested during
11249     * the next hierarchy layout pass.</p>
11250     *
11251     * @return true if the layout will be forced during next layout pass
11252     */
11253    public boolean isLayoutRequested() {
11254        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11255    }
11256
11257    /**
11258     * Assign a size and position to a view and all of its
11259     * descendants
11260     *
11261     * <p>This is the second phase of the layout mechanism.
11262     * (The first is measuring). In this phase, each parent calls
11263     * layout on all of its children to position them.
11264     * This is typically done using the child measurements
11265     * that were stored in the measure pass().</p>
11266     *
11267     * <p>Derived classes should not override this method.
11268     * Derived classes with children should override
11269     * onLayout. In that method, they should
11270     * call layout on each of their children.</p>
11271     *
11272     * @param l Left position, relative to parent
11273     * @param t Top position, relative to parent
11274     * @param r Right position, relative to parent
11275     * @param b Bottom position, relative to parent
11276     */
11277    @SuppressWarnings({"unchecked"})
11278    public void layout(int l, int t, int r, int b) {
11279        int oldL = mLeft;
11280        int oldT = mTop;
11281        int oldB = mBottom;
11282        int oldR = mRight;
11283        boolean changed = setFrame(l, t, r, b);
11284        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11285            if (ViewDebug.TRACE_HIERARCHY) {
11286                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11287            }
11288
11289            onLayout(changed, l, t, r, b);
11290            mPrivateFlags &= ~LAYOUT_REQUIRED;
11291
11292            ListenerInfo li = mListenerInfo;
11293            if (li != null && li.mOnLayoutChangeListeners != null) {
11294                ArrayList<OnLayoutChangeListener> listenersCopy =
11295                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
11296                int numListeners = listenersCopy.size();
11297                for (int i = 0; i < numListeners; ++i) {
11298                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11299                }
11300            }
11301        }
11302        mPrivateFlags &= ~FORCE_LAYOUT;
11303    }
11304
11305    /**
11306     * Called from layout when this view should
11307     * assign a size and position to each of its children.
11308     *
11309     * Derived classes with children should override
11310     * this method and call layout on each of
11311     * their children.
11312     * @param changed This is a new size or position for this view
11313     * @param left Left position, relative to parent
11314     * @param top Top position, relative to parent
11315     * @param right Right position, relative to parent
11316     * @param bottom Bottom position, relative to parent
11317     */
11318    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11319    }
11320
11321    /**
11322     * Assign a size and position to this view.
11323     *
11324     * This is called from layout.
11325     *
11326     * @param left Left position, relative to parent
11327     * @param top Top position, relative to parent
11328     * @param right Right position, relative to parent
11329     * @param bottom Bottom position, relative to parent
11330     * @return true if the new size and position are different than the
11331     *         previous ones
11332     * {@hide}
11333     */
11334    protected boolean setFrame(int left, int top, int right, int bottom) {
11335        boolean changed = false;
11336
11337        if (DBG) {
11338            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11339                    + right + "," + bottom + ")");
11340        }
11341
11342        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11343            changed = true;
11344
11345            // Remember our drawn bit
11346            int drawn = mPrivateFlags & DRAWN;
11347
11348            int oldWidth = mRight - mLeft;
11349            int oldHeight = mBottom - mTop;
11350            int newWidth = right - left;
11351            int newHeight = bottom - top;
11352            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11353
11354            // Invalidate our old position
11355            invalidate(sizeChanged);
11356
11357            mLeft = left;
11358            mTop = top;
11359            mRight = right;
11360            mBottom = bottom;
11361
11362            mPrivateFlags |= HAS_BOUNDS;
11363
11364
11365            if (sizeChanged) {
11366                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11367                    // A change in dimension means an auto-centered pivot point changes, too
11368                    if (mTransformationInfo != null) {
11369                        mTransformationInfo.mMatrixDirty = true;
11370                    }
11371                }
11372                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11373            }
11374
11375            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11376                // If we are visible, force the DRAWN bit to on so that
11377                // this invalidate will go through (at least to our parent).
11378                // This is because someone may have invalidated this view
11379                // before this call to setFrame came in, thereby clearing
11380                // the DRAWN bit.
11381                mPrivateFlags |= DRAWN;
11382                invalidate(sizeChanged);
11383                // parent display list may need to be recreated based on a change in the bounds
11384                // of any child
11385                invalidateParentCaches();
11386            }
11387
11388            // Reset drawn bit to original value (invalidate turns it off)
11389            mPrivateFlags |= drawn;
11390
11391            mBackgroundSizeChanged = true;
11392        }
11393        return changed;
11394    }
11395
11396    /**
11397     * Finalize inflating a view from XML.  This is called as the last phase
11398     * of inflation, after all child views have been added.
11399     *
11400     * <p>Even if the subclass overrides onFinishInflate, they should always be
11401     * sure to call the super method, so that we get called.
11402     */
11403    protected void onFinishInflate() {
11404    }
11405
11406    /**
11407     * Returns the resources associated with this view.
11408     *
11409     * @return Resources object.
11410     */
11411    public Resources getResources() {
11412        return mResources;
11413    }
11414
11415    /**
11416     * Invalidates the specified Drawable.
11417     *
11418     * @param drawable the drawable to invalidate
11419     */
11420    public void invalidateDrawable(Drawable drawable) {
11421        if (verifyDrawable(drawable)) {
11422            final Rect dirty = drawable.getBounds();
11423            final int scrollX = mScrollX;
11424            final int scrollY = mScrollY;
11425
11426            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11427                    dirty.right + scrollX, dirty.bottom + scrollY);
11428        }
11429    }
11430
11431    /**
11432     * Schedules an action on a drawable to occur at a specified time.
11433     *
11434     * @param who the recipient of the action
11435     * @param what the action to run on the drawable
11436     * @param when the time at which the action must occur. Uses the
11437     *        {@link SystemClock#uptimeMillis} timebase.
11438     */
11439    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11440        if (verifyDrawable(who) && what != null) {
11441            if (mAttachInfo != null) {
11442                mAttachInfo.mHandler.postAtTime(what, who, when);
11443            } else {
11444                ViewRootImpl.getRunQueue().postDelayed(what, when - SystemClock.uptimeMillis());
11445            }
11446        }
11447    }
11448
11449    /**
11450     * Cancels a scheduled action on a drawable.
11451     *
11452     * @param who the recipient of the action
11453     * @param what the action to cancel
11454     */
11455    public void unscheduleDrawable(Drawable who, Runnable what) {
11456        if (verifyDrawable(who) && what != null) {
11457            if (mAttachInfo != null) {
11458                mAttachInfo.mHandler.removeCallbacks(what, who);
11459            } else {
11460                ViewRootImpl.getRunQueue().removeCallbacks(what);
11461            }
11462        }
11463    }
11464
11465    /**
11466     * Unschedule any events associated with the given Drawable.  This can be
11467     * used when selecting a new Drawable into a view, so that the previous
11468     * one is completely unscheduled.
11469     *
11470     * @param who The Drawable to unschedule.
11471     *
11472     * @see #drawableStateChanged
11473     */
11474    public void unscheduleDrawable(Drawable who) {
11475        if (mAttachInfo != null) {
11476            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11477        }
11478    }
11479
11480    /**
11481    * Return the layout direction of a given Drawable.
11482    *
11483    * @param who the Drawable to query
11484    *
11485    * @hide
11486    */
11487    public int getResolvedLayoutDirection(Drawable who) {
11488        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11489    }
11490
11491    /**
11492     * If your view subclass is displaying its own Drawable objects, it should
11493     * override this function and return true for any Drawable it is
11494     * displaying.  This allows animations for those drawables to be
11495     * scheduled.
11496     *
11497     * <p>Be sure to call through to the super class when overriding this
11498     * function.
11499     *
11500     * @param who The Drawable to verify.  Return true if it is one you are
11501     *            displaying, else return the result of calling through to the
11502     *            super class.
11503     *
11504     * @return boolean If true than the Drawable is being displayed in the
11505     *         view; else false and it is not allowed to animate.
11506     *
11507     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11508     * @see #drawableStateChanged()
11509     */
11510    protected boolean verifyDrawable(Drawable who) {
11511        return who == mBGDrawable;
11512    }
11513
11514    /**
11515     * This function is called whenever the state of the view changes in such
11516     * a way that it impacts the state of drawables being shown.
11517     *
11518     * <p>Be sure to call through to the superclass when overriding this
11519     * function.
11520     *
11521     * @see Drawable#setState(int[])
11522     */
11523    protected void drawableStateChanged() {
11524        Drawable d = mBGDrawable;
11525        if (d != null && d.isStateful()) {
11526            d.setState(getDrawableState());
11527        }
11528    }
11529
11530    /**
11531     * Call this to force a view to update its drawable state. This will cause
11532     * drawableStateChanged to be called on this view. Views that are interested
11533     * in the new state should call getDrawableState.
11534     *
11535     * @see #drawableStateChanged
11536     * @see #getDrawableState
11537     */
11538    public void refreshDrawableState() {
11539        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11540        drawableStateChanged();
11541
11542        ViewParent parent = mParent;
11543        if (parent != null) {
11544            parent.childDrawableStateChanged(this);
11545        }
11546    }
11547
11548    /**
11549     * Return an array of resource IDs of the drawable states representing the
11550     * current state of the view.
11551     *
11552     * @return The current drawable state
11553     *
11554     * @see Drawable#setState(int[])
11555     * @see #drawableStateChanged()
11556     * @see #onCreateDrawableState(int)
11557     */
11558    public final int[] getDrawableState() {
11559        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11560            return mDrawableState;
11561        } else {
11562            mDrawableState = onCreateDrawableState(0);
11563            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11564            return mDrawableState;
11565        }
11566    }
11567
11568    /**
11569     * Generate the new {@link android.graphics.drawable.Drawable} state for
11570     * this view. This is called by the view
11571     * system when the cached Drawable state is determined to be invalid.  To
11572     * retrieve the current state, you should use {@link #getDrawableState}.
11573     *
11574     * @param extraSpace if non-zero, this is the number of extra entries you
11575     * would like in the returned array in which you can place your own
11576     * states.
11577     *
11578     * @return Returns an array holding the current {@link Drawable} state of
11579     * the view.
11580     *
11581     * @see #mergeDrawableStates(int[], int[])
11582     */
11583    protected int[] onCreateDrawableState(int extraSpace) {
11584        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11585                mParent instanceof View) {
11586            return ((View) mParent).onCreateDrawableState(extraSpace);
11587        }
11588
11589        int[] drawableState;
11590
11591        int privateFlags = mPrivateFlags;
11592
11593        int viewStateIndex = 0;
11594        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11595        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11596        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11597        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11598        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11599        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11600        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11601                HardwareRenderer.isAvailable()) {
11602            // This is set if HW acceleration is requested, even if the current
11603            // process doesn't allow it.  This is just to allow app preview
11604            // windows to better match their app.
11605            viewStateIndex |= VIEW_STATE_ACCELERATED;
11606        }
11607        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11608
11609        final int privateFlags2 = mPrivateFlags2;
11610        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11611        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11612
11613        drawableState = VIEW_STATE_SETS[viewStateIndex];
11614
11615        //noinspection ConstantIfStatement
11616        if (false) {
11617            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11618            Log.i("View", toString()
11619                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11620                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11621                    + " fo=" + hasFocus()
11622                    + " sl=" + ((privateFlags & SELECTED) != 0)
11623                    + " wf=" + hasWindowFocus()
11624                    + ": " + Arrays.toString(drawableState));
11625        }
11626
11627        if (extraSpace == 0) {
11628            return drawableState;
11629        }
11630
11631        final int[] fullState;
11632        if (drawableState != null) {
11633            fullState = new int[drawableState.length + extraSpace];
11634            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11635        } else {
11636            fullState = new int[extraSpace];
11637        }
11638
11639        return fullState;
11640    }
11641
11642    /**
11643     * Merge your own state values in <var>additionalState</var> into the base
11644     * state values <var>baseState</var> that were returned by
11645     * {@link #onCreateDrawableState(int)}.
11646     *
11647     * @param baseState The base state values returned by
11648     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11649     * own additional state values.
11650     *
11651     * @param additionalState The additional state values you would like
11652     * added to <var>baseState</var>; this array is not modified.
11653     *
11654     * @return As a convenience, the <var>baseState</var> array you originally
11655     * passed into the function is returned.
11656     *
11657     * @see #onCreateDrawableState(int)
11658     */
11659    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11660        final int N = baseState.length;
11661        int i = N - 1;
11662        while (i >= 0 && baseState[i] == 0) {
11663            i--;
11664        }
11665        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11666        return baseState;
11667    }
11668
11669    /**
11670     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11671     * on all Drawable objects associated with this view.
11672     */
11673    public void jumpDrawablesToCurrentState() {
11674        if (mBGDrawable != null) {
11675            mBGDrawable.jumpToCurrentState();
11676        }
11677    }
11678
11679    /**
11680     * Sets the background color for this view.
11681     * @param color the color of the background
11682     */
11683    @RemotableViewMethod
11684    public void setBackgroundColor(int color) {
11685        if (mBGDrawable instanceof ColorDrawable) {
11686            ((ColorDrawable) mBGDrawable).setColor(color);
11687        } else {
11688            setBackgroundDrawable(new ColorDrawable(color));
11689        }
11690    }
11691
11692    /**
11693     * Set the background to a given resource. The resource should refer to
11694     * a Drawable object or 0 to remove the background.
11695     * @param resid The identifier of the resource.
11696     * @attr ref android.R.styleable#View_background
11697     */
11698    @RemotableViewMethod
11699    public void setBackgroundResource(int resid) {
11700        if (resid != 0 && resid == mBackgroundResource) {
11701            return;
11702        }
11703
11704        Drawable d= null;
11705        if (resid != 0) {
11706            d = mResources.getDrawable(resid);
11707        }
11708        setBackgroundDrawable(d);
11709
11710        mBackgroundResource = resid;
11711    }
11712
11713    /**
11714     * Set the background to a given Drawable, or remove the background. If the
11715     * background has padding, this View's padding is set to the background's
11716     * padding. However, when a background is removed, this View's padding isn't
11717     * touched. If setting the padding is desired, please use
11718     * {@link #setPadding(int, int, int, int)}.
11719     *
11720     * @param d The Drawable to use as the background, or null to remove the
11721     *        background
11722     */
11723    public void setBackgroundDrawable(Drawable d) {
11724        if (d == mBGDrawable) {
11725            return;
11726        }
11727
11728        boolean requestLayout = false;
11729
11730        mBackgroundResource = 0;
11731
11732        /*
11733         * Regardless of whether we're setting a new background or not, we want
11734         * to clear the previous drawable.
11735         */
11736        if (mBGDrawable != null) {
11737            mBGDrawable.setCallback(null);
11738            unscheduleDrawable(mBGDrawable);
11739        }
11740
11741        if (d != null) {
11742            Rect padding = sThreadLocal.get();
11743            if (padding == null) {
11744                padding = new Rect();
11745                sThreadLocal.set(padding);
11746            }
11747            if (d.getPadding(padding)) {
11748                switch (d.getResolvedLayoutDirectionSelf()) {
11749                    case LAYOUT_DIRECTION_RTL:
11750                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11751                        break;
11752                    case LAYOUT_DIRECTION_LTR:
11753                    default:
11754                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11755                }
11756            }
11757
11758            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11759            // if it has a different minimum size, we should layout again
11760            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11761                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11762                requestLayout = true;
11763            }
11764
11765            d.setCallback(this);
11766            if (d.isStateful()) {
11767                d.setState(getDrawableState());
11768            }
11769            d.setVisible(getVisibility() == VISIBLE, false);
11770            mBGDrawable = d;
11771
11772            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11773                mPrivateFlags &= ~SKIP_DRAW;
11774                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11775                requestLayout = true;
11776            }
11777        } else {
11778            /* Remove the background */
11779            mBGDrawable = null;
11780
11781            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11782                /*
11783                 * This view ONLY drew the background before and we're removing
11784                 * the background, so now it won't draw anything
11785                 * (hence we SKIP_DRAW)
11786                 */
11787                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11788                mPrivateFlags |= SKIP_DRAW;
11789            }
11790
11791            /*
11792             * When the background is set, we try to apply its padding to this
11793             * View. When the background is removed, we don't touch this View's
11794             * padding. This is noted in the Javadocs. Hence, we don't need to
11795             * requestLayout(), the invalidate() below is sufficient.
11796             */
11797
11798            // The old background's minimum size could have affected this
11799            // View's layout, so let's requestLayout
11800            requestLayout = true;
11801        }
11802
11803        computeOpaqueFlags();
11804
11805        if (requestLayout) {
11806            requestLayout();
11807        }
11808
11809        mBackgroundSizeChanged = true;
11810        invalidate(true);
11811    }
11812
11813    /**
11814     * Gets the background drawable
11815     * @return The drawable used as the background for this view, if any.
11816     */
11817    public Drawable getBackground() {
11818        return mBGDrawable;
11819    }
11820
11821    /**
11822     * Sets the padding. The view may add on the space required to display
11823     * the scrollbars, depending on the style and visibility of the scrollbars.
11824     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11825     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11826     * from the values set in this call.
11827     *
11828     * @attr ref android.R.styleable#View_padding
11829     * @attr ref android.R.styleable#View_paddingBottom
11830     * @attr ref android.R.styleable#View_paddingLeft
11831     * @attr ref android.R.styleable#View_paddingRight
11832     * @attr ref android.R.styleable#View_paddingTop
11833     * @param left the left padding in pixels
11834     * @param top the top padding in pixels
11835     * @param right the right padding in pixels
11836     * @param bottom the bottom padding in pixels
11837     */
11838    public void setPadding(int left, int top, int right, int bottom) {
11839        boolean changed = false;
11840
11841        mUserPaddingRelative = false;
11842
11843        mUserPaddingLeft = left;
11844        mUserPaddingRight = right;
11845        mUserPaddingBottom = bottom;
11846
11847        final int viewFlags = mViewFlags;
11848
11849        // Common case is there are no scroll bars.
11850        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11851            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11852                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11853                        ? 0 : getVerticalScrollbarWidth();
11854                switch (mVerticalScrollbarPosition) {
11855                    case SCROLLBAR_POSITION_DEFAULT:
11856                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11857                            left += offset;
11858                        } else {
11859                            right += offset;
11860                        }
11861                        break;
11862                    case SCROLLBAR_POSITION_RIGHT:
11863                        right += offset;
11864                        break;
11865                    case SCROLLBAR_POSITION_LEFT:
11866                        left += offset;
11867                        break;
11868                }
11869            }
11870            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11871                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11872                        ? 0 : getHorizontalScrollbarHeight();
11873            }
11874        }
11875
11876        if (mPaddingLeft != left) {
11877            changed = true;
11878            mPaddingLeft = left;
11879        }
11880        if (mPaddingTop != top) {
11881            changed = true;
11882            mPaddingTop = top;
11883        }
11884        if (mPaddingRight != right) {
11885            changed = true;
11886            mPaddingRight = right;
11887        }
11888        if (mPaddingBottom != bottom) {
11889            changed = true;
11890            mPaddingBottom = bottom;
11891        }
11892
11893        if (changed) {
11894            requestLayout();
11895        }
11896    }
11897
11898    /**
11899     * Sets the relative padding. The view may add on the space required to display
11900     * the scrollbars, depending on the style and visibility of the scrollbars.
11901     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11902     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11903     * from the values set in this call.
11904     *
11905     * @attr ref android.R.styleable#View_padding
11906     * @attr ref android.R.styleable#View_paddingBottom
11907     * @attr ref android.R.styleable#View_paddingStart
11908     * @attr ref android.R.styleable#View_paddingEnd
11909     * @attr ref android.R.styleable#View_paddingTop
11910     * @param start the start padding in pixels
11911     * @param top the top padding in pixels
11912     * @param end the end padding in pixels
11913     * @param bottom the bottom padding in pixels
11914     *
11915     * @hide
11916     */
11917    public void setPaddingRelative(int start, int top, int end, int bottom) {
11918        mUserPaddingRelative = true;
11919
11920        mUserPaddingStart = start;
11921        mUserPaddingEnd = end;
11922
11923        switch(getResolvedLayoutDirection()) {
11924            case LAYOUT_DIRECTION_RTL:
11925                setPadding(end, top, start, bottom);
11926                break;
11927            case LAYOUT_DIRECTION_LTR:
11928            default:
11929                setPadding(start, top, end, bottom);
11930        }
11931    }
11932
11933    /**
11934     * Returns the top padding of this view.
11935     *
11936     * @return the top padding in pixels
11937     */
11938    public int getPaddingTop() {
11939        return mPaddingTop;
11940    }
11941
11942    /**
11943     * Returns the bottom padding of this view. If there are inset and enabled
11944     * scrollbars, this value may include the space required to display the
11945     * scrollbars as well.
11946     *
11947     * @return the bottom padding in pixels
11948     */
11949    public int getPaddingBottom() {
11950        return mPaddingBottom;
11951    }
11952
11953    /**
11954     * Returns the left padding of this view. If there are inset and enabled
11955     * scrollbars, this value may include the space required to display the
11956     * scrollbars as well.
11957     *
11958     * @return the left padding in pixels
11959     */
11960    public int getPaddingLeft() {
11961        return mPaddingLeft;
11962    }
11963
11964    /**
11965     * Returns the start padding of this view. If there are inset and enabled
11966     * scrollbars, this value may include the space required to display the
11967     * scrollbars as well.
11968     *
11969     * @return the start padding in pixels
11970     *
11971     * @hide
11972     */
11973    public int getPaddingStart() {
11974        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11975                mPaddingRight : mPaddingLeft;
11976    }
11977
11978    /**
11979     * Returns the right padding of this view. If there are inset and enabled
11980     * scrollbars, this value may include the space required to display the
11981     * scrollbars as well.
11982     *
11983     * @return the right padding in pixels
11984     */
11985    public int getPaddingRight() {
11986        return mPaddingRight;
11987    }
11988
11989    /**
11990     * Returns the end padding of this view. If there are inset and enabled
11991     * scrollbars, this value may include the space required to display the
11992     * scrollbars as well.
11993     *
11994     * @return the end padding in pixels
11995     *
11996     * @hide
11997     */
11998    public int getPaddingEnd() {
11999        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12000                mPaddingLeft : mPaddingRight;
12001    }
12002
12003    /**
12004     * Return if the padding as been set thru relative values
12005     * {@link #setPaddingRelative(int, int, int, int)} or thru
12006     * @attr ref android.R.styleable#View_paddingStart or
12007     * @attr ref android.R.styleable#View_paddingEnd
12008     *
12009     * @return true if the padding is relative or false if it is not.
12010     *
12011     * @hide
12012     */
12013    public boolean isPaddingRelative() {
12014        return mUserPaddingRelative;
12015    }
12016
12017    /**
12018     * Changes the selection state of this view. A view can be selected or not.
12019     * Note that selection is not the same as focus. Views are typically
12020     * selected in the context of an AdapterView like ListView or GridView;
12021     * the selected view is the view that is highlighted.
12022     *
12023     * @param selected true if the view must be selected, false otherwise
12024     */
12025    public void setSelected(boolean selected) {
12026        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12027            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12028            if (!selected) resetPressedState();
12029            invalidate(true);
12030            refreshDrawableState();
12031            dispatchSetSelected(selected);
12032        }
12033    }
12034
12035    /**
12036     * Dispatch setSelected to all of this View's children.
12037     *
12038     * @see #setSelected(boolean)
12039     *
12040     * @param selected The new selected state
12041     */
12042    protected void dispatchSetSelected(boolean selected) {
12043    }
12044
12045    /**
12046     * Indicates the selection state of this view.
12047     *
12048     * @return true if the view is selected, false otherwise
12049     */
12050    @ViewDebug.ExportedProperty
12051    public boolean isSelected() {
12052        return (mPrivateFlags & SELECTED) != 0;
12053    }
12054
12055    /**
12056     * Changes the activated state of this view. A view can be activated or not.
12057     * Note that activation is not the same as selection.  Selection is
12058     * a transient property, representing the view (hierarchy) the user is
12059     * currently interacting with.  Activation is a longer-term state that the
12060     * user can move views in and out of.  For example, in a list view with
12061     * single or multiple selection enabled, the views in the current selection
12062     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12063     * here.)  The activated state is propagated down to children of the view it
12064     * is set on.
12065     *
12066     * @param activated true if the view must be activated, false otherwise
12067     */
12068    public void setActivated(boolean activated) {
12069        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12070            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12071            invalidate(true);
12072            refreshDrawableState();
12073            dispatchSetActivated(activated);
12074        }
12075    }
12076
12077    /**
12078     * Dispatch setActivated to all of this View's children.
12079     *
12080     * @see #setActivated(boolean)
12081     *
12082     * @param activated The new activated state
12083     */
12084    protected void dispatchSetActivated(boolean activated) {
12085    }
12086
12087    /**
12088     * Indicates the activation state of this view.
12089     *
12090     * @return true if the view is activated, false otherwise
12091     */
12092    @ViewDebug.ExportedProperty
12093    public boolean isActivated() {
12094        return (mPrivateFlags & ACTIVATED) != 0;
12095    }
12096
12097    /**
12098     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12099     * observer can be used to get notifications when global events, like
12100     * layout, happen.
12101     *
12102     * The returned ViewTreeObserver observer is not guaranteed to remain
12103     * valid for the lifetime of this View. If the caller of this method keeps
12104     * a long-lived reference to ViewTreeObserver, it should always check for
12105     * the return value of {@link ViewTreeObserver#isAlive()}.
12106     *
12107     * @return The ViewTreeObserver for this view's hierarchy.
12108     */
12109    public ViewTreeObserver getViewTreeObserver() {
12110        if (mAttachInfo != null) {
12111            return mAttachInfo.mTreeObserver;
12112        }
12113        if (mFloatingTreeObserver == null) {
12114            mFloatingTreeObserver = new ViewTreeObserver();
12115        }
12116        return mFloatingTreeObserver;
12117    }
12118
12119    /**
12120     * <p>Finds the topmost view in the current view hierarchy.</p>
12121     *
12122     * @return the topmost view containing this view
12123     */
12124    public View getRootView() {
12125        if (mAttachInfo != null) {
12126            final View v = mAttachInfo.mRootView;
12127            if (v != null) {
12128                return v;
12129            }
12130        }
12131
12132        View parent = this;
12133
12134        while (parent.mParent != null && parent.mParent instanceof View) {
12135            parent = (View) parent.mParent;
12136        }
12137
12138        return parent;
12139    }
12140
12141    /**
12142     * <p>Computes the coordinates of this view on the screen. The argument
12143     * must be an array of two integers. After the method returns, the array
12144     * contains the x and y location in that order.</p>
12145     *
12146     * @param location an array of two integers in which to hold the coordinates
12147     */
12148    public void getLocationOnScreen(int[] location) {
12149        getLocationInWindow(location);
12150
12151        final AttachInfo info = mAttachInfo;
12152        if (info != null) {
12153            location[0] += info.mWindowLeft;
12154            location[1] += info.mWindowTop;
12155        }
12156    }
12157
12158    /**
12159     * <p>Computes the coordinates of this view in its window. The argument
12160     * must be an array of two integers. After the method returns, the array
12161     * contains the x and y location in that order.</p>
12162     *
12163     * @param location an array of two integers in which to hold the coordinates
12164     */
12165    public void getLocationInWindow(int[] location) {
12166        if (location == null || location.length < 2) {
12167            throw new IllegalArgumentException("location must be an array of two integers");
12168        }
12169
12170        if (mAttachInfo == null) {
12171            // When the view is not attached to a window, this method does not make sense
12172            location[0] = location[1] = 0;
12173            return;
12174        }
12175
12176        float[] position = mAttachInfo.mTmpTransformLocation;
12177        position[0] = position[1] = 0.0f;
12178
12179        if (!hasIdentityMatrix()) {
12180            getMatrix().mapPoints(position);
12181        }
12182
12183        position[0] += mLeft;
12184        position[1] += mTop;
12185
12186        ViewParent viewParent = mParent;
12187        while (viewParent instanceof View) {
12188            final View view = (View) viewParent;
12189
12190            position[0] -= view.mScrollX;
12191            position[1] -= view.mScrollY;
12192
12193            if (!view.hasIdentityMatrix()) {
12194                view.getMatrix().mapPoints(position);
12195            }
12196
12197            position[0] += view.mLeft;
12198            position[1] += view.mTop;
12199
12200            viewParent = view.mParent;
12201        }
12202
12203        if (viewParent instanceof ViewRootImpl) {
12204            // *cough*
12205            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12206            position[1] -= vr.mCurScrollY;
12207        }
12208
12209        location[0] = (int) (position[0] + 0.5f);
12210        location[1] = (int) (position[1] + 0.5f);
12211    }
12212
12213    /**
12214     * {@hide}
12215     * @param id the id of the view to be found
12216     * @return the view of the specified id, null if cannot be found
12217     */
12218    protected View findViewTraversal(int id) {
12219        if (id == mID) {
12220            return this;
12221        }
12222        return null;
12223    }
12224
12225    /**
12226     * {@hide}
12227     * @param tag the tag of the view to be found
12228     * @return the view of specified tag, null if cannot be found
12229     */
12230    protected View findViewWithTagTraversal(Object tag) {
12231        if (tag != null && tag.equals(mTag)) {
12232            return this;
12233        }
12234        return null;
12235    }
12236
12237    /**
12238     * {@hide}
12239     * @param predicate The predicate to evaluate.
12240     * @param childToSkip If not null, ignores this child during the recursive traversal.
12241     * @return The first view that matches the predicate or null.
12242     */
12243    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12244        if (predicate.apply(this)) {
12245            return this;
12246        }
12247        return null;
12248    }
12249
12250    /**
12251     * Look for a child view with the given id.  If this view has the given
12252     * id, return this view.
12253     *
12254     * @param id The id to search for.
12255     * @return The view that has the given id in the hierarchy or null
12256     */
12257    public final View findViewById(int id) {
12258        if (id < 0) {
12259            return null;
12260        }
12261        return findViewTraversal(id);
12262    }
12263
12264    /**
12265     * Finds a view by its unuque and stable accessibility id.
12266     *
12267     * @param accessibilityId The searched accessibility id.
12268     * @return The found view.
12269     */
12270    final View findViewByAccessibilityId(int accessibilityId) {
12271        if (accessibilityId < 0) {
12272            return null;
12273        }
12274        return findViewByAccessibilityIdTraversal(accessibilityId);
12275    }
12276
12277    /**
12278     * Performs the traversal to find a view by its unuque and stable accessibility id.
12279     *
12280     * <strong>Note:</strong>This method does not stop at the root namespace
12281     * boundary since the user can touch the screen at an arbitrary location
12282     * potentially crossing the root namespace bounday which will send an
12283     * accessibility event to accessibility services and they should be able
12284     * to obtain the event source. Also accessibility ids are guaranteed to be
12285     * unique in the window.
12286     *
12287     * @param accessibilityId The accessibility id.
12288     * @return The found view.
12289     */
12290    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12291        if (getAccessibilityViewId() == accessibilityId) {
12292            return this;
12293        }
12294        return null;
12295    }
12296
12297    /**
12298     * Look for a child view with the given tag.  If this view has the given
12299     * tag, return this view.
12300     *
12301     * @param tag The tag to search for, using "tag.equals(getTag())".
12302     * @return The View that has the given tag in the hierarchy or null
12303     */
12304    public final View findViewWithTag(Object tag) {
12305        if (tag == null) {
12306            return null;
12307        }
12308        return findViewWithTagTraversal(tag);
12309    }
12310
12311    /**
12312     * {@hide}
12313     * Look for a child view that matches the specified predicate.
12314     * If this view matches the predicate, return this view.
12315     *
12316     * @param predicate The predicate to evaluate.
12317     * @return The first view that matches the predicate or null.
12318     */
12319    public final View findViewByPredicate(Predicate<View> predicate) {
12320        return findViewByPredicateTraversal(predicate, null);
12321    }
12322
12323    /**
12324     * {@hide}
12325     * Look for a child view that matches the specified predicate,
12326     * starting with the specified view and its descendents and then
12327     * recusively searching the ancestors and siblings of that view
12328     * until this view is reached.
12329     *
12330     * This method is useful in cases where the predicate does not match
12331     * a single unique view (perhaps multiple views use the same id)
12332     * and we are trying to find the view that is "closest" in scope to the
12333     * starting view.
12334     *
12335     * @param start The view to start from.
12336     * @param predicate The predicate to evaluate.
12337     * @return The first view that matches the predicate or null.
12338     */
12339    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12340        View childToSkip = null;
12341        for (;;) {
12342            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12343            if (view != null || start == this) {
12344                return view;
12345            }
12346
12347            ViewParent parent = start.getParent();
12348            if (parent == null || !(parent instanceof View)) {
12349                return null;
12350            }
12351
12352            childToSkip = start;
12353            start = (View) parent;
12354        }
12355    }
12356
12357    /**
12358     * Sets the identifier for this view. The identifier does not have to be
12359     * unique in this view's hierarchy. The identifier should be a positive
12360     * number.
12361     *
12362     * @see #NO_ID
12363     * @see #getId()
12364     * @see #findViewById(int)
12365     *
12366     * @param id a number used to identify the view
12367     *
12368     * @attr ref android.R.styleable#View_id
12369     */
12370    public void setId(int id) {
12371        mID = id;
12372    }
12373
12374    /**
12375     * {@hide}
12376     *
12377     * @param isRoot true if the view belongs to the root namespace, false
12378     *        otherwise
12379     */
12380    public void setIsRootNamespace(boolean isRoot) {
12381        if (isRoot) {
12382            mPrivateFlags |= IS_ROOT_NAMESPACE;
12383        } else {
12384            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12385        }
12386    }
12387
12388    /**
12389     * {@hide}
12390     *
12391     * @return true if the view belongs to the root namespace, false otherwise
12392     */
12393    public boolean isRootNamespace() {
12394        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12395    }
12396
12397    /**
12398     * Returns this view's identifier.
12399     *
12400     * @return a positive integer used to identify the view or {@link #NO_ID}
12401     *         if the view has no ID
12402     *
12403     * @see #setId(int)
12404     * @see #findViewById(int)
12405     * @attr ref android.R.styleable#View_id
12406     */
12407    @ViewDebug.CapturedViewProperty
12408    public int getId() {
12409        return mID;
12410    }
12411
12412    /**
12413     * Returns this view's tag.
12414     *
12415     * @return the Object stored in this view as a tag
12416     *
12417     * @see #setTag(Object)
12418     * @see #getTag(int)
12419     */
12420    @ViewDebug.ExportedProperty
12421    public Object getTag() {
12422        return mTag;
12423    }
12424
12425    /**
12426     * Sets the tag associated with this view. A tag can be used to mark
12427     * a view in its hierarchy and does not have to be unique within the
12428     * hierarchy. Tags can also be used to store data within a view without
12429     * resorting to another data structure.
12430     *
12431     * @param tag an Object to tag the view with
12432     *
12433     * @see #getTag()
12434     * @see #setTag(int, Object)
12435     */
12436    public void setTag(final Object tag) {
12437        mTag = tag;
12438    }
12439
12440    /**
12441     * Returns the tag associated with this view and the specified key.
12442     *
12443     * @param key The key identifying the tag
12444     *
12445     * @return the Object stored in this view as a tag
12446     *
12447     * @see #setTag(int, Object)
12448     * @see #getTag()
12449     */
12450    public Object getTag(int key) {
12451        if (mKeyedTags != null) return mKeyedTags.get(key);
12452        return null;
12453    }
12454
12455    /**
12456     * Sets a tag associated with this view and a key. A tag can be used
12457     * to mark a view in its hierarchy and does not have to be unique within
12458     * the hierarchy. Tags can also be used to store data within a view
12459     * without resorting to another data structure.
12460     *
12461     * The specified key should be an id declared in the resources of the
12462     * application to ensure it is unique (see the <a
12463     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12464     * Keys identified as belonging to
12465     * the Android framework or not associated with any package will cause
12466     * an {@link IllegalArgumentException} to be thrown.
12467     *
12468     * @param key The key identifying the tag
12469     * @param tag An Object to tag the view with
12470     *
12471     * @throws IllegalArgumentException If they specified key is not valid
12472     *
12473     * @see #setTag(Object)
12474     * @see #getTag(int)
12475     */
12476    public void setTag(int key, final Object tag) {
12477        // If the package id is 0x00 or 0x01, it's either an undefined package
12478        // or a framework id
12479        if ((key >>> 24) < 2) {
12480            throw new IllegalArgumentException("The key must be an application-specific "
12481                    + "resource id.");
12482        }
12483
12484        setKeyedTag(key, tag);
12485    }
12486
12487    /**
12488     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12489     * framework id.
12490     *
12491     * @hide
12492     */
12493    public void setTagInternal(int key, Object tag) {
12494        if ((key >>> 24) != 0x1) {
12495            throw new IllegalArgumentException("The key must be a framework-specific "
12496                    + "resource id.");
12497        }
12498
12499        setKeyedTag(key, tag);
12500    }
12501
12502    private void setKeyedTag(int key, Object tag) {
12503        if (mKeyedTags == null) {
12504            mKeyedTags = new SparseArray<Object>();
12505        }
12506
12507        mKeyedTags.put(key, tag);
12508    }
12509
12510    /**
12511     * @param consistency The type of consistency. See ViewDebug for more information.
12512     *
12513     * @hide
12514     */
12515    protected boolean dispatchConsistencyCheck(int consistency) {
12516        return onConsistencyCheck(consistency);
12517    }
12518
12519    /**
12520     * Method that subclasses should implement to check their consistency. The type of
12521     * consistency check is indicated by the bit field passed as a parameter.
12522     *
12523     * @param consistency The type of consistency. See ViewDebug for more information.
12524     *
12525     * @throws IllegalStateException if the view is in an inconsistent state.
12526     *
12527     * @hide
12528     */
12529    protected boolean onConsistencyCheck(int consistency) {
12530        boolean result = true;
12531
12532        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12533        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12534
12535        if (checkLayout) {
12536            if (getParent() == null) {
12537                result = false;
12538                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12539                        "View " + this + " does not have a parent.");
12540            }
12541
12542            if (mAttachInfo == null) {
12543                result = false;
12544                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12545                        "View " + this + " is not attached to a window.");
12546            }
12547        }
12548
12549        if (checkDrawing) {
12550            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12551            // from their draw() method
12552
12553            if ((mPrivateFlags & DRAWN) != DRAWN &&
12554                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12555                result = false;
12556                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12557                        "View " + this + " was invalidated but its drawing cache is valid.");
12558            }
12559        }
12560
12561        return result;
12562    }
12563
12564    /**
12565     * Prints information about this view in the log output, with the tag
12566     * {@link #VIEW_LOG_TAG}.
12567     *
12568     * @hide
12569     */
12570    public void debug() {
12571        debug(0);
12572    }
12573
12574    /**
12575     * Prints information about this view in the log output, with the tag
12576     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12577     * indentation defined by the <code>depth</code>.
12578     *
12579     * @param depth the indentation level
12580     *
12581     * @hide
12582     */
12583    protected void debug(int depth) {
12584        String output = debugIndent(depth - 1);
12585
12586        output += "+ " + this;
12587        int id = getId();
12588        if (id != -1) {
12589            output += " (id=" + id + ")";
12590        }
12591        Object tag = getTag();
12592        if (tag != null) {
12593            output += " (tag=" + tag + ")";
12594        }
12595        Log.d(VIEW_LOG_TAG, output);
12596
12597        if ((mPrivateFlags & FOCUSED) != 0) {
12598            output = debugIndent(depth) + " FOCUSED";
12599            Log.d(VIEW_LOG_TAG, output);
12600        }
12601
12602        output = debugIndent(depth);
12603        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12604                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12605                + "} ";
12606        Log.d(VIEW_LOG_TAG, output);
12607
12608        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12609                || mPaddingBottom != 0) {
12610            output = debugIndent(depth);
12611            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12612                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12613            Log.d(VIEW_LOG_TAG, output);
12614        }
12615
12616        output = debugIndent(depth);
12617        output += "mMeasureWidth=" + mMeasuredWidth +
12618                " mMeasureHeight=" + mMeasuredHeight;
12619        Log.d(VIEW_LOG_TAG, output);
12620
12621        output = debugIndent(depth);
12622        if (mLayoutParams == null) {
12623            output += "BAD! no layout params";
12624        } else {
12625            output = mLayoutParams.debug(output);
12626        }
12627        Log.d(VIEW_LOG_TAG, output);
12628
12629        output = debugIndent(depth);
12630        output += "flags={";
12631        output += View.printFlags(mViewFlags);
12632        output += "}";
12633        Log.d(VIEW_LOG_TAG, output);
12634
12635        output = debugIndent(depth);
12636        output += "privateFlags={";
12637        output += View.printPrivateFlags(mPrivateFlags);
12638        output += "}";
12639        Log.d(VIEW_LOG_TAG, output);
12640    }
12641
12642    /**
12643     * Creates an string of whitespaces used for indentation.
12644     *
12645     * @param depth the indentation level
12646     * @return a String containing (depth * 2 + 3) * 2 white spaces
12647     *
12648     * @hide
12649     */
12650    protected static String debugIndent(int depth) {
12651        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12652        for (int i = 0; i < (depth * 2) + 3; i++) {
12653            spaces.append(' ').append(' ');
12654        }
12655        return spaces.toString();
12656    }
12657
12658    /**
12659     * <p>Return the offset of the widget's text baseline from the widget's top
12660     * boundary. If this widget does not support baseline alignment, this
12661     * method returns -1. </p>
12662     *
12663     * @return the offset of the baseline within the widget's bounds or -1
12664     *         if baseline alignment is not supported
12665     */
12666    @ViewDebug.ExportedProperty(category = "layout")
12667    public int getBaseline() {
12668        return -1;
12669    }
12670
12671    /**
12672     * Call this when something has changed which has invalidated the
12673     * layout of this view. This will schedule a layout pass of the view
12674     * tree.
12675     */
12676    public void requestLayout() {
12677        if (ViewDebug.TRACE_HIERARCHY) {
12678            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12679        }
12680
12681        mPrivateFlags |= FORCE_LAYOUT;
12682        mPrivateFlags |= INVALIDATED;
12683
12684        if (mParent != null) {
12685            if (mLayoutParams != null) {
12686                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12687            }
12688            if (!mParent.isLayoutRequested()) {
12689                mParent.requestLayout();
12690            }
12691        }
12692    }
12693
12694    /**
12695     * Forces this view to be laid out during the next layout pass.
12696     * This method does not call requestLayout() or forceLayout()
12697     * on the parent.
12698     */
12699    public void forceLayout() {
12700        mPrivateFlags |= FORCE_LAYOUT;
12701        mPrivateFlags |= INVALIDATED;
12702    }
12703
12704    /**
12705     * <p>
12706     * This is called to find out how big a view should be. The parent
12707     * supplies constraint information in the width and height parameters.
12708     * </p>
12709     *
12710     * <p>
12711     * The actual mesurement work of a view is performed in
12712     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12713     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12714     * </p>
12715     *
12716     *
12717     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12718     *        parent
12719     * @param heightMeasureSpec Vertical space requirements as imposed by the
12720     *        parent
12721     *
12722     * @see #onMeasure(int, int)
12723     */
12724    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12725        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12726                widthMeasureSpec != mOldWidthMeasureSpec ||
12727                heightMeasureSpec != mOldHeightMeasureSpec) {
12728
12729            // first clears the measured dimension flag
12730            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12731
12732            if (ViewDebug.TRACE_HIERARCHY) {
12733                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12734            }
12735
12736            // measure ourselves, this should set the measured dimension flag back
12737            onMeasure(widthMeasureSpec, heightMeasureSpec);
12738
12739            // flag not set, setMeasuredDimension() was not invoked, we raise
12740            // an exception to warn the developer
12741            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12742                throw new IllegalStateException("onMeasure() did not set the"
12743                        + " measured dimension by calling"
12744                        + " setMeasuredDimension()");
12745            }
12746
12747            mPrivateFlags |= LAYOUT_REQUIRED;
12748        }
12749
12750        mOldWidthMeasureSpec = widthMeasureSpec;
12751        mOldHeightMeasureSpec = heightMeasureSpec;
12752    }
12753
12754    /**
12755     * <p>
12756     * Measure the view and its content to determine the measured width and the
12757     * measured height. This method is invoked by {@link #measure(int, int)} and
12758     * should be overriden by subclasses to provide accurate and efficient
12759     * measurement of their contents.
12760     * </p>
12761     *
12762     * <p>
12763     * <strong>CONTRACT:</strong> When overriding this method, you
12764     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12765     * measured width and height of this view. Failure to do so will trigger an
12766     * <code>IllegalStateException</code>, thrown by
12767     * {@link #measure(int, int)}. Calling the superclass'
12768     * {@link #onMeasure(int, int)} is a valid use.
12769     * </p>
12770     *
12771     * <p>
12772     * The base class implementation of measure defaults to the background size,
12773     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12774     * override {@link #onMeasure(int, int)} to provide better measurements of
12775     * their content.
12776     * </p>
12777     *
12778     * <p>
12779     * If this method is overridden, it is the subclass's responsibility to make
12780     * sure the measured height and width are at least the view's minimum height
12781     * and width ({@link #getSuggestedMinimumHeight()} and
12782     * {@link #getSuggestedMinimumWidth()}).
12783     * </p>
12784     *
12785     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12786     *                         The requirements are encoded with
12787     *                         {@link android.view.View.MeasureSpec}.
12788     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12789     *                         The requirements are encoded with
12790     *                         {@link android.view.View.MeasureSpec}.
12791     *
12792     * @see #getMeasuredWidth()
12793     * @see #getMeasuredHeight()
12794     * @see #setMeasuredDimension(int, int)
12795     * @see #getSuggestedMinimumHeight()
12796     * @see #getSuggestedMinimumWidth()
12797     * @see android.view.View.MeasureSpec#getMode(int)
12798     * @see android.view.View.MeasureSpec#getSize(int)
12799     */
12800    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12801        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12802                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12803    }
12804
12805    /**
12806     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12807     * measured width and measured height. Failing to do so will trigger an
12808     * exception at measurement time.</p>
12809     *
12810     * @param measuredWidth The measured width of this view.  May be a complex
12811     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12812     * {@link #MEASURED_STATE_TOO_SMALL}.
12813     * @param measuredHeight The measured height of this view.  May be a complex
12814     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12815     * {@link #MEASURED_STATE_TOO_SMALL}.
12816     */
12817    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12818        mMeasuredWidth = measuredWidth;
12819        mMeasuredHeight = measuredHeight;
12820
12821        mPrivateFlags |= MEASURED_DIMENSION_SET;
12822    }
12823
12824    /**
12825     * Merge two states as returned by {@link #getMeasuredState()}.
12826     * @param curState The current state as returned from a view or the result
12827     * of combining multiple views.
12828     * @param newState The new view state to combine.
12829     * @return Returns a new integer reflecting the combination of the two
12830     * states.
12831     */
12832    public static int combineMeasuredStates(int curState, int newState) {
12833        return curState | newState;
12834    }
12835
12836    /**
12837     * Version of {@link #resolveSizeAndState(int, int, int)}
12838     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12839     */
12840    public static int resolveSize(int size, int measureSpec) {
12841        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12842    }
12843
12844    /**
12845     * Utility to reconcile a desired size and state, with constraints imposed
12846     * by a MeasureSpec.  Will take the desired size, unless a different size
12847     * is imposed by the constraints.  The returned value is a compound integer,
12848     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12849     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12850     * size is smaller than the size the view wants to be.
12851     *
12852     * @param size How big the view wants to be
12853     * @param measureSpec Constraints imposed by the parent
12854     * @return Size information bit mask as defined by
12855     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12856     */
12857    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12858        int result = size;
12859        int specMode = MeasureSpec.getMode(measureSpec);
12860        int specSize =  MeasureSpec.getSize(measureSpec);
12861        switch (specMode) {
12862        case MeasureSpec.UNSPECIFIED:
12863            result = size;
12864            break;
12865        case MeasureSpec.AT_MOST:
12866            if (specSize < size) {
12867                result = specSize | MEASURED_STATE_TOO_SMALL;
12868            } else {
12869                result = size;
12870            }
12871            break;
12872        case MeasureSpec.EXACTLY:
12873            result = specSize;
12874            break;
12875        }
12876        return result | (childMeasuredState&MEASURED_STATE_MASK);
12877    }
12878
12879    /**
12880     * Utility to return a default size. Uses the supplied size if the
12881     * MeasureSpec imposed no constraints. Will get larger if allowed
12882     * by the MeasureSpec.
12883     *
12884     * @param size Default size for this view
12885     * @param measureSpec Constraints imposed by the parent
12886     * @return The size this view should be.
12887     */
12888    public static int getDefaultSize(int size, int measureSpec) {
12889        int result = size;
12890        int specMode = MeasureSpec.getMode(measureSpec);
12891        int specSize = MeasureSpec.getSize(measureSpec);
12892
12893        switch (specMode) {
12894        case MeasureSpec.UNSPECIFIED:
12895            result = size;
12896            break;
12897        case MeasureSpec.AT_MOST:
12898        case MeasureSpec.EXACTLY:
12899            result = specSize;
12900            break;
12901        }
12902        return result;
12903    }
12904
12905    /**
12906     * Returns the suggested minimum height that the view should use. This
12907     * returns the maximum of the view's minimum height
12908     * and the background's minimum height
12909     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12910     * <p>
12911     * When being used in {@link #onMeasure(int, int)}, the caller should still
12912     * ensure the returned height is within the requirements of the parent.
12913     *
12914     * @return The suggested minimum height of the view.
12915     */
12916    protected int getSuggestedMinimumHeight() {
12917        int suggestedMinHeight = mMinHeight;
12918
12919        if (mBGDrawable != null) {
12920            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12921            if (suggestedMinHeight < bgMinHeight) {
12922                suggestedMinHeight = bgMinHeight;
12923            }
12924        }
12925
12926        return suggestedMinHeight;
12927    }
12928
12929    /**
12930     * Returns the suggested minimum width that the view should use. This
12931     * returns the maximum of the view's minimum width)
12932     * and the background's minimum width
12933     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12934     * <p>
12935     * When being used in {@link #onMeasure(int, int)}, the caller should still
12936     * ensure the returned width is within the requirements of the parent.
12937     *
12938     * @return The suggested minimum width of the view.
12939     */
12940    protected int getSuggestedMinimumWidth() {
12941        int suggestedMinWidth = mMinWidth;
12942
12943        if (mBGDrawable != null) {
12944            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12945            if (suggestedMinWidth < bgMinWidth) {
12946                suggestedMinWidth = bgMinWidth;
12947            }
12948        }
12949
12950        return suggestedMinWidth;
12951    }
12952
12953    /**
12954     * Sets the minimum height of the view. It is not guaranteed the view will
12955     * be able to achieve this minimum height (for example, if its parent layout
12956     * constrains it with less available height).
12957     *
12958     * @param minHeight The minimum height the view will try to be.
12959     */
12960    public void setMinimumHeight(int minHeight) {
12961        mMinHeight = minHeight;
12962    }
12963
12964    /**
12965     * Sets the minimum width of the view. It is not guaranteed the view will
12966     * be able to achieve this minimum width (for example, if its parent layout
12967     * constrains it with less available width).
12968     *
12969     * @param minWidth The minimum width the view will try to be.
12970     */
12971    public void setMinimumWidth(int minWidth) {
12972        mMinWidth = minWidth;
12973    }
12974
12975    /**
12976     * Get the animation currently associated with this view.
12977     *
12978     * @return The animation that is currently playing or
12979     *         scheduled to play for this view.
12980     */
12981    public Animation getAnimation() {
12982        return mCurrentAnimation;
12983    }
12984
12985    /**
12986     * Start the specified animation now.
12987     *
12988     * @param animation the animation to start now
12989     */
12990    public void startAnimation(Animation animation) {
12991        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12992        setAnimation(animation);
12993        invalidateParentCaches();
12994        invalidate(true);
12995    }
12996
12997    /**
12998     * Cancels any animations for this view.
12999     */
13000    public void clearAnimation() {
13001        if (mCurrentAnimation != null) {
13002            mCurrentAnimation.detach();
13003        }
13004        mCurrentAnimation = null;
13005        invalidateParentIfNeeded();
13006    }
13007
13008    /**
13009     * Sets the next animation to play for this view.
13010     * If you want the animation to play immediately, use
13011     * startAnimation. This method provides allows fine-grained
13012     * control over the start time and invalidation, but you
13013     * must make sure that 1) the animation has a start time set, and
13014     * 2) the view will be invalidated when the animation is supposed to
13015     * start.
13016     *
13017     * @param animation The next animation, or null.
13018     */
13019    public void setAnimation(Animation animation) {
13020        mCurrentAnimation = animation;
13021        if (animation != null) {
13022            animation.reset();
13023        }
13024    }
13025
13026    /**
13027     * Invoked by a parent ViewGroup to notify the start of the animation
13028     * currently associated with this view. If you override this method,
13029     * always call super.onAnimationStart();
13030     *
13031     * @see #setAnimation(android.view.animation.Animation)
13032     * @see #getAnimation()
13033     */
13034    protected void onAnimationStart() {
13035        mPrivateFlags |= ANIMATION_STARTED;
13036    }
13037
13038    /**
13039     * Invoked by a parent ViewGroup to notify the end of the animation
13040     * currently associated with this view. If you override this method,
13041     * always call super.onAnimationEnd();
13042     *
13043     * @see #setAnimation(android.view.animation.Animation)
13044     * @see #getAnimation()
13045     */
13046    protected void onAnimationEnd() {
13047        mPrivateFlags &= ~ANIMATION_STARTED;
13048    }
13049
13050    /**
13051     * Invoked if there is a Transform that involves alpha. Subclass that can
13052     * draw themselves with the specified alpha should return true, and then
13053     * respect that alpha when their onDraw() is called. If this returns false
13054     * then the view may be redirected to draw into an offscreen buffer to
13055     * fulfill the request, which will look fine, but may be slower than if the
13056     * subclass handles it internally. The default implementation returns false.
13057     *
13058     * @param alpha The alpha (0..255) to apply to the view's drawing
13059     * @return true if the view can draw with the specified alpha.
13060     */
13061    protected boolean onSetAlpha(int alpha) {
13062        return false;
13063    }
13064
13065    /**
13066     * This is used by the RootView to perform an optimization when
13067     * the view hierarchy contains one or several SurfaceView.
13068     * SurfaceView is always considered transparent, but its children are not,
13069     * therefore all View objects remove themselves from the global transparent
13070     * region (passed as a parameter to this function).
13071     *
13072     * @param region The transparent region for this ViewAncestor (window).
13073     *
13074     * @return Returns true if the effective visibility of the view at this
13075     * point is opaque, regardless of the transparent region; returns false
13076     * if it is possible for underlying windows to be seen behind the view.
13077     *
13078     * {@hide}
13079     */
13080    public boolean gatherTransparentRegion(Region region) {
13081        final AttachInfo attachInfo = mAttachInfo;
13082        if (region != null && attachInfo != null) {
13083            final int pflags = mPrivateFlags;
13084            if ((pflags & SKIP_DRAW) == 0) {
13085                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13086                // remove it from the transparent region.
13087                final int[] location = attachInfo.mTransparentLocation;
13088                getLocationInWindow(location);
13089                region.op(location[0], location[1], location[0] + mRight - mLeft,
13090                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13091            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13092                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13093                // exists, so we remove the background drawable's non-transparent
13094                // parts from this transparent region.
13095                applyDrawableToTransparentRegion(mBGDrawable, region);
13096            }
13097        }
13098        return true;
13099    }
13100
13101    /**
13102     * Play a sound effect for this view.
13103     *
13104     * <p>The framework will play sound effects for some built in actions, such as
13105     * clicking, but you may wish to play these effects in your widget,
13106     * for instance, for internal navigation.
13107     *
13108     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13109     * {@link #isSoundEffectsEnabled()} is true.
13110     *
13111     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13112     */
13113    public void playSoundEffect(int soundConstant) {
13114        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13115            return;
13116        }
13117        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13118    }
13119
13120    /**
13121     * BZZZTT!!1!
13122     *
13123     * <p>Provide haptic feedback to the user for this view.
13124     *
13125     * <p>The framework will provide haptic feedback for some built in actions,
13126     * such as long presses, but you may wish to provide feedback for your
13127     * own widget.
13128     *
13129     * <p>The feedback will only be performed if
13130     * {@link #isHapticFeedbackEnabled()} is true.
13131     *
13132     * @param feedbackConstant One of the constants defined in
13133     * {@link HapticFeedbackConstants}
13134     */
13135    public boolean performHapticFeedback(int feedbackConstant) {
13136        return performHapticFeedback(feedbackConstant, 0);
13137    }
13138
13139    /**
13140     * BZZZTT!!1!
13141     *
13142     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13143     *
13144     * @param feedbackConstant One of the constants defined in
13145     * {@link HapticFeedbackConstants}
13146     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13147     */
13148    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13149        if (mAttachInfo == null) {
13150            return false;
13151        }
13152        //noinspection SimplifiableIfStatement
13153        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13154                && !isHapticFeedbackEnabled()) {
13155            return false;
13156        }
13157        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13158                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13159    }
13160
13161    /**
13162     * Request that the visibility of the status bar be changed.
13163     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13164     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13165     */
13166    public void setSystemUiVisibility(int visibility) {
13167        if (visibility != mSystemUiVisibility) {
13168            mSystemUiVisibility = visibility;
13169            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13170                mParent.recomputeViewAttributes(this);
13171            }
13172        }
13173    }
13174
13175    /**
13176     * Returns the status bar visibility that this view has requested.
13177     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13178     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13179     */
13180    public int getSystemUiVisibility() {
13181        return mSystemUiVisibility;
13182    }
13183
13184    /**
13185     * Set a listener to receive callbacks when the visibility of the system bar changes.
13186     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13187     */
13188    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13189        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13190        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13191            mParent.recomputeViewAttributes(this);
13192        }
13193    }
13194
13195    /**
13196     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13197     * the view hierarchy.
13198     */
13199    public void dispatchSystemUiVisibilityChanged(int visibility) {
13200        ListenerInfo li = mListenerInfo;
13201        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13202            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13203                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13204        }
13205    }
13206
13207    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13208        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13209        if (val != mSystemUiVisibility) {
13210            setSystemUiVisibility(val);
13211        }
13212    }
13213
13214    /**
13215     * Creates an image that the system displays during the drag and drop
13216     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13217     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13218     * appearance as the given View. The default also positions the center of the drag shadow
13219     * directly under the touch point. If no View is provided (the constructor with no parameters
13220     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13221     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13222     * default is an invisible drag shadow.
13223     * <p>
13224     * You are not required to use the View you provide to the constructor as the basis of the
13225     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13226     * anything you want as the drag shadow.
13227     * </p>
13228     * <p>
13229     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13230     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13231     *  size and position of the drag shadow. It uses this data to construct a
13232     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13233     *  so that your application can draw the shadow image in the Canvas.
13234     * </p>
13235     *
13236     * <div class="special reference">
13237     * <h3>Developer Guides</h3>
13238     * <p>For a guide to implementing drag and drop features, read the
13239     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13240     * </div>
13241     */
13242    public static class DragShadowBuilder {
13243        private final WeakReference<View> mView;
13244
13245        /**
13246         * Constructs a shadow image builder based on a View. By default, the resulting drag
13247         * shadow will have the same appearance and dimensions as the View, with the touch point
13248         * over the center of the View.
13249         * @param view A View. Any View in scope can be used.
13250         */
13251        public DragShadowBuilder(View view) {
13252            mView = new WeakReference<View>(view);
13253        }
13254
13255        /**
13256         * Construct a shadow builder object with no associated View.  This
13257         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13258         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13259         * to supply the drag shadow's dimensions and appearance without
13260         * reference to any View object. If they are not overridden, then the result is an
13261         * invisible drag shadow.
13262         */
13263        public DragShadowBuilder() {
13264            mView = new WeakReference<View>(null);
13265        }
13266
13267        /**
13268         * Returns the View object that had been passed to the
13269         * {@link #View.DragShadowBuilder(View)}
13270         * constructor.  If that View parameter was {@code null} or if the
13271         * {@link #View.DragShadowBuilder()}
13272         * constructor was used to instantiate the builder object, this method will return
13273         * null.
13274         *
13275         * @return The View object associate with this builder object.
13276         */
13277        @SuppressWarnings({"JavadocReference"})
13278        final public View getView() {
13279            return mView.get();
13280        }
13281
13282        /**
13283         * Provides the metrics for the shadow image. These include the dimensions of
13284         * the shadow image, and the point within that shadow that should
13285         * be centered under the touch location while dragging.
13286         * <p>
13287         * The default implementation sets the dimensions of the shadow to be the
13288         * same as the dimensions of the View itself and centers the shadow under
13289         * the touch point.
13290         * </p>
13291         *
13292         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13293         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13294         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13295         * image.
13296         *
13297         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13298         * shadow image that should be underneath the touch point during the drag and drop
13299         * operation. Your application must set {@link android.graphics.Point#x} to the
13300         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13301         */
13302        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13303            final View view = mView.get();
13304            if (view != null) {
13305                shadowSize.set(view.getWidth(), view.getHeight());
13306                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13307            } else {
13308                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13309            }
13310        }
13311
13312        /**
13313         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13314         * based on the dimensions it received from the
13315         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13316         *
13317         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13318         */
13319        public void onDrawShadow(Canvas canvas) {
13320            final View view = mView.get();
13321            if (view != null) {
13322                view.draw(canvas);
13323            } else {
13324                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13325            }
13326        }
13327    }
13328
13329    /**
13330     * Starts a drag and drop operation. When your application calls this method, it passes a
13331     * {@link android.view.View.DragShadowBuilder} object to the system. The
13332     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13333     * to get metrics for the drag shadow, and then calls the object's
13334     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13335     * <p>
13336     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13337     *  drag events to all the View objects in your application that are currently visible. It does
13338     *  this either by calling the View object's drag listener (an implementation of
13339     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13340     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13341     *  Both are passed a {@link android.view.DragEvent} object that has a
13342     *  {@link android.view.DragEvent#getAction()} value of
13343     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13344     * </p>
13345     * <p>
13346     * Your application can invoke startDrag() on any attached View object. The View object does not
13347     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13348     * be related to the View the user selected for dragging.
13349     * </p>
13350     * @param data A {@link android.content.ClipData} object pointing to the data to be
13351     * transferred by the drag and drop operation.
13352     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13353     * drag shadow.
13354     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13355     * drop operation. This Object is put into every DragEvent object sent by the system during the
13356     * current drag.
13357     * <p>
13358     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13359     * to the target Views. For example, it can contain flags that differentiate between a
13360     * a copy operation and a move operation.
13361     * </p>
13362     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13363     * so the parameter should be set to 0.
13364     * @return {@code true} if the method completes successfully, or
13365     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13366     * do a drag, and so no drag operation is in progress.
13367     */
13368    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13369            Object myLocalState, int flags) {
13370        if (ViewDebug.DEBUG_DRAG) {
13371            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13372        }
13373        boolean okay = false;
13374
13375        Point shadowSize = new Point();
13376        Point shadowTouchPoint = new Point();
13377        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13378
13379        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13380                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13381            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13382        }
13383
13384        if (ViewDebug.DEBUG_DRAG) {
13385            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13386                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13387        }
13388        Surface surface = new Surface();
13389        try {
13390            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13391                    flags, shadowSize.x, shadowSize.y, surface);
13392            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13393                    + " surface=" + surface);
13394            if (token != null) {
13395                Canvas canvas = surface.lockCanvas(null);
13396                try {
13397                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13398                    shadowBuilder.onDrawShadow(canvas);
13399                } finally {
13400                    surface.unlockCanvasAndPost(canvas);
13401                }
13402
13403                final ViewRootImpl root = getViewRootImpl();
13404
13405                // Cache the local state object for delivery with DragEvents
13406                root.setLocalDragState(myLocalState);
13407
13408                // repurpose 'shadowSize' for the last touch point
13409                root.getLastTouchPoint(shadowSize);
13410
13411                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13412                        shadowSize.x, shadowSize.y,
13413                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13414                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13415
13416                // Off and running!  Release our local surface instance; the drag
13417                // shadow surface is now managed by the system process.
13418                surface.release();
13419            }
13420        } catch (Exception e) {
13421            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13422            surface.destroy();
13423        }
13424
13425        return okay;
13426    }
13427
13428    /**
13429     * Handles drag events sent by the system following a call to
13430     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13431     *<p>
13432     * When the system calls this method, it passes a
13433     * {@link android.view.DragEvent} object. A call to
13434     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13435     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13436     * operation.
13437     * @param event The {@link android.view.DragEvent} sent by the system.
13438     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13439     * in DragEvent, indicating the type of drag event represented by this object.
13440     * @return {@code true} if the method was successful, otherwise {@code false}.
13441     * <p>
13442     *  The method should return {@code true} in response to an action type of
13443     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13444     *  operation.
13445     * </p>
13446     * <p>
13447     *  The method should also return {@code true} in response to an action type of
13448     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13449     *  {@code false} if it didn't.
13450     * </p>
13451     */
13452    public boolean onDragEvent(DragEvent event) {
13453        return false;
13454    }
13455
13456    /**
13457     * Detects if this View is enabled and has a drag event listener.
13458     * If both are true, then it calls the drag event listener with the
13459     * {@link android.view.DragEvent} it received. If the drag event listener returns
13460     * {@code true}, then dispatchDragEvent() returns {@code true}.
13461     * <p>
13462     * For all other cases, the method calls the
13463     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13464     * method and returns its result.
13465     * </p>
13466     * <p>
13467     * This ensures that a drag event is always consumed, even if the View does not have a drag
13468     * event listener. However, if the View has a listener and the listener returns true, then
13469     * onDragEvent() is not called.
13470     * </p>
13471     */
13472    public boolean dispatchDragEvent(DragEvent event) {
13473        //noinspection SimplifiableIfStatement
13474        ListenerInfo li = mListenerInfo;
13475        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13476                && li.mOnDragListener.onDrag(this, event)) {
13477            return true;
13478        }
13479        return onDragEvent(event);
13480    }
13481
13482    boolean canAcceptDrag() {
13483        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13484    }
13485
13486    /**
13487     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13488     * it is ever exposed at all.
13489     * @hide
13490     */
13491    public void onCloseSystemDialogs(String reason) {
13492    }
13493
13494    /**
13495     * Given a Drawable whose bounds have been set to draw into this view,
13496     * update a Region being computed for
13497     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13498     * that any non-transparent parts of the Drawable are removed from the
13499     * given transparent region.
13500     *
13501     * @param dr The Drawable whose transparency is to be applied to the region.
13502     * @param region A Region holding the current transparency information,
13503     * where any parts of the region that are set are considered to be
13504     * transparent.  On return, this region will be modified to have the
13505     * transparency information reduced by the corresponding parts of the
13506     * Drawable that are not transparent.
13507     * {@hide}
13508     */
13509    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13510        if (DBG) {
13511            Log.i("View", "Getting transparent region for: " + this);
13512        }
13513        final Region r = dr.getTransparentRegion();
13514        final Rect db = dr.getBounds();
13515        final AttachInfo attachInfo = mAttachInfo;
13516        if (r != null && attachInfo != null) {
13517            final int w = getRight()-getLeft();
13518            final int h = getBottom()-getTop();
13519            if (db.left > 0) {
13520                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13521                r.op(0, 0, db.left, h, Region.Op.UNION);
13522            }
13523            if (db.right < w) {
13524                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13525                r.op(db.right, 0, w, h, Region.Op.UNION);
13526            }
13527            if (db.top > 0) {
13528                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13529                r.op(0, 0, w, db.top, Region.Op.UNION);
13530            }
13531            if (db.bottom < h) {
13532                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13533                r.op(0, db.bottom, w, h, Region.Op.UNION);
13534            }
13535            final int[] location = attachInfo.mTransparentLocation;
13536            getLocationInWindow(location);
13537            r.translate(location[0], location[1]);
13538            region.op(r, Region.Op.INTERSECT);
13539        } else {
13540            region.op(db, Region.Op.DIFFERENCE);
13541        }
13542    }
13543
13544    private void checkForLongClick(int delayOffset) {
13545        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13546            mHasPerformedLongPress = false;
13547
13548            if (mPendingCheckForLongPress == null) {
13549                mPendingCheckForLongPress = new CheckForLongPress();
13550            }
13551            mPendingCheckForLongPress.rememberWindowAttachCount();
13552            postDelayed(mPendingCheckForLongPress,
13553                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13554        }
13555    }
13556
13557    /**
13558     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13559     * LayoutInflater} class, which provides a full range of options for view inflation.
13560     *
13561     * @param context The Context object for your activity or application.
13562     * @param resource The resource ID to inflate
13563     * @param root A view group that will be the parent.  Used to properly inflate the
13564     * layout_* parameters.
13565     * @see LayoutInflater
13566     */
13567    public static View inflate(Context context, int resource, ViewGroup root) {
13568        LayoutInflater factory = LayoutInflater.from(context);
13569        return factory.inflate(resource, root);
13570    }
13571
13572    /**
13573     * Scroll the view with standard behavior for scrolling beyond the normal
13574     * content boundaries. Views that call this method should override
13575     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13576     * results of an over-scroll operation.
13577     *
13578     * Views can use this method to handle any touch or fling-based scrolling.
13579     *
13580     * @param deltaX Change in X in pixels
13581     * @param deltaY Change in Y in pixels
13582     * @param scrollX Current X scroll value in pixels before applying deltaX
13583     * @param scrollY Current Y scroll value in pixels before applying deltaY
13584     * @param scrollRangeX Maximum content scroll range along the X axis
13585     * @param scrollRangeY Maximum content scroll range along the Y axis
13586     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13587     *          along the X axis.
13588     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13589     *          along the Y axis.
13590     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13591     * @return true if scrolling was clamped to an over-scroll boundary along either
13592     *          axis, false otherwise.
13593     */
13594    @SuppressWarnings({"UnusedParameters"})
13595    protected boolean overScrollBy(int deltaX, int deltaY,
13596            int scrollX, int scrollY,
13597            int scrollRangeX, int scrollRangeY,
13598            int maxOverScrollX, int maxOverScrollY,
13599            boolean isTouchEvent) {
13600        final int overScrollMode = mOverScrollMode;
13601        final boolean canScrollHorizontal =
13602                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13603        final boolean canScrollVertical =
13604                computeVerticalScrollRange() > computeVerticalScrollExtent();
13605        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13606                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13607        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13608                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13609
13610        int newScrollX = scrollX + deltaX;
13611        if (!overScrollHorizontal) {
13612            maxOverScrollX = 0;
13613        }
13614
13615        int newScrollY = scrollY + deltaY;
13616        if (!overScrollVertical) {
13617            maxOverScrollY = 0;
13618        }
13619
13620        // Clamp values if at the limits and record
13621        final int left = -maxOverScrollX;
13622        final int right = maxOverScrollX + scrollRangeX;
13623        final int top = -maxOverScrollY;
13624        final int bottom = maxOverScrollY + scrollRangeY;
13625
13626        boolean clampedX = false;
13627        if (newScrollX > right) {
13628            newScrollX = right;
13629            clampedX = true;
13630        } else if (newScrollX < left) {
13631            newScrollX = left;
13632            clampedX = true;
13633        }
13634
13635        boolean clampedY = false;
13636        if (newScrollY > bottom) {
13637            newScrollY = bottom;
13638            clampedY = true;
13639        } else if (newScrollY < top) {
13640            newScrollY = top;
13641            clampedY = true;
13642        }
13643
13644        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13645
13646        return clampedX || clampedY;
13647    }
13648
13649    /**
13650     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13651     * respond to the results of an over-scroll operation.
13652     *
13653     * @param scrollX New X scroll value in pixels
13654     * @param scrollY New Y scroll value in pixels
13655     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13656     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13657     */
13658    protected void onOverScrolled(int scrollX, int scrollY,
13659            boolean clampedX, boolean clampedY) {
13660        // Intentionally empty.
13661    }
13662
13663    /**
13664     * Returns the over-scroll mode for this view. The result will be
13665     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13666     * (allow over-scrolling only if the view content is larger than the container),
13667     * or {@link #OVER_SCROLL_NEVER}.
13668     *
13669     * @return This view's over-scroll mode.
13670     */
13671    public int getOverScrollMode() {
13672        return mOverScrollMode;
13673    }
13674
13675    /**
13676     * Set the over-scroll mode for this view. Valid over-scroll modes are
13677     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13678     * (allow over-scrolling only if the view content is larger than the container),
13679     * or {@link #OVER_SCROLL_NEVER}.
13680     *
13681     * Setting the over-scroll mode of a view will have an effect only if the
13682     * view is capable of scrolling.
13683     *
13684     * @param overScrollMode The new over-scroll mode for this view.
13685     */
13686    public void setOverScrollMode(int overScrollMode) {
13687        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13688                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13689                overScrollMode != OVER_SCROLL_NEVER) {
13690            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13691        }
13692        mOverScrollMode = overScrollMode;
13693    }
13694
13695    /**
13696     * Gets a scale factor that determines the distance the view should scroll
13697     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13698     * @return The vertical scroll scale factor.
13699     * @hide
13700     */
13701    protected float getVerticalScrollFactor() {
13702        if (mVerticalScrollFactor == 0) {
13703            TypedValue outValue = new TypedValue();
13704            if (!mContext.getTheme().resolveAttribute(
13705                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13706                throw new IllegalStateException(
13707                        "Expected theme to define listPreferredItemHeight.");
13708            }
13709            mVerticalScrollFactor = outValue.getDimension(
13710                    mContext.getResources().getDisplayMetrics());
13711        }
13712        return mVerticalScrollFactor;
13713    }
13714
13715    /**
13716     * Gets a scale factor that determines the distance the view should scroll
13717     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13718     * @return The horizontal scroll scale factor.
13719     * @hide
13720     */
13721    protected float getHorizontalScrollFactor() {
13722        // TODO: Should use something else.
13723        return getVerticalScrollFactor();
13724    }
13725
13726    /**
13727     * Return the value specifying the text direction or policy that was set with
13728     * {@link #setTextDirection(int)}.
13729     *
13730     * @return the defined text direction. It can be one of:
13731     *
13732     * {@link #TEXT_DIRECTION_INHERIT},
13733     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13734     * {@link #TEXT_DIRECTION_ANY_RTL},
13735     * {@link #TEXT_DIRECTION_LTR},
13736     * {@link #TEXT_DIRECTION_RTL},
13737     * {@link #TEXT_DIRECTION_LOCALE},
13738     *
13739     * @hide
13740     */
13741    public int getTextDirection() {
13742        return mTextDirection;
13743    }
13744
13745    /**
13746     * Set the text direction.
13747     *
13748     * @param textDirection the direction to set. Should be one of:
13749     *
13750     * {@link #TEXT_DIRECTION_INHERIT},
13751     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13752     * {@link #TEXT_DIRECTION_ANY_RTL},
13753     * {@link #TEXT_DIRECTION_LTR},
13754     * {@link #TEXT_DIRECTION_RTL},
13755     * {@link #TEXT_DIRECTION_LOCALE},
13756     *
13757     * @hide
13758     */
13759    public void setTextDirection(int textDirection) {
13760        if (textDirection != mTextDirection) {
13761            mTextDirection = textDirection;
13762            resetResolvedTextDirection();
13763            requestLayout();
13764        }
13765    }
13766
13767    /**
13768     * Return the resolved text direction.
13769     *
13770     * @return the resolved text direction. Return one of:
13771     *
13772     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13773     * {@link #TEXT_DIRECTION_ANY_RTL},
13774     * {@link #TEXT_DIRECTION_LTR},
13775     * {@link #TEXT_DIRECTION_RTL},
13776     * {@link #TEXT_DIRECTION_LOCALE},
13777     *
13778     * @hide
13779     */
13780    public int getResolvedTextDirection() {
13781        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13782            resolveTextDirection();
13783        }
13784        return mResolvedTextDirection;
13785    }
13786
13787    /**
13788     * Resolve the text direction.
13789     *
13790     * @hide
13791     */
13792    protected void resolveTextDirection() {
13793        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13794            mResolvedTextDirection = mTextDirection;
13795            return;
13796        }
13797        if (mParent != null && mParent instanceof ViewGroup) {
13798            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13799            return;
13800        }
13801        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13802    }
13803
13804    /**
13805     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13806     *
13807     * @hide
13808     */
13809    protected void resetResolvedTextDirection() {
13810        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13811    }
13812
13813    //
13814    // Properties
13815    //
13816    /**
13817     * A Property wrapper around the <code>alpha</code> functionality handled by the
13818     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13819     */
13820    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13821        @Override
13822        public void setValue(View object, float value) {
13823            object.setAlpha(value);
13824        }
13825
13826        @Override
13827        public Float get(View object) {
13828            return object.getAlpha();
13829        }
13830    };
13831
13832    /**
13833     * A Property wrapper around the <code>translationX</code> functionality handled by the
13834     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13835     */
13836    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13837        @Override
13838        public void setValue(View object, float value) {
13839            object.setTranslationX(value);
13840        }
13841
13842                @Override
13843        public Float get(View object) {
13844            return object.getTranslationX();
13845        }
13846    };
13847
13848    /**
13849     * A Property wrapper around the <code>translationY</code> functionality handled by the
13850     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13851     */
13852    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13853        @Override
13854        public void setValue(View object, float value) {
13855            object.setTranslationY(value);
13856        }
13857
13858        @Override
13859        public Float get(View object) {
13860            return object.getTranslationY();
13861        }
13862    };
13863
13864    /**
13865     * A Property wrapper around the <code>x</code> functionality handled by the
13866     * {@link View#setX(float)} and {@link View#getX()} methods.
13867     */
13868    public static final Property<View, Float> X = new FloatProperty<View>("x") {
13869        @Override
13870        public void setValue(View object, float value) {
13871            object.setX(value);
13872        }
13873
13874        @Override
13875        public Float get(View object) {
13876            return object.getX();
13877        }
13878    };
13879
13880    /**
13881     * A Property wrapper around the <code>y</code> functionality handled by the
13882     * {@link View#setY(float)} and {@link View#getY()} methods.
13883     */
13884    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
13885        @Override
13886        public void setValue(View object, float value) {
13887            object.setY(value);
13888        }
13889
13890        @Override
13891        public Float get(View object) {
13892            return object.getY();
13893        }
13894    };
13895
13896    /**
13897     * A Property wrapper around the <code>rotation</code> functionality handled by the
13898     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13899     */
13900    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13901        @Override
13902        public void setValue(View object, float value) {
13903            object.setRotation(value);
13904        }
13905
13906        @Override
13907        public Float get(View object) {
13908            return object.getRotation();
13909        }
13910    };
13911
13912    /**
13913     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13914     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13915     */
13916    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13917        @Override
13918        public void setValue(View object, float value) {
13919            object.setRotationX(value);
13920        }
13921
13922        @Override
13923        public Float get(View object) {
13924            return object.getRotationX();
13925        }
13926    };
13927
13928    /**
13929     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13930     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13931     */
13932    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13933        @Override
13934        public void setValue(View object, float value) {
13935            object.setRotationY(value);
13936        }
13937
13938        @Override
13939        public Float get(View object) {
13940            return object.getRotationY();
13941        }
13942    };
13943
13944    /**
13945     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13946     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13947     */
13948    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13949        @Override
13950        public void setValue(View object, float value) {
13951            object.setScaleX(value);
13952        }
13953
13954        @Override
13955        public Float get(View object) {
13956            return object.getScaleX();
13957        }
13958    };
13959
13960    /**
13961     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13962     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13963     */
13964    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13965        @Override
13966        public void setValue(View object, float value) {
13967            object.setScaleY(value);
13968        }
13969
13970        @Override
13971        public Float get(View object) {
13972            return object.getScaleY();
13973        }
13974    };
13975
13976    /**
13977     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13978     * Each MeasureSpec represents a requirement for either the width or the height.
13979     * A MeasureSpec is comprised of a size and a mode. There are three possible
13980     * modes:
13981     * <dl>
13982     * <dt>UNSPECIFIED</dt>
13983     * <dd>
13984     * The parent has not imposed any constraint on the child. It can be whatever size
13985     * it wants.
13986     * </dd>
13987     *
13988     * <dt>EXACTLY</dt>
13989     * <dd>
13990     * The parent has determined an exact size for the child. The child is going to be
13991     * given those bounds regardless of how big it wants to be.
13992     * </dd>
13993     *
13994     * <dt>AT_MOST</dt>
13995     * <dd>
13996     * The child can be as large as it wants up to the specified size.
13997     * </dd>
13998     * </dl>
13999     *
14000     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14001     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14002     */
14003    public static class MeasureSpec {
14004        private static final int MODE_SHIFT = 30;
14005        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14006
14007        /**
14008         * Measure specification mode: The parent has not imposed any constraint
14009         * on the child. It can be whatever size it wants.
14010         */
14011        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14012
14013        /**
14014         * Measure specification mode: The parent has determined an exact size
14015         * for the child. The child is going to be given those bounds regardless
14016         * of how big it wants to be.
14017         */
14018        public static final int EXACTLY     = 1 << MODE_SHIFT;
14019
14020        /**
14021         * Measure specification mode: The child can be as large as it wants up
14022         * to the specified size.
14023         */
14024        public static final int AT_MOST     = 2 << MODE_SHIFT;
14025
14026        /**
14027         * Creates a measure specification based on the supplied size and mode.
14028         *
14029         * The mode must always be one of the following:
14030         * <ul>
14031         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14032         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14033         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14034         * </ul>
14035         *
14036         * @param size the size of the measure specification
14037         * @param mode the mode of the measure specification
14038         * @return the measure specification based on size and mode
14039         */
14040        public static int makeMeasureSpec(int size, int mode) {
14041            return size + mode;
14042        }
14043
14044        /**
14045         * Extracts the mode from the supplied measure specification.
14046         *
14047         * @param measureSpec the measure specification to extract the mode from
14048         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14049         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14050         *         {@link android.view.View.MeasureSpec#EXACTLY}
14051         */
14052        public static int getMode(int measureSpec) {
14053            return (measureSpec & MODE_MASK);
14054        }
14055
14056        /**
14057         * Extracts the size from the supplied measure specification.
14058         *
14059         * @param measureSpec the measure specification to extract the size from
14060         * @return the size in pixels defined in the supplied measure specification
14061         */
14062        public static int getSize(int measureSpec) {
14063            return (measureSpec & ~MODE_MASK);
14064        }
14065
14066        /**
14067         * Returns a String representation of the specified measure
14068         * specification.
14069         *
14070         * @param measureSpec the measure specification to convert to a String
14071         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14072         */
14073        public static String toString(int measureSpec) {
14074            int mode = getMode(measureSpec);
14075            int size = getSize(measureSpec);
14076
14077            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14078
14079            if (mode == UNSPECIFIED)
14080                sb.append("UNSPECIFIED ");
14081            else if (mode == EXACTLY)
14082                sb.append("EXACTLY ");
14083            else if (mode == AT_MOST)
14084                sb.append("AT_MOST ");
14085            else
14086                sb.append(mode).append(" ");
14087
14088            sb.append(size);
14089            return sb.toString();
14090        }
14091    }
14092
14093    class CheckForLongPress implements Runnable {
14094
14095        private int mOriginalWindowAttachCount;
14096
14097        public void run() {
14098            if (isPressed() && (mParent != null)
14099                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14100                if (performLongClick()) {
14101                    mHasPerformedLongPress = true;
14102                }
14103            }
14104        }
14105
14106        public void rememberWindowAttachCount() {
14107            mOriginalWindowAttachCount = mWindowAttachCount;
14108        }
14109    }
14110
14111    private final class CheckForTap implements Runnable {
14112        public void run() {
14113            mPrivateFlags &= ~PREPRESSED;
14114            mPrivateFlags |= PRESSED;
14115            refreshDrawableState();
14116            checkForLongClick(ViewConfiguration.getTapTimeout());
14117        }
14118    }
14119
14120    private final class PerformClick implements Runnable {
14121        public void run() {
14122            performClick();
14123        }
14124    }
14125
14126    /** @hide */
14127    public void hackTurnOffWindowResizeAnim(boolean off) {
14128        mAttachInfo.mTurnOffWindowResizeAnim = off;
14129    }
14130
14131    /**
14132     * This method returns a ViewPropertyAnimator object, which can be used to animate
14133     * specific properties on this View.
14134     *
14135     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14136     */
14137    public ViewPropertyAnimator animate() {
14138        if (mAnimator == null) {
14139            mAnimator = new ViewPropertyAnimator(this);
14140        }
14141        return mAnimator;
14142    }
14143
14144    /**
14145     * Interface definition for a callback to be invoked when a key event is
14146     * dispatched to this view. The callback will be invoked before the key
14147     * event is given to the view.
14148     */
14149    public interface OnKeyListener {
14150        /**
14151         * Called when a key is dispatched to a view. This allows listeners to
14152         * get a chance to respond before the target view.
14153         *
14154         * @param v The view the key has been dispatched to.
14155         * @param keyCode The code for the physical key that was pressed
14156         * @param event The KeyEvent object containing full information about
14157         *        the event.
14158         * @return True if the listener has consumed the event, false otherwise.
14159         */
14160        boolean onKey(View v, int keyCode, KeyEvent event);
14161    }
14162
14163    /**
14164     * Interface definition for a callback to be invoked when a touch event is
14165     * dispatched to this view. The callback will be invoked before the touch
14166     * event is given to the view.
14167     */
14168    public interface OnTouchListener {
14169        /**
14170         * Called when a touch event is dispatched to a view. This allows listeners to
14171         * get a chance to respond before the target view.
14172         *
14173         * @param v The view the touch event has been dispatched to.
14174         * @param event The MotionEvent object containing full information about
14175         *        the event.
14176         * @return True if the listener has consumed the event, false otherwise.
14177         */
14178        boolean onTouch(View v, MotionEvent event);
14179    }
14180
14181    /**
14182     * Interface definition for a callback to be invoked when a hover event is
14183     * dispatched to this view. The callback will be invoked before the hover
14184     * event is given to the view.
14185     */
14186    public interface OnHoverListener {
14187        /**
14188         * Called when a hover event is dispatched to a view. This allows listeners to
14189         * get a chance to respond before the target view.
14190         *
14191         * @param v The view the hover event has been dispatched to.
14192         * @param event The MotionEvent object containing full information about
14193         *        the event.
14194         * @return True if the listener has consumed the event, false otherwise.
14195         */
14196        boolean onHover(View v, MotionEvent event);
14197    }
14198
14199    /**
14200     * Interface definition for a callback to be invoked when a generic motion event is
14201     * dispatched to this view. The callback will be invoked before the generic motion
14202     * event is given to the view.
14203     */
14204    public interface OnGenericMotionListener {
14205        /**
14206         * Called when a generic motion event is dispatched to a view. This allows listeners to
14207         * get a chance to respond before the target view.
14208         *
14209         * @param v The view the generic motion event has been dispatched to.
14210         * @param event The MotionEvent object containing full information about
14211         *        the event.
14212         * @return True if the listener has consumed the event, false otherwise.
14213         */
14214        boolean onGenericMotion(View v, MotionEvent event);
14215    }
14216
14217    /**
14218     * Interface definition for a callback to be invoked when a view has been clicked and held.
14219     */
14220    public interface OnLongClickListener {
14221        /**
14222         * Called when a view has been clicked and held.
14223         *
14224         * @param v The view that was clicked and held.
14225         *
14226         * @return true if the callback consumed the long click, false otherwise.
14227         */
14228        boolean onLongClick(View v);
14229    }
14230
14231    /**
14232     * Interface definition for a callback to be invoked when a drag is being dispatched
14233     * to this view.  The callback will be invoked before the hosting view's own
14234     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14235     * onDrag(event) behavior, it should return 'false' from this callback.
14236     *
14237     * <div class="special reference">
14238     * <h3>Developer Guides</h3>
14239     * <p>For a guide to implementing drag and drop features, read the
14240     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14241     * </div>
14242     */
14243    public interface OnDragListener {
14244        /**
14245         * Called when a drag event is dispatched to a view. This allows listeners
14246         * to get a chance to override base View behavior.
14247         *
14248         * @param v The View that received the drag event.
14249         * @param event The {@link android.view.DragEvent} object for the drag event.
14250         * @return {@code true} if the drag event was handled successfully, or {@code false}
14251         * if the drag event was not handled. Note that {@code false} will trigger the View
14252         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14253         */
14254        boolean onDrag(View v, DragEvent event);
14255    }
14256
14257    /**
14258     * Interface definition for a callback to be invoked when the focus state of
14259     * a view changed.
14260     */
14261    public interface OnFocusChangeListener {
14262        /**
14263         * Called when the focus state of a view has changed.
14264         *
14265         * @param v The view whose state has changed.
14266         * @param hasFocus The new focus state of v.
14267         */
14268        void onFocusChange(View v, boolean hasFocus);
14269    }
14270
14271    /**
14272     * Interface definition for a callback to be invoked when a view is clicked.
14273     */
14274    public interface OnClickListener {
14275        /**
14276         * Called when a view has been clicked.
14277         *
14278         * @param v The view that was clicked.
14279         */
14280        void onClick(View v);
14281    }
14282
14283    /**
14284     * Interface definition for a callback to be invoked when the context menu
14285     * for this view is being built.
14286     */
14287    public interface OnCreateContextMenuListener {
14288        /**
14289         * Called when the context menu for this view is being built. It is not
14290         * safe to hold onto the menu after this method returns.
14291         *
14292         * @param menu The context menu that is being built
14293         * @param v The view for which the context menu is being built
14294         * @param menuInfo Extra information about the item for which the
14295         *            context menu should be shown. This information will vary
14296         *            depending on the class of v.
14297         */
14298        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14299    }
14300
14301    /**
14302     * Interface definition for a callback to be invoked when the status bar changes
14303     * visibility.  This reports <strong>global</strong> changes to the system UI
14304     * state, not just what the application is requesting.
14305     *
14306     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14307     */
14308    public interface OnSystemUiVisibilityChangeListener {
14309        /**
14310         * Called when the status bar changes visibility because of a call to
14311         * {@link View#setSystemUiVisibility(int)}.
14312         *
14313         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14314         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
14315         * <strong>global</strong> state of the UI visibility flags, not what your
14316         * app is currently applying.
14317         */
14318        public void onSystemUiVisibilityChange(int visibility);
14319    }
14320
14321    /**
14322     * Interface definition for a callback to be invoked when this view is attached
14323     * or detached from its window.
14324     */
14325    public interface OnAttachStateChangeListener {
14326        /**
14327         * Called when the view is attached to a window.
14328         * @param v The view that was attached
14329         */
14330        public void onViewAttachedToWindow(View v);
14331        /**
14332         * Called when the view is detached from a window.
14333         * @param v The view that was detached
14334         */
14335        public void onViewDetachedFromWindow(View v);
14336    }
14337
14338    private final class UnsetPressedState implements Runnable {
14339        public void run() {
14340            setPressed(false);
14341        }
14342    }
14343
14344    /**
14345     * Base class for derived classes that want to save and restore their own
14346     * state in {@link android.view.View#onSaveInstanceState()}.
14347     */
14348    public static class BaseSavedState extends AbsSavedState {
14349        /**
14350         * Constructor used when reading from a parcel. Reads the state of the superclass.
14351         *
14352         * @param source
14353         */
14354        public BaseSavedState(Parcel source) {
14355            super(source);
14356        }
14357
14358        /**
14359         * Constructor called by derived classes when creating their SavedState objects
14360         *
14361         * @param superState The state of the superclass of this view
14362         */
14363        public BaseSavedState(Parcelable superState) {
14364            super(superState);
14365        }
14366
14367        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14368                new Parcelable.Creator<BaseSavedState>() {
14369            public BaseSavedState createFromParcel(Parcel in) {
14370                return new BaseSavedState(in);
14371            }
14372
14373            public BaseSavedState[] newArray(int size) {
14374                return new BaseSavedState[size];
14375            }
14376        };
14377    }
14378
14379    /**
14380     * A set of information given to a view when it is attached to its parent
14381     * window.
14382     */
14383    static class AttachInfo {
14384        interface Callbacks {
14385            void playSoundEffect(int effectId);
14386            boolean performHapticFeedback(int effectId, boolean always);
14387        }
14388
14389        /**
14390         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14391         * to a Handler. This class contains the target (View) to invalidate and
14392         * the coordinates of the dirty rectangle.
14393         *
14394         * For performance purposes, this class also implements a pool of up to
14395         * POOL_LIMIT objects that get reused. This reduces memory allocations
14396         * whenever possible.
14397         */
14398        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14399            private static final int POOL_LIMIT = 10;
14400            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14401                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14402                        public InvalidateInfo newInstance() {
14403                            return new InvalidateInfo();
14404                        }
14405
14406                        public void onAcquired(InvalidateInfo element) {
14407                        }
14408
14409                        public void onReleased(InvalidateInfo element) {
14410                            element.target = null;
14411                        }
14412                    }, POOL_LIMIT)
14413            );
14414
14415            private InvalidateInfo mNext;
14416            private boolean mIsPooled;
14417
14418            View target;
14419
14420            int left;
14421            int top;
14422            int right;
14423            int bottom;
14424
14425            public void setNextPoolable(InvalidateInfo element) {
14426                mNext = element;
14427            }
14428
14429            public InvalidateInfo getNextPoolable() {
14430                return mNext;
14431            }
14432
14433            static InvalidateInfo acquire() {
14434                return sPool.acquire();
14435            }
14436
14437            void release() {
14438                sPool.release(this);
14439            }
14440
14441            public boolean isPooled() {
14442                return mIsPooled;
14443            }
14444
14445            public void setPooled(boolean isPooled) {
14446                mIsPooled = isPooled;
14447            }
14448        }
14449
14450        final IWindowSession mSession;
14451
14452        final IWindow mWindow;
14453
14454        final IBinder mWindowToken;
14455
14456        final Callbacks mRootCallbacks;
14457
14458        HardwareCanvas mHardwareCanvas;
14459
14460        /**
14461         * The top view of the hierarchy.
14462         */
14463        View mRootView;
14464
14465        IBinder mPanelParentWindowToken;
14466        Surface mSurface;
14467
14468        boolean mHardwareAccelerated;
14469        boolean mHardwareAccelerationRequested;
14470        HardwareRenderer mHardwareRenderer;
14471
14472        /**
14473         * Scale factor used by the compatibility mode
14474         */
14475        float mApplicationScale;
14476
14477        /**
14478         * Indicates whether the application is in compatibility mode
14479         */
14480        boolean mScalingRequired;
14481
14482        /**
14483         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14484         */
14485        boolean mTurnOffWindowResizeAnim;
14486
14487        /**
14488         * Left position of this view's window
14489         */
14490        int mWindowLeft;
14491
14492        /**
14493         * Top position of this view's window
14494         */
14495        int mWindowTop;
14496
14497        /**
14498         * Indicates whether views need to use 32-bit drawing caches
14499         */
14500        boolean mUse32BitDrawingCache;
14501
14502        /**
14503         * For windows that are full-screen but using insets to layout inside
14504         * of the screen decorations, these are the current insets for the
14505         * content of the window.
14506         */
14507        final Rect mContentInsets = new Rect();
14508
14509        /**
14510         * For windows that are full-screen but using insets to layout inside
14511         * of the screen decorations, these are the current insets for the
14512         * actual visible parts of the window.
14513         */
14514        final Rect mVisibleInsets = new Rect();
14515
14516        /**
14517         * The internal insets given by this window.  This value is
14518         * supplied by the client (through
14519         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14520         * be given to the window manager when changed to be used in laying
14521         * out windows behind it.
14522         */
14523        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14524                = new ViewTreeObserver.InternalInsetsInfo();
14525
14526        /**
14527         * All views in the window's hierarchy that serve as scroll containers,
14528         * used to determine if the window can be resized or must be panned
14529         * to adjust for a soft input area.
14530         */
14531        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14532
14533        final KeyEvent.DispatcherState mKeyDispatchState
14534                = new KeyEvent.DispatcherState();
14535
14536        /**
14537         * Indicates whether the view's window currently has the focus.
14538         */
14539        boolean mHasWindowFocus;
14540
14541        /**
14542         * The current visibility of the window.
14543         */
14544        int mWindowVisibility;
14545
14546        /**
14547         * Indicates the time at which drawing started to occur.
14548         */
14549        long mDrawingTime;
14550
14551        /**
14552         * Indicates whether or not ignoring the DIRTY_MASK flags.
14553         */
14554        boolean mIgnoreDirtyState;
14555
14556        /**
14557         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14558         * to avoid clearing that flag prematurely.
14559         */
14560        boolean mSetIgnoreDirtyState = false;
14561
14562        /**
14563         * Indicates whether the view's window is currently in touch mode.
14564         */
14565        boolean mInTouchMode;
14566
14567        /**
14568         * Indicates that ViewAncestor should trigger a global layout change
14569         * the next time it performs a traversal
14570         */
14571        boolean mRecomputeGlobalAttributes;
14572
14573        /**
14574         * Always report new attributes at next traversal.
14575         */
14576        boolean mForceReportNewAttributes;
14577
14578        /**
14579         * Set during a traveral if any views want to keep the screen on.
14580         */
14581        boolean mKeepScreenOn;
14582
14583        /**
14584         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14585         */
14586        int mSystemUiVisibility;
14587
14588        /**
14589         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14590         * attached.
14591         */
14592        boolean mHasSystemUiListeners;
14593
14594        /**
14595         * Set if the visibility of any views has changed.
14596         */
14597        boolean mViewVisibilityChanged;
14598
14599        /**
14600         * Set to true if a view has been scrolled.
14601         */
14602        boolean mViewScrollChanged;
14603
14604        /**
14605         * Global to the view hierarchy used as a temporary for dealing with
14606         * x/y points in the transparent region computations.
14607         */
14608        final int[] mTransparentLocation = new int[2];
14609
14610        /**
14611         * Global to the view hierarchy used as a temporary for dealing with
14612         * x/y points in the ViewGroup.invalidateChild implementation.
14613         */
14614        final int[] mInvalidateChildLocation = new int[2];
14615
14616
14617        /**
14618         * Global to the view hierarchy used as a temporary for dealing with
14619         * x/y location when view is transformed.
14620         */
14621        final float[] mTmpTransformLocation = new float[2];
14622
14623        /**
14624         * The view tree observer used to dispatch global events like
14625         * layout, pre-draw, touch mode change, etc.
14626         */
14627        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14628
14629        /**
14630         * A Canvas used by the view hierarchy to perform bitmap caching.
14631         */
14632        Canvas mCanvas;
14633
14634        /**
14635         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14636         * handler can be used to pump events in the UI events queue.
14637         */
14638        final Handler mHandler;
14639
14640        /**
14641         * Identifier for messages requesting the view to be invalidated.
14642         * Such messages should be sent to {@link #mHandler}.
14643         */
14644        static final int INVALIDATE_MSG = 0x1;
14645
14646        /**
14647         * Identifier for messages requesting the view to invalidate a region.
14648         * Such messages should be sent to {@link #mHandler}.
14649         */
14650        static final int INVALIDATE_RECT_MSG = 0x2;
14651
14652        /**
14653         * Temporary for use in computing invalidate rectangles while
14654         * calling up the hierarchy.
14655         */
14656        final Rect mTmpInvalRect = new Rect();
14657
14658        /**
14659         * Temporary for use in computing hit areas with transformed views
14660         */
14661        final RectF mTmpTransformRect = new RectF();
14662
14663        /**
14664         * Temporary list for use in collecting focusable descendents of a view.
14665         */
14666        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14667
14668        /**
14669         * The id of the window for accessibility purposes.
14670         */
14671        int mAccessibilityWindowId = View.NO_ID;
14672
14673        /**
14674         * Creates a new set of attachment information with the specified
14675         * events handler and thread.
14676         *
14677         * @param handler the events handler the view must use
14678         */
14679        AttachInfo(IWindowSession session, IWindow window,
14680                Handler handler, Callbacks effectPlayer) {
14681            mSession = session;
14682            mWindow = window;
14683            mWindowToken = window.asBinder();
14684            mHandler = handler;
14685            mRootCallbacks = effectPlayer;
14686        }
14687    }
14688
14689    /**
14690     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14691     * is supported. This avoids keeping too many unused fields in most
14692     * instances of View.</p>
14693     */
14694    private static class ScrollabilityCache implements Runnable {
14695
14696        /**
14697         * Scrollbars are not visible
14698         */
14699        public static final int OFF = 0;
14700
14701        /**
14702         * Scrollbars are visible
14703         */
14704        public static final int ON = 1;
14705
14706        /**
14707         * Scrollbars are fading away
14708         */
14709        public static final int FADING = 2;
14710
14711        public boolean fadeScrollBars;
14712
14713        public int fadingEdgeLength;
14714        public int scrollBarDefaultDelayBeforeFade;
14715        public int scrollBarFadeDuration;
14716
14717        public int scrollBarSize;
14718        public ScrollBarDrawable scrollBar;
14719        public float[] interpolatorValues;
14720        public View host;
14721
14722        public final Paint paint;
14723        public final Matrix matrix;
14724        public Shader shader;
14725
14726        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14727
14728        private static final float[] OPAQUE = { 255 };
14729        private static final float[] TRANSPARENT = { 0.0f };
14730
14731        /**
14732         * When fading should start. This time moves into the future every time
14733         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14734         */
14735        public long fadeStartTime;
14736
14737
14738        /**
14739         * The current state of the scrollbars: ON, OFF, or FADING
14740         */
14741        public int state = OFF;
14742
14743        private int mLastColor;
14744
14745        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14746            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14747            scrollBarSize = configuration.getScaledScrollBarSize();
14748            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14749            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14750
14751            paint = new Paint();
14752            matrix = new Matrix();
14753            // use use a height of 1, and then wack the matrix each time we
14754            // actually use it.
14755            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14756
14757            paint.setShader(shader);
14758            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14759            this.host = host;
14760        }
14761
14762        public void setFadeColor(int color) {
14763            if (color != 0 && color != mLastColor) {
14764                mLastColor = color;
14765                color |= 0xFF000000;
14766
14767                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14768                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14769
14770                paint.setShader(shader);
14771                // Restore the default transfer mode (src_over)
14772                paint.setXfermode(null);
14773            }
14774        }
14775
14776        public void run() {
14777            long now = AnimationUtils.currentAnimationTimeMillis();
14778            if (now >= fadeStartTime) {
14779
14780                // the animation fades the scrollbars out by changing
14781                // the opacity (alpha) from fully opaque to fully
14782                // transparent
14783                int nextFrame = (int) now;
14784                int framesCount = 0;
14785
14786                Interpolator interpolator = scrollBarInterpolator;
14787
14788                // Start opaque
14789                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14790
14791                // End transparent
14792                nextFrame += scrollBarFadeDuration;
14793                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14794
14795                state = FADING;
14796
14797                // Kick off the fade animation
14798                host.invalidate(true);
14799            }
14800        }
14801    }
14802
14803    /**
14804     * Resuable callback for sending
14805     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14806     */
14807    private class SendViewScrolledAccessibilityEvent implements Runnable {
14808        public volatile boolean mIsPending;
14809
14810        public void run() {
14811            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14812            mIsPending = false;
14813        }
14814    }
14815
14816    /**
14817     * <p>
14818     * This class represents a delegate that can be registered in a {@link View}
14819     * to enhance accessibility support via composition rather via inheritance.
14820     * It is specifically targeted to widget developers that extend basic View
14821     * classes i.e. classes in package android.view, that would like their
14822     * applications to be backwards compatible.
14823     * </p>
14824     * <p>
14825     * A scenario in which a developer would like to use an accessibility delegate
14826     * is overriding a method introduced in a later API version then the minimal API
14827     * version supported by the application. For example, the method
14828     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
14829     * in API version 4 when the accessibility APIs were first introduced. If a
14830     * developer would like his application to run on API version 4 devices (assuming
14831     * all other APIs used by the application are version 4 or lower) and take advantage
14832     * of this method, instead of overriding the method which would break the application's
14833     * backwards compatibility, he can override the corresponding method in this
14834     * delegate and register the delegate in the target View if the API version of
14835     * the system is high enough i.e. the API version is same or higher to the API
14836     * version that introduced
14837     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
14838     * </p>
14839     * <p>
14840     * Here is an example implementation:
14841     * </p>
14842     * <code><pre><p>
14843     * if (Build.VERSION.SDK_INT >= 14) {
14844     *     // If the API version is equal of higher than the version in
14845     *     // which onInitializeAccessibilityNodeInfo was introduced we
14846     *     // register a delegate with a customized implementation.
14847     *     View view = findViewById(R.id.view_id);
14848     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
14849     *         public void onInitializeAccessibilityNodeInfo(View host,
14850     *                 AccessibilityNodeInfo info) {
14851     *             // Let the default implementation populate the info.
14852     *             super.onInitializeAccessibilityNodeInfo(host, info);
14853     *             // Set some other information.
14854     *             info.setEnabled(host.isEnabled());
14855     *         }
14856     *     });
14857     * }
14858     * </code></pre></p>
14859     * <p>
14860     * This delegate contains methods that correspond to the accessibility methods
14861     * in View. If a delegate has been specified the implementation in View hands
14862     * off handling to the corresponding method in this delegate. The default
14863     * implementation the delegate methods behaves exactly as the corresponding
14864     * method in View for the case of no accessibility delegate been set. Hence,
14865     * to customize the behavior of a View method, clients can override only the
14866     * corresponding delegate method without altering the behavior of the rest
14867     * accessibility related methods of the host view.
14868     * </p>
14869     */
14870    public static class AccessibilityDelegate {
14871
14872        /**
14873         * Sends an accessibility event of the given type. If accessibility is not
14874         * enabled this method has no effect.
14875         * <p>
14876         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
14877         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
14878         * been set.
14879         * </p>
14880         *
14881         * @param host The View hosting the delegate.
14882         * @param eventType The type of the event to send.
14883         *
14884         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
14885         */
14886        public void sendAccessibilityEvent(View host, int eventType) {
14887            host.sendAccessibilityEventInternal(eventType);
14888        }
14889
14890        /**
14891         * Sends an accessibility event. This method behaves exactly as
14892         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
14893         * empty {@link AccessibilityEvent} and does not perform a check whether
14894         * accessibility is enabled.
14895         * <p>
14896         * The default implementation behaves as
14897         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14898         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
14899         * the case of no accessibility delegate been set.
14900         * </p>
14901         *
14902         * @param host The View hosting the delegate.
14903         * @param event The event to send.
14904         *
14905         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14906         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14907         */
14908        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
14909            host.sendAccessibilityEventUncheckedInternal(event);
14910        }
14911
14912        /**
14913         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
14914         * to its children for adding their text content to the event.
14915         * <p>
14916         * The default implementation behaves as
14917         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14918         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
14919         * the case of no accessibility delegate been set.
14920         * </p>
14921         *
14922         * @param host The View hosting the delegate.
14923         * @param event The event.
14924         * @return True if the event population was completed.
14925         *
14926         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14927         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14928         */
14929        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14930            return host.dispatchPopulateAccessibilityEventInternal(event);
14931        }
14932
14933        /**
14934         * Gives a chance to the host View to populate the accessibility event with its
14935         * text content.
14936         * <p>
14937         * The default implementation behaves as
14938         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
14939         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
14940         * the case of no accessibility delegate been set.
14941         * </p>
14942         *
14943         * @param host The View hosting the delegate.
14944         * @param event The accessibility event which to populate.
14945         *
14946         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
14947         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
14948         */
14949        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14950            host.onPopulateAccessibilityEventInternal(event);
14951        }
14952
14953        /**
14954         * Initializes an {@link AccessibilityEvent} with information about the
14955         * the host View which is the event source.
14956         * <p>
14957         * The default implementation behaves as
14958         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
14959         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
14960         * the case of no accessibility delegate been set.
14961         * </p>
14962         *
14963         * @param host The View hosting the delegate.
14964         * @param event The event to initialize.
14965         *
14966         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
14967         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
14968         */
14969        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
14970            host.onInitializeAccessibilityEventInternal(event);
14971        }
14972
14973        /**
14974         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
14975         * <p>
14976         * The default implementation behaves as
14977         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14978         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
14979         * the case of no accessibility delegate been set.
14980         * </p>
14981         *
14982         * @param host The View hosting the delegate.
14983         * @param info The instance to initialize.
14984         *
14985         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14986         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14987         */
14988        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
14989            host.onInitializeAccessibilityNodeInfoInternal(info);
14990        }
14991
14992        /**
14993         * Called when a child of the host View has requested sending an
14994         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
14995         * to augment the event.
14996         * <p>
14997         * The default implementation behaves as
14998         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14999         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15000         * the case of no accessibility delegate been set.
15001         * </p>
15002         *
15003         * @param host The View hosting the delegate.
15004         * @param child The child which requests sending the event.
15005         * @param event The event to be sent.
15006         * @return True if the event should be sent
15007         *
15008         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15009         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15010         */
15011        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15012                AccessibilityEvent event) {
15013            return host.onRequestSendAccessibilityEventInternal(child, event);
15014        }
15015
15016        /**
15017         * Gets the provider for managing a virtual view hierarchy rooted at this View
15018         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15019         * that explore the window content.
15020         * <p>
15021         * The default implementation behaves as
15022         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15023         * the case of no accessibility delegate been set.
15024         * </p>
15025         *
15026         * @return The provider.
15027         *
15028         * @see AccessibilityNodeProvider
15029         */
15030        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15031            return null;
15032        }
15033    }
15034}
15035