View.java revision dd29f8c4e3db3338bc055302145c3bc51a27566f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.text.TextUtils;
49import android.util.AttributeSet;
50import android.util.FloatProperty;
51import android.util.LocaleUtil;
52import android.util.Log;
53import android.util.Pool;
54import android.util.Poolable;
55import android.util.PoolableManager;
56import android.util.Pools;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.accessibility.AccessibilityNodeProvider;
66import android.view.animation.Animation;
67import android.view.animation.AnimationUtils;
68import android.view.animation.Transformation;
69import android.view.inputmethod.EditorInfo;
70import android.view.inputmethod.InputConnection;
71import android.view.inputmethod.InputMethodManager;
72import android.widget.ScrollBarDrawable;
73
74import static android.os.Build.VERSION_CODES.*;
75
76import com.android.internal.R;
77import com.android.internal.util.Predicate;
78import com.android.internal.view.menu.MenuBuilder;
79
80import java.lang.ref.WeakReference;
81import java.lang.reflect.InvocationTargetException;
82import java.lang.reflect.Method;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Locale;
86import java.util.concurrent.CopyOnWriteArrayList;
87
88/**
89 * <p>
90 * This class represents the basic building block for user interface components. A View
91 * occupies a rectangular area on the screen and is responsible for drawing and
92 * event handling. View is the base class for <em>widgets</em>, which are
93 * used to create interactive UI components (buttons, text fields, etc.). The
94 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
95 * are invisible containers that hold other Views (or other ViewGroups) and define
96 * their layout properties.
97 * </p>
98 *
99 * <div class="special reference">
100 * <h3>Developer Guides</h3>
101 * <p>For information about using this class to develop your application's user interface,
102 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
103 * </div>
104 *
105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
130 * Other view subclasses offer more specialized listeners. For example, a Button
131 * exposes a listener to notify clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility(int)}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 *     <thead>
153 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 *     </thead>
155 *
156 *     <tbody>
157 *     <tr>
158 *         <td rowspan="2">Creation</td>
159 *         <td>Constructors</td>
160 *         <td>There is a form of the constructor that are called when the view
161 *         is created from code and a form that is called when the view is
162 *         inflated from a layout file. The second form should parse and apply
163 *         any attributes defined in the layout file.
164 *         </td>
165 *     </tr>
166 *     <tr>
167 *         <td><code>{@link #onFinishInflate()}</code></td>
168 *         <td>Called after a view and all of its children has been inflated
169 *         from XML.</td>
170 *     </tr>
171 *
172 *     <tr>
173 *         <td rowspan="3">Layout</td>
174 *         <td><code>{@link #onMeasure(int, int)}</code></td>
175 *         <td>Called to determine the size requirements for this view and all
176 *         of its children.
177 *         </td>
178 *     </tr>
179 *     <tr>
180 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
181 *         <td>Called when this view should assign a size and position to all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
187 *         <td>Called when the size of this view has changed.
188 *         </td>
189 *     </tr>
190 *
191 *     <tr>
192 *         <td>Drawing</td>
193 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
194 *         <td>Called when the view should render its content.
195 *         </td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="4">Event processing</td>
200 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
201 *         <td>Called when a new key event occurs.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
206 *         <td>Called when a key up event occurs.
207 *         </td>
208 *     </tr>
209 *     <tr>
210 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
211 *         <td>Called when a trackball motion event occurs.
212 *         </td>
213 *     </tr>
214 *     <tr>
215 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
216 *         <td>Called when a touch screen motion event occurs.
217 *         </td>
218 *     </tr>
219 *
220 *     <tr>
221 *         <td rowspan="2">Focus</td>
222 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
223 *         <td>Called when the view gains or loses focus.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
229 *         <td>Called when the window containing the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td rowspan="3">Attaching</td>
235 *         <td><code>{@link #onAttachedToWindow()}</code></td>
236 *         <td>Called when the view is attached to a window.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td><code>{@link #onDetachedFromWindow}</code></td>
242 *         <td>Called when the view is detached from its window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
248 *         <td>Called when the visibility of the window containing the view
249 *         has changed.
250 *         </td>
251 *     </tr>
252 *     </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
265 * &lt;Button
266 *     android:id="@+id/my_button"
267 *     android:layout_width="wrap_content"
268 *     android:layout_height="wrap_content"
269 *     android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 *      Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} method and queried by calling
341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
343 * </p>
344 *
345 * <p>
346 * Even though a view can define a padding, it does not provide any support for
347 * margins. However, view groups provide such a support. Refer to
348 * {@link android.view.ViewGroup} and
349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
350 * </p>
351 *
352 * <a name="Layout"></a>
353 * <h3>Layout</h3>
354 * <p>
355 * Layout is a two pass process: a measure pass and a layout pass. The measuring
356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
357 * of the view tree. Each view pushes dimension specifications down the tree
358 * during the recursion. At the end of the measure pass, every view has stored
359 * its measurements. The second pass happens in
360 * {@link #layout(int,int,int,int)} and is also top-down. During
361 * this pass each parent is responsible for positioning all of its children
362 * using the sizes computed in the measure pass.
363 * </p>
364 *
365 * <p>
366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
367 * {@link #getMeasuredHeight()} values must be set, along with those for all of
368 * that view's descendants. A view's measured width and measured height values
369 * must respect the constraints imposed by the view's parents. This guarantees
370 * that at the end of the measure pass, all parents accept all of their
371 * children's measurements. A parent view may call measure() more than once on
372 * its children. For example, the parent may measure each child once with
373 * unspecified dimensions to find out how big they want to be, then call
374 * measure() on them again with actual numbers if the sum of all the children's
375 * unconstrained sizes is too big or too small.
376 * </p>
377 *
378 * <p>
379 * The measure pass uses two classes to communicate dimensions. The
380 * {@link MeasureSpec} class is used by views to tell their parents how they
381 * want to be measured and positioned. The base LayoutParams class just
382 * describes how big the view wants to be for both width and height. For each
383 * dimension, it can specify one of:
384 * <ul>
385 * <li> an exact number
386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
387 * (minus padding)
388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
389 * enclose its content (plus padding).
390 * </ul>
391 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
393 * an X and Y value.
394 * </p>
395 *
396 * <p>
397 * MeasureSpecs are used to push requirements down the tree from parent to
398 * child. A MeasureSpec can be in one of three modes:
399 * <ul>
400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
401 * of a child view. For example, a LinearLayout may call measure() on its child
402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
403 * tall the child view wants to be given a width of 240 pixels.
404 * <li>EXACTLY: This is used by the parent to impose an exact size on the
405 * child. The child must use this size, and guarantee that all of its
406 * descendants will fit within this size.
407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
408 * child. The child must gurantee that it and all of its descendants will fit
409 * within this size.
410 * </ul>
411 * </p>
412 *
413 * <p>
414 * To intiate a layout, call {@link #requestLayout}. This method is typically
415 * called by a view on itself when it believes that is can no longer fit within
416 * its current bounds.
417 * </p>
418 *
419 * <a name="Drawing"></a>
420 * <h3>Drawing</h3>
421 * <p>
422 * Drawing is handled by walking the tree and rendering each view that
423 * intersects the invalid region. Because the tree is traversed in-order,
424 * this means that parents will draw before (i.e., behind) their children, with
425 * siblings drawn in the order they appear in the tree.
426 * If you set a background drawable for a View, then the View will draw it for you
427 * before calling back to its <code>onDraw()</code> method.
428 * </p>
429 *
430 * <p>
431 * Note that the framework will not draw views that are not in the invalid region.
432 * </p>
433 *
434 * <p>
435 * To force a view to draw, call {@link #invalidate()}.
436 * </p>
437 *
438 * <a name="EventHandlingThreading"></a>
439 * <h3>Event Handling and Threading</h3>
440 * <p>
441 * The basic cycle of a view is as follows:
442 * <ol>
443 * <li>An event comes in and is dispatched to the appropriate view. The view
444 * handles the event and notifies any listeners.</li>
445 * <li>If in the course of processing the event, the view's bounds may need
446 * to be changed, the view will call {@link #requestLayout()}.</li>
447 * <li>Similarly, if in the course of processing the event the view's appearance
448 * may need to be changed, the view will call {@link #invalidate()}.</li>
449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
450 * the framework will take care of measuring, laying out, and drawing the tree
451 * as appropriate.</li>
452 * </ol>
453 * </p>
454 *
455 * <p><em>Note: The entire view tree is single threaded. You must always be on
456 * the UI thread when calling any method on any view.</em>
457 * If you are doing work on other threads and want to update the state of a view
458 * from that thread, you should use a {@link Handler}.
459 * </p>
460 *
461 * <a name="FocusHandling"></a>
462 * <h3>Focus Handling</h3>
463 * <p>
464 * The framework will handle routine focus movement in response to user input.
465 * This includes changing the focus as views are removed or hidden, or as new
466 * views become available. Views indicate their willingness to take focus
467 * through the {@link #isFocusable} method. To change whether a view can take
468 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
470 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
471 * </p>
472 * <p>
473 * Focus movement is based on an algorithm which finds the nearest neighbor in a
474 * given direction. In rare cases, the default algorithm may not match the
475 * intended behavior of the developer. In these situations, you can provide
476 * explicit overrides by using these XML attributes in the layout file:
477 * <pre>
478 * nextFocusDown
479 * nextFocusLeft
480 * nextFocusRight
481 * nextFocusUp
482 * </pre>
483 * </p>
484 *
485 *
486 * <p>
487 * To get a particular view to take focus, call {@link #requestFocus()}.
488 * </p>
489 *
490 * <a name="TouchMode"></a>
491 * <h3>Touch Mode</h3>
492 * <p>
493 * When a user is navigating a user interface via directional keys such as a D-pad, it is
494 * necessary to give focus to actionable items such as buttons so the user can see
495 * what will take input.  If the device has touch capabilities, however, and the user
496 * begins interacting with the interface by touching it, it is no longer necessary to
497 * always highlight, or give focus to, a particular view.  This motivates a mode
498 * for interaction named 'touch mode'.
499 * </p>
500 * <p>
501 * For a touch capable device, once the user touches the screen, the device
502 * will enter touch mode.  From this point onward, only views for which
503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
504 * Other views that are touchable, like buttons, will not take focus when touched; they will
505 * only fire the on click listeners.
506 * </p>
507 * <p>
508 * Any time a user hits a directional key, such as a D-pad direction, the view device will
509 * exit touch mode, and find a view to take focus, so that the user may resume interacting
510 * with the user interface without touching the screen again.
511 * </p>
512 * <p>
513 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
514 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
515 * </p>
516 *
517 * <a name="Scrolling"></a>
518 * <h3>Scrolling</h3>
519 * <p>
520 * The framework provides basic support for views that wish to internally
521 * scroll their content. This includes keeping track of the X and Y scroll
522 * offset as well as mechanisms for drawing scrollbars. See
523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
524 * {@link #awakenScrollBars()} for more details.
525 * </p>
526 *
527 * <a name="Tags"></a>
528 * <h3>Tags</h3>
529 * <p>
530 * Unlike IDs, tags are not used to identify views. Tags are essentially an
531 * extra piece of information that can be associated with a view. They are most
532 * often used as a convenience to store data related to views in the views
533 * themselves rather than by putting them in a separate structure.
534 * </p>
535 *
536 * <a name="Animation"></a>
537 * <h3>Animation</h3>
538 * <p>
539 * You can attach an {@link Animation} object to a view using
540 * {@link #setAnimation(Animation)} or
541 * {@link #startAnimation(Animation)}. The animation can alter the scale,
542 * rotation, translation and alpha of a view over time. If the animation is
543 * attached to a view that has children, the animation will affect the entire
544 * subtree rooted by that node. When an animation is started, the framework will
545 * take care of redrawing the appropriate views until the animation completes.
546 * </p>
547 * <p>
548 * Starting with Android 3.0, the preferred way of animating views is to use the
549 * {@link android.animation} package APIs.
550 * </p>
551 *
552 * <a name="Security"></a>
553 * <h3>Security</h3>
554 * <p>
555 * Sometimes it is essential that an application be able to verify that an action
556 * is being performed with the full knowledge and consent of the user, such as
557 * granting a permission request, making a purchase or clicking on an advertisement.
558 * Unfortunately, a malicious application could try to spoof the user into
559 * performing these actions, unaware, by concealing the intended purpose of the view.
560 * As a remedy, the framework offers a touch filtering mechanism that can be used to
561 * improve the security of views that provide access to sensitive functionality.
562 * </p><p>
563 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
564 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
565 * will discard touches that are received whenever the view's window is obscured by
566 * another visible window.  As a result, the view will not receive touches whenever a
567 * toast, dialog or other window appears above the view's window.
568 * </p><p>
569 * For more fine-grained control over security, consider overriding the
570 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
571 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
572 * </p>
573 *
574 * @attr ref android.R.styleable#View_alpha
575 * @attr ref android.R.styleable#View_background
576 * @attr ref android.R.styleable#View_clickable
577 * @attr ref android.R.styleable#View_contentDescription
578 * @attr ref android.R.styleable#View_drawingCacheQuality
579 * @attr ref android.R.styleable#View_duplicateParentState
580 * @attr ref android.R.styleable#View_id
581 * @attr ref android.R.styleable#View_requiresFadingEdge
582 * @attr ref android.R.styleable#View_fadingEdgeLength
583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
584 * @attr ref android.R.styleable#View_fitsSystemWindows
585 * @attr ref android.R.styleable#View_isScrollContainer
586 * @attr ref android.R.styleable#View_focusable
587 * @attr ref android.R.styleable#View_focusableInTouchMode
588 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
589 * @attr ref android.R.styleable#View_keepScreenOn
590 * @attr ref android.R.styleable#View_layerType
591 * @attr ref android.R.styleable#View_longClickable
592 * @attr ref android.R.styleable#View_minHeight
593 * @attr ref android.R.styleable#View_minWidth
594 * @attr ref android.R.styleable#View_nextFocusDown
595 * @attr ref android.R.styleable#View_nextFocusLeft
596 * @attr ref android.R.styleable#View_nextFocusRight
597 * @attr ref android.R.styleable#View_nextFocusUp
598 * @attr ref android.R.styleable#View_onClick
599 * @attr ref android.R.styleable#View_padding
600 * @attr ref android.R.styleable#View_paddingBottom
601 * @attr ref android.R.styleable#View_paddingLeft
602 * @attr ref android.R.styleable#View_paddingRight
603 * @attr ref android.R.styleable#View_paddingTop
604 * @attr ref android.R.styleable#View_saveEnabled
605 * @attr ref android.R.styleable#View_rotation
606 * @attr ref android.R.styleable#View_rotationX
607 * @attr ref android.R.styleable#View_rotationY
608 * @attr ref android.R.styleable#View_scaleX
609 * @attr ref android.R.styleable#View_scaleY
610 * @attr ref android.R.styleable#View_scrollX
611 * @attr ref android.R.styleable#View_scrollY
612 * @attr ref android.R.styleable#View_scrollbarSize
613 * @attr ref android.R.styleable#View_scrollbarStyle
614 * @attr ref android.R.styleable#View_scrollbars
615 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
616 * @attr ref android.R.styleable#View_scrollbarFadeDuration
617 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
618 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbVertical
620 * @attr ref android.R.styleable#View_scrollbarTrackVertical
621 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
623 * @attr ref android.R.styleable#View_soundEffectsEnabled
624 * @attr ref android.R.styleable#View_tag
625 * @attr ref android.R.styleable#View_transformPivotX
626 * @attr ref android.R.styleable#View_transformPivotY
627 * @attr ref android.R.styleable#View_translationX
628 * @attr ref android.R.styleable#View_translationY
629 * @attr ref android.R.styleable#View_visibility
630 *
631 * @see android.view.ViewGroup
632 */
633public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
634        AccessibilityEventSource {
635    private static final boolean DBG = false;
636
637    /**
638     * The logging tag used by this class with android.util.Log.
639     */
640    protected static final String VIEW_LOG_TAG = "View";
641
642    /**
643     * Used to mark a View that has no ID.
644     */
645    public static final int NO_ID = -1;
646
647    /**
648     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649     * calling setFlags.
650     */
651    private static final int NOT_FOCUSABLE = 0x00000000;
652
653    /**
654     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655     * setFlags.
656     */
657    private static final int FOCUSABLE = 0x00000001;
658
659    /**
660     * Mask for use with setFlags indicating bits used for focus.
661     */
662    private static final int FOCUSABLE_MASK = 0x00000001;
663
664    /**
665     * This view will adjust its padding to fit sytem windows (e.g. status bar)
666     */
667    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669    /**
670     * This view is visible.
671     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
672     * android:visibility}.
673     */
674    public static final int VISIBLE = 0x00000000;
675
676    /**
677     * This view is invisible, but it still takes up space for layout purposes.
678     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
679     * android:visibility}.
680     */
681    public static final int INVISIBLE = 0x00000004;
682
683    /**
684     * This view is invisible, and it doesn't take any space for layout
685     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
686     * android:visibility}.
687     */
688    public static final int GONE = 0x00000008;
689
690    /**
691     * Mask for use with setFlags indicating bits used for visibility.
692     * {@hide}
693     */
694    static final int VISIBILITY_MASK = 0x0000000C;
695
696    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
697
698    /**
699     * This view is enabled. Intrepretation varies by subclass.
700     * Use with ENABLED_MASK when calling setFlags.
701     * {@hide}
702     */
703    static final int ENABLED = 0x00000000;
704
705    /**
706     * This view is disabled. Intrepretation varies by subclass.
707     * Use with ENABLED_MASK when calling setFlags.
708     * {@hide}
709     */
710    static final int DISABLED = 0x00000020;
711
712   /**
713    * Mask for use with setFlags indicating bits used for indicating whether
714    * this view is enabled
715    * {@hide}
716    */
717    static final int ENABLED_MASK = 0x00000020;
718
719    /**
720     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
721     * called and further optimizations will be performed. It is okay to have
722     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
723     * {@hide}
724     */
725    static final int WILL_NOT_DRAW = 0x00000080;
726
727    /**
728     * Mask for use with setFlags indicating bits used for indicating whether
729     * this view is will draw
730     * {@hide}
731     */
732    static final int DRAW_MASK = 0x00000080;
733
734    /**
735     * <p>This view doesn't show scrollbars.</p>
736     * {@hide}
737     */
738    static final int SCROLLBARS_NONE = 0x00000000;
739
740    /**
741     * <p>This view shows horizontal scrollbars.</p>
742     * {@hide}
743     */
744    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
745
746    /**
747     * <p>This view shows vertical scrollbars.</p>
748     * {@hide}
749     */
750    static final int SCROLLBARS_VERTICAL = 0x00000200;
751
752    /**
753     * <p>Mask for use with setFlags indicating bits used for indicating which
754     * scrollbars are enabled.</p>
755     * {@hide}
756     */
757    static final int SCROLLBARS_MASK = 0x00000300;
758
759    /**
760     * Indicates that the view should filter touches when its window is obscured.
761     * Refer to the class comments for more information about this security feature.
762     * {@hide}
763     */
764    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
765
766    // note flag value 0x00000800 is now available for next flags...
767
768    /**
769     * <p>This view doesn't show fading edges.</p>
770     * {@hide}
771     */
772    static final int FADING_EDGE_NONE = 0x00000000;
773
774    /**
775     * <p>This view shows horizontal fading edges.</p>
776     * {@hide}
777     */
778    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
779
780    /**
781     * <p>This view shows vertical fading edges.</p>
782     * {@hide}
783     */
784    static final int FADING_EDGE_VERTICAL = 0x00002000;
785
786    /**
787     * <p>Mask for use with setFlags indicating bits used for indicating which
788     * fading edges are enabled.</p>
789     * {@hide}
790     */
791    static final int FADING_EDGE_MASK = 0x00003000;
792
793    /**
794     * <p>Indicates this view can be clicked. When clickable, a View reacts
795     * to clicks by notifying the OnClickListener.<p>
796     * {@hide}
797     */
798    static final int CLICKABLE = 0x00004000;
799
800    /**
801     * <p>Indicates this view is caching its drawing into a bitmap.</p>
802     * {@hide}
803     */
804    static final int DRAWING_CACHE_ENABLED = 0x00008000;
805
806    /**
807     * <p>Indicates that no icicle should be saved for this view.<p>
808     * {@hide}
809     */
810    static final int SAVE_DISABLED = 0x000010000;
811
812    /**
813     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
814     * property.</p>
815     * {@hide}
816     */
817    static final int SAVE_DISABLED_MASK = 0x000010000;
818
819    /**
820     * <p>Indicates that no drawing cache should ever be created for this view.<p>
821     * {@hide}
822     */
823    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
824
825    /**
826     * <p>Indicates this view can take / keep focus when int touch mode.</p>
827     * {@hide}
828     */
829    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
830
831    /**
832     * <p>Enables low quality mode for the drawing cache.</p>
833     */
834    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
835
836    /**
837     * <p>Enables high quality mode for the drawing cache.</p>
838     */
839    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
840
841    /**
842     * <p>Enables automatic quality mode for the drawing cache.</p>
843     */
844    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
845
846    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
847            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
848    };
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for the cache
852     * quality property.</p>
853     * {@hide}
854     */
855    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
856
857    /**
858     * <p>
859     * Indicates this view can be long clicked. When long clickable, a View
860     * reacts to long clicks by notifying the OnLongClickListener or showing a
861     * context menu.
862     * </p>
863     * {@hide}
864     */
865    static final int LONG_CLICKABLE = 0x00200000;
866
867    /**
868     * <p>Indicates that this view gets its drawable states from its direct parent
869     * and ignores its original internal states.</p>
870     *
871     * @hide
872     */
873    static final int DUPLICATE_PARENT_STATE = 0x00400000;
874
875    /**
876     * The scrollbar style to display the scrollbars inside the content area,
877     * without increasing the padding. The scrollbars will be overlaid with
878     * translucency on the view's content.
879     */
880    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
881
882    /**
883     * The scrollbar style to display the scrollbars inside the padded area,
884     * increasing the padding of the view. The scrollbars will not overlap the
885     * content area of the view.
886     */
887    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
888
889    /**
890     * The scrollbar style to display the scrollbars at the edge of the view,
891     * without increasing the padding. The scrollbars will be overlaid with
892     * translucency.
893     */
894    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
895
896    /**
897     * The scrollbar style to display the scrollbars at the edge of the view,
898     * increasing the padding of the view. The scrollbars will only overlap the
899     * background, if any.
900     */
901    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
902
903    /**
904     * Mask to check if the scrollbar style is overlay or inset.
905     * {@hide}
906     */
907    static final int SCROLLBARS_INSET_MASK = 0x01000000;
908
909    /**
910     * Mask to check if the scrollbar style is inside or outside.
911     * {@hide}
912     */
913    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
914
915    /**
916     * Mask for scrollbar style.
917     * {@hide}
918     */
919    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
920
921    /**
922     * View flag indicating that the screen should remain on while the
923     * window containing this view is visible to the user.  This effectively
924     * takes care of automatically setting the WindowManager's
925     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
926     */
927    public static final int KEEP_SCREEN_ON = 0x04000000;
928
929    /**
930     * View flag indicating whether this view should have sound effects enabled
931     * for events such as clicking and touching.
932     */
933    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
934
935    /**
936     * View flag indicating whether this view should have haptic feedback
937     * enabled for events such as long presses.
938     */
939    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
940
941    /**
942     * <p>Indicates that the view hierarchy should stop saving state when
943     * it reaches this view.  If state saving is initiated immediately at
944     * the view, it will be allowed.
945     * {@hide}
946     */
947    static final int PARENT_SAVE_DISABLED = 0x20000000;
948
949    /**
950     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
951     * {@hide}
952     */
953    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
954
955    /**
956     * Horizontal direction of this view is from Left to Right.
957     * Use with {@link #setLayoutDirection}.
958     * {@hide}
959     */
960    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
961
962    /**
963     * Horizontal direction of this view is from Right to Left.
964     * Use with {@link #setLayoutDirection}.
965     * {@hide}
966     */
967    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
968
969    /**
970     * Horizontal direction of this view is inherited from its parent.
971     * Use with {@link #setLayoutDirection}.
972     * {@hide}
973     */
974    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
975
976    /**
977     * Horizontal direction of this view is from deduced from the default language
978     * script for the locale. Use with {@link #setLayoutDirection}.
979     * {@hide}
980     */
981    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
982
983    /**
984     * Mask for use with setFlags indicating bits used for horizontalDirection.
985     * {@hide}
986     */
987    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
988
989    /*
990     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
991     * flag value.
992     * {@hide}
993     */
994    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
995        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
996
997    /**
998     * Default horizontalDirection.
999     * {@hide}
1000     */
1001    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1002
1003    /**
1004     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1005     * should add all focusable Views regardless if they are focusable in touch mode.
1006     */
1007    public static final int FOCUSABLES_ALL = 0x00000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add only Views focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1014
1015    /**
1016     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1017     * item.
1018     */
1019    public static final int FOCUS_BACKWARD = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1023     * item.
1024     */
1025    public static final int FOCUS_FORWARD = 0x00000002;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the left.
1029     */
1030    public static final int FOCUS_LEFT = 0x00000011;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus up.
1034     */
1035    public static final int FOCUS_UP = 0x00000021;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus to the right.
1039     */
1040    public static final int FOCUS_RIGHT = 0x00000042;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus down.
1044     */
1045    public static final int FOCUS_DOWN = 0x00000082;
1046
1047    /**
1048     * Bits of {@link #getMeasuredWidthAndState()} and
1049     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1050     */
1051    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1056     */
1057    public static final int MEASURED_STATE_MASK = 0xff000000;
1058
1059    /**
1060     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1061     * for functions that combine both width and height into a single int,
1062     * such as {@link #getMeasuredState()} and the childState argument of
1063     * {@link #resolveSizeAndState(int, int, int)}.
1064     */
1065    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1066
1067    /**
1068     * Bit of {@link #getMeasuredWidthAndState()} and
1069     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1070     * is smaller that the space the view would like to have.
1071     */
1072    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1073
1074    /**
1075     * Base View state sets
1076     */
1077    // Singles
1078    /**
1079     * Indicates the view has no states set. States are used with
1080     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1081     * view depending on its state.
1082     *
1083     * @see android.graphics.drawable.Drawable
1084     * @see #getDrawableState()
1085     */
1086    protected static final int[] EMPTY_STATE_SET;
1087    /**
1088     * Indicates the view is enabled. States are used with
1089     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1090     * view depending on its state.
1091     *
1092     * @see android.graphics.drawable.Drawable
1093     * @see #getDrawableState()
1094     */
1095    protected static final int[] ENABLED_STATE_SET;
1096    /**
1097     * Indicates the view is focused. States are used with
1098     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1099     * view depending on its state.
1100     *
1101     * @see android.graphics.drawable.Drawable
1102     * @see #getDrawableState()
1103     */
1104    protected static final int[] FOCUSED_STATE_SET;
1105    /**
1106     * Indicates the view is selected. States are used with
1107     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1108     * view depending on its state.
1109     *
1110     * @see android.graphics.drawable.Drawable
1111     * @see #getDrawableState()
1112     */
1113    protected static final int[] SELECTED_STATE_SET;
1114    /**
1115     * Indicates the view is pressed. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     * @hide
1122     */
1123    protected static final int[] PRESSED_STATE_SET;
1124    /**
1125     * Indicates the view's window has focus. States are used with
1126     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1127     * view depending on its state.
1128     *
1129     * @see android.graphics.drawable.Drawable
1130     * @see #getDrawableState()
1131     */
1132    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1133    // Doubles
1134    /**
1135     * Indicates the view is enabled and has the focus.
1136     *
1137     * @see #ENABLED_STATE_SET
1138     * @see #FOCUSED_STATE_SET
1139     */
1140    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1141    /**
1142     * Indicates the view is enabled and selected.
1143     *
1144     * @see #ENABLED_STATE_SET
1145     * @see #SELECTED_STATE_SET
1146     */
1147    protected static final int[] ENABLED_SELECTED_STATE_SET;
1148    /**
1149     * Indicates the view is enabled and that its window has focus.
1150     *
1151     * @see #ENABLED_STATE_SET
1152     * @see #WINDOW_FOCUSED_STATE_SET
1153     */
1154    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1155    /**
1156     * Indicates the view is focused and selected.
1157     *
1158     * @see #FOCUSED_STATE_SET
1159     * @see #SELECTED_STATE_SET
1160     */
1161    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1162    /**
1163     * Indicates the view has the focus and that its window has the focus.
1164     *
1165     * @see #FOCUSED_STATE_SET
1166     * @see #WINDOW_FOCUSED_STATE_SET
1167     */
1168    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1169    /**
1170     * Indicates the view is selected and that its window has the focus.
1171     *
1172     * @see #SELECTED_STATE_SET
1173     * @see #WINDOW_FOCUSED_STATE_SET
1174     */
1175    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1176    // Triples
1177    /**
1178     * Indicates the view is enabled, focused and selected.
1179     *
1180     * @see #ENABLED_STATE_SET
1181     * @see #FOCUSED_STATE_SET
1182     * @see #SELECTED_STATE_SET
1183     */
1184    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1185    /**
1186     * Indicates the view is enabled, focused and its window has the focus.
1187     *
1188     * @see #ENABLED_STATE_SET
1189     * @see #FOCUSED_STATE_SET
1190     * @see #WINDOW_FOCUSED_STATE_SET
1191     */
1192    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1193    /**
1194     * Indicates the view is enabled, selected and its window has the focus.
1195     *
1196     * @see #ENABLED_STATE_SET
1197     * @see #SELECTED_STATE_SET
1198     * @see #WINDOW_FOCUSED_STATE_SET
1199     */
1200    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is focused, selected and its window has the focus.
1203     *
1204     * @see #FOCUSED_STATE_SET
1205     * @see #SELECTED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is enabled, focused, selected and its window
1211     * has the focus.
1212     *
1213     * @see #ENABLED_STATE_SET
1214     * @see #FOCUSED_STATE_SET
1215     * @see #SELECTED_STATE_SET
1216     * @see #WINDOW_FOCUSED_STATE_SET
1217     */
1218    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1219    /**
1220     * Indicates the view is pressed and its window has the focus.
1221     *
1222     * @see #PRESSED_STATE_SET
1223     * @see #WINDOW_FOCUSED_STATE_SET
1224     */
1225    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1226    /**
1227     * Indicates the view is pressed and selected.
1228     *
1229     * @see #PRESSED_STATE_SET
1230     * @see #SELECTED_STATE_SET
1231     */
1232    protected static final int[] PRESSED_SELECTED_STATE_SET;
1233    /**
1234     * Indicates the view is pressed, selected and its window has the focus.
1235     *
1236     * @see #PRESSED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is pressed and focused.
1243     *
1244     * @see #PRESSED_STATE_SET
1245     * @see #FOCUSED_STATE_SET
1246     */
1247    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1248    /**
1249     * Indicates the view is pressed, focused and its window has the focus.
1250     *
1251     * @see #PRESSED_STATE_SET
1252     * @see #FOCUSED_STATE_SET
1253     * @see #WINDOW_FOCUSED_STATE_SET
1254     */
1255    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed, focused and selected.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #SELECTED_STATE_SET
1261     * @see #FOCUSED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, focused, selected and its window has the focus.
1266     *
1267     * @see #PRESSED_STATE_SET
1268     * @see #FOCUSED_STATE_SET
1269     * @see #SELECTED_STATE_SET
1270     * @see #WINDOW_FOCUSED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed and enabled.
1275     *
1276     * @see #PRESSED_STATE_SET
1277     * @see #ENABLED_STATE_SET
1278     */
1279    protected static final int[] PRESSED_ENABLED_STATE_SET;
1280    /**
1281     * Indicates the view is pressed, enabled and its window has the focus.
1282     *
1283     * @see #PRESSED_STATE_SET
1284     * @see #ENABLED_STATE_SET
1285     * @see #WINDOW_FOCUSED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, enabled and selected.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #ENABLED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, enabled, selected and its window has the
1298     * focus.
1299     *
1300     * @see #PRESSED_STATE_SET
1301     * @see #ENABLED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed, enabled and focused.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #ENABLED_STATE_SET
1311     * @see #FOCUSED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, enabled, focused and its window has the
1316     * focus.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #ENABLED_STATE_SET
1320     * @see #FOCUSED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled, focused and selected.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #SELECTED_STATE_SET
1330     * @see #FOCUSED_STATE_SET
1331     */
1332    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1333    /**
1334     * Indicates the view is pressed, enabled, focused, selected and its window
1335     * has the focus.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #ENABLED_STATE_SET
1339     * @see #SELECTED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     * @see #WINDOW_FOCUSED_STATE_SET
1342     */
1343    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1344
1345    /**
1346     * The order here is very important to {@link #getDrawableState()}
1347     */
1348    private static final int[][] VIEW_STATE_SETS;
1349
1350    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1351    static final int VIEW_STATE_SELECTED = 1 << 1;
1352    static final int VIEW_STATE_FOCUSED = 1 << 2;
1353    static final int VIEW_STATE_ENABLED = 1 << 3;
1354    static final int VIEW_STATE_PRESSED = 1 << 4;
1355    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1356    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1357    static final int VIEW_STATE_HOVERED = 1 << 7;
1358    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1359    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1360
1361    static final int[] VIEW_STATE_IDS = new int[] {
1362        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1363        R.attr.state_selected,          VIEW_STATE_SELECTED,
1364        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1365        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1366        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1367        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1368        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1369        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1370        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1371        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1372    };
1373
1374    static {
1375        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1376            throw new IllegalStateException(
1377                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1378        }
1379        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1380        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1381            int viewState = R.styleable.ViewDrawableStates[i];
1382            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1383                if (VIEW_STATE_IDS[j] == viewState) {
1384                    orderedIds[i * 2] = viewState;
1385                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1386                }
1387            }
1388        }
1389        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1390        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1391        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1392            int numBits = Integer.bitCount(i);
1393            int[] set = new int[numBits];
1394            int pos = 0;
1395            for (int j = 0; j < orderedIds.length; j += 2) {
1396                if ((i & orderedIds[j+1]) != 0) {
1397                    set[pos++] = orderedIds[j];
1398                }
1399            }
1400            VIEW_STATE_SETS[i] = set;
1401        }
1402
1403        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1404        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1405        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1406        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1408        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1409        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1411        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1413        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1415                | VIEW_STATE_FOCUSED];
1416        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1417        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1419        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1421        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1423                | VIEW_STATE_ENABLED];
1424        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1431                | VIEW_STATE_ENABLED];
1432        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1434                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1435
1436        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1437        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1439        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1441        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1443                | VIEW_STATE_PRESSED];
1444        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1451                | VIEW_STATE_PRESSED];
1452        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1454                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1455        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1462                | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1465                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1468                | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1472        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1474                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1475        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1477                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1478                | VIEW_STATE_PRESSED];
1479    }
1480
1481    /**
1482     * Accessibility event types that are dispatched for text population.
1483     */
1484    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1485            AccessibilityEvent.TYPE_VIEW_CLICKED
1486            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1487            | AccessibilityEvent.TYPE_VIEW_SELECTED
1488            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1489            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1490            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1491            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1492            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1493            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1494
1495    /**
1496     * Temporary Rect currently for use in setBackground().  This will probably
1497     * be extended in the future to hold our own class with more than just
1498     * a Rect. :)
1499     */
1500    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1501
1502    /**
1503     * Map used to store views' tags.
1504     */
1505    private SparseArray<Object> mKeyedTags;
1506
1507    /**
1508     * The next available accessiiblity id.
1509     */
1510    private static int sNextAccessibilityViewId;
1511
1512    /**
1513     * The animation currently associated with this view.
1514     * @hide
1515     */
1516    protected Animation mCurrentAnimation = null;
1517
1518    /**
1519     * Width as measured during measure pass.
1520     * {@hide}
1521     */
1522    @ViewDebug.ExportedProperty(category = "measurement")
1523    int mMeasuredWidth;
1524
1525    /**
1526     * Height as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredHeight;
1531
1532    /**
1533     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1534     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1535     * its display list. This flag, used only when hw accelerated, allows us to clear the
1536     * flag while retaining this information until it's needed (at getDisplayList() time and
1537     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1538     *
1539     * {@hide}
1540     */
1541    boolean mRecreateDisplayList = false;
1542
1543    /**
1544     * The view's identifier.
1545     * {@hide}
1546     *
1547     * @see #setId(int)
1548     * @see #getId()
1549     */
1550    @ViewDebug.ExportedProperty(resolveId = true)
1551    int mID = NO_ID;
1552
1553    /**
1554     * The stable ID of this view for accessibility purposes.
1555     */
1556    int mAccessibilityViewId = NO_ID;
1557
1558    /**
1559     * The view's tag.
1560     * {@hide}
1561     *
1562     * @see #setTag(Object)
1563     * @see #getTag()
1564     */
1565    protected Object mTag;
1566
1567    // for mPrivateFlags:
1568    /** {@hide} */
1569    static final int WANTS_FOCUS                    = 0x00000001;
1570    /** {@hide} */
1571    static final int FOCUSED                        = 0x00000002;
1572    /** {@hide} */
1573    static final int SELECTED                       = 0x00000004;
1574    /** {@hide} */
1575    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1576    /** {@hide} */
1577    static final int HAS_BOUNDS                     = 0x00000010;
1578    /** {@hide} */
1579    static final int DRAWN                          = 0x00000020;
1580    /**
1581     * When this flag is set, this view is running an animation on behalf of its
1582     * children and should therefore not cancel invalidate requests, even if they
1583     * lie outside of this view's bounds.
1584     *
1585     * {@hide}
1586     */
1587    static final int DRAW_ANIMATION                 = 0x00000040;
1588    /** {@hide} */
1589    static final int SKIP_DRAW                      = 0x00000080;
1590    /** {@hide} */
1591    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1592    /** {@hide} */
1593    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1594    /** {@hide} */
1595    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1596    /** {@hide} */
1597    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1598    /** {@hide} */
1599    static final int FORCE_LAYOUT                   = 0x00001000;
1600    /** {@hide} */
1601    static final int LAYOUT_REQUIRED                = 0x00002000;
1602
1603    private static final int PRESSED                = 0x00004000;
1604
1605    /** {@hide} */
1606    static final int DRAWING_CACHE_VALID            = 0x00008000;
1607    /**
1608     * Flag used to indicate that this view should be drawn once more (and only once
1609     * more) after its animation has completed.
1610     * {@hide}
1611     */
1612    static final int ANIMATION_STARTED              = 0x00010000;
1613
1614    private static final int SAVE_STATE_CALLED      = 0x00020000;
1615
1616    /**
1617     * Indicates that the View returned true when onSetAlpha() was called and that
1618     * the alpha must be restored.
1619     * {@hide}
1620     */
1621    static final int ALPHA_SET                      = 0x00040000;
1622
1623    /**
1624     * Set by {@link #setScrollContainer(boolean)}.
1625     */
1626    static final int SCROLL_CONTAINER               = 0x00080000;
1627
1628    /**
1629     * Set by {@link #setScrollContainer(boolean)}.
1630     */
1631    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1632
1633    /**
1634     * View flag indicating whether this view was invalidated (fully or partially.)
1635     *
1636     * @hide
1637     */
1638    static final int DIRTY                          = 0x00200000;
1639
1640    /**
1641     * View flag indicating whether this view was invalidated by an opaque
1642     * invalidate request.
1643     *
1644     * @hide
1645     */
1646    static final int DIRTY_OPAQUE                   = 0x00400000;
1647
1648    /**
1649     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1650     *
1651     * @hide
1652     */
1653    static final int DIRTY_MASK                     = 0x00600000;
1654
1655    /**
1656     * Indicates whether the background is opaque.
1657     *
1658     * @hide
1659     */
1660    static final int OPAQUE_BACKGROUND              = 0x00800000;
1661
1662    /**
1663     * Indicates whether the scrollbars are opaque.
1664     *
1665     * @hide
1666     */
1667    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1668
1669    /**
1670     * Indicates whether the view is opaque.
1671     *
1672     * @hide
1673     */
1674    static final int OPAQUE_MASK                    = 0x01800000;
1675
1676    /**
1677     * Indicates a prepressed state;
1678     * the short time between ACTION_DOWN and recognizing
1679     * a 'real' press. Prepressed is used to recognize quick taps
1680     * even when they are shorter than ViewConfiguration.getTapTimeout().
1681     *
1682     * @hide
1683     */
1684    private static final int PREPRESSED             = 0x02000000;
1685
1686    /**
1687     * Indicates whether the view is temporarily detached.
1688     *
1689     * @hide
1690     */
1691    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1692
1693    /**
1694     * Indicates that we should awaken scroll bars once attached
1695     *
1696     * @hide
1697     */
1698    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1699
1700    /**
1701     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1702     * @hide
1703     */
1704    private static final int HOVERED              = 0x10000000;
1705
1706    /**
1707     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1708     * for transform operations
1709     *
1710     * @hide
1711     */
1712    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1713
1714    /** {@hide} */
1715    static final int ACTIVATED                    = 0x40000000;
1716
1717    /**
1718     * Indicates that this view was specifically invalidated, not just dirtied because some
1719     * child view was invalidated. The flag is used to determine when we need to recreate
1720     * a view's display list (as opposed to just returning a reference to its existing
1721     * display list).
1722     *
1723     * @hide
1724     */
1725    static final int INVALIDATED                  = 0x80000000;
1726
1727    /* Masks for mPrivateFlags2 */
1728
1729    /**
1730     * Indicates that this view has reported that it can accept the current drag's content.
1731     * Cleared when the drag operation concludes.
1732     * @hide
1733     */
1734    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1735
1736    /**
1737     * Indicates that this view is currently directly under the drag location in a
1738     * drag-and-drop operation involving content that it can accept.  Cleared when
1739     * the drag exits the view, or when the drag operation concludes.
1740     * @hide
1741     */
1742    static final int DRAG_HOVERED                 = 0x00000002;
1743
1744    /**
1745     * Indicates whether the view layout direction has been resolved and drawn to the
1746     * right-to-left direction.
1747     *
1748     * @hide
1749     */
1750    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1751
1752    /**
1753     * Indicates whether the view layout direction has been resolved.
1754     *
1755     * @hide
1756     */
1757    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1758
1759
1760    /* End of masks for mPrivateFlags2 */
1761
1762    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1763
1764    /**
1765     * Always allow a user to over-scroll this view, provided it is a
1766     * view that can scroll.
1767     *
1768     * @see #getOverScrollMode()
1769     * @see #setOverScrollMode(int)
1770     */
1771    public static final int OVER_SCROLL_ALWAYS = 0;
1772
1773    /**
1774     * Allow a user to over-scroll this view only if the content is large
1775     * enough to meaningfully scroll, provided it is a view that can scroll.
1776     *
1777     * @see #getOverScrollMode()
1778     * @see #setOverScrollMode(int)
1779     */
1780    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1781
1782    /**
1783     * Never allow a user to over-scroll this view.
1784     *
1785     * @see #getOverScrollMode()
1786     * @see #setOverScrollMode(int)
1787     */
1788    public static final int OVER_SCROLL_NEVER = 2;
1789
1790    /**
1791     * View has requested the system UI (status bar) to be visible (the default).
1792     *
1793     * @see #setSystemUiVisibility(int)
1794     */
1795    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1796
1797    /**
1798     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1799     *
1800     * This is for use in games, book readers, video players, or any other "immersive" application
1801     * where the usual system chrome is deemed too distracting.
1802     *
1803     * In low profile mode, the status bar and/or navigation icons may dim.
1804     *
1805     * @see #setSystemUiVisibility(int)
1806     */
1807    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1808
1809    /**
1810     * View has requested that the system navigation be temporarily hidden.
1811     *
1812     * This is an even less obtrusive state than that called for by
1813     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1814     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1815     * those to disappear. This is useful (in conjunction with the
1816     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1817     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1818     * window flags) for displaying content using every last pixel on the display.
1819     *
1820     * There is a limitation: because navigation controls are so important, the least user
1821     * interaction will cause them to reappear immediately.
1822     *
1823     * @see #setSystemUiVisibility(int)
1824     */
1825    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1826
1827    /**
1828     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1829     */
1830    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1831
1832    /**
1833     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1834     */
1835    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1836
1837    /**
1838     * @hide
1839     *
1840     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1841     * out of the public fields to keep the undefined bits out of the developer's way.
1842     *
1843     * Flag to make the status bar not expandable.  Unless you also
1844     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1845     */
1846    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1847
1848    /**
1849     * @hide
1850     *
1851     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1852     * out of the public fields to keep the undefined bits out of the developer's way.
1853     *
1854     * Flag to hide notification icons and scrolling ticker text.
1855     */
1856    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1857
1858    /**
1859     * @hide
1860     *
1861     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1862     * out of the public fields to keep the undefined bits out of the developer's way.
1863     *
1864     * Flag to disable incoming notification alerts.  This will not block
1865     * icons, but it will block sound, vibrating and other visual or aural notifications.
1866     */
1867    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1868
1869    /**
1870     * @hide
1871     *
1872     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1873     * out of the public fields to keep the undefined bits out of the developer's way.
1874     *
1875     * Flag to hide only the scrolling ticker.  Note that
1876     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1877     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1878     */
1879    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1880
1881    /**
1882     * @hide
1883     *
1884     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1885     * out of the public fields to keep the undefined bits out of the developer's way.
1886     *
1887     * Flag to hide the center system info area.
1888     */
1889    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1890
1891    /**
1892     * @hide
1893     *
1894     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1895     * out of the public fields to keep the undefined bits out of the developer's way.
1896     *
1897     * Flag to hide only the home button.  Don't use this
1898     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1899     */
1900    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
1901
1902    /**
1903     * @hide
1904     *
1905     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1906     * out of the public fields to keep the undefined bits out of the developer's way.
1907     *
1908     * Flag to hide only the back button. Don't use this
1909     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1910     */
1911    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1912
1913    /**
1914     * @hide
1915     *
1916     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1917     * out of the public fields to keep the undefined bits out of the developer's way.
1918     *
1919     * Flag to hide only the clock.  You might use this if your activity has
1920     * its own clock making the status bar's clock redundant.
1921     */
1922    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1923
1924    /**
1925     * @hide
1926     *
1927     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1928     * out of the public fields to keep the undefined bits out of the developer's way.
1929     *
1930     * Flag to hide only the recent apps button. Don't use this
1931     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1932     */
1933    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
1934
1935    /**
1936     * @hide
1937     *
1938     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
1939     *
1940     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
1941     */
1942    @Deprecated
1943    public static final int STATUS_BAR_DISABLE_NAVIGATION =
1944            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
1945
1946    /**
1947     * @hide
1948     */
1949    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1950
1951    /**
1952     * These are the system UI flags that can be cleared by events outside
1953     * of an application.  Currently this is just the ability to tap on the
1954     * screen while hiding the navigation bar to have it return.
1955     * @hide
1956     */
1957    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1958            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1959
1960    /**
1961     * Find views that render the specified text.
1962     *
1963     * @see #findViewsWithText(ArrayList, CharSequence, int)
1964     */
1965    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1966
1967    /**
1968     * Find find views that contain the specified content description.
1969     *
1970     * @see #findViewsWithText(ArrayList, CharSequence, int)
1971     */
1972    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1973
1974    /**
1975     * Find views that contain {@link AccessibilityNodeProvider}. Such
1976     * a View is a root of virtual view hierarchy and may contain the searched
1977     * text. If this flag is set Views with providers are automatically
1978     * added and it is a responsibility of the client to call the APIs of
1979     * the provider to determine whether the virtual tree rooted at this View
1980     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
1981     * represeting the virtual views with this text.
1982     *
1983     * @see #findViewsWithText(ArrayList, CharSequence, int)
1984     *
1985     * @hide
1986     */
1987    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
1988
1989    /**
1990     * Controls the over-scroll mode for this view.
1991     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1992     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1993     * and {@link #OVER_SCROLL_NEVER}.
1994     */
1995    private int mOverScrollMode;
1996
1997    /**
1998     * The parent this view is attached to.
1999     * {@hide}
2000     *
2001     * @see #getParent()
2002     */
2003    protected ViewParent mParent;
2004
2005    /**
2006     * {@hide}
2007     */
2008    AttachInfo mAttachInfo;
2009
2010    /**
2011     * {@hide}
2012     */
2013    @ViewDebug.ExportedProperty(flagMapping = {
2014        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2015                name = "FORCE_LAYOUT"),
2016        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2017                name = "LAYOUT_REQUIRED"),
2018        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2019            name = "DRAWING_CACHE_INVALID", outputIf = false),
2020        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2021        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2022        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2023        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2024    })
2025    int mPrivateFlags;
2026    int mPrivateFlags2;
2027
2028    /**
2029     * This view's request for the visibility of the status bar.
2030     * @hide
2031     */
2032    @ViewDebug.ExportedProperty(flagMapping = {
2033        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2034                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2035                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2036        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2037                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2038                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2039        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2040                                equals = SYSTEM_UI_FLAG_VISIBLE,
2041                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2042    })
2043    int mSystemUiVisibility;
2044
2045    /**
2046     * Count of how many windows this view has been attached to.
2047     */
2048    int mWindowAttachCount;
2049
2050    /**
2051     * The layout parameters associated with this view and used by the parent
2052     * {@link android.view.ViewGroup} to determine how this view should be
2053     * laid out.
2054     * {@hide}
2055     */
2056    protected ViewGroup.LayoutParams mLayoutParams;
2057
2058    /**
2059     * The view flags hold various views states.
2060     * {@hide}
2061     */
2062    @ViewDebug.ExportedProperty
2063    int mViewFlags;
2064
2065    static class TransformationInfo {
2066        /**
2067         * The transform matrix for the View. This transform is calculated internally
2068         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2069         * is used by default. Do *not* use this variable directly; instead call
2070         * getMatrix(), which will automatically recalculate the matrix if necessary
2071         * to get the correct matrix based on the latest rotation and scale properties.
2072         */
2073        private final Matrix mMatrix = new Matrix();
2074
2075        /**
2076         * The transform matrix for the View. This transform is calculated internally
2077         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2078         * is used by default. Do *not* use this variable directly; instead call
2079         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2080         * to get the correct matrix based on the latest rotation and scale properties.
2081         */
2082        private Matrix mInverseMatrix;
2083
2084        /**
2085         * An internal variable that tracks whether we need to recalculate the
2086         * transform matrix, based on whether the rotation or scaleX/Y properties
2087         * have changed since the matrix was last calculated.
2088         */
2089        boolean mMatrixDirty = false;
2090
2091        /**
2092         * An internal variable that tracks whether we need to recalculate the
2093         * transform matrix, based on whether the rotation or scaleX/Y properties
2094         * have changed since the matrix was last calculated.
2095         */
2096        private boolean mInverseMatrixDirty = true;
2097
2098        /**
2099         * A variable that tracks whether we need to recalculate the
2100         * transform matrix, based on whether the rotation or scaleX/Y properties
2101         * have changed since the matrix was last calculated. This variable
2102         * is only valid after a call to updateMatrix() or to a function that
2103         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2104         */
2105        private boolean mMatrixIsIdentity = true;
2106
2107        /**
2108         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2109         */
2110        private Camera mCamera = null;
2111
2112        /**
2113         * This matrix is used when computing the matrix for 3D rotations.
2114         */
2115        private Matrix matrix3D = null;
2116
2117        /**
2118         * These prev values are used to recalculate a centered pivot point when necessary. The
2119         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2120         * set), so thes values are only used then as well.
2121         */
2122        private int mPrevWidth = -1;
2123        private int mPrevHeight = -1;
2124
2125        /**
2126         * The degrees rotation around the vertical axis through the pivot point.
2127         */
2128        @ViewDebug.ExportedProperty
2129        float mRotationY = 0f;
2130
2131        /**
2132         * The degrees rotation around the horizontal axis through the pivot point.
2133         */
2134        @ViewDebug.ExportedProperty
2135        float mRotationX = 0f;
2136
2137        /**
2138         * The degrees rotation around the pivot point.
2139         */
2140        @ViewDebug.ExportedProperty
2141        float mRotation = 0f;
2142
2143        /**
2144         * The amount of translation of the object away from its left property (post-layout).
2145         */
2146        @ViewDebug.ExportedProperty
2147        float mTranslationX = 0f;
2148
2149        /**
2150         * The amount of translation of the object away from its top property (post-layout).
2151         */
2152        @ViewDebug.ExportedProperty
2153        float mTranslationY = 0f;
2154
2155        /**
2156         * The amount of scale in the x direction around the pivot point. A
2157         * value of 1 means no scaling is applied.
2158         */
2159        @ViewDebug.ExportedProperty
2160        float mScaleX = 1f;
2161
2162        /**
2163         * The amount of scale in the y direction around the pivot point. A
2164         * value of 1 means no scaling is applied.
2165         */
2166        @ViewDebug.ExportedProperty
2167        float mScaleY = 1f;
2168
2169        /**
2170         * The x location of the point around which the view is rotated and scaled.
2171         */
2172        @ViewDebug.ExportedProperty
2173        float mPivotX = 0f;
2174
2175        /**
2176         * The y location of the point around which the view is rotated and scaled.
2177         */
2178        @ViewDebug.ExportedProperty
2179        float mPivotY = 0f;
2180
2181        /**
2182         * The opacity of the View. This is a value from 0 to 1, where 0 means
2183         * completely transparent and 1 means completely opaque.
2184         */
2185        @ViewDebug.ExportedProperty
2186        float mAlpha = 1f;
2187    }
2188
2189    TransformationInfo mTransformationInfo;
2190
2191    private boolean mLastIsOpaque;
2192
2193    /**
2194     * Convenience value to check for float values that are close enough to zero to be considered
2195     * zero.
2196     */
2197    private static final float NONZERO_EPSILON = .001f;
2198
2199    /**
2200     * The distance in pixels from the left edge of this view's parent
2201     * to the left edge of this view.
2202     * {@hide}
2203     */
2204    @ViewDebug.ExportedProperty(category = "layout")
2205    protected int mLeft;
2206    /**
2207     * The distance in pixels from the left edge of this view's parent
2208     * to the right edge of this view.
2209     * {@hide}
2210     */
2211    @ViewDebug.ExportedProperty(category = "layout")
2212    protected int mRight;
2213    /**
2214     * The distance in pixels from the top edge of this view's parent
2215     * to the top edge of this view.
2216     * {@hide}
2217     */
2218    @ViewDebug.ExportedProperty(category = "layout")
2219    protected int mTop;
2220    /**
2221     * The distance in pixels from the top edge of this view's parent
2222     * to the bottom edge of this view.
2223     * {@hide}
2224     */
2225    @ViewDebug.ExportedProperty(category = "layout")
2226    protected int mBottom;
2227
2228    /**
2229     * The offset, in pixels, by which the content of this view is scrolled
2230     * horizontally.
2231     * {@hide}
2232     */
2233    @ViewDebug.ExportedProperty(category = "scrolling")
2234    protected int mScrollX;
2235    /**
2236     * The offset, in pixels, by which the content of this view is scrolled
2237     * vertically.
2238     * {@hide}
2239     */
2240    @ViewDebug.ExportedProperty(category = "scrolling")
2241    protected int mScrollY;
2242
2243    /**
2244     * The left padding in pixels, that is the distance in pixels between the
2245     * left edge of this view and the left edge of its content.
2246     * {@hide}
2247     */
2248    @ViewDebug.ExportedProperty(category = "padding")
2249    protected int mPaddingLeft;
2250    /**
2251     * The right padding in pixels, that is the distance in pixels between the
2252     * right edge of this view and the right edge of its content.
2253     * {@hide}
2254     */
2255    @ViewDebug.ExportedProperty(category = "padding")
2256    protected int mPaddingRight;
2257    /**
2258     * The top padding in pixels, that is the distance in pixels between the
2259     * top edge of this view and the top edge of its content.
2260     * {@hide}
2261     */
2262    @ViewDebug.ExportedProperty(category = "padding")
2263    protected int mPaddingTop;
2264    /**
2265     * The bottom padding in pixels, that is the distance in pixels between the
2266     * bottom edge of this view and the bottom edge of its content.
2267     * {@hide}
2268     */
2269    @ViewDebug.ExportedProperty(category = "padding")
2270    protected int mPaddingBottom;
2271
2272    /**
2273     * Briefly describes the view and is primarily used for accessibility support.
2274     */
2275    private CharSequence mContentDescription;
2276
2277    /**
2278     * Cache the paddingRight set by the user to append to the scrollbar's size.
2279     *
2280     * @hide
2281     */
2282    @ViewDebug.ExportedProperty(category = "padding")
2283    protected int mUserPaddingRight;
2284
2285    /**
2286     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2287     *
2288     * @hide
2289     */
2290    @ViewDebug.ExportedProperty(category = "padding")
2291    protected int mUserPaddingBottom;
2292
2293    /**
2294     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2295     *
2296     * @hide
2297     */
2298    @ViewDebug.ExportedProperty(category = "padding")
2299    protected int mUserPaddingLeft;
2300
2301    /**
2302     * Cache if the user padding is relative.
2303     *
2304     */
2305    @ViewDebug.ExportedProperty(category = "padding")
2306    boolean mUserPaddingRelative;
2307
2308    /**
2309     * Cache the paddingStart set by the user to append to the scrollbar's size.
2310     *
2311     */
2312    @ViewDebug.ExportedProperty(category = "padding")
2313    int mUserPaddingStart;
2314
2315    /**
2316     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2317     *
2318     */
2319    @ViewDebug.ExportedProperty(category = "padding")
2320    int mUserPaddingEnd;
2321
2322    /**
2323     * @hide
2324     */
2325    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2326    /**
2327     * @hide
2328     */
2329    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2330
2331    private Drawable mBGDrawable;
2332
2333    private int mBackgroundResource;
2334    private boolean mBackgroundSizeChanged;
2335
2336    static class ListenerInfo {
2337        /**
2338         * Listener used to dispatch focus change events.
2339         * This field should be made private, so it is hidden from the SDK.
2340         * {@hide}
2341         */
2342        protected OnFocusChangeListener mOnFocusChangeListener;
2343
2344        /**
2345         * Listeners for layout change events.
2346         */
2347        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2348
2349        /**
2350         * Listeners for attach events.
2351         */
2352        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2353
2354        /**
2355         * Listener used to dispatch click events.
2356         * This field should be made private, so it is hidden from the SDK.
2357         * {@hide}
2358         */
2359        public OnClickListener mOnClickListener;
2360
2361        /**
2362         * Listener used to dispatch long click events.
2363         * This field should be made private, so it is hidden from the SDK.
2364         * {@hide}
2365         */
2366        protected OnLongClickListener mOnLongClickListener;
2367
2368        /**
2369         * Listener used to build the context menu.
2370         * This field should be made private, so it is hidden from the SDK.
2371         * {@hide}
2372         */
2373        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2374
2375        private OnKeyListener mOnKeyListener;
2376
2377        private OnTouchListener mOnTouchListener;
2378
2379        private OnHoverListener mOnHoverListener;
2380
2381        private OnGenericMotionListener mOnGenericMotionListener;
2382
2383        private OnDragListener mOnDragListener;
2384
2385        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2386    }
2387
2388    ListenerInfo mListenerInfo;
2389
2390    /**
2391     * The application environment this view lives in.
2392     * This field should be made private, so it is hidden from the SDK.
2393     * {@hide}
2394     */
2395    protected Context mContext;
2396
2397    private final Resources mResources;
2398
2399    private ScrollabilityCache mScrollCache;
2400
2401    private int[] mDrawableState = null;
2402
2403    /**
2404     * Set to true when drawing cache is enabled and cannot be created.
2405     *
2406     * @hide
2407     */
2408    public boolean mCachingFailed;
2409
2410    private Bitmap mDrawingCache;
2411    private Bitmap mUnscaledDrawingCache;
2412    private HardwareLayer mHardwareLayer;
2413    DisplayList mDisplayList;
2414
2415    /**
2416     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2417     * the user may specify which view to go to next.
2418     */
2419    private int mNextFocusLeftId = View.NO_ID;
2420
2421    /**
2422     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2423     * the user may specify which view to go to next.
2424     */
2425    private int mNextFocusRightId = View.NO_ID;
2426
2427    /**
2428     * When this view has focus and the next focus is {@link #FOCUS_UP},
2429     * the user may specify which view to go to next.
2430     */
2431    private int mNextFocusUpId = View.NO_ID;
2432
2433    /**
2434     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2435     * the user may specify which view to go to next.
2436     */
2437    private int mNextFocusDownId = View.NO_ID;
2438
2439    /**
2440     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2441     * the user may specify which view to go to next.
2442     */
2443    int mNextFocusForwardId = View.NO_ID;
2444
2445    private CheckForLongPress mPendingCheckForLongPress;
2446    private CheckForTap mPendingCheckForTap = null;
2447    private PerformClick mPerformClick;
2448    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2449
2450    private UnsetPressedState mUnsetPressedState;
2451
2452    /**
2453     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2454     * up event while a long press is invoked as soon as the long press duration is reached, so
2455     * a long press could be performed before the tap is checked, in which case the tap's action
2456     * should not be invoked.
2457     */
2458    private boolean mHasPerformedLongPress;
2459
2460    /**
2461     * The minimum height of the view. We'll try our best to have the height
2462     * of this view to at least this amount.
2463     */
2464    @ViewDebug.ExportedProperty(category = "measurement")
2465    private int mMinHeight;
2466
2467    /**
2468     * The minimum width of the view. We'll try our best to have the width
2469     * of this view to at least this amount.
2470     */
2471    @ViewDebug.ExportedProperty(category = "measurement")
2472    private int mMinWidth;
2473
2474    /**
2475     * The delegate to handle touch events that are physically in this view
2476     * but should be handled by another view.
2477     */
2478    private TouchDelegate mTouchDelegate = null;
2479
2480    /**
2481     * Solid color to use as a background when creating the drawing cache. Enables
2482     * the cache to use 16 bit bitmaps instead of 32 bit.
2483     */
2484    private int mDrawingCacheBackgroundColor = 0;
2485
2486    /**
2487     * Special tree observer used when mAttachInfo is null.
2488     */
2489    private ViewTreeObserver mFloatingTreeObserver;
2490
2491    /**
2492     * Cache the touch slop from the context that created the view.
2493     */
2494    private int mTouchSlop;
2495
2496    /**
2497     * Object that handles automatic animation of view properties.
2498     */
2499    private ViewPropertyAnimator mAnimator = null;
2500
2501    /**
2502     * Flag indicating that a drag can cross window boundaries.  When
2503     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2504     * with this flag set, all visible applications will be able to participate
2505     * in the drag operation and receive the dragged content.
2506     *
2507     * @hide
2508     */
2509    public static final int DRAG_FLAG_GLOBAL = 1;
2510
2511    /**
2512     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2513     */
2514    private float mVerticalScrollFactor;
2515
2516    /**
2517     * Position of the vertical scroll bar.
2518     */
2519    private int mVerticalScrollbarPosition;
2520
2521    /**
2522     * Position the scroll bar at the default position as determined by the system.
2523     */
2524    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2525
2526    /**
2527     * Position the scroll bar along the left edge.
2528     */
2529    public static final int SCROLLBAR_POSITION_LEFT = 1;
2530
2531    /**
2532     * Position the scroll bar along the right edge.
2533     */
2534    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2535
2536    /**
2537     * Indicates that the view does not have a layer.
2538     *
2539     * @see #getLayerType()
2540     * @see #setLayerType(int, android.graphics.Paint)
2541     * @see #LAYER_TYPE_SOFTWARE
2542     * @see #LAYER_TYPE_HARDWARE
2543     */
2544    public static final int LAYER_TYPE_NONE = 0;
2545
2546    /**
2547     * <p>Indicates that the view has a software layer. A software layer is backed
2548     * by a bitmap and causes the view to be rendered using Android's software
2549     * rendering pipeline, even if hardware acceleration is enabled.</p>
2550     *
2551     * <p>Software layers have various usages:</p>
2552     * <p>When the application is not using hardware acceleration, a software layer
2553     * is useful to apply a specific color filter and/or blending mode and/or
2554     * translucency to a view and all its children.</p>
2555     * <p>When the application is using hardware acceleration, a software layer
2556     * is useful to render drawing primitives not supported by the hardware
2557     * accelerated pipeline. It can also be used to cache a complex view tree
2558     * into a texture and reduce the complexity of drawing operations. For instance,
2559     * when animating a complex view tree with a translation, a software layer can
2560     * be used to render the view tree only once.</p>
2561     * <p>Software layers should be avoided when the affected view tree updates
2562     * often. Every update will require to re-render the software layer, which can
2563     * potentially be slow (particularly when hardware acceleration is turned on
2564     * since the layer will have to be uploaded into a hardware texture after every
2565     * update.)</p>
2566     *
2567     * @see #getLayerType()
2568     * @see #setLayerType(int, android.graphics.Paint)
2569     * @see #LAYER_TYPE_NONE
2570     * @see #LAYER_TYPE_HARDWARE
2571     */
2572    public static final int LAYER_TYPE_SOFTWARE = 1;
2573
2574    /**
2575     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2576     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2577     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2578     * rendering pipeline, but only if hardware acceleration is turned on for the
2579     * view hierarchy. When hardware acceleration is turned off, hardware layers
2580     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2581     *
2582     * <p>A hardware layer is useful to apply a specific color filter and/or
2583     * blending mode and/or translucency to a view and all its children.</p>
2584     * <p>A hardware layer can be used to cache a complex view tree into a
2585     * texture and reduce the complexity of drawing operations. For instance,
2586     * when animating a complex view tree with a translation, a hardware layer can
2587     * be used to render the view tree only once.</p>
2588     * <p>A hardware layer can also be used to increase the rendering quality when
2589     * rotation transformations are applied on a view. It can also be used to
2590     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2591     *
2592     * @see #getLayerType()
2593     * @see #setLayerType(int, android.graphics.Paint)
2594     * @see #LAYER_TYPE_NONE
2595     * @see #LAYER_TYPE_SOFTWARE
2596     */
2597    public static final int LAYER_TYPE_HARDWARE = 2;
2598
2599    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2600            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2601            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2602            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2603    })
2604    int mLayerType = LAYER_TYPE_NONE;
2605    Paint mLayerPaint;
2606    Rect mLocalDirtyRect;
2607
2608    /**
2609     * Set to true when the view is sending hover accessibility events because it
2610     * is the innermost hovered view.
2611     */
2612    private boolean mSendingHoverAccessibilityEvents;
2613
2614    /**
2615     * Delegate for injecting accessiblity functionality.
2616     */
2617    AccessibilityDelegate mAccessibilityDelegate;
2618
2619    /**
2620     * Text direction is inherited thru {@link ViewGroup}
2621     */
2622    public static final int TEXT_DIRECTION_INHERIT = 0;
2623
2624    /**
2625     * Text direction is using "first strong algorithm". The first strong directional character
2626     * determines the paragraph direction. If there is no strong directional character, the
2627     * paragraph direction is the view's resolved layout direction.
2628     *
2629     */
2630    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2631
2632    /**
2633     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2634     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2635     * If there are neither, the paragraph direction is the view's resolved layout direction.
2636     *
2637     */
2638    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2639
2640    /**
2641     * Text direction is forced to LTR.
2642     *
2643     */
2644    public static final int TEXT_DIRECTION_LTR = 3;
2645
2646    /**
2647     * Text direction is forced to RTL.
2648     *
2649     */
2650    public static final int TEXT_DIRECTION_RTL = 4;
2651
2652    /**
2653     * Text direction is coming from the system Locale.
2654     *
2655     */
2656    public static final int TEXT_DIRECTION_LOCALE = 5;
2657
2658    /**
2659     * Default text direction is inherited
2660     *
2661     */
2662    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2663
2664    /**
2665     * The text direction that has been defined by {@link #setTextDirection(int)}.
2666     *
2667     */
2668    @ViewDebug.ExportedProperty(category = "text", mapping = {
2669            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2670            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2671            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2672            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2673            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2674            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2675    })
2676    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2677
2678    /**
2679     * The resolved text direction.  This needs resolution if the value is
2680     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if it is
2681     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2682     * chain of the view.
2683     *
2684     */
2685    @ViewDebug.ExportedProperty(category = "text", mapping = {
2686            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2687            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2688            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2689            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2690            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2691            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2692    })
2693    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2694
2695    /**
2696     * Consistency verifier for debugging purposes.
2697     * @hide
2698     */
2699    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2700            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2701                    new InputEventConsistencyVerifier(this, 0) : null;
2702
2703    /**
2704     * Simple constructor to use when creating a view from code.
2705     *
2706     * @param context The Context the view is running in, through which it can
2707     *        access the current theme, resources, etc.
2708     */
2709    public View(Context context) {
2710        mContext = context;
2711        mResources = context != null ? context.getResources() : null;
2712        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2713        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2714        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2715        mUserPaddingStart = -1;
2716        mUserPaddingEnd = -1;
2717        mUserPaddingRelative = false;
2718    }
2719
2720    /**
2721     * Constructor that is called when inflating a view from XML. This is called
2722     * when a view is being constructed from an XML file, supplying attributes
2723     * that were specified in the XML file. This version uses a default style of
2724     * 0, so the only attribute values applied are those in the Context's Theme
2725     * and the given AttributeSet.
2726     *
2727     * <p>
2728     * The method onFinishInflate() will be called after all children have been
2729     * added.
2730     *
2731     * @param context The Context the view is running in, through which it can
2732     *        access the current theme, resources, etc.
2733     * @param attrs The attributes of the XML tag that is inflating the view.
2734     * @see #View(Context, AttributeSet, int)
2735     */
2736    public View(Context context, AttributeSet attrs) {
2737        this(context, attrs, 0);
2738    }
2739
2740    /**
2741     * Perform inflation from XML and apply a class-specific base style. This
2742     * constructor of View allows subclasses to use their own base style when
2743     * they are inflating. For example, a Button class's constructor would call
2744     * this version of the super class constructor and supply
2745     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2746     * the theme's button style to modify all of the base view attributes (in
2747     * particular its background) as well as the Button class's attributes.
2748     *
2749     * @param context The Context the view is running in, through which it can
2750     *        access the current theme, resources, etc.
2751     * @param attrs The attributes of the XML tag that is inflating the view.
2752     * @param defStyle The default style to apply to this view. If 0, no style
2753     *        will be applied (beyond what is included in the theme). This may
2754     *        either be an attribute resource, whose value will be retrieved
2755     *        from the current theme, or an explicit style resource.
2756     * @see #View(Context, AttributeSet)
2757     */
2758    public View(Context context, AttributeSet attrs, int defStyle) {
2759        this(context);
2760
2761        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2762                defStyle, 0);
2763
2764        Drawable background = null;
2765
2766        int leftPadding = -1;
2767        int topPadding = -1;
2768        int rightPadding = -1;
2769        int bottomPadding = -1;
2770        int startPadding = -1;
2771        int endPadding = -1;
2772
2773        int padding = -1;
2774
2775        int viewFlagValues = 0;
2776        int viewFlagMasks = 0;
2777
2778        boolean setScrollContainer = false;
2779
2780        int x = 0;
2781        int y = 0;
2782
2783        float tx = 0;
2784        float ty = 0;
2785        float rotation = 0;
2786        float rotationX = 0;
2787        float rotationY = 0;
2788        float sx = 1f;
2789        float sy = 1f;
2790        boolean transformSet = false;
2791
2792        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2793
2794        int overScrollMode = mOverScrollMode;
2795        final int N = a.getIndexCount();
2796        for (int i = 0; i < N; i++) {
2797            int attr = a.getIndex(i);
2798            switch (attr) {
2799                case com.android.internal.R.styleable.View_background:
2800                    background = a.getDrawable(attr);
2801                    break;
2802                case com.android.internal.R.styleable.View_padding:
2803                    padding = a.getDimensionPixelSize(attr, -1);
2804                    break;
2805                 case com.android.internal.R.styleable.View_paddingLeft:
2806                    leftPadding = a.getDimensionPixelSize(attr, -1);
2807                    break;
2808                case com.android.internal.R.styleable.View_paddingTop:
2809                    topPadding = a.getDimensionPixelSize(attr, -1);
2810                    break;
2811                case com.android.internal.R.styleable.View_paddingRight:
2812                    rightPadding = a.getDimensionPixelSize(attr, -1);
2813                    break;
2814                case com.android.internal.R.styleable.View_paddingBottom:
2815                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2816                    break;
2817                case com.android.internal.R.styleable.View_paddingStart:
2818                    startPadding = a.getDimensionPixelSize(attr, -1);
2819                    break;
2820                case com.android.internal.R.styleable.View_paddingEnd:
2821                    endPadding = a.getDimensionPixelSize(attr, -1);
2822                    break;
2823                case com.android.internal.R.styleable.View_scrollX:
2824                    x = a.getDimensionPixelOffset(attr, 0);
2825                    break;
2826                case com.android.internal.R.styleable.View_scrollY:
2827                    y = a.getDimensionPixelOffset(attr, 0);
2828                    break;
2829                case com.android.internal.R.styleable.View_alpha:
2830                    setAlpha(a.getFloat(attr, 1f));
2831                    break;
2832                case com.android.internal.R.styleable.View_transformPivotX:
2833                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2834                    break;
2835                case com.android.internal.R.styleable.View_transformPivotY:
2836                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2837                    break;
2838                case com.android.internal.R.styleable.View_translationX:
2839                    tx = a.getDimensionPixelOffset(attr, 0);
2840                    transformSet = true;
2841                    break;
2842                case com.android.internal.R.styleable.View_translationY:
2843                    ty = a.getDimensionPixelOffset(attr, 0);
2844                    transformSet = true;
2845                    break;
2846                case com.android.internal.R.styleable.View_rotation:
2847                    rotation = a.getFloat(attr, 0);
2848                    transformSet = true;
2849                    break;
2850                case com.android.internal.R.styleable.View_rotationX:
2851                    rotationX = a.getFloat(attr, 0);
2852                    transformSet = true;
2853                    break;
2854                case com.android.internal.R.styleable.View_rotationY:
2855                    rotationY = a.getFloat(attr, 0);
2856                    transformSet = true;
2857                    break;
2858                case com.android.internal.R.styleable.View_scaleX:
2859                    sx = a.getFloat(attr, 1f);
2860                    transformSet = true;
2861                    break;
2862                case com.android.internal.R.styleable.View_scaleY:
2863                    sy = a.getFloat(attr, 1f);
2864                    transformSet = true;
2865                    break;
2866                case com.android.internal.R.styleable.View_id:
2867                    mID = a.getResourceId(attr, NO_ID);
2868                    break;
2869                case com.android.internal.R.styleable.View_tag:
2870                    mTag = a.getText(attr);
2871                    break;
2872                case com.android.internal.R.styleable.View_fitsSystemWindows:
2873                    if (a.getBoolean(attr, false)) {
2874                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2875                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2876                    }
2877                    break;
2878                case com.android.internal.R.styleable.View_focusable:
2879                    if (a.getBoolean(attr, false)) {
2880                        viewFlagValues |= FOCUSABLE;
2881                        viewFlagMasks |= FOCUSABLE_MASK;
2882                    }
2883                    break;
2884                case com.android.internal.R.styleable.View_focusableInTouchMode:
2885                    if (a.getBoolean(attr, false)) {
2886                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2887                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2888                    }
2889                    break;
2890                case com.android.internal.R.styleable.View_clickable:
2891                    if (a.getBoolean(attr, false)) {
2892                        viewFlagValues |= CLICKABLE;
2893                        viewFlagMasks |= CLICKABLE;
2894                    }
2895                    break;
2896                case com.android.internal.R.styleable.View_longClickable:
2897                    if (a.getBoolean(attr, false)) {
2898                        viewFlagValues |= LONG_CLICKABLE;
2899                        viewFlagMasks |= LONG_CLICKABLE;
2900                    }
2901                    break;
2902                case com.android.internal.R.styleable.View_saveEnabled:
2903                    if (!a.getBoolean(attr, true)) {
2904                        viewFlagValues |= SAVE_DISABLED;
2905                        viewFlagMasks |= SAVE_DISABLED_MASK;
2906                    }
2907                    break;
2908                case com.android.internal.R.styleable.View_duplicateParentState:
2909                    if (a.getBoolean(attr, false)) {
2910                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2911                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2912                    }
2913                    break;
2914                case com.android.internal.R.styleable.View_visibility:
2915                    final int visibility = a.getInt(attr, 0);
2916                    if (visibility != 0) {
2917                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2918                        viewFlagMasks |= VISIBILITY_MASK;
2919                    }
2920                    break;
2921                case com.android.internal.R.styleable.View_layoutDirection:
2922                    // Clear any HORIZONTAL_DIRECTION flag already set
2923                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2924                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2925                    final int layoutDirection = a.getInt(attr, -1);
2926                    if (layoutDirection != -1) {
2927                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2928                    } else {
2929                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2930                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2931                    }
2932                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2933                    break;
2934                case com.android.internal.R.styleable.View_drawingCacheQuality:
2935                    final int cacheQuality = a.getInt(attr, 0);
2936                    if (cacheQuality != 0) {
2937                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2938                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2939                    }
2940                    break;
2941                case com.android.internal.R.styleable.View_contentDescription:
2942                    mContentDescription = a.getString(attr);
2943                    break;
2944                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2945                    if (!a.getBoolean(attr, true)) {
2946                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2947                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2948                    }
2949                    break;
2950                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2951                    if (!a.getBoolean(attr, true)) {
2952                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2953                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2954                    }
2955                    break;
2956                case R.styleable.View_scrollbars:
2957                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2958                    if (scrollbars != SCROLLBARS_NONE) {
2959                        viewFlagValues |= scrollbars;
2960                        viewFlagMasks |= SCROLLBARS_MASK;
2961                        initializeScrollbars(a);
2962                    }
2963                    break;
2964                //noinspection deprecation
2965                case R.styleable.View_fadingEdge:
2966                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2967                        // Ignore the attribute starting with ICS
2968                        break;
2969                    }
2970                    // With builds < ICS, fall through and apply fading edges
2971                case R.styleable.View_requiresFadingEdge:
2972                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2973                    if (fadingEdge != FADING_EDGE_NONE) {
2974                        viewFlagValues |= fadingEdge;
2975                        viewFlagMasks |= FADING_EDGE_MASK;
2976                        initializeFadingEdge(a);
2977                    }
2978                    break;
2979                case R.styleable.View_scrollbarStyle:
2980                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2981                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2982                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2983                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2984                    }
2985                    break;
2986                case R.styleable.View_isScrollContainer:
2987                    setScrollContainer = true;
2988                    if (a.getBoolean(attr, false)) {
2989                        setScrollContainer(true);
2990                    }
2991                    break;
2992                case com.android.internal.R.styleable.View_keepScreenOn:
2993                    if (a.getBoolean(attr, false)) {
2994                        viewFlagValues |= KEEP_SCREEN_ON;
2995                        viewFlagMasks |= KEEP_SCREEN_ON;
2996                    }
2997                    break;
2998                case R.styleable.View_filterTouchesWhenObscured:
2999                    if (a.getBoolean(attr, false)) {
3000                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3001                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3002                    }
3003                    break;
3004                case R.styleable.View_nextFocusLeft:
3005                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3006                    break;
3007                case R.styleable.View_nextFocusRight:
3008                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3009                    break;
3010                case R.styleable.View_nextFocusUp:
3011                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3012                    break;
3013                case R.styleable.View_nextFocusDown:
3014                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3015                    break;
3016                case R.styleable.View_nextFocusForward:
3017                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3018                    break;
3019                case R.styleable.View_minWidth:
3020                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3021                    break;
3022                case R.styleable.View_minHeight:
3023                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3024                    break;
3025                case R.styleable.View_onClick:
3026                    if (context.isRestricted()) {
3027                        throw new IllegalStateException("The android:onClick attribute cannot "
3028                                + "be used within a restricted context");
3029                    }
3030
3031                    final String handlerName = a.getString(attr);
3032                    if (handlerName != null) {
3033                        setOnClickListener(new OnClickListener() {
3034                            private Method mHandler;
3035
3036                            public void onClick(View v) {
3037                                if (mHandler == null) {
3038                                    try {
3039                                        mHandler = getContext().getClass().getMethod(handlerName,
3040                                                View.class);
3041                                    } catch (NoSuchMethodException e) {
3042                                        int id = getId();
3043                                        String idText = id == NO_ID ? "" : " with id '"
3044                                                + getContext().getResources().getResourceEntryName(
3045                                                    id) + "'";
3046                                        throw new IllegalStateException("Could not find a method " +
3047                                                handlerName + "(View) in the activity "
3048                                                + getContext().getClass() + " for onClick handler"
3049                                                + " on view " + View.this.getClass() + idText, e);
3050                                    }
3051                                }
3052
3053                                try {
3054                                    mHandler.invoke(getContext(), View.this);
3055                                } catch (IllegalAccessException e) {
3056                                    throw new IllegalStateException("Could not execute non "
3057                                            + "public method of the activity", e);
3058                                } catch (InvocationTargetException e) {
3059                                    throw new IllegalStateException("Could not execute "
3060                                            + "method of the activity", e);
3061                                }
3062                            }
3063                        });
3064                    }
3065                    break;
3066                case R.styleable.View_overScrollMode:
3067                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3068                    break;
3069                case R.styleable.View_verticalScrollbarPosition:
3070                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3071                    break;
3072                case R.styleable.View_layerType:
3073                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3074                    break;
3075                case R.styleable.View_textDirection:
3076                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3077                    break;
3078            }
3079        }
3080
3081        a.recycle();
3082
3083        setOverScrollMode(overScrollMode);
3084
3085        if (background != null) {
3086            setBackgroundDrawable(background);
3087        }
3088
3089        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3090
3091        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3092        // layout direction). Those cached values will be used later during padding resolution.
3093        mUserPaddingStart = startPadding;
3094        mUserPaddingEnd = endPadding;
3095
3096        if (padding >= 0) {
3097            leftPadding = padding;
3098            topPadding = padding;
3099            rightPadding = padding;
3100            bottomPadding = padding;
3101        }
3102
3103        // If the user specified the padding (either with android:padding or
3104        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3105        // use the default padding or the padding from the background drawable
3106        // (stored at this point in mPadding*)
3107        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3108                topPadding >= 0 ? topPadding : mPaddingTop,
3109                rightPadding >= 0 ? rightPadding : mPaddingRight,
3110                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3111
3112        if (viewFlagMasks != 0) {
3113            setFlags(viewFlagValues, viewFlagMasks);
3114        }
3115
3116        // Needs to be called after mViewFlags is set
3117        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3118            recomputePadding();
3119        }
3120
3121        if (x != 0 || y != 0) {
3122            scrollTo(x, y);
3123        }
3124
3125        if (transformSet) {
3126            setTranslationX(tx);
3127            setTranslationY(ty);
3128            setRotation(rotation);
3129            setRotationX(rotationX);
3130            setRotationY(rotationY);
3131            setScaleX(sx);
3132            setScaleY(sy);
3133        }
3134
3135        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3136            setScrollContainer(true);
3137        }
3138
3139        computeOpaqueFlags();
3140    }
3141
3142    /**
3143     * Non-public constructor for use in testing
3144     */
3145    View() {
3146        mResources = null;
3147    }
3148
3149    /**
3150     * <p>
3151     * Initializes the fading edges from a given set of styled attributes. This
3152     * method should be called by subclasses that need fading edges and when an
3153     * instance of these subclasses is created programmatically rather than
3154     * being inflated from XML. This method is automatically called when the XML
3155     * is inflated.
3156     * </p>
3157     *
3158     * @param a the styled attributes set to initialize the fading edges from
3159     */
3160    protected void initializeFadingEdge(TypedArray a) {
3161        initScrollCache();
3162
3163        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3164                R.styleable.View_fadingEdgeLength,
3165                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3166    }
3167
3168    /**
3169     * Returns the size of the vertical faded edges used to indicate that more
3170     * content in this view is visible.
3171     *
3172     * @return The size in pixels of the vertical faded edge or 0 if vertical
3173     *         faded edges are not enabled for this view.
3174     * @attr ref android.R.styleable#View_fadingEdgeLength
3175     */
3176    public int getVerticalFadingEdgeLength() {
3177        if (isVerticalFadingEdgeEnabled()) {
3178            ScrollabilityCache cache = mScrollCache;
3179            if (cache != null) {
3180                return cache.fadingEdgeLength;
3181            }
3182        }
3183        return 0;
3184    }
3185
3186    /**
3187     * Set the size of the faded edge used to indicate that more content in this
3188     * view is available.  Will not change whether the fading edge is enabled; use
3189     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3190     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3191     * for the vertical or horizontal fading edges.
3192     *
3193     * @param length The size in pixels of the faded edge used to indicate that more
3194     *        content in this view is visible.
3195     */
3196    public void setFadingEdgeLength(int length) {
3197        initScrollCache();
3198        mScrollCache.fadingEdgeLength = length;
3199    }
3200
3201    /**
3202     * Returns the size of the horizontal faded edges used to indicate that more
3203     * content in this view is visible.
3204     *
3205     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3206     *         faded edges are not enabled for this view.
3207     * @attr ref android.R.styleable#View_fadingEdgeLength
3208     */
3209    public int getHorizontalFadingEdgeLength() {
3210        if (isHorizontalFadingEdgeEnabled()) {
3211            ScrollabilityCache cache = mScrollCache;
3212            if (cache != null) {
3213                return cache.fadingEdgeLength;
3214            }
3215        }
3216        return 0;
3217    }
3218
3219    /**
3220     * Returns the width of the vertical scrollbar.
3221     *
3222     * @return The width in pixels of the vertical scrollbar or 0 if there
3223     *         is no vertical scrollbar.
3224     */
3225    public int getVerticalScrollbarWidth() {
3226        ScrollabilityCache cache = mScrollCache;
3227        if (cache != null) {
3228            ScrollBarDrawable scrollBar = cache.scrollBar;
3229            if (scrollBar != null) {
3230                int size = scrollBar.getSize(true);
3231                if (size <= 0) {
3232                    size = cache.scrollBarSize;
3233                }
3234                return size;
3235            }
3236            return 0;
3237        }
3238        return 0;
3239    }
3240
3241    /**
3242     * Returns the height of the horizontal scrollbar.
3243     *
3244     * @return The height in pixels of the horizontal scrollbar or 0 if
3245     *         there is no horizontal scrollbar.
3246     */
3247    protected int getHorizontalScrollbarHeight() {
3248        ScrollabilityCache cache = mScrollCache;
3249        if (cache != null) {
3250            ScrollBarDrawable scrollBar = cache.scrollBar;
3251            if (scrollBar != null) {
3252                int size = scrollBar.getSize(false);
3253                if (size <= 0) {
3254                    size = cache.scrollBarSize;
3255                }
3256                return size;
3257            }
3258            return 0;
3259        }
3260        return 0;
3261    }
3262
3263    /**
3264     * <p>
3265     * Initializes the scrollbars from a given set of styled attributes. This
3266     * method should be called by subclasses that need scrollbars and when an
3267     * instance of these subclasses is created programmatically rather than
3268     * being inflated from XML. This method is automatically called when the XML
3269     * is inflated.
3270     * </p>
3271     *
3272     * @param a the styled attributes set to initialize the scrollbars from
3273     */
3274    protected void initializeScrollbars(TypedArray a) {
3275        initScrollCache();
3276
3277        final ScrollabilityCache scrollabilityCache = mScrollCache;
3278
3279        if (scrollabilityCache.scrollBar == null) {
3280            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3281        }
3282
3283        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3284
3285        if (!fadeScrollbars) {
3286            scrollabilityCache.state = ScrollabilityCache.ON;
3287        }
3288        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3289
3290
3291        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3292                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3293                        .getScrollBarFadeDuration());
3294        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3295                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3296                ViewConfiguration.getScrollDefaultDelay());
3297
3298
3299        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3300                com.android.internal.R.styleable.View_scrollbarSize,
3301                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3302
3303        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3304        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3305
3306        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3307        if (thumb != null) {
3308            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3309        }
3310
3311        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3312                false);
3313        if (alwaysDraw) {
3314            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3315        }
3316
3317        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3318        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3319
3320        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3321        if (thumb != null) {
3322            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3323        }
3324
3325        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3326                false);
3327        if (alwaysDraw) {
3328            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3329        }
3330
3331        // Re-apply user/background padding so that scrollbar(s) get added
3332        resolvePadding();
3333    }
3334
3335    /**
3336     * <p>
3337     * Initalizes the scrollability cache if necessary.
3338     * </p>
3339     */
3340    private void initScrollCache() {
3341        if (mScrollCache == null) {
3342            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3343        }
3344    }
3345
3346    /**
3347     * Set the position of the vertical scroll bar. Should be one of
3348     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3349     * {@link #SCROLLBAR_POSITION_RIGHT}.
3350     *
3351     * @param position Where the vertical scroll bar should be positioned.
3352     */
3353    public void setVerticalScrollbarPosition(int position) {
3354        if (mVerticalScrollbarPosition != position) {
3355            mVerticalScrollbarPosition = position;
3356            computeOpaqueFlags();
3357            resolvePadding();
3358        }
3359    }
3360
3361    /**
3362     * @return The position where the vertical scroll bar will show, if applicable.
3363     * @see #setVerticalScrollbarPosition(int)
3364     */
3365    public int getVerticalScrollbarPosition() {
3366        return mVerticalScrollbarPosition;
3367    }
3368
3369    ListenerInfo getListenerInfo() {
3370        if (mListenerInfo != null) {
3371            return mListenerInfo;
3372        }
3373        mListenerInfo = new ListenerInfo();
3374        return mListenerInfo;
3375    }
3376
3377    /**
3378     * Register a callback to be invoked when focus of this view changed.
3379     *
3380     * @param l The callback that will run.
3381     */
3382    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3383        getListenerInfo().mOnFocusChangeListener = l;
3384    }
3385
3386    /**
3387     * Add a listener that will be called when the bounds of the view change due to
3388     * layout processing.
3389     *
3390     * @param listener The listener that will be called when layout bounds change.
3391     */
3392    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3393        ListenerInfo li = getListenerInfo();
3394        if (li.mOnLayoutChangeListeners == null) {
3395            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3396        }
3397        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3398            li.mOnLayoutChangeListeners.add(listener);
3399        }
3400    }
3401
3402    /**
3403     * Remove a listener for layout changes.
3404     *
3405     * @param listener The listener for layout bounds change.
3406     */
3407    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3408        ListenerInfo li = mListenerInfo;
3409        if (li == null || li.mOnLayoutChangeListeners == null) {
3410            return;
3411        }
3412        li.mOnLayoutChangeListeners.remove(listener);
3413    }
3414
3415    /**
3416     * Add a listener for attach state changes.
3417     *
3418     * This listener will be called whenever this view is attached or detached
3419     * from a window. Remove the listener using
3420     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3421     *
3422     * @param listener Listener to attach
3423     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3424     */
3425    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3426        ListenerInfo li = getListenerInfo();
3427        if (li.mOnAttachStateChangeListeners == null) {
3428            li.mOnAttachStateChangeListeners
3429                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3430        }
3431        li.mOnAttachStateChangeListeners.add(listener);
3432    }
3433
3434    /**
3435     * Remove a listener for attach state changes. The listener will receive no further
3436     * notification of window attach/detach events.
3437     *
3438     * @param listener Listener to remove
3439     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3440     */
3441    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3442        ListenerInfo li = mListenerInfo;
3443        if (li == null || li.mOnAttachStateChangeListeners == null) {
3444            return;
3445        }
3446        li.mOnAttachStateChangeListeners.remove(listener);
3447    }
3448
3449    /**
3450     * Returns the focus-change callback registered for this view.
3451     *
3452     * @return The callback, or null if one is not registered.
3453     */
3454    public OnFocusChangeListener getOnFocusChangeListener() {
3455        ListenerInfo li = mListenerInfo;
3456        return li != null ? li.mOnFocusChangeListener : null;
3457    }
3458
3459    /**
3460     * Register a callback to be invoked when this view is clicked. If this view is not
3461     * clickable, it becomes clickable.
3462     *
3463     * @param l The callback that will run
3464     *
3465     * @see #setClickable(boolean)
3466     */
3467    public void setOnClickListener(OnClickListener l) {
3468        if (!isClickable()) {
3469            setClickable(true);
3470        }
3471        getListenerInfo().mOnClickListener = l;
3472    }
3473
3474    /**
3475     * Return whether this view has an attached OnClickListener.  Returns
3476     * true if there is a listener, false if there is none.
3477     */
3478    public boolean hasOnClickListeners() {
3479        ListenerInfo li = mListenerInfo;
3480        return (li != null && li.mOnClickListener != null);
3481    }
3482
3483    /**
3484     * Register a callback to be invoked when this view is clicked and held. If this view is not
3485     * long clickable, it becomes long clickable.
3486     *
3487     * @param l The callback that will run
3488     *
3489     * @see #setLongClickable(boolean)
3490     */
3491    public void setOnLongClickListener(OnLongClickListener l) {
3492        if (!isLongClickable()) {
3493            setLongClickable(true);
3494        }
3495        getListenerInfo().mOnLongClickListener = l;
3496    }
3497
3498    /**
3499     * Register a callback to be invoked when the context menu for this view is
3500     * being built. If this view is not long clickable, it becomes long clickable.
3501     *
3502     * @param l The callback that will run
3503     *
3504     */
3505    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3506        if (!isLongClickable()) {
3507            setLongClickable(true);
3508        }
3509        getListenerInfo().mOnCreateContextMenuListener = l;
3510    }
3511
3512    /**
3513     * Call this view's OnClickListener, if it is defined.  Performs all normal
3514     * actions associated with clicking: reporting accessibility event, playing
3515     * a sound, etc.
3516     *
3517     * @return True there was an assigned OnClickListener that was called, false
3518     *         otherwise is returned.
3519     */
3520    public boolean performClick() {
3521        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3522
3523        ListenerInfo li = mListenerInfo;
3524        if (li != null && li.mOnClickListener != null) {
3525            playSoundEffect(SoundEffectConstants.CLICK);
3526            li.mOnClickListener.onClick(this);
3527            return true;
3528        }
3529
3530        return false;
3531    }
3532
3533    /**
3534     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3535     * this only calls the listener, and does not do any associated clicking
3536     * actions like reporting an accessibility event.
3537     *
3538     * @return True there was an assigned OnClickListener that was called, false
3539     *         otherwise is returned.
3540     */
3541    public boolean callOnClick() {
3542        ListenerInfo li = mListenerInfo;
3543        if (li != null && li.mOnClickListener != null) {
3544            li.mOnClickListener.onClick(this);
3545            return true;
3546        }
3547        return false;
3548    }
3549
3550    /**
3551     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3552     * OnLongClickListener did not consume the event.
3553     *
3554     * @return True if one of the above receivers consumed the event, false otherwise.
3555     */
3556    public boolean performLongClick() {
3557        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3558
3559        boolean handled = false;
3560        ListenerInfo li = mListenerInfo;
3561        if (li != null && li.mOnLongClickListener != null) {
3562            handled = li.mOnLongClickListener.onLongClick(View.this);
3563        }
3564        if (!handled) {
3565            handled = showContextMenu();
3566        }
3567        if (handled) {
3568            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3569        }
3570        return handled;
3571    }
3572
3573    /**
3574     * Performs button-related actions during a touch down event.
3575     *
3576     * @param event The event.
3577     * @return True if the down was consumed.
3578     *
3579     * @hide
3580     */
3581    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3582        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3583            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3584                return true;
3585            }
3586        }
3587        return false;
3588    }
3589
3590    /**
3591     * Bring up the context menu for this view.
3592     *
3593     * @return Whether a context menu was displayed.
3594     */
3595    public boolean showContextMenu() {
3596        return getParent().showContextMenuForChild(this);
3597    }
3598
3599    /**
3600     * Bring up the context menu for this view, referring to the item under the specified point.
3601     *
3602     * @param x The referenced x coordinate.
3603     * @param y The referenced y coordinate.
3604     * @param metaState The keyboard modifiers that were pressed.
3605     * @return Whether a context menu was displayed.
3606     *
3607     * @hide
3608     */
3609    public boolean showContextMenu(float x, float y, int metaState) {
3610        return showContextMenu();
3611    }
3612
3613    /**
3614     * Start an action mode.
3615     *
3616     * @param callback Callback that will control the lifecycle of the action mode
3617     * @return The new action mode if it is started, null otherwise
3618     *
3619     * @see ActionMode
3620     */
3621    public ActionMode startActionMode(ActionMode.Callback callback) {
3622        return getParent().startActionModeForChild(this, callback);
3623    }
3624
3625    /**
3626     * Register a callback to be invoked when a key is pressed in this view.
3627     * @param l the key listener to attach to this view
3628     */
3629    public void setOnKeyListener(OnKeyListener l) {
3630        getListenerInfo().mOnKeyListener = l;
3631    }
3632
3633    /**
3634     * Register a callback to be invoked when a touch event is sent to this view.
3635     * @param l the touch listener to attach to this view
3636     */
3637    public void setOnTouchListener(OnTouchListener l) {
3638        getListenerInfo().mOnTouchListener = l;
3639    }
3640
3641    /**
3642     * Register a callback to be invoked when a generic motion event is sent to this view.
3643     * @param l the generic motion listener to attach to this view
3644     */
3645    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3646        getListenerInfo().mOnGenericMotionListener = l;
3647    }
3648
3649    /**
3650     * Register a callback to be invoked when a hover event is sent to this view.
3651     * @param l the hover listener to attach to this view
3652     */
3653    public void setOnHoverListener(OnHoverListener l) {
3654        getListenerInfo().mOnHoverListener = l;
3655    }
3656
3657    /**
3658     * Register a drag event listener callback object for this View. The parameter is
3659     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3660     * View, the system calls the
3661     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3662     * @param l An implementation of {@link android.view.View.OnDragListener}.
3663     */
3664    public void setOnDragListener(OnDragListener l) {
3665        getListenerInfo().mOnDragListener = l;
3666    }
3667
3668    /**
3669     * Give this view focus. This will cause
3670     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3671     *
3672     * Note: this does not check whether this {@link View} should get focus, it just
3673     * gives it focus no matter what.  It should only be called internally by framework
3674     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3675     *
3676     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3677     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3678     *        focus moved when requestFocus() is called. It may not always
3679     *        apply, in which case use the default View.FOCUS_DOWN.
3680     * @param previouslyFocusedRect The rectangle of the view that had focus
3681     *        prior in this View's coordinate system.
3682     */
3683    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3684        if (DBG) {
3685            System.out.println(this + " requestFocus()");
3686        }
3687
3688        if ((mPrivateFlags & FOCUSED) == 0) {
3689            mPrivateFlags |= FOCUSED;
3690
3691            if (mParent != null) {
3692                mParent.requestChildFocus(this, this);
3693            }
3694
3695            onFocusChanged(true, direction, previouslyFocusedRect);
3696            refreshDrawableState();
3697        }
3698    }
3699
3700    /**
3701     * Request that a rectangle of this view be visible on the screen,
3702     * scrolling if necessary just enough.
3703     *
3704     * <p>A View should call this if it maintains some notion of which part
3705     * of its content is interesting.  For example, a text editing view
3706     * should call this when its cursor moves.
3707     *
3708     * @param rectangle The rectangle.
3709     * @return Whether any parent scrolled.
3710     */
3711    public boolean requestRectangleOnScreen(Rect rectangle) {
3712        return requestRectangleOnScreen(rectangle, false);
3713    }
3714
3715    /**
3716     * Request that a rectangle of this view be visible on the screen,
3717     * scrolling if necessary just enough.
3718     *
3719     * <p>A View should call this if it maintains some notion of which part
3720     * of its content is interesting.  For example, a text editing view
3721     * should call this when its cursor moves.
3722     *
3723     * <p>When <code>immediate</code> is set to true, scrolling will not be
3724     * animated.
3725     *
3726     * @param rectangle The rectangle.
3727     * @param immediate True to forbid animated scrolling, false otherwise
3728     * @return Whether any parent scrolled.
3729     */
3730    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3731        View child = this;
3732        ViewParent parent = mParent;
3733        boolean scrolled = false;
3734        while (parent != null) {
3735            scrolled |= parent.requestChildRectangleOnScreen(child,
3736                    rectangle, immediate);
3737
3738            // offset rect so next call has the rectangle in the
3739            // coordinate system of its direct child.
3740            rectangle.offset(child.getLeft(), child.getTop());
3741            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3742
3743            if (!(parent instanceof View)) {
3744                break;
3745            }
3746
3747            child = (View) parent;
3748            parent = child.getParent();
3749        }
3750        return scrolled;
3751    }
3752
3753    /**
3754     * Called when this view wants to give up focus. If focus is cleared
3755     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3756     * <p>
3757     * <strong>Note:</strong> When a View clears focus the framework is trying
3758     * to give focus to the first focusable View from the top. Hence, if this
3759     * View is the first from the top that can take focus, then its focus will
3760     * not be cleared nor will the focus change callback be invoked.
3761     * </p>
3762     */
3763    public void clearFocus() {
3764        if (DBG) {
3765            System.out.println(this + " clearFocus()");
3766        }
3767
3768        if ((mPrivateFlags & FOCUSED) != 0) {
3769            mPrivateFlags &= ~FOCUSED;
3770
3771            if (mParent != null) {
3772                mParent.clearChildFocus(this);
3773            }
3774
3775            onFocusChanged(false, 0, null);
3776            refreshDrawableState();
3777        }
3778    }
3779
3780    /**
3781     * Called to clear the focus of a view that is about to be removed.
3782     * Doesn't call clearChildFocus, which prevents this view from taking
3783     * focus again before it has been removed from the parent
3784     */
3785    void clearFocusForRemoval() {
3786        if ((mPrivateFlags & FOCUSED) != 0) {
3787            mPrivateFlags &= ~FOCUSED;
3788
3789            onFocusChanged(false, 0, null);
3790            refreshDrawableState();
3791        }
3792    }
3793
3794    /**
3795     * Called internally by the view system when a new view is getting focus.
3796     * This is what clears the old focus.
3797     */
3798    void unFocus() {
3799        if (DBG) {
3800            System.out.println(this + " unFocus()");
3801        }
3802
3803        if ((mPrivateFlags & FOCUSED) != 0) {
3804            mPrivateFlags &= ~FOCUSED;
3805
3806            onFocusChanged(false, 0, null);
3807            refreshDrawableState();
3808        }
3809    }
3810
3811    /**
3812     * Returns true if this view has focus iteself, or is the ancestor of the
3813     * view that has focus.
3814     *
3815     * @return True if this view has or contains focus, false otherwise.
3816     */
3817    @ViewDebug.ExportedProperty(category = "focus")
3818    public boolean hasFocus() {
3819        return (mPrivateFlags & FOCUSED) != 0;
3820    }
3821
3822    /**
3823     * Returns true if this view is focusable or if it contains a reachable View
3824     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3825     * is a View whose parents do not block descendants focus.
3826     *
3827     * Only {@link #VISIBLE} views are considered focusable.
3828     *
3829     * @return True if the view is focusable or if the view contains a focusable
3830     *         View, false otherwise.
3831     *
3832     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3833     */
3834    public boolean hasFocusable() {
3835        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3836    }
3837
3838    /**
3839     * Called by the view system when the focus state of this view changes.
3840     * When the focus change event is caused by directional navigation, direction
3841     * and previouslyFocusedRect provide insight into where the focus is coming from.
3842     * When overriding, be sure to call up through to the super class so that
3843     * the standard focus handling will occur.
3844     *
3845     * @param gainFocus True if the View has focus; false otherwise.
3846     * @param direction The direction focus has moved when requestFocus()
3847     *                  is called to give this view focus. Values are
3848     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3849     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3850     *                  It may not always apply, in which case use the default.
3851     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3852     *        system, of the previously focused view.  If applicable, this will be
3853     *        passed in as finer grained information about where the focus is coming
3854     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3855     */
3856    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3857        if (gainFocus) {
3858            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3859        }
3860
3861        InputMethodManager imm = InputMethodManager.peekInstance();
3862        if (!gainFocus) {
3863            if (isPressed()) {
3864                setPressed(false);
3865            }
3866            if (imm != null && mAttachInfo != null
3867                    && mAttachInfo.mHasWindowFocus) {
3868                imm.focusOut(this);
3869            }
3870            onFocusLost();
3871        } else if (imm != null && mAttachInfo != null
3872                && mAttachInfo.mHasWindowFocus) {
3873            imm.focusIn(this);
3874        }
3875
3876        invalidate(true);
3877        ListenerInfo li = mListenerInfo;
3878        if (li != null && li.mOnFocusChangeListener != null) {
3879            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3880        }
3881
3882        if (mAttachInfo != null) {
3883            mAttachInfo.mKeyDispatchState.reset(this);
3884        }
3885    }
3886
3887    /**
3888     * Sends an accessibility event of the given type. If accessiiblity is
3889     * not enabled this method has no effect. The default implementation calls
3890     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3891     * to populate information about the event source (this View), then calls
3892     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3893     * populate the text content of the event source including its descendants,
3894     * and last calls
3895     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3896     * on its parent to resuest sending of the event to interested parties.
3897     * <p>
3898     * If an {@link AccessibilityDelegate} has been specified via calling
3899     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3900     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3901     * responsible for handling this call.
3902     * </p>
3903     *
3904     * @param eventType The type of the event to send, as defined by several types from
3905     * {@link android.view.accessibility.AccessibilityEvent}, such as
3906     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3907     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3908     *
3909     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3910     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3911     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3912     * @see AccessibilityDelegate
3913     */
3914    public void sendAccessibilityEvent(int eventType) {
3915        if (mAccessibilityDelegate != null) {
3916            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3917        } else {
3918            sendAccessibilityEventInternal(eventType);
3919        }
3920    }
3921
3922    /**
3923     * @see #sendAccessibilityEvent(int)
3924     *
3925     * Note: Called from the default {@link AccessibilityDelegate}.
3926     */
3927    void sendAccessibilityEventInternal(int eventType) {
3928        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3929            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3930        }
3931    }
3932
3933    /**
3934     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3935     * takes as an argument an empty {@link AccessibilityEvent} and does not
3936     * perform a check whether accessibility is enabled.
3937     * <p>
3938     * If an {@link AccessibilityDelegate} has been specified via calling
3939     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3940     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3941     * is responsible for handling this call.
3942     * </p>
3943     *
3944     * @param event The event to send.
3945     *
3946     * @see #sendAccessibilityEvent(int)
3947     */
3948    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3949        if (mAccessibilityDelegate != null) {
3950           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3951        } else {
3952            sendAccessibilityEventUncheckedInternal(event);
3953        }
3954    }
3955
3956    /**
3957     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3958     *
3959     * Note: Called from the default {@link AccessibilityDelegate}.
3960     */
3961    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3962        if (!isShown()) {
3963            return;
3964        }
3965        onInitializeAccessibilityEvent(event);
3966        // Only a subset of accessibility events populates text content.
3967        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
3968            dispatchPopulateAccessibilityEvent(event);
3969        }
3970        // In the beginning we called #isShown(), so we know that getParent() is not null.
3971        getParent().requestSendAccessibilityEvent(this, event);
3972    }
3973
3974    /**
3975     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3976     * to its children for adding their text content to the event. Note that the
3977     * event text is populated in a separate dispatch path since we add to the
3978     * event not only the text of the source but also the text of all its descendants.
3979     * A typical implementation will call
3980     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3981     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3982     * on each child. Override this method if custom population of the event text
3983     * content is required.
3984     * <p>
3985     * If an {@link AccessibilityDelegate} has been specified via calling
3986     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3987     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
3988     * is responsible for handling this call.
3989     * </p>
3990     * <p>
3991     * <em>Note:</em> Accessibility events of certain types are not dispatched for
3992     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
3993     * </p>
3994     *
3995     * @param event The event.
3996     *
3997     * @return True if the event population was completed.
3998     */
3999    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4000        if (mAccessibilityDelegate != null) {
4001            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4002        } else {
4003            return dispatchPopulateAccessibilityEventInternal(event);
4004        }
4005    }
4006
4007    /**
4008     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4009     *
4010     * Note: Called from the default {@link AccessibilityDelegate}.
4011     */
4012    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4013        onPopulateAccessibilityEvent(event);
4014        return false;
4015    }
4016
4017    /**
4018     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4019     * giving a chance to this View to populate the accessibility event with its
4020     * text content. While this method is free to modify event
4021     * attributes other than text content, doing so should normally be performed in
4022     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4023     * <p>
4024     * Example: Adding formatted date string to an accessibility event in addition
4025     *          to the text added by the super implementation:
4026     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4027     *     super.onPopulateAccessibilityEvent(event);
4028     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4029     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4030     *         mCurrentDate.getTimeInMillis(), flags);
4031     *     event.getText().add(selectedDateUtterance);
4032     * }</pre>
4033     * <p>
4034     * If an {@link AccessibilityDelegate} has been specified via calling
4035     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4036     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4037     * is responsible for handling this call.
4038     * </p>
4039     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4040     * information to the event, in case the default implementation has basic information to add.
4041     * </p>
4042     *
4043     * @param event The accessibility event which to populate.
4044     *
4045     * @see #sendAccessibilityEvent(int)
4046     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4047     */
4048    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4049        if (mAccessibilityDelegate != null) {
4050            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4051        } else {
4052            onPopulateAccessibilityEventInternal(event);
4053        }
4054    }
4055
4056    /**
4057     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4058     *
4059     * Note: Called from the default {@link AccessibilityDelegate}.
4060     */
4061    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4062
4063    }
4064
4065    /**
4066     * Initializes an {@link AccessibilityEvent} with information about
4067     * this View which is the event source. In other words, the source of
4068     * an accessibility event is the view whose state change triggered firing
4069     * the event.
4070     * <p>
4071     * Example: Setting the password property of an event in addition
4072     *          to properties set by the super implementation:
4073     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4074     *     super.onInitializeAccessibilityEvent(event);
4075     *     event.setPassword(true);
4076     * }</pre>
4077     * <p>
4078     * If an {@link AccessibilityDelegate} has been specified via calling
4079     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4080     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4081     * is responsible for handling this call.
4082     * </p>
4083     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4084     * information to the event, in case the default implementation has basic information to add.
4085     * </p>
4086     * @param event The event to initialize.
4087     *
4088     * @see #sendAccessibilityEvent(int)
4089     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4090     */
4091    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4092        if (mAccessibilityDelegate != null) {
4093            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4094        } else {
4095            onInitializeAccessibilityEventInternal(event);
4096        }
4097    }
4098
4099    /**
4100     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4101     *
4102     * Note: Called from the default {@link AccessibilityDelegate}.
4103     */
4104    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4105        event.setSource(this);
4106        event.setClassName(View.class.getName());
4107        event.setPackageName(getContext().getPackageName());
4108        event.setEnabled(isEnabled());
4109        event.setContentDescription(mContentDescription);
4110
4111        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4112            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4113            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4114                    FOCUSABLES_ALL);
4115            event.setItemCount(focusablesTempList.size());
4116            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4117            focusablesTempList.clear();
4118        }
4119    }
4120
4121    /**
4122     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4123     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4124     * This method is responsible for obtaining an accessibility node info from a
4125     * pool of reusable instances and calling
4126     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4127     * initialize the former.
4128     * <p>
4129     * Note: The client is responsible for recycling the obtained instance by calling
4130     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4131     * </p>
4132     *
4133     * @return A populated {@link AccessibilityNodeInfo}.
4134     *
4135     * @see AccessibilityNodeInfo
4136     */
4137    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4138        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4139        if (provider != null) {
4140            return provider.createAccessibilityNodeInfo(View.NO_ID);
4141        } else {
4142            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4143            onInitializeAccessibilityNodeInfo(info);
4144            return info;
4145        }
4146    }
4147
4148    /**
4149     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4150     * The base implementation sets:
4151     * <ul>
4152     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4153     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4154     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4155     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4156     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4157     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4158     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4159     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4160     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4161     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4162     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4163     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4164     * </ul>
4165     * <p>
4166     * Subclasses should override this method, call the super implementation,
4167     * and set additional attributes.
4168     * </p>
4169     * <p>
4170     * If an {@link AccessibilityDelegate} has been specified via calling
4171     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4172     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4173     * is responsible for handling this call.
4174     * </p>
4175     *
4176     * @param info The instance to initialize.
4177     */
4178    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4179        if (mAccessibilityDelegate != null) {
4180            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4181        } else {
4182            onInitializeAccessibilityNodeInfoInternal(info);
4183        }
4184    }
4185
4186    /**
4187     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4188     *
4189     * Note: Called from the default {@link AccessibilityDelegate}.
4190     */
4191    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4192        Rect bounds = mAttachInfo.mTmpInvalRect;
4193        getDrawingRect(bounds);
4194        info.setBoundsInParent(bounds);
4195
4196        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4197        getLocationOnScreen(locationOnScreen);
4198        bounds.offsetTo(0, 0);
4199        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4200        info.setBoundsInScreen(bounds);
4201
4202        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4203            ViewParent parent = getParent();
4204            if (parent instanceof View) {
4205                View parentView = (View) parent;
4206                info.setParent(parentView);
4207            }
4208        }
4209
4210        info.setPackageName(mContext.getPackageName());
4211        info.setClassName(View.class.getName());
4212        info.setContentDescription(getContentDescription());
4213
4214        info.setEnabled(isEnabled());
4215        info.setClickable(isClickable());
4216        info.setFocusable(isFocusable());
4217        info.setFocused(isFocused());
4218        info.setSelected(isSelected());
4219        info.setLongClickable(isLongClickable());
4220
4221        // TODO: These make sense only if we are in an AdapterView but all
4222        // views can be selected. Maybe from accessiiblity perspective
4223        // we should report as selectable view in an AdapterView.
4224        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4225        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4226
4227        if (isFocusable()) {
4228            if (isFocused()) {
4229                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4230            } else {
4231                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4232            }
4233        }
4234    }
4235
4236    /**
4237     * Sets a delegate for implementing accessibility support via compositon as
4238     * opposed to inheritance. The delegate's primary use is for implementing
4239     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4240     *
4241     * @param delegate The delegate instance.
4242     *
4243     * @see AccessibilityDelegate
4244     */
4245    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4246        mAccessibilityDelegate = delegate;
4247    }
4248
4249    /**
4250     * Gets the provider for managing a virtual view hierarchy rooted at this View
4251     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4252     * that explore the window content.
4253     * <p>
4254     * If this method returns an instance, this instance is responsible for managing
4255     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4256     * View including the one representing the View itself. Similarly the returned
4257     * instance is responsible for performing accessibility actions on any virtual
4258     * view or the root view itself.
4259     * </p>
4260     * <p>
4261     * If an {@link AccessibilityDelegate} has been specified via calling
4262     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4263     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4264     * is responsible for handling this call.
4265     * </p>
4266     *
4267     * @return The provider.
4268     *
4269     * @see AccessibilityNodeProvider
4270     */
4271    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4272        if (mAccessibilityDelegate != null) {
4273            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4274        } else {
4275            return null;
4276        }
4277    }
4278
4279    /**
4280     * Gets the unique identifier of this view on the screen for accessibility purposes.
4281     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4282     *
4283     * @return The view accessibility id.
4284     *
4285     * @hide
4286     */
4287    public int getAccessibilityViewId() {
4288        if (mAccessibilityViewId == NO_ID) {
4289            mAccessibilityViewId = sNextAccessibilityViewId++;
4290        }
4291        return mAccessibilityViewId;
4292    }
4293
4294    /**
4295     * Gets the unique identifier of the window in which this View reseides.
4296     *
4297     * @return The window accessibility id.
4298     *
4299     * @hide
4300     */
4301    public int getAccessibilityWindowId() {
4302        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4303    }
4304
4305    /**
4306     * Gets the {@link View} description. It briefly describes the view and is
4307     * primarily used for accessibility support. Set this property to enable
4308     * better accessibility support for your application. This is especially
4309     * true for views that do not have textual representation (For example,
4310     * ImageButton).
4311     *
4312     * @return The content descriptiopn.
4313     *
4314     * @attr ref android.R.styleable#View_contentDescription
4315     */
4316    public CharSequence getContentDescription() {
4317        return mContentDescription;
4318    }
4319
4320    /**
4321     * Sets the {@link View} description. It briefly describes the view and is
4322     * primarily used for accessibility support. Set this property to enable
4323     * better accessibility support for your application. This is especially
4324     * true for views that do not have textual representation (For example,
4325     * ImageButton).
4326     *
4327     * @param contentDescription The content description.
4328     *
4329     * @attr ref android.R.styleable#View_contentDescription
4330     */
4331    @RemotableViewMethod
4332    public void setContentDescription(CharSequence contentDescription) {
4333        mContentDescription = contentDescription;
4334    }
4335
4336    /**
4337     * Invoked whenever this view loses focus, either by losing window focus or by losing
4338     * focus within its window. This method can be used to clear any state tied to the
4339     * focus. For instance, if a button is held pressed with the trackball and the window
4340     * loses focus, this method can be used to cancel the press.
4341     *
4342     * Subclasses of View overriding this method should always call super.onFocusLost().
4343     *
4344     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4345     * @see #onWindowFocusChanged(boolean)
4346     *
4347     * @hide pending API council approval
4348     */
4349    protected void onFocusLost() {
4350        resetPressedState();
4351    }
4352
4353    private void resetPressedState() {
4354        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4355            return;
4356        }
4357
4358        if (isPressed()) {
4359            setPressed(false);
4360
4361            if (!mHasPerformedLongPress) {
4362                removeLongPressCallback();
4363            }
4364        }
4365    }
4366
4367    /**
4368     * Returns true if this view has focus
4369     *
4370     * @return True if this view has focus, false otherwise.
4371     */
4372    @ViewDebug.ExportedProperty(category = "focus")
4373    public boolean isFocused() {
4374        return (mPrivateFlags & FOCUSED) != 0;
4375    }
4376
4377    /**
4378     * Find the view in the hierarchy rooted at this view that currently has
4379     * focus.
4380     *
4381     * @return The view that currently has focus, or null if no focused view can
4382     *         be found.
4383     */
4384    public View findFocus() {
4385        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4386    }
4387
4388    /**
4389     * Change whether this view is one of the set of scrollable containers in
4390     * its window.  This will be used to determine whether the window can
4391     * resize or must pan when a soft input area is open -- scrollable
4392     * containers allow the window to use resize mode since the container
4393     * will appropriately shrink.
4394     */
4395    public void setScrollContainer(boolean isScrollContainer) {
4396        if (isScrollContainer) {
4397            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4398                mAttachInfo.mScrollContainers.add(this);
4399                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4400            }
4401            mPrivateFlags |= SCROLL_CONTAINER;
4402        } else {
4403            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4404                mAttachInfo.mScrollContainers.remove(this);
4405            }
4406            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4407        }
4408    }
4409
4410    /**
4411     * Returns the quality of the drawing cache.
4412     *
4413     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4414     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4415     *
4416     * @see #setDrawingCacheQuality(int)
4417     * @see #setDrawingCacheEnabled(boolean)
4418     * @see #isDrawingCacheEnabled()
4419     *
4420     * @attr ref android.R.styleable#View_drawingCacheQuality
4421     */
4422    public int getDrawingCacheQuality() {
4423        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4424    }
4425
4426    /**
4427     * Set the drawing cache quality of this view. This value is used only when the
4428     * drawing cache is enabled
4429     *
4430     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4431     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4432     *
4433     * @see #getDrawingCacheQuality()
4434     * @see #setDrawingCacheEnabled(boolean)
4435     * @see #isDrawingCacheEnabled()
4436     *
4437     * @attr ref android.R.styleable#View_drawingCacheQuality
4438     */
4439    public void setDrawingCacheQuality(int quality) {
4440        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4441    }
4442
4443    /**
4444     * Returns whether the screen should remain on, corresponding to the current
4445     * value of {@link #KEEP_SCREEN_ON}.
4446     *
4447     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4448     *
4449     * @see #setKeepScreenOn(boolean)
4450     *
4451     * @attr ref android.R.styleable#View_keepScreenOn
4452     */
4453    public boolean getKeepScreenOn() {
4454        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4455    }
4456
4457    /**
4458     * Controls whether the screen should remain on, modifying the
4459     * value of {@link #KEEP_SCREEN_ON}.
4460     *
4461     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4462     *
4463     * @see #getKeepScreenOn()
4464     *
4465     * @attr ref android.R.styleable#View_keepScreenOn
4466     */
4467    public void setKeepScreenOn(boolean keepScreenOn) {
4468        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4469    }
4470
4471    /**
4472     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4473     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4474     *
4475     * @attr ref android.R.styleable#View_nextFocusLeft
4476     */
4477    public int getNextFocusLeftId() {
4478        return mNextFocusLeftId;
4479    }
4480
4481    /**
4482     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4483     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4484     * decide automatically.
4485     *
4486     * @attr ref android.R.styleable#View_nextFocusLeft
4487     */
4488    public void setNextFocusLeftId(int nextFocusLeftId) {
4489        mNextFocusLeftId = nextFocusLeftId;
4490    }
4491
4492    /**
4493     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4494     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4495     *
4496     * @attr ref android.R.styleable#View_nextFocusRight
4497     */
4498    public int getNextFocusRightId() {
4499        return mNextFocusRightId;
4500    }
4501
4502    /**
4503     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4504     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4505     * decide automatically.
4506     *
4507     * @attr ref android.R.styleable#View_nextFocusRight
4508     */
4509    public void setNextFocusRightId(int nextFocusRightId) {
4510        mNextFocusRightId = nextFocusRightId;
4511    }
4512
4513    /**
4514     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4515     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4516     *
4517     * @attr ref android.R.styleable#View_nextFocusUp
4518     */
4519    public int getNextFocusUpId() {
4520        return mNextFocusUpId;
4521    }
4522
4523    /**
4524     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4525     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4526     * decide automatically.
4527     *
4528     * @attr ref android.R.styleable#View_nextFocusUp
4529     */
4530    public void setNextFocusUpId(int nextFocusUpId) {
4531        mNextFocusUpId = nextFocusUpId;
4532    }
4533
4534    /**
4535     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4536     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4537     *
4538     * @attr ref android.R.styleable#View_nextFocusDown
4539     */
4540    public int getNextFocusDownId() {
4541        return mNextFocusDownId;
4542    }
4543
4544    /**
4545     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4546     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4547     * decide automatically.
4548     *
4549     * @attr ref android.R.styleable#View_nextFocusDown
4550     */
4551    public void setNextFocusDownId(int nextFocusDownId) {
4552        mNextFocusDownId = nextFocusDownId;
4553    }
4554
4555    /**
4556     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4557     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4558     *
4559     * @attr ref android.R.styleable#View_nextFocusForward
4560     */
4561    public int getNextFocusForwardId() {
4562        return mNextFocusForwardId;
4563    }
4564
4565    /**
4566     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4567     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4568     * decide automatically.
4569     *
4570     * @attr ref android.R.styleable#View_nextFocusForward
4571     */
4572    public void setNextFocusForwardId(int nextFocusForwardId) {
4573        mNextFocusForwardId = nextFocusForwardId;
4574    }
4575
4576    /**
4577     * Returns the visibility of this view and all of its ancestors
4578     *
4579     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4580     */
4581    public boolean isShown() {
4582        View current = this;
4583        //noinspection ConstantConditions
4584        do {
4585            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4586                return false;
4587            }
4588            ViewParent parent = current.mParent;
4589            if (parent == null) {
4590                return false; // We are not attached to the view root
4591            }
4592            if (!(parent instanceof View)) {
4593                return true;
4594            }
4595            current = (View) parent;
4596        } while (current != null);
4597
4598        return false;
4599    }
4600
4601    /**
4602     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4603     * is set
4604     *
4605     * @param insets Insets for system windows
4606     *
4607     * @return True if this view applied the insets, false otherwise
4608     */
4609    protected boolean fitSystemWindows(Rect insets) {
4610        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4611            mPaddingLeft = insets.left;
4612            mPaddingTop = insets.top;
4613            mPaddingRight = insets.right;
4614            mPaddingBottom = insets.bottom;
4615            requestLayout();
4616            return true;
4617        }
4618        return false;
4619    }
4620
4621    /**
4622     * Set whether or not this view should account for system screen decorations
4623     * such as the status bar and inset its content. This allows this view to be
4624     * positioned in absolute screen coordinates and remain visible to the user.
4625     *
4626     * <p>This should only be used by top-level window decor views.
4627     *
4628     * @param fitSystemWindows true to inset content for system screen decorations, false for
4629     *                         default behavior.
4630     *
4631     * @attr ref android.R.styleable#View_fitsSystemWindows
4632     */
4633    public void setFitsSystemWindows(boolean fitSystemWindows) {
4634        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4635    }
4636
4637    /**
4638     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4639     * will account for system screen decorations such as the status bar and inset its
4640     * content. This allows the view to be positioned in absolute screen coordinates
4641     * and remain visible to the user.
4642     *
4643     * @return true if this view will adjust its content bounds for system screen decorations.
4644     *
4645     * @attr ref android.R.styleable#View_fitsSystemWindows
4646     */
4647    public boolean fitsSystemWindows() {
4648        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4649    }
4650
4651    /**
4652     * Returns the visibility status for this view.
4653     *
4654     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4655     * @attr ref android.R.styleable#View_visibility
4656     */
4657    @ViewDebug.ExportedProperty(mapping = {
4658        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4659        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4660        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4661    })
4662    public int getVisibility() {
4663        return mViewFlags & VISIBILITY_MASK;
4664    }
4665
4666    /**
4667     * Set the enabled state of this view.
4668     *
4669     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4670     * @attr ref android.R.styleable#View_visibility
4671     */
4672    @RemotableViewMethod
4673    public void setVisibility(int visibility) {
4674        setFlags(visibility, VISIBILITY_MASK);
4675        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4676    }
4677
4678    /**
4679     * Returns the enabled status for this view. The interpretation of the
4680     * enabled state varies by subclass.
4681     *
4682     * @return True if this view is enabled, false otherwise.
4683     */
4684    @ViewDebug.ExportedProperty
4685    public boolean isEnabled() {
4686        return (mViewFlags & ENABLED_MASK) == ENABLED;
4687    }
4688
4689    /**
4690     * Set the enabled state of this view. The interpretation of the enabled
4691     * state varies by subclass.
4692     *
4693     * @param enabled True if this view is enabled, false otherwise.
4694     */
4695    @RemotableViewMethod
4696    public void setEnabled(boolean enabled) {
4697        if (enabled == isEnabled()) return;
4698
4699        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4700
4701        /*
4702         * The View most likely has to change its appearance, so refresh
4703         * the drawable state.
4704         */
4705        refreshDrawableState();
4706
4707        // Invalidate too, since the default behavior for views is to be
4708        // be drawn at 50% alpha rather than to change the drawable.
4709        invalidate(true);
4710    }
4711
4712    /**
4713     * Set whether this view can receive the focus.
4714     *
4715     * Setting this to false will also ensure that this view is not focusable
4716     * in touch mode.
4717     *
4718     * @param focusable If true, this view can receive the focus.
4719     *
4720     * @see #setFocusableInTouchMode(boolean)
4721     * @attr ref android.R.styleable#View_focusable
4722     */
4723    public void setFocusable(boolean focusable) {
4724        if (!focusable) {
4725            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4726        }
4727        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4728    }
4729
4730    /**
4731     * Set whether this view can receive focus while in touch mode.
4732     *
4733     * Setting this to true will also ensure that this view is focusable.
4734     *
4735     * @param focusableInTouchMode If true, this view can receive the focus while
4736     *   in touch mode.
4737     *
4738     * @see #setFocusable(boolean)
4739     * @attr ref android.R.styleable#View_focusableInTouchMode
4740     */
4741    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4742        // Focusable in touch mode should always be set before the focusable flag
4743        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4744        // which, in touch mode, will not successfully request focus on this view
4745        // because the focusable in touch mode flag is not set
4746        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4747        if (focusableInTouchMode) {
4748            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4749        }
4750    }
4751
4752    /**
4753     * Set whether this view should have sound effects enabled for events such as
4754     * clicking and touching.
4755     *
4756     * <p>You may wish to disable sound effects for a view if you already play sounds,
4757     * for instance, a dial key that plays dtmf tones.
4758     *
4759     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4760     * @see #isSoundEffectsEnabled()
4761     * @see #playSoundEffect(int)
4762     * @attr ref android.R.styleable#View_soundEffectsEnabled
4763     */
4764    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4765        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4766    }
4767
4768    /**
4769     * @return whether this view should have sound effects enabled for events such as
4770     *     clicking and touching.
4771     *
4772     * @see #setSoundEffectsEnabled(boolean)
4773     * @see #playSoundEffect(int)
4774     * @attr ref android.R.styleable#View_soundEffectsEnabled
4775     */
4776    @ViewDebug.ExportedProperty
4777    public boolean isSoundEffectsEnabled() {
4778        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4779    }
4780
4781    /**
4782     * Set whether this view should have haptic feedback for events such as
4783     * long presses.
4784     *
4785     * <p>You may wish to disable haptic feedback if your view already controls
4786     * its own haptic feedback.
4787     *
4788     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4789     * @see #isHapticFeedbackEnabled()
4790     * @see #performHapticFeedback(int)
4791     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4792     */
4793    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4794        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4795    }
4796
4797    /**
4798     * @return whether this view should have haptic feedback enabled for events
4799     * long presses.
4800     *
4801     * @see #setHapticFeedbackEnabled(boolean)
4802     * @see #performHapticFeedback(int)
4803     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4804     */
4805    @ViewDebug.ExportedProperty
4806    public boolean isHapticFeedbackEnabled() {
4807        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4808    }
4809
4810    /**
4811     * Returns the layout direction for this view.
4812     *
4813     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4814     *   {@link #LAYOUT_DIRECTION_RTL},
4815     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4816     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4817     * @attr ref android.R.styleable#View_layoutDirection
4818     *
4819     * @hide
4820     */
4821    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4822        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4823        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4824        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4825        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4826    })
4827    public int getLayoutDirection() {
4828        return mViewFlags & LAYOUT_DIRECTION_MASK;
4829    }
4830
4831    /**
4832     * Set the layout direction for this view. This will propagate a reset of layout direction
4833     * resolution to the view's children and resolve layout direction for this view.
4834     *
4835     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4836     *   {@link #LAYOUT_DIRECTION_RTL},
4837     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4838     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4839     *
4840     * @attr ref android.R.styleable#View_layoutDirection
4841     *
4842     * @hide
4843     */
4844    @RemotableViewMethod
4845    public void setLayoutDirection(int layoutDirection) {
4846        if (getLayoutDirection() != layoutDirection) {
4847            resetResolvedLayoutDirection();
4848            // Setting the flag will also request a layout.
4849            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4850        }
4851    }
4852
4853    /**
4854     * Returns the resolved layout direction for this view.
4855     *
4856     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4857     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4858     *
4859     * @hide
4860     */
4861    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4862        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4863        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4864    })
4865    public int getResolvedLayoutDirection() {
4866        resolveLayoutDirectionIfNeeded();
4867        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4868                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4869    }
4870
4871    /**
4872     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4873     * layout attribute and/or the inherited value from the parent.</p>
4874     *
4875     * @return true if the layout is right-to-left.
4876     *
4877     * @hide
4878     */
4879    @ViewDebug.ExportedProperty(category = "layout")
4880    public boolean isLayoutRtl() {
4881        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4882    }
4883
4884    /**
4885     * If this view doesn't do any drawing on its own, set this flag to
4886     * allow further optimizations. By default, this flag is not set on
4887     * View, but could be set on some View subclasses such as ViewGroup.
4888     *
4889     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4890     * you should clear this flag.
4891     *
4892     * @param willNotDraw whether or not this View draw on its own
4893     */
4894    public void setWillNotDraw(boolean willNotDraw) {
4895        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4896    }
4897
4898    /**
4899     * Returns whether or not this View draws on its own.
4900     *
4901     * @return true if this view has nothing to draw, false otherwise
4902     */
4903    @ViewDebug.ExportedProperty(category = "drawing")
4904    public boolean willNotDraw() {
4905        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4906    }
4907
4908    /**
4909     * When a View's drawing cache is enabled, drawing is redirected to an
4910     * offscreen bitmap. Some views, like an ImageView, must be able to
4911     * bypass this mechanism if they already draw a single bitmap, to avoid
4912     * unnecessary usage of the memory.
4913     *
4914     * @param willNotCacheDrawing true if this view does not cache its
4915     *        drawing, false otherwise
4916     */
4917    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4918        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4919    }
4920
4921    /**
4922     * Returns whether or not this View can cache its drawing or not.
4923     *
4924     * @return true if this view does not cache its drawing, false otherwise
4925     */
4926    @ViewDebug.ExportedProperty(category = "drawing")
4927    public boolean willNotCacheDrawing() {
4928        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4929    }
4930
4931    /**
4932     * Indicates whether this view reacts to click events or not.
4933     *
4934     * @return true if the view is clickable, false otherwise
4935     *
4936     * @see #setClickable(boolean)
4937     * @attr ref android.R.styleable#View_clickable
4938     */
4939    @ViewDebug.ExportedProperty
4940    public boolean isClickable() {
4941        return (mViewFlags & CLICKABLE) == CLICKABLE;
4942    }
4943
4944    /**
4945     * Enables or disables click events for this view. When a view
4946     * is clickable it will change its state to "pressed" on every click.
4947     * Subclasses should set the view clickable to visually react to
4948     * user's clicks.
4949     *
4950     * @param clickable true to make the view clickable, false otherwise
4951     *
4952     * @see #isClickable()
4953     * @attr ref android.R.styleable#View_clickable
4954     */
4955    public void setClickable(boolean clickable) {
4956        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4957    }
4958
4959    /**
4960     * Indicates whether this view reacts to long click events or not.
4961     *
4962     * @return true if the view is long clickable, false otherwise
4963     *
4964     * @see #setLongClickable(boolean)
4965     * @attr ref android.R.styleable#View_longClickable
4966     */
4967    public boolean isLongClickable() {
4968        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4969    }
4970
4971    /**
4972     * Enables or disables long click events for this view. When a view is long
4973     * clickable it reacts to the user holding down the button for a longer
4974     * duration than a tap. This event can either launch the listener or a
4975     * context menu.
4976     *
4977     * @param longClickable true to make the view long clickable, false otherwise
4978     * @see #isLongClickable()
4979     * @attr ref android.R.styleable#View_longClickable
4980     */
4981    public void setLongClickable(boolean longClickable) {
4982        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4983    }
4984
4985    /**
4986     * Sets the pressed state for this view.
4987     *
4988     * @see #isClickable()
4989     * @see #setClickable(boolean)
4990     *
4991     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4992     *        the View's internal state from a previously set "pressed" state.
4993     */
4994    public void setPressed(boolean pressed) {
4995        if (pressed) {
4996            mPrivateFlags |= PRESSED;
4997        } else {
4998            mPrivateFlags &= ~PRESSED;
4999        }
5000        refreshDrawableState();
5001        dispatchSetPressed(pressed);
5002    }
5003
5004    /**
5005     * Dispatch setPressed to all of this View's children.
5006     *
5007     * @see #setPressed(boolean)
5008     *
5009     * @param pressed The new pressed state
5010     */
5011    protected void dispatchSetPressed(boolean pressed) {
5012    }
5013
5014    /**
5015     * Indicates whether the view is currently in pressed state. Unless
5016     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5017     * the pressed state.
5018     *
5019     * @see #setPressed(boolean)
5020     * @see #isClickable()
5021     * @see #setClickable(boolean)
5022     *
5023     * @return true if the view is currently pressed, false otherwise
5024     */
5025    public boolean isPressed() {
5026        return (mPrivateFlags & PRESSED) == PRESSED;
5027    }
5028
5029    /**
5030     * Indicates whether this view will save its state (that is,
5031     * whether its {@link #onSaveInstanceState} method will be called).
5032     *
5033     * @return Returns true if the view state saving is enabled, else false.
5034     *
5035     * @see #setSaveEnabled(boolean)
5036     * @attr ref android.R.styleable#View_saveEnabled
5037     */
5038    public boolean isSaveEnabled() {
5039        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5040    }
5041
5042    /**
5043     * Controls whether the saving of this view's state is
5044     * enabled (that is, whether its {@link #onSaveInstanceState} method
5045     * will be called).  Note that even if freezing is enabled, the
5046     * view still must have an id assigned to it (via {@link #setId(int)})
5047     * for its state to be saved.  This flag can only disable the
5048     * saving of this view; any child views may still have their state saved.
5049     *
5050     * @param enabled Set to false to <em>disable</em> state saving, or true
5051     * (the default) to allow it.
5052     *
5053     * @see #isSaveEnabled()
5054     * @see #setId(int)
5055     * @see #onSaveInstanceState()
5056     * @attr ref android.R.styleable#View_saveEnabled
5057     */
5058    public void setSaveEnabled(boolean enabled) {
5059        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5060    }
5061
5062    /**
5063     * Gets whether the framework should discard touches when the view's
5064     * window is obscured by another visible window.
5065     * Refer to the {@link View} security documentation for more details.
5066     *
5067     * @return True if touch filtering is enabled.
5068     *
5069     * @see #setFilterTouchesWhenObscured(boolean)
5070     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5071     */
5072    @ViewDebug.ExportedProperty
5073    public boolean getFilterTouchesWhenObscured() {
5074        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5075    }
5076
5077    /**
5078     * Sets whether the framework should discard touches when the view's
5079     * window is obscured by another visible window.
5080     * Refer to the {@link View} security documentation for more details.
5081     *
5082     * @param enabled True if touch filtering should be enabled.
5083     *
5084     * @see #getFilterTouchesWhenObscured
5085     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5086     */
5087    public void setFilterTouchesWhenObscured(boolean enabled) {
5088        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5089                FILTER_TOUCHES_WHEN_OBSCURED);
5090    }
5091
5092    /**
5093     * Indicates whether the entire hierarchy under this view will save its
5094     * state when a state saving traversal occurs from its parent.  The default
5095     * is true; if false, these views will not be saved unless
5096     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5097     *
5098     * @return Returns true if the view state saving from parent is enabled, else false.
5099     *
5100     * @see #setSaveFromParentEnabled(boolean)
5101     */
5102    public boolean isSaveFromParentEnabled() {
5103        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5104    }
5105
5106    /**
5107     * Controls whether the entire hierarchy under this view will save its
5108     * state when a state saving traversal occurs from its parent.  The default
5109     * is true; if false, these views will not be saved unless
5110     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5111     *
5112     * @param enabled Set to false to <em>disable</em> state saving, or true
5113     * (the default) to allow it.
5114     *
5115     * @see #isSaveFromParentEnabled()
5116     * @see #setId(int)
5117     * @see #onSaveInstanceState()
5118     */
5119    public void setSaveFromParentEnabled(boolean enabled) {
5120        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5121    }
5122
5123
5124    /**
5125     * Returns whether this View is able to take focus.
5126     *
5127     * @return True if this view can take focus, or false otherwise.
5128     * @attr ref android.R.styleable#View_focusable
5129     */
5130    @ViewDebug.ExportedProperty(category = "focus")
5131    public final boolean isFocusable() {
5132        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5133    }
5134
5135    /**
5136     * When a view is focusable, it may not want to take focus when in touch mode.
5137     * For example, a button would like focus when the user is navigating via a D-pad
5138     * so that the user can click on it, but once the user starts touching the screen,
5139     * the button shouldn't take focus
5140     * @return Whether the view is focusable in touch mode.
5141     * @attr ref android.R.styleable#View_focusableInTouchMode
5142     */
5143    @ViewDebug.ExportedProperty
5144    public final boolean isFocusableInTouchMode() {
5145        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5146    }
5147
5148    /**
5149     * Find the nearest view in the specified direction that can take focus.
5150     * This does not actually give focus to that view.
5151     *
5152     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5153     *
5154     * @return The nearest focusable in the specified direction, or null if none
5155     *         can be found.
5156     */
5157    public View focusSearch(int direction) {
5158        if (mParent != null) {
5159            return mParent.focusSearch(this, direction);
5160        } else {
5161            return null;
5162        }
5163    }
5164
5165    /**
5166     * This method is the last chance for the focused view and its ancestors to
5167     * respond to an arrow key. This is called when the focused view did not
5168     * consume the key internally, nor could the view system find a new view in
5169     * the requested direction to give focus to.
5170     *
5171     * @param focused The currently focused view.
5172     * @param direction The direction focus wants to move. One of FOCUS_UP,
5173     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5174     * @return True if the this view consumed this unhandled move.
5175     */
5176    public boolean dispatchUnhandledMove(View focused, int direction) {
5177        return false;
5178    }
5179
5180    /**
5181     * If a user manually specified the next view id for a particular direction,
5182     * use the root to look up the view.
5183     * @param root The root view of the hierarchy containing this view.
5184     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5185     * or FOCUS_BACKWARD.
5186     * @return The user specified next view, or null if there is none.
5187     */
5188    View findUserSetNextFocus(View root, int direction) {
5189        switch (direction) {
5190            case FOCUS_LEFT:
5191                if (mNextFocusLeftId == View.NO_ID) return null;
5192                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5193            case FOCUS_RIGHT:
5194                if (mNextFocusRightId == View.NO_ID) return null;
5195                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5196            case FOCUS_UP:
5197                if (mNextFocusUpId == View.NO_ID) return null;
5198                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5199            case FOCUS_DOWN:
5200                if (mNextFocusDownId == View.NO_ID) return null;
5201                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5202            case FOCUS_FORWARD:
5203                if (mNextFocusForwardId == View.NO_ID) return null;
5204                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5205            case FOCUS_BACKWARD: {
5206                final int id = mID;
5207                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5208                    @Override
5209                    public boolean apply(View t) {
5210                        return t.mNextFocusForwardId == id;
5211                    }
5212                });
5213            }
5214        }
5215        return null;
5216    }
5217
5218    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5219        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5220            @Override
5221            public boolean apply(View t) {
5222                return t.mID == childViewId;
5223            }
5224        });
5225
5226        if (result == null) {
5227            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5228                    + "by user for id " + childViewId);
5229        }
5230        return result;
5231    }
5232
5233    /**
5234     * Find and return all focusable views that are descendants of this view,
5235     * possibly including this view if it is focusable itself.
5236     *
5237     * @param direction The direction of the focus
5238     * @return A list of focusable views
5239     */
5240    public ArrayList<View> getFocusables(int direction) {
5241        ArrayList<View> result = new ArrayList<View>(24);
5242        addFocusables(result, direction);
5243        return result;
5244    }
5245
5246    /**
5247     * Add any focusable views that are descendants of this view (possibly
5248     * including this view if it is focusable itself) to views.  If we are in touch mode,
5249     * only add views that are also focusable in touch mode.
5250     *
5251     * @param views Focusable views found so far
5252     * @param direction The direction of the focus
5253     */
5254    public void addFocusables(ArrayList<View> views, int direction) {
5255        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5256    }
5257
5258    /**
5259     * Adds any focusable views that are descendants of this view (possibly
5260     * including this view if it is focusable itself) to views. This method
5261     * adds all focusable views regardless if we are in touch mode or
5262     * only views focusable in touch mode if we are in touch mode depending on
5263     * the focusable mode paramater.
5264     *
5265     * @param views Focusable views found so far or null if all we are interested is
5266     *        the number of focusables.
5267     * @param direction The direction of the focus.
5268     * @param focusableMode The type of focusables to be added.
5269     *
5270     * @see #FOCUSABLES_ALL
5271     * @see #FOCUSABLES_TOUCH_MODE
5272     */
5273    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5274        if (!isFocusable()) {
5275            return;
5276        }
5277
5278        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5279                isInTouchMode() && !isFocusableInTouchMode()) {
5280            return;
5281        }
5282
5283        if (views != null) {
5284            views.add(this);
5285        }
5286    }
5287
5288    /**
5289     * Finds the Views that contain given text. The containment is case insensitive.
5290     * The search is performed by either the text that the View renders or the content
5291     * description that describes the view for accessibility purposes and the view does
5292     * not render or both. Clients can specify how the search is to be performed via
5293     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5294     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5295     *
5296     * @param outViews The output list of matching Views.
5297     * @param searched The text to match against.
5298     *
5299     * @see #FIND_VIEWS_WITH_TEXT
5300     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5301     * @see #setContentDescription(CharSequence)
5302     */
5303    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5304        if (getAccessibilityNodeProvider() != null) {
5305            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5306                outViews.add(this);
5307            }
5308        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5309                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5310            String searchedLowerCase = searched.toString().toLowerCase();
5311            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5312            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5313                outViews.add(this);
5314            }
5315        }
5316    }
5317
5318    /**
5319     * Find and return all touchable views that are descendants of this view,
5320     * possibly including this view if it is touchable itself.
5321     *
5322     * @return A list of touchable views
5323     */
5324    public ArrayList<View> getTouchables() {
5325        ArrayList<View> result = new ArrayList<View>();
5326        addTouchables(result);
5327        return result;
5328    }
5329
5330    /**
5331     * Add any touchable views that are descendants of this view (possibly
5332     * including this view if it is touchable itself) to views.
5333     *
5334     * @param views Touchable views found so far
5335     */
5336    public void addTouchables(ArrayList<View> views) {
5337        final int viewFlags = mViewFlags;
5338
5339        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5340                && (viewFlags & ENABLED_MASK) == ENABLED) {
5341            views.add(this);
5342        }
5343    }
5344
5345    /**
5346     * Call this to try to give focus to a specific view or to one of its
5347     * descendants.
5348     *
5349     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5350     * false), or if it is focusable and it is not focusable in touch mode
5351     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5352     *
5353     * See also {@link #focusSearch(int)}, which is what you call to say that you
5354     * have focus, and you want your parent to look for the next one.
5355     *
5356     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5357     * {@link #FOCUS_DOWN} and <code>null</code>.
5358     *
5359     * @return Whether this view or one of its descendants actually took focus.
5360     */
5361    public final boolean requestFocus() {
5362        return requestFocus(View.FOCUS_DOWN);
5363    }
5364
5365
5366    /**
5367     * Call this to try to give focus to a specific view or to one of its
5368     * descendants and give it a hint about what direction focus is heading.
5369     *
5370     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5371     * false), or if it is focusable and it is not focusable in touch mode
5372     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5373     *
5374     * See also {@link #focusSearch(int)}, which is what you call to say that you
5375     * have focus, and you want your parent to look for the next one.
5376     *
5377     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5378     * <code>null</code> set for the previously focused rectangle.
5379     *
5380     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5381     * @return Whether this view or one of its descendants actually took focus.
5382     */
5383    public final boolean requestFocus(int direction) {
5384        return requestFocus(direction, null);
5385    }
5386
5387    /**
5388     * Call this to try to give focus to a specific view or to one of its descendants
5389     * and give it hints about the direction and a specific rectangle that the focus
5390     * is coming from.  The rectangle can help give larger views a finer grained hint
5391     * about where focus is coming from, and therefore, where to show selection, or
5392     * forward focus change internally.
5393     *
5394     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5395     * false), or if it is focusable and it is not focusable in touch mode
5396     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5397     *
5398     * A View will not take focus if it is not visible.
5399     *
5400     * A View will not take focus if one of its parents has
5401     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5402     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5403     *
5404     * See also {@link #focusSearch(int)}, which is what you call to say that you
5405     * have focus, and you want your parent to look for the next one.
5406     *
5407     * You may wish to override this method if your custom {@link View} has an internal
5408     * {@link View} that it wishes to forward the request to.
5409     *
5410     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5411     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5412     *        to give a finer grained hint about where focus is coming from.  May be null
5413     *        if there is no hint.
5414     * @return Whether this view or one of its descendants actually took focus.
5415     */
5416    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5417        // need to be focusable
5418        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5419                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5420            return false;
5421        }
5422
5423        // need to be focusable in touch mode if in touch mode
5424        if (isInTouchMode() &&
5425            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5426               return false;
5427        }
5428
5429        // need to not have any parents blocking us
5430        if (hasAncestorThatBlocksDescendantFocus()) {
5431            return false;
5432        }
5433
5434        handleFocusGainInternal(direction, previouslyFocusedRect);
5435        return true;
5436    }
5437
5438    /** Gets the ViewAncestor, or null if not attached. */
5439    /*package*/ ViewRootImpl getViewRootImpl() {
5440        View root = getRootView();
5441        return root != null ? (ViewRootImpl)root.getParent() : null;
5442    }
5443
5444    /**
5445     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5446     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5447     * touch mode to request focus when they are touched.
5448     *
5449     * @return Whether this view or one of its descendants actually took focus.
5450     *
5451     * @see #isInTouchMode()
5452     *
5453     */
5454    public final boolean requestFocusFromTouch() {
5455        // Leave touch mode if we need to
5456        if (isInTouchMode()) {
5457            ViewRootImpl viewRoot = getViewRootImpl();
5458            if (viewRoot != null) {
5459                viewRoot.ensureTouchMode(false);
5460            }
5461        }
5462        return requestFocus(View.FOCUS_DOWN);
5463    }
5464
5465    /**
5466     * @return Whether any ancestor of this view blocks descendant focus.
5467     */
5468    private boolean hasAncestorThatBlocksDescendantFocus() {
5469        ViewParent ancestor = mParent;
5470        while (ancestor instanceof ViewGroup) {
5471            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5472            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5473                return true;
5474            } else {
5475                ancestor = vgAncestor.getParent();
5476            }
5477        }
5478        return false;
5479    }
5480
5481    /**
5482     * @hide
5483     */
5484    public void dispatchStartTemporaryDetach() {
5485        onStartTemporaryDetach();
5486    }
5487
5488    /**
5489     * This is called when a container is going to temporarily detach a child, with
5490     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5491     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5492     * {@link #onDetachedFromWindow()} when the container is done.
5493     */
5494    public void onStartTemporaryDetach() {
5495        removeUnsetPressCallback();
5496        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5497    }
5498
5499    /**
5500     * @hide
5501     */
5502    public void dispatchFinishTemporaryDetach() {
5503        onFinishTemporaryDetach();
5504    }
5505
5506    /**
5507     * Called after {@link #onStartTemporaryDetach} when the container is done
5508     * changing the view.
5509     */
5510    public void onFinishTemporaryDetach() {
5511    }
5512
5513    /**
5514     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5515     * for this view's window.  Returns null if the view is not currently attached
5516     * to the window.  Normally you will not need to use this directly, but
5517     * just use the standard high-level event callbacks like
5518     * {@link #onKeyDown(int, KeyEvent)}.
5519     */
5520    public KeyEvent.DispatcherState getKeyDispatcherState() {
5521        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5522    }
5523
5524    /**
5525     * Dispatch a key event before it is processed by any input method
5526     * associated with the view hierarchy.  This can be used to intercept
5527     * key events in special situations before the IME consumes them; a
5528     * typical example would be handling the BACK key to update the application's
5529     * UI instead of allowing the IME to see it and close itself.
5530     *
5531     * @param event The key event to be dispatched.
5532     * @return True if the event was handled, false otherwise.
5533     */
5534    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5535        return onKeyPreIme(event.getKeyCode(), event);
5536    }
5537
5538    /**
5539     * Dispatch a key event to the next view on the focus path. This path runs
5540     * from the top of the view tree down to the currently focused view. If this
5541     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5542     * the next node down the focus path. This method also fires any key
5543     * listeners.
5544     *
5545     * @param event The key event to be dispatched.
5546     * @return True if the event was handled, false otherwise.
5547     */
5548    public boolean dispatchKeyEvent(KeyEvent event) {
5549        if (mInputEventConsistencyVerifier != null) {
5550            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5551        }
5552
5553        // Give any attached key listener a first crack at the event.
5554        //noinspection SimplifiableIfStatement
5555        ListenerInfo li = mListenerInfo;
5556        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5557                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5558            return true;
5559        }
5560
5561        if (event.dispatch(this, mAttachInfo != null
5562                ? mAttachInfo.mKeyDispatchState : null, this)) {
5563            return true;
5564        }
5565
5566        if (mInputEventConsistencyVerifier != null) {
5567            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5568        }
5569        return false;
5570    }
5571
5572    /**
5573     * Dispatches a key shortcut event.
5574     *
5575     * @param event The key event to be dispatched.
5576     * @return True if the event was handled by the view, false otherwise.
5577     */
5578    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5579        return onKeyShortcut(event.getKeyCode(), event);
5580    }
5581
5582    /**
5583     * Pass the touch screen motion event down to the target view, or this
5584     * view if it is the target.
5585     *
5586     * @param event The motion event to be dispatched.
5587     * @return True if the event was handled by the view, false otherwise.
5588     */
5589    public boolean dispatchTouchEvent(MotionEvent event) {
5590        if (mInputEventConsistencyVerifier != null) {
5591            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5592        }
5593
5594        if (onFilterTouchEventForSecurity(event)) {
5595            //noinspection SimplifiableIfStatement
5596            ListenerInfo li = mListenerInfo;
5597            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5598                    && li.mOnTouchListener.onTouch(this, event)) {
5599                return true;
5600            }
5601
5602            if (onTouchEvent(event)) {
5603                return true;
5604            }
5605        }
5606
5607        if (mInputEventConsistencyVerifier != null) {
5608            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5609        }
5610        return false;
5611    }
5612
5613    /**
5614     * Filter the touch event to apply security policies.
5615     *
5616     * @param event The motion event to be filtered.
5617     * @return True if the event should be dispatched, false if the event should be dropped.
5618     *
5619     * @see #getFilterTouchesWhenObscured
5620     */
5621    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5622        //noinspection RedundantIfStatement
5623        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5624                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5625            // Window is obscured, drop this touch.
5626            return false;
5627        }
5628        return true;
5629    }
5630
5631    /**
5632     * Pass a trackball motion event down to the focused view.
5633     *
5634     * @param event The motion event to be dispatched.
5635     * @return True if the event was handled by the view, false otherwise.
5636     */
5637    public boolean dispatchTrackballEvent(MotionEvent event) {
5638        if (mInputEventConsistencyVerifier != null) {
5639            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5640        }
5641
5642        return onTrackballEvent(event);
5643    }
5644
5645    /**
5646     * Dispatch a generic motion event.
5647     * <p>
5648     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5649     * are delivered to the view under the pointer.  All other generic motion events are
5650     * delivered to the focused view.  Hover events are handled specially and are delivered
5651     * to {@link #onHoverEvent(MotionEvent)}.
5652     * </p>
5653     *
5654     * @param event The motion event to be dispatched.
5655     * @return True if the event was handled by the view, false otherwise.
5656     */
5657    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5658        if (mInputEventConsistencyVerifier != null) {
5659            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5660        }
5661
5662        final int source = event.getSource();
5663        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5664            final int action = event.getAction();
5665            if (action == MotionEvent.ACTION_HOVER_ENTER
5666                    || action == MotionEvent.ACTION_HOVER_MOVE
5667                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5668                if (dispatchHoverEvent(event)) {
5669                    return true;
5670                }
5671            } else if (dispatchGenericPointerEvent(event)) {
5672                return true;
5673            }
5674        } else if (dispatchGenericFocusedEvent(event)) {
5675            return true;
5676        }
5677
5678        if (dispatchGenericMotionEventInternal(event)) {
5679            return true;
5680        }
5681
5682        if (mInputEventConsistencyVerifier != null) {
5683            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5684        }
5685        return false;
5686    }
5687
5688    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5689        //noinspection SimplifiableIfStatement
5690        ListenerInfo li = mListenerInfo;
5691        if (li != null && li.mOnGenericMotionListener != null
5692                && (mViewFlags & ENABLED_MASK) == ENABLED
5693                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5694            return true;
5695        }
5696
5697        if (onGenericMotionEvent(event)) {
5698            return true;
5699        }
5700
5701        if (mInputEventConsistencyVerifier != null) {
5702            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5703        }
5704        return false;
5705    }
5706
5707    /**
5708     * Dispatch a hover event.
5709     * <p>
5710     * Do not call this method directly.
5711     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5712     * </p>
5713     *
5714     * @param event The motion event to be dispatched.
5715     * @return True if the event was handled by the view, false otherwise.
5716     */
5717    protected boolean dispatchHoverEvent(MotionEvent event) {
5718        //noinspection SimplifiableIfStatement
5719        ListenerInfo li = mListenerInfo;
5720        if (li != null && li.mOnHoverListener != null
5721                && (mViewFlags & ENABLED_MASK) == ENABLED
5722                && li.mOnHoverListener.onHover(this, event)) {
5723            return true;
5724        }
5725
5726        return onHoverEvent(event);
5727    }
5728
5729    /**
5730     * Returns true if the view has a child to which it has recently sent
5731     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5732     * it does not have a hovered child, then it must be the innermost hovered view.
5733     * @hide
5734     */
5735    protected boolean hasHoveredChild() {
5736        return false;
5737    }
5738
5739    /**
5740     * Dispatch a generic motion event to the view under the first pointer.
5741     * <p>
5742     * Do not call this method directly.
5743     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5744     * </p>
5745     *
5746     * @param event The motion event to be dispatched.
5747     * @return True if the event was handled by the view, false otherwise.
5748     */
5749    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5750        return false;
5751    }
5752
5753    /**
5754     * Dispatch a generic motion event to the currently focused view.
5755     * <p>
5756     * Do not call this method directly.
5757     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5758     * </p>
5759     *
5760     * @param event The motion event to be dispatched.
5761     * @return True if the event was handled by the view, false otherwise.
5762     */
5763    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5764        return false;
5765    }
5766
5767    /**
5768     * Dispatch a pointer event.
5769     * <p>
5770     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5771     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5772     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5773     * and should not be expected to handle other pointing device features.
5774     * </p>
5775     *
5776     * @param event The motion event to be dispatched.
5777     * @return True if the event was handled by the view, false otherwise.
5778     * @hide
5779     */
5780    public final boolean dispatchPointerEvent(MotionEvent event) {
5781        if (event.isTouchEvent()) {
5782            return dispatchTouchEvent(event);
5783        } else {
5784            return dispatchGenericMotionEvent(event);
5785        }
5786    }
5787
5788    /**
5789     * Called when the window containing this view gains or loses window focus.
5790     * ViewGroups should override to route to their children.
5791     *
5792     * @param hasFocus True if the window containing this view now has focus,
5793     *        false otherwise.
5794     */
5795    public void dispatchWindowFocusChanged(boolean hasFocus) {
5796        onWindowFocusChanged(hasFocus);
5797    }
5798
5799    /**
5800     * Called when the window containing this view gains or loses focus.  Note
5801     * that this is separate from view focus: to receive key events, both
5802     * your view and its window must have focus.  If a window is displayed
5803     * on top of yours that takes input focus, then your own window will lose
5804     * focus but the view focus will remain unchanged.
5805     *
5806     * @param hasWindowFocus True if the window containing this view now has
5807     *        focus, false otherwise.
5808     */
5809    public void onWindowFocusChanged(boolean hasWindowFocus) {
5810        InputMethodManager imm = InputMethodManager.peekInstance();
5811        if (!hasWindowFocus) {
5812            if (isPressed()) {
5813                setPressed(false);
5814            }
5815            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5816                imm.focusOut(this);
5817            }
5818            removeLongPressCallback();
5819            removeTapCallback();
5820            onFocusLost();
5821        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5822            imm.focusIn(this);
5823        }
5824        refreshDrawableState();
5825    }
5826
5827    /**
5828     * Returns true if this view is in a window that currently has window focus.
5829     * Note that this is not the same as the view itself having focus.
5830     *
5831     * @return True if this view is in a window that currently has window focus.
5832     */
5833    public boolean hasWindowFocus() {
5834        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5835    }
5836
5837    /**
5838     * Dispatch a view visibility change down the view hierarchy.
5839     * ViewGroups should override to route to their children.
5840     * @param changedView The view whose visibility changed. Could be 'this' or
5841     * an ancestor view.
5842     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5843     * {@link #INVISIBLE} or {@link #GONE}.
5844     */
5845    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5846        onVisibilityChanged(changedView, visibility);
5847    }
5848
5849    /**
5850     * Called when the visibility of the view or an ancestor of the view is changed.
5851     * @param changedView The view whose visibility changed. Could be 'this' or
5852     * an ancestor view.
5853     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5854     * {@link #INVISIBLE} or {@link #GONE}.
5855     */
5856    protected void onVisibilityChanged(View changedView, int visibility) {
5857        if (visibility == VISIBLE) {
5858            if (mAttachInfo != null) {
5859                initialAwakenScrollBars();
5860            } else {
5861                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5862            }
5863        }
5864    }
5865
5866    /**
5867     * Dispatch a hint about whether this view is displayed. For instance, when
5868     * a View moves out of the screen, it might receives a display hint indicating
5869     * the view is not displayed. Applications should not <em>rely</em> on this hint
5870     * as there is no guarantee that they will receive one.
5871     *
5872     * @param hint A hint about whether or not this view is displayed:
5873     * {@link #VISIBLE} or {@link #INVISIBLE}.
5874     */
5875    public void dispatchDisplayHint(int hint) {
5876        onDisplayHint(hint);
5877    }
5878
5879    /**
5880     * Gives this view a hint about whether is displayed or not. For instance, when
5881     * a View moves out of the screen, it might receives a display hint indicating
5882     * the view is not displayed. Applications should not <em>rely</em> on this hint
5883     * as there is no guarantee that they will receive one.
5884     *
5885     * @param hint A hint about whether or not this view is displayed:
5886     * {@link #VISIBLE} or {@link #INVISIBLE}.
5887     */
5888    protected void onDisplayHint(int hint) {
5889    }
5890
5891    /**
5892     * Dispatch a window visibility change down the view hierarchy.
5893     * ViewGroups should override to route to their children.
5894     *
5895     * @param visibility The new visibility of the window.
5896     *
5897     * @see #onWindowVisibilityChanged(int)
5898     */
5899    public void dispatchWindowVisibilityChanged(int visibility) {
5900        onWindowVisibilityChanged(visibility);
5901    }
5902
5903    /**
5904     * Called when the window containing has change its visibility
5905     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5906     * that this tells you whether or not your window is being made visible
5907     * to the window manager; this does <em>not</em> tell you whether or not
5908     * your window is obscured by other windows on the screen, even if it
5909     * is itself visible.
5910     *
5911     * @param visibility The new visibility of the window.
5912     */
5913    protected void onWindowVisibilityChanged(int visibility) {
5914        if (visibility == VISIBLE) {
5915            initialAwakenScrollBars();
5916        }
5917    }
5918
5919    /**
5920     * Returns the current visibility of the window this view is attached to
5921     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5922     *
5923     * @return Returns the current visibility of the view's window.
5924     */
5925    public int getWindowVisibility() {
5926        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5927    }
5928
5929    /**
5930     * Retrieve the overall visible display size in which the window this view is
5931     * attached to has been positioned in.  This takes into account screen
5932     * decorations above the window, for both cases where the window itself
5933     * is being position inside of them or the window is being placed under
5934     * then and covered insets are used for the window to position its content
5935     * inside.  In effect, this tells you the available area where content can
5936     * be placed and remain visible to users.
5937     *
5938     * <p>This function requires an IPC back to the window manager to retrieve
5939     * the requested information, so should not be used in performance critical
5940     * code like drawing.
5941     *
5942     * @param outRect Filled in with the visible display frame.  If the view
5943     * is not attached to a window, this is simply the raw display size.
5944     */
5945    public void getWindowVisibleDisplayFrame(Rect outRect) {
5946        if (mAttachInfo != null) {
5947            try {
5948                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5949            } catch (RemoteException e) {
5950                return;
5951            }
5952            // XXX This is really broken, and probably all needs to be done
5953            // in the window manager, and we need to know more about whether
5954            // we want the area behind or in front of the IME.
5955            final Rect insets = mAttachInfo.mVisibleInsets;
5956            outRect.left += insets.left;
5957            outRect.top += insets.top;
5958            outRect.right -= insets.right;
5959            outRect.bottom -= insets.bottom;
5960            return;
5961        }
5962        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5963        d.getRectSize(outRect);
5964    }
5965
5966    /**
5967     * Dispatch a notification about a resource configuration change down
5968     * the view hierarchy.
5969     * ViewGroups should override to route to their children.
5970     *
5971     * @param newConfig The new resource configuration.
5972     *
5973     * @see #onConfigurationChanged(android.content.res.Configuration)
5974     */
5975    public void dispatchConfigurationChanged(Configuration newConfig) {
5976        onConfigurationChanged(newConfig);
5977    }
5978
5979    /**
5980     * Called when the current configuration of the resources being used
5981     * by the application have changed.  You can use this to decide when
5982     * to reload resources that can changed based on orientation and other
5983     * configuration characterstics.  You only need to use this if you are
5984     * not relying on the normal {@link android.app.Activity} mechanism of
5985     * recreating the activity instance upon a configuration change.
5986     *
5987     * @param newConfig The new resource configuration.
5988     */
5989    protected void onConfigurationChanged(Configuration newConfig) {
5990    }
5991
5992    /**
5993     * Private function to aggregate all per-view attributes in to the view
5994     * root.
5995     */
5996    void dispatchCollectViewAttributes(int visibility) {
5997        performCollectViewAttributes(visibility);
5998    }
5999
6000    void performCollectViewAttributes(int visibility) {
6001        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6002            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6003                mAttachInfo.mKeepScreenOn = true;
6004            }
6005            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6006            ListenerInfo li = mListenerInfo;
6007            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6008                mAttachInfo.mHasSystemUiListeners = true;
6009            }
6010        }
6011    }
6012
6013    void needGlobalAttributesUpdate(boolean force) {
6014        final AttachInfo ai = mAttachInfo;
6015        if (ai != null) {
6016            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6017                    || ai.mHasSystemUiListeners) {
6018                ai.mRecomputeGlobalAttributes = true;
6019            }
6020        }
6021    }
6022
6023    /**
6024     * Returns whether the device is currently in touch mode.  Touch mode is entered
6025     * once the user begins interacting with the device by touch, and affects various
6026     * things like whether focus is always visible to the user.
6027     *
6028     * @return Whether the device is in touch mode.
6029     */
6030    @ViewDebug.ExportedProperty
6031    public boolean isInTouchMode() {
6032        if (mAttachInfo != null) {
6033            return mAttachInfo.mInTouchMode;
6034        } else {
6035            return ViewRootImpl.isInTouchMode();
6036        }
6037    }
6038
6039    /**
6040     * Returns the context the view is running in, through which it can
6041     * access the current theme, resources, etc.
6042     *
6043     * @return The view's Context.
6044     */
6045    @ViewDebug.CapturedViewProperty
6046    public final Context getContext() {
6047        return mContext;
6048    }
6049
6050    /**
6051     * Handle a key event before it is processed by any input method
6052     * associated with the view hierarchy.  This can be used to intercept
6053     * key events in special situations before the IME consumes them; a
6054     * typical example would be handling the BACK key to update the application's
6055     * UI instead of allowing the IME to see it and close itself.
6056     *
6057     * @param keyCode The value in event.getKeyCode().
6058     * @param event Description of the key event.
6059     * @return If you handled the event, return true. If you want to allow the
6060     *         event to be handled by the next receiver, return false.
6061     */
6062    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6063        return false;
6064    }
6065
6066    /**
6067     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6068     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6069     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6070     * is released, if the view is enabled and clickable.
6071     *
6072     * @param keyCode A key code that represents the button pressed, from
6073     *                {@link android.view.KeyEvent}.
6074     * @param event   The KeyEvent object that defines the button action.
6075     */
6076    public boolean onKeyDown(int keyCode, KeyEvent event) {
6077        boolean result = false;
6078
6079        switch (keyCode) {
6080            case KeyEvent.KEYCODE_DPAD_CENTER:
6081            case KeyEvent.KEYCODE_ENTER: {
6082                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6083                    return true;
6084                }
6085                // Long clickable items don't necessarily have to be clickable
6086                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6087                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6088                        (event.getRepeatCount() == 0)) {
6089                    setPressed(true);
6090                    checkForLongClick(0);
6091                    return true;
6092                }
6093                break;
6094            }
6095        }
6096        return result;
6097    }
6098
6099    /**
6100     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6101     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6102     * the event).
6103     */
6104    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6105        return false;
6106    }
6107
6108    /**
6109     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6110     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6111     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6112     * {@link KeyEvent#KEYCODE_ENTER} is released.
6113     *
6114     * @param keyCode A key code that represents the button pressed, from
6115     *                {@link android.view.KeyEvent}.
6116     * @param event   The KeyEvent object that defines the button action.
6117     */
6118    public boolean onKeyUp(int keyCode, KeyEvent event) {
6119        boolean result = false;
6120
6121        switch (keyCode) {
6122            case KeyEvent.KEYCODE_DPAD_CENTER:
6123            case KeyEvent.KEYCODE_ENTER: {
6124                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6125                    return true;
6126                }
6127                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6128                    setPressed(false);
6129
6130                    if (!mHasPerformedLongPress) {
6131                        // This is a tap, so remove the longpress check
6132                        removeLongPressCallback();
6133
6134                        result = performClick();
6135                    }
6136                }
6137                break;
6138            }
6139        }
6140        return result;
6141    }
6142
6143    /**
6144     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6145     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6146     * the event).
6147     *
6148     * @param keyCode     A key code that represents the button pressed, from
6149     *                    {@link android.view.KeyEvent}.
6150     * @param repeatCount The number of times the action was made.
6151     * @param event       The KeyEvent object that defines the button action.
6152     */
6153    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6154        return false;
6155    }
6156
6157    /**
6158     * Called on the focused view when a key shortcut event is not handled.
6159     * Override this method to implement local key shortcuts for the View.
6160     * Key shortcuts can also be implemented by setting the
6161     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6162     *
6163     * @param keyCode The value in event.getKeyCode().
6164     * @param event Description of the key event.
6165     * @return If you handled the event, return true. If you want to allow the
6166     *         event to be handled by the next receiver, return false.
6167     */
6168    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6169        return false;
6170    }
6171
6172    /**
6173     * Check whether the called view is a text editor, in which case it
6174     * would make sense to automatically display a soft input window for
6175     * it.  Subclasses should override this if they implement
6176     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6177     * a call on that method would return a non-null InputConnection, and
6178     * they are really a first-class editor that the user would normally
6179     * start typing on when the go into a window containing your view.
6180     *
6181     * <p>The default implementation always returns false.  This does
6182     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6183     * will not be called or the user can not otherwise perform edits on your
6184     * view; it is just a hint to the system that this is not the primary
6185     * purpose of this view.
6186     *
6187     * @return Returns true if this view is a text editor, else false.
6188     */
6189    public boolean onCheckIsTextEditor() {
6190        return false;
6191    }
6192
6193    /**
6194     * Create a new InputConnection for an InputMethod to interact
6195     * with the view.  The default implementation returns null, since it doesn't
6196     * support input methods.  You can override this to implement such support.
6197     * This is only needed for views that take focus and text input.
6198     *
6199     * <p>When implementing this, you probably also want to implement
6200     * {@link #onCheckIsTextEditor()} to indicate you will return a
6201     * non-null InputConnection.
6202     *
6203     * @param outAttrs Fill in with attribute information about the connection.
6204     */
6205    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6206        return null;
6207    }
6208
6209    /**
6210     * Called by the {@link android.view.inputmethod.InputMethodManager}
6211     * when a view who is not the current
6212     * input connection target is trying to make a call on the manager.  The
6213     * default implementation returns false; you can override this to return
6214     * true for certain views if you are performing InputConnection proxying
6215     * to them.
6216     * @param view The View that is making the InputMethodManager call.
6217     * @return Return true to allow the call, false to reject.
6218     */
6219    public boolean checkInputConnectionProxy(View view) {
6220        return false;
6221    }
6222
6223    /**
6224     * Show the context menu for this view. It is not safe to hold on to the
6225     * menu after returning from this method.
6226     *
6227     * You should normally not overload this method. Overload
6228     * {@link #onCreateContextMenu(ContextMenu)} or define an
6229     * {@link OnCreateContextMenuListener} to add items to the context menu.
6230     *
6231     * @param menu The context menu to populate
6232     */
6233    public void createContextMenu(ContextMenu menu) {
6234        ContextMenuInfo menuInfo = getContextMenuInfo();
6235
6236        // Sets the current menu info so all items added to menu will have
6237        // my extra info set.
6238        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6239
6240        onCreateContextMenu(menu);
6241        ListenerInfo li = mListenerInfo;
6242        if (li != null && li.mOnCreateContextMenuListener != null) {
6243            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6244        }
6245
6246        // Clear the extra information so subsequent items that aren't mine don't
6247        // have my extra info.
6248        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6249
6250        if (mParent != null) {
6251            mParent.createContextMenu(menu);
6252        }
6253    }
6254
6255    /**
6256     * Views should implement this if they have extra information to associate
6257     * with the context menu. The return result is supplied as a parameter to
6258     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6259     * callback.
6260     *
6261     * @return Extra information about the item for which the context menu
6262     *         should be shown. This information will vary across different
6263     *         subclasses of View.
6264     */
6265    protected ContextMenuInfo getContextMenuInfo() {
6266        return null;
6267    }
6268
6269    /**
6270     * Views should implement this if the view itself is going to add items to
6271     * the context menu.
6272     *
6273     * @param menu the context menu to populate
6274     */
6275    protected void onCreateContextMenu(ContextMenu menu) {
6276    }
6277
6278    /**
6279     * Implement this method to handle trackball motion events.  The
6280     * <em>relative</em> movement of the trackball since the last event
6281     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6282     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6283     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6284     * they will often be fractional values, representing the more fine-grained
6285     * movement information available from a trackball).
6286     *
6287     * @param event The motion event.
6288     * @return True if the event was handled, false otherwise.
6289     */
6290    public boolean onTrackballEvent(MotionEvent event) {
6291        return false;
6292    }
6293
6294    /**
6295     * Implement this method to handle generic motion events.
6296     * <p>
6297     * Generic motion events describe joystick movements, mouse hovers, track pad
6298     * touches, scroll wheel movements and other input events.  The
6299     * {@link MotionEvent#getSource() source} of the motion event specifies
6300     * the class of input that was received.  Implementations of this method
6301     * must examine the bits in the source before processing the event.
6302     * The following code example shows how this is done.
6303     * </p><p>
6304     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6305     * are delivered to the view under the pointer.  All other generic motion events are
6306     * delivered to the focused view.
6307     * </p>
6308     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6309     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6310     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6311     *             // process the joystick movement...
6312     *             return true;
6313     *         }
6314     *     }
6315     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6316     *         switch (event.getAction()) {
6317     *             case MotionEvent.ACTION_HOVER_MOVE:
6318     *                 // process the mouse hover movement...
6319     *                 return true;
6320     *             case MotionEvent.ACTION_SCROLL:
6321     *                 // process the scroll wheel movement...
6322     *                 return true;
6323     *         }
6324     *     }
6325     *     return super.onGenericMotionEvent(event);
6326     * }</pre>
6327     *
6328     * @param event The generic motion event being processed.
6329     * @return True if the event was handled, false otherwise.
6330     */
6331    public boolean onGenericMotionEvent(MotionEvent event) {
6332        return false;
6333    }
6334
6335    /**
6336     * Implement this method to handle hover events.
6337     * <p>
6338     * This method is called whenever a pointer is hovering into, over, or out of the
6339     * bounds of a view and the view is not currently being touched.
6340     * Hover events are represented as pointer events with action
6341     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6342     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6343     * </p>
6344     * <ul>
6345     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6346     * when the pointer enters the bounds of the view.</li>
6347     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6348     * when the pointer has already entered the bounds of the view and has moved.</li>
6349     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6350     * when the pointer has exited the bounds of the view or when the pointer is
6351     * about to go down due to a button click, tap, or similar user action that
6352     * causes the view to be touched.</li>
6353     * </ul>
6354     * <p>
6355     * The view should implement this method to return true to indicate that it is
6356     * handling the hover event, such as by changing its drawable state.
6357     * </p><p>
6358     * The default implementation calls {@link #setHovered} to update the hovered state
6359     * of the view when a hover enter or hover exit event is received, if the view
6360     * is enabled and is clickable.  The default implementation also sends hover
6361     * accessibility events.
6362     * </p>
6363     *
6364     * @param event The motion event that describes the hover.
6365     * @return True if the view handled the hover event.
6366     *
6367     * @see #isHovered
6368     * @see #setHovered
6369     * @see #onHoverChanged
6370     */
6371    public boolean onHoverEvent(MotionEvent event) {
6372        // The root view may receive hover (or touch) events that are outside the bounds of
6373        // the window.  This code ensures that we only send accessibility events for
6374        // hovers that are actually within the bounds of the root view.
6375        final int action = event.getAction();
6376        if (!mSendingHoverAccessibilityEvents) {
6377            if ((action == MotionEvent.ACTION_HOVER_ENTER
6378                    || action == MotionEvent.ACTION_HOVER_MOVE)
6379                    && !hasHoveredChild()
6380                    && pointInView(event.getX(), event.getY())) {
6381                mSendingHoverAccessibilityEvents = true;
6382                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6383            }
6384        } else {
6385            if (action == MotionEvent.ACTION_HOVER_EXIT
6386                    || (action == MotionEvent.ACTION_HOVER_MOVE
6387                            && !pointInView(event.getX(), event.getY()))) {
6388                mSendingHoverAccessibilityEvents = false;
6389                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6390            }
6391        }
6392
6393        if (isHoverable()) {
6394            switch (action) {
6395                case MotionEvent.ACTION_HOVER_ENTER:
6396                    setHovered(true);
6397                    break;
6398                case MotionEvent.ACTION_HOVER_EXIT:
6399                    setHovered(false);
6400                    break;
6401            }
6402
6403            // Dispatch the event to onGenericMotionEvent before returning true.
6404            // This is to provide compatibility with existing applications that
6405            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6406            // break because of the new default handling for hoverable views
6407            // in onHoverEvent.
6408            // Note that onGenericMotionEvent will be called by default when
6409            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6410            dispatchGenericMotionEventInternal(event);
6411            return true;
6412        }
6413        return false;
6414    }
6415
6416    /**
6417     * Returns true if the view should handle {@link #onHoverEvent}
6418     * by calling {@link #setHovered} to change its hovered state.
6419     *
6420     * @return True if the view is hoverable.
6421     */
6422    private boolean isHoverable() {
6423        final int viewFlags = mViewFlags;
6424        //noinspection SimplifiableIfStatement
6425        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6426            return false;
6427        }
6428
6429        return (viewFlags & CLICKABLE) == CLICKABLE
6430                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6431    }
6432
6433    /**
6434     * Returns true if the view is currently hovered.
6435     *
6436     * @return True if the view is currently hovered.
6437     *
6438     * @see #setHovered
6439     * @see #onHoverChanged
6440     */
6441    @ViewDebug.ExportedProperty
6442    public boolean isHovered() {
6443        return (mPrivateFlags & HOVERED) != 0;
6444    }
6445
6446    /**
6447     * Sets whether the view is currently hovered.
6448     * <p>
6449     * Calling this method also changes the drawable state of the view.  This
6450     * enables the view to react to hover by using different drawable resources
6451     * to change its appearance.
6452     * </p><p>
6453     * The {@link #onHoverChanged} method is called when the hovered state changes.
6454     * </p>
6455     *
6456     * @param hovered True if the view is hovered.
6457     *
6458     * @see #isHovered
6459     * @see #onHoverChanged
6460     */
6461    public void setHovered(boolean hovered) {
6462        if (hovered) {
6463            if ((mPrivateFlags & HOVERED) == 0) {
6464                mPrivateFlags |= HOVERED;
6465                refreshDrawableState();
6466                onHoverChanged(true);
6467            }
6468        } else {
6469            if ((mPrivateFlags & HOVERED) != 0) {
6470                mPrivateFlags &= ~HOVERED;
6471                refreshDrawableState();
6472                onHoverChanged(false);
6473            }
6474        }
6475    }
6476
6477    /**
6478     * Implement this method to handle hover state changes.
6479     * <p>
6480     * This method is called whenever the hover state changes as a result of a
6481     * call to {@link #setHovered}.
6482     * </p>
6483     *
6484     * @param hovered The current hover state, as returned by {@link #isHovered}.
6485     *
6486     * @see #isHovered
6487     * @see #setHovered
6488     */
6489    public void onHoverChanged(boolean hovered) {
6490    }
6491
6492    /**
6493     * Implement this method to handle touch screen motion events.
6494     *
6495     * @param event The motion event.
6496     * @return True if the event was handled, false otherwise.
6497     */
6498    public boolean onTouchEvent(MotionEvent event) {
6499        final int viewFlags = mViewFlags;
6500
6501        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6502            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6503                mPrivateFlags &= ~PRESSED;
6504                refreshDrawableState();
6505            }
6506            // A disabled view that is clickable still consumes the touch
6507            // events, it just doesn't respond to them.
6508            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6509                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6510        }
6511
6512        if (mTouchDelegate != null) {
6513            if (mTouchDelegate.onTouchEvent(event)) {
6514                return true;
6515            }
6516        }
6517
6518        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6519                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6520            switch (event.getAction()) {
6521                case MotionEvent.ACTION_UP:
6522                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6523                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6524                        // take focus if we don't have it already and we should in
6525                        // touch mode.
6526                        boolean focusTaken = false;
6527                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6528                            focusTaken = requestFocus();
6529                        }
6530
6531                        if (prepressed) {
6532                            // The button is being released before we actually
6533                            // showed it as pressed.  Make it show the pressed
6534                            // state now (before scheduling the click) to ensure
6535                            // the user sees it.
6536                            mPrivateFlags |= PRESSED;
6537                            refreshDrawableState();
6538                       }
6539
6540                        if (!mHasPerformedLongPress) {
6541                            // This is a tap, so remove the longpress check
6542                            removeLongPressCallback();
6543
6544                            // Only perform take click actions if we were in the pressed state
6545                            if (!focusTaken) {
6546                                // Use a Runnable and post this rather than calling
6547                                // performClick directly. This lets other visual state
6548                                // of the view update before click actions start.
6549                                if (mPerformClick == null) {
6550                                    mPerformClick = new PerformClick();
6551                                }
6552                                if (!post(mPerformClick)) {
6553                                    performClick();
6554                                }
6555                            }
6556                        }
6557
6558                        if (mUnsetPressedState == null) {
6559                            mUnsetPressedState = new UnsetPressedState();
6560                        }
6561
6562                        if (prepressed) {
6563                            postDelayed(mUnsetPressedState,
6564                                    ViewConfiguration.getPressedStateDuration());
6565                        } else if (!post(mUnsetPressedState)) {
6566                            // If the post failed, unpress right now
6567                            mUnsetPressedState.run();
6568                        }
6569                        removeTapCallback();
6570                    }
6571                    break;
6572
6573                case MotionEvent.ACTION_DOWN:
6574                    mHasPerformedLongPress = false;
6575
6576                    if (performButtonActionOnTouchDown(event)) {
6577                        break;
6578                    }
6579
6580                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6581                    boolean isInScrollingContainer = isInScrollingContainer();
6582
6583                    // For views inside a scrolling container, delay the pressed feedback for
6584                    // a short period in case this is a scroll.
6585                    if (isInScrollingContainer) {
6586                        mPrivateFlags |= PREPRESSED;
6587                        if (mPendingCheckForTap == null) {
6588                            mPendingCheckForTap = new CheckForTap();
6589                        }
6590                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6591                    } else {
6592                        // Not inside a scrolling container, so show the feedback right away
6593                        mPrivateFlags |= PRESSED;
6594                        refreshDrawableState();
6595                        checkForLongClick(0);
6596                    }
6597                    break;
6598
6599                case MotionEvent.ACTION_CANCEL:
6600                    mPrivateFlags &= ~PRESSED;
6601                    refreshDrawableState();
6602                    removeTapCallback();
6603                    break;
6604
6605                case MotionEvent.ACTION_MOVE:
6606                    final int x = (int) event.getX();
6607                    final int y = (int) event.getY();
6608
6609                    // Be lenient about moving outside of buttons
6610                    if (!pointInView(x, y, mTouchSlop)) {
6611                        // Outside button
6612                        removeTapCallback();
6613                        if ((mPrivateFlags & PRESSED) != 0) {
6614                            // Remove any future long press/tap checks
6615                            removeLongPressCallback();
6616
6617                            // Need to switch from pressed to not pressed
6618                            mPrivateFlags &= ~PRESSED;
6619                            refreshDrawableState();
6620                        }
6621                    }
6622                    break;
6623            }
6624            return true;
6625        }
6626
6627        return false;
6628    }
6629
6630    /**
6631     * @hide
6632     */
6633    public boolean isInScrollingContainer() {
6634        ViewParent p = getParent();
6635        while (p != null && p instanceof ViewGroup) {
6636            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6637                return true;
6638            }
6639            p = p.getParent();
6640        }
6641        return false;
6642    }
6643
6644    /**
6645     * Remove the longpress detection timer.
6646     */
6647    private void removeLongPressCallback() {
6648        if (mPendingCheckForLongPress != null) {
6649          removeCallbacks(mPendingCheckForLongPress);
6650        }
6651    }
6652
6653    /**
6654     * Remove the pending click action
6655     */
6656    private void removePerformClickCallback() {
6657        if (mPerformClick != null) {
6658            removeCallbacks(mPerformClick);
6659        }
6660    }
6661
6662    /**
6663     * Remove the prepress detection timer.
6664     */
6665    private void removeUnsetPressCallback() {
6666        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6667            setPressed(false);
6668            removeCallbacks(mUnsetPressedState);
6669        }
6670    }
6671
6672    /**
6673     * Remove the tap detection timer.
6674     */
6675    private void removeTapCallback() {
6676        if (mPendingCheckForTap != null) {
6677            mPrivateFlags &= ~PREPRESSED;
6678            removeCallbacks(mPendingCheckForTap);
6679        }
6680    }
6681
6682    /**
6683     * Cancels a pending long press.  Your subclass can use this if you
6684     * want the context menu to come up if the user presses and holds
6685     * at the same place, but you don't want it to come up if they press
6686     * and then move around enough to cause scrolling.
6687     */
6688    public void cancelLongPress() {
6689        removeLongPressCallback();
6690
6691        /*
6692         * The prepressed state handled by the tap callback is a display
6693         * construct, but the tap callback will post a long press callback
6694         * less its own timeout. Remove it here.
6695         */
6696        removeTapCallback();
6697    }
6698
6699    /**
6700     * Remove the pending callback for sending a
6701     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6702     */
6703    private void removeSendViewScrolledAccessibilityEventCallback() {
6704        if (mSendViewScrolledAccessibilityEvent != null) {
6705            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6706        }
6707    }
6708
6709    /**
6710     * Sets the TouchDelegate for this View.
6711     */
6712    public void setTouchDelegate(TouchDelegate delegate) {
6713        mTouchDelegate = delegate;
6714    }
6715
6716    /**
6717     * Gets the TouchDelegate for this View.
6718     */
6719    public TouchDelegate getTouchDelegate() {
6720        return mTouchDelegate;
6721    }
6722
6723    /**
6724     * Set flags controlling behavior of this view.
6725     *
6726     * @param flags Constant indicating the value which should be set
6727     * @param mask Constant indicating the bit range that should be changed
6728     */
6729    void setFlags(int flags, int mask) {
6730        int old = mViewFlags;
6731        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6732
6733        int changed = mViewFlags ^ old;
6734        if (changed == 0) {
6735            return;
6736        }
6737        int privateFlags = mPrivateFlags;
6738
6739        /* Check if the FOCUSABLE bit has changed */
6740        if (((changed & FOCUSABLE_MASK) != 0) &&
6741                ((privateFlags & HAS_BOUNDS) !=0)) {
6742            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6743                    && ((privateFlags & FOCUSED) != 0)) {
6744                /* Give up focus if we are no longer focusable */
6745                clearFocus();
6746            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6747                    && ((privateFlags & FOCUSED) == 0)) {
6748                /*
6749                 * Tell the view system that we are now available to take focus
6750                 * if no one else already has it.
6751                 */
6752                if (mParent != null) mParent.focusableViewAvailable(this);
6753            }
6754        }
6755
6756        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6757            if ((changed & VISIBILITY_MASK) != 0) {
6758                /*
6759                 * If this view is becoming visible, invalidate it in case it changed while
6760                 * it was not visible. Marking it drawn ensures that the invalidation will
6761                 * go through.
6762                 */
6763                mPrivateFlags |= DRAWN;
6764                invalidate(true);
6765
6766                needGlobalAttributesUpdate(true);
6767
6768                // a view becoming visible is worth notifying the parent
6769                // about in case nothing has focus.  even if this specific view
6770                // isn't focusable, it may contain something that is, so let
6771                // the root view try to give this focus if nothing else does.
6772                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6773                    mParent.focusableViewAvailable(this);
6774                }
6775            }
6776        }
6777
6778        /* Check if the GONE bit has changed */
6779        if ((changed & GONE) != 0) {
6780            needGlobalAttributesUpdate(false);
6781            requestLayout();
6782
6783            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6784                if (hasFocus()) clearFocus();
6785                destroyDrawingCache();
6786                if (mParent instanceof View) {
6787                    // GONE views noop invalidation, so invalidate the parent
6788                    ((View) mParent).invalidate(true);
6789                }
6790                // Mark the view drawn to ensure that it gets invalidated properly the next
6791                // time it is visible and gets invalidated
6792                mPrivateFlags |= DRAWN;
6793            }
6794            if (mAttachInfo != null) {
6795                mAttachInfo.mViewVisibilityChanged = true;
6796            }
6797        }
6798
6799        /* Check if the VISIBLE bit has changed */
6800        if ((changed & INVISIBLE) != 0) {
6801            needGlobalAttributesUpdate(false);
6802            /*
6803             * If this view is becoming invisible, set the DRAWN flag so that
6804             * the next invalidate() will not be skipped.
6805             */
6806            mPrivateFlags |= DRAWN;
6807
6808            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6809                // root view becoming invisible shouldn't clear focus
6810                if (getRootView() != this) {
6811                    clearFocus();
6812                }
6813            }
6814            if (mAttachInfo != null) {
6815                mAttachInfo.mViewVisibilityChanged = true;
6816            }
6817        }
6818
6819        if ((changed & VISIBILITY_MASK) != 0) {
6820            if (mParent instanceof ViewGroup) {
6821                ((ViewGroup) mParent).onChildVisibilityChanged(this, (changed & VISIBILITY_MASK),
6822                        (flags & VISIBILITY_MASK));
6823                ((View) mParent).invalidate(true);
6824            } else if (mParent != null) {
6825                mParent.invalidateChild(this, null);
6826            }
6827            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6828        }
6829
6830        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6831            destroyDrawingCache();
6832        }
6833
6834        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6835            destroyDrawingCache();
6836            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6837            invalidateParentCaches();
6838        }
6839
6840        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6841            destroyDrawingCache();
6842            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6843        }
6844
6845        if ((changed & DRAW_MASK) != 0) {
6846            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6847                if (mBGDrawable != null) {
6848                    mPrivateFlags &= ~SKIP_DRAW;
6849                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6850                } else {
6851                    mPrivateFlags |= SKIP_DRAW;
6852                }
6853            } else {
6854                mPrivateFlags &= ~SKIP_DRAW;
6855            }
6856            requestLayout();
6857            invalidate(true);
6858        }
6859
6860        if ((changed & KEEP_SCREEN_ON) != 0) {
6861            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6862                mParent.recomputeViewAttributes(this);
6863            }
6864        }
6865
6866        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6867            requestLayout();
6868        }
6869    }
6870
6871    /**
6872     * Change the view's z order in the tree, so it's on top of other sibling
6873     * views
6874     */
6875    public void bringToFront() {
6876        if (mParent != null) {
6877            mParent.bringChildToFront(this);
6878        }
6879    }
6880
6881    /**
6882     * This is called in response to an internal scroll in this view (i.e., the
6883     * view scrolled its own contents). This is typically as a result of
6884     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6885     * called.
6886     *
6887     * @param l Current horizontal scroll origin.
6888     * @param t Current vertical scroll origin.
6889     * @param oldl Previous horizontal scroll origin.
6890     * @param oldt Previous vertical scroll origin.
6891     */
6892    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6893        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6894            postSendViewScrolledAccessibilityEventCallback();
6895        }
6896
6897        mBackgroundSizeChanged = true;
6898
6899        final AttachInfo ai = mAttachInfo;
6900        if (ai != null) {
6901            ai.mViewScrollChanged = true;
6902        }
6903    }
6904
6905    /**
6906     * Interface definition for a callback to be invoked when the layout bounds of a view
6907     * changes due to layout processing.
6908     */
6909    public interface OnLayoutChangeListener {
6910        /**
6911         * Called when the focus state of a view has changed.
6912         *
6913         * @param v The view whose state has changed.
6914         * @param left The new value of the view's left property.
6915         * @param top The new value of the view's top property.
6916         * @param right The new value of the view's right property.
6917         * @param bottom The new value of the view's bottom property.
6918         * @param oldLeft The previous value of the view's left property.
6919         * @param oldTop The previous value of the view's top property.
6920         * @param oldRight The previous value of the view's right property.
6921         * @param oldBottom The previous value of the view's bottom property.
6922         */
6923        void onLayoutChange(View v, int left, int top, int right, int bottom,
6924            int oldLeft, int oldTop, int oldRight, int oldBottom);
6925    }
6926
6927    /**
6928     * This is called during layout when the size of this view has changed. If
6929     * you were just added to the view hierarchy, you're called with the old
6930     * values of 0.
6931     *
6932     * @param w Current width of this view.
6933     * @param h Current height of this view.
6934     * @param oldw Old width of this view.
6935     * @param oldh Old height of this view.
6936     */
6937    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6938    }
6939
6940    /**
6941     * Called by draw to draw the child views. This may be overridden
6942     * by derived classes to gain control just before its children are drawn
6943     * (but after its own view has been drawn).
6944     * @param canvas the canvas on which to draw the view
6945     */
6946    protected void dispatchDraw(Canvas canvas) {
6947    }
6948
6949    /**
6950     * Gets the parent of this view. Note that the parent is a
6951     * ViewParent and not necessarily a View.
6952     *
6953     * @return Parent of this view.
6954     */
6955    public final ViewParent getParent() {
6956        return mParent;
6957    }
6958
6959    /**
6960     * Set the horizontal scrolled position of your view. This will cause a call to
6961     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6962     * invalidated.
6963     * @param value the x position to scroll to
6964     */
6965    public void setScrollX(int value) {
6966        scrollTo(value, mScrollY);
6967    }
6968
6969    /**
6970     * Set the vertical scrolled position of your view. This will cause a call to
6971     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6972     * invalidated.
6973     * @param value the y position to scroll to
6974     */
6975    public void setScrollY(int value) {
6976        scrollTo(mScrollX, value);
6977    }
6978
6979    /**
6980     * Return the scrolled left position of this view. This is the left edge of
6981     * the displayed part of your view. You do not need to draw any pixels
6982     * farther left, since those are outside of the frame of your view on
6983     * screen.
6984     *
6985     * @return The left edge of the displayed part of your view, in pixels.
6986     */
6987    public final int getScrollX() {
6988        return mScrollX;
6989    }
6990
6991    /**
6992     * Return the scrolled top position of this view. This is the top edge of
6993     * the displayed part of your view. You do not need to draw any pixels above
6994     * it, since those are outside of the frame of your view on screen.
6995     *
6996     * @return The top edge of the displayed part of your view, in pixels.
6997     */
6998    public final int getScrollY() {
6999        return mScrollY;
7000    }
7001
7002    /**
7003     * Return the width of the your view.
7004     *
7005     * @return The width of your view, in pixels.
7006     */
7007    @ViewDebug.ExportedProperty(category = "layout")
7008    public final int getWidth() {
7009        return mRight - mLeft;
7010    }
7011
7012    /**
7013     * Return the height of your view.
7014     *
7015     * @return The height of your view, in pixels.
7016     */
7017    @ViewDebug.ExportedProperty(category = "layout")
7018    public final int getHeight() {
7019        return mBottom - mTop;
7020    }
7021
7022    /**
7023     * Return the visible drawing bounds of your view. Fills in the output
7024     * rectangle with the values from getScrollX(), getScrollY(),
7025     * getWidth(), and getHeight().
7026     *
7027     * @param outRect The (scrolled) drawing bounds of the view.
7028     */
7029    public void getDrawingRect(Rect outRect) {
7030        outRect.left = mScrollX;
7031        outRect.top = mScrollY;
7032        outRect.right = mScrollX + (mRight - mLeft);
7033        outRect.bottom = mScrollY + (mBottom - mTop);
7034    }
7035
7036    /**
7037     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7038     * raw width component (that is the result is masked by
7039     * {@link #MEASURED_SIZE_MASK}).
7040     *
7041     * @return The raw measured width of this view.
7042     */
7043    public final int getMeasuredWidth() {
7044        return mMeasuredWidth & MEASURED_SIZE_MASK;
7045    }
7046
7047    /**
7048     * Return the full width measurement information for this view as computed
7049     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7050     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7051     * This should be used during measurement and layout calculations only. Use
7052     * {@link #getWidth()} to see how wide a view is after layout.
7053     *
7054     * @return The measured width of this view as a bit mask.
7055     */
7056    public final int getMeasuredWidthAndState() {
7057        return mMeasuredWidth;
7058    }
7059
7060    /**
7061     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7062     * raw width component (that is the result is masked by
7063     * {@link #MEASURED_SIZE_MASK}).
7064     *
7065     * @return The raw measured height of this view.
7066     */
7067    public final int getMeasuredHeight() {
7068        return mMeasuredHeight & MEASURED_SIZE_MASK;
7069    }
7070
7071    /**
7072     * Return the full height measurement information for this view as computed
7073     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7074     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7075     * This should be used during measurement and layout calculations only. Use
7076     * {@link #getHeight()} to see how wide a view is after layout.
7077     *
7078     * @return The measured width of this view as a bit mask.
7079     */
7080    public final int getMeasuredHeightAndState() {
7081        return mMeasuredHeight;
7082    }
7083
7084    /**
7085     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7086     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7087     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7088     * and the height component is at the shifted bits
7089     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7090     */
7091    public final int getMeasuredState() {
7092        return (mMeasuredWidth&MEASURED_STATE_MASK)
7093                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7094                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7095    }
7096
7097    /**
7098     * The transform matrix of this view, which is calculated based on the current
7099     * roation, scale, and pivot properties.
7100     *
7101     * @see #getRotation()
7102     * @see #getScaleX()
7103     * @see #getScaleY()
7104     * @see #getPivotX()
7105     * @see #getPivotY()
7106     * @return The current transform matrix for the view
7107     */
7108    public Matrix getMatrix() {
7109        if (mTransformationInfo != null) {
7110            updateMatrix();
7111            return mTransformationInfo.mMatrix;
7112        }
7113        return Matrix.IDENTITY_MATRIX;
7114    }
7115
7116    /**
7117     * Utility function to determine if the value is far enough away from zero to be
7118     * considered non-zero.
7119     * @param value A floating point value to check for zero-ness
7120     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7121     */
7122    private static boolean nonzero(float value) {
7123        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7124    }
7125
7126    /**
7127     * Returns true if the transform matrix is the identity matrix.
7128     * Recomputes the matrix if necessary.
7129     *
7130     * @return True if the transform matrix is the identity matrix, false otherwise.
7131     */
7132    final boolean hasIdentityMatrix() {
7133        if (mTransformationInfo != null) {
7134            updateMatrix();
7135            return mTransformationInfo.mMatrixIsIdentity;
7136        }
7137        return true;
7138    }
7139
7140    void ensureTransformationInfo() {
7141        if (mTransformationInfo == null) {
7142            mTransformationInfo = new TransformationInfo();
7143        }
7144    }
7145
7146    /**
7147     * Recomputes the transform matrix if necessary.
7148     */
7149    private void updateMatrix() {
7150        final TransformationInfo info = mTransformationInfo;
7151        if (info == null) {
7152            return;
7153        }
7154        if (info.mMatrixDirty) {
7155            // transform-related properties have changed since the last time someone
7156            // asked for the matrix; recalculate it with the current values
7157
7158            // Figure out if we need to update the pivot point
7159            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7160                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7161                    info.mPrevWidth = mRight - mLeft;
7162                    info.mPrevHeight = mBottom - mTop;
7163                    info.mPivotX = info.mPrevWidth / 2f;
7164                    info.mPivotY = info.mPrevHeight / 2f;
7165                }
7166            }
7167            info.mMatrix.reset();
7168            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7169                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7170                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7171                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7172            } else {
7173                if (info.mCamera == null) {
7174                    info.mCamera = new Camera();
7175                    info.matrix3D = new Matrix();
7176                }
7177                info.mCamera.save();
7178                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7179                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7180                info.mCamera.getMatrix(info.matrix3D);
7181                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7182                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7183                        info.mPivotY + info.mTranslationY);
7184                info.mMatrix.postConcat(info.matrix3D);
7185                info.mCamera.restore();
7186            }
7187            info.mMatrixDirty = false;
7188            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7189            info.mInverseMatrixDirty = true;
7190        }
7191    }
7192
7193    /**
7194     * Utility method to retrieve the inverse of the current mMatrix property.
7195     * We cache the matrix to avoid recalculating it when transform properties
7196     * have not changed.
7197     *
7198     * @return The inverse of the current matrix of this view.
7199     */
7200    final Matrix getInverseMatrix() {
7201        final TransformationInfo info = mTransformationInfo;
7202        if (info != null) {
7203            updateMatrix();
7204            if (info.mInverseMatrixDirty) {
7205                if (info.mInverseMatrix == null) {
7206                    info.mInverseMatrix = new Matrix();
7207                }
7208                info.mMatrix.invert(info.mInverseMatrix);
7209                info.mInverseMatrixDirty = false;
7210            }
7211            return info.mInverseMatrix;
7212        }
7213        return Matrix.IDENTITY_MATRIX;
7214    }
7215
7216    /**
7217     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7218     * views are drawn) from the camera to this view. The camera's distance
7219     * affects 3D transformations, for instance rotations around the X and Y
7220     * axis. If the rotationX or rotationY properties are changed and this view is
7221     * large (more than half the size of the screen), it is recommended to always
7222     * use a camera distance that's greater than the height (X axis rotation) or
7223     * the width (Y axis rotation) of this view.</p>
7224     *
7225     * <p>The distance of the camera from the view plane can have an affect on the
7226     * perspective distortion of the view when it is rotated around the x or y axis.
7227     * For example, a large distance will result in a large viewing angle, and there
7228     * will not be much perspective distortion of the view as it rotates. A short
7229     * distance may cause much more perspective distortion upon rotation, and can
7230     * also result in some drawing artifacts if the rotated view ends up partially
7231     * behind the camera (which is why the recommendation is to use a distance at
7232     * least as far as the size of the view, if the view is to be rotated.)</p>
7233     *
7234     * <p>The distance is expressed in "depth pixels." The default distance depends
7235     * on the screen density. For instance, on a medium density display, the
7236     * default distance is 1280. On a high density display, the default distance
7237     * is 1920.</p>
7238     *
7239     * <p>If you want to specify a distance that leads to visually consistent
7240     * results across various densities, use the following formula:</p>
7241     * <pre>
7242     * float scale = context.getResources().getDisplayMetrics().density;
7243     * view.setCameraDistance(distance * scale);
7244     * </pre>
7245     *
7246     * <p>The density scale factor of a high density display is 1.5,
7247     * and 1920 = 1280 * 1.5.</p>
7248     *
7249     * @param distance The distance in "depth pixels", if negative the opposite
7250     *        value is used
7251     *
7252     * @see #setRotationX(float)
7253     * @see #setRotationY(float)
7254     */
7255    public void setCameraDistance(float distance) {
7256        invalidateParentCaches();
7257        invalidate(false);
7258
7259        ensureTransformationInfo();
7260        final float dpi = mResources.getDisplayMetrics().densityDpi;
7261        final TransformationInfo info = mTransformationInfo;
7262        if (info.mCamera == null) {
7263            info.mCamera = new Camera();
7264            info.matrix3D = new Matrix();
7265        }
7266
7267        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7268        info.mMatrixDirty = true;
7269
7270        invalidate(false);
7271    }
7272
7273    /**
7274     * The degrees that the view is rotated around the pivot point.
7275     *
7276     * @see #setRotation(float)
7277     * @see #getPivotX()
7278     * @see #getPivotY()
7279     *
7280     * @return The degrees of rotation.
7281     */
7282    @ViewDebug.ExportedProperty(category = "drawing")
7283    public float getRotation() {
7284        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7285    }
7286
7287    /**
7288     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7289     * result in clockwise rotation.
7290     *
7291     * @param rotation The degrees of rotation.
7292     *
7293     * @see #getRotation()
7294     * @see #getPivotX()
7295     * @see #getPivotY()
7296     * @see #setRotationX(float)
7297     * @see #setRotationY(float)
7298     *
7299     * @attr ref android.R.styleable#View_rotation
7300     */
7301    public void setRotation(float rotation) {
7302        ensureTransformationInfo();
7303        final TransformationInfo info = mTransformationInfo;
7304        if (info.mRotation != rotation) {
7305            invalidateParentCaches();
7306            // Double-invalidation is necessary to capture view's old and new areas
7307            invalidate(false);
7308            info.mRotation = rotation;
7309            info.mMatrixDirty = true;
7310            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7311            invalidate(false);
7312        }
7313    }
7314
7315    /**
7316     * The degrees that the view is rotated around the vertical axis through the pivot point.
7317     *
7318     * @see #getPivotX()
7319     * @see #getPivotY()
7320     * @see #setRotationY(float)
7321     *
7322     * @return The degrees of Y rotation.
7323     */
7324    @ViewDebug.ExportedProperty(category = "drawing")
7325    public float getRotationY() {
7326        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7327    }
7328
7329    /**
7330     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7331     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7332     * down the y axis.
7333     *
7334     * When rotating large views, it is recommended to adjust the camera distance
7335     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7336     *
7337     * @param rotationY The degrees of Y rotation.
7338     *
7339     * @see #getRotationY()
7340     * @see #getPivotX()
7341     * @see #getPivotY()
7342     * @see #setRotation(float)
7343     * @see #setRotationX(float)
7344     * @see #setCameraDistance(float)
7345     *
7346     * @attr ref android.R.styleable#View_rotationY
7347     */
7348    public void setRotationY(float rotationY) {
7349        ensureTransformationInfo();
7350        final TransformationInfo info = mTransformationInfo;
7351        if (info.mRotationY != rotationY) {
7352            invalidateParentCaches();
7353            // Double-invalidation is necessary to capture view's old and new areas
7354            invalidate(false);
7355            info.mRotationY = rotationY;
7356            info.mMatrixDirty = true;
7357            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7358            invalidate(false);
7359        }
7360    }
7361
7362    /**
7363     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7364     *
7365     * @see #getPivotX()
7366     * @see #getPivotY()
7367     * @see #setRotationX(float)
7368     *
7369     * @return The degrees of X rotation.
7370     */
7371    @ViewDebug.ExportedProperty(category = "drawing")
7372    public float getRotationX() {
7373        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7374    }
7375
7376    /**
7377     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7378     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7379     * x axis.
7380     *
7381     * When rotating large views, it is recommended to adjust the camera distance
7382     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7383     *
7384     * @param rotationX The degrees of X rotation.
7385     *
7386     * @see #getRotationX()
7387     * @see #getPivotX()
7388     * @see #getPivotY()
7389     * @see #setRotation(float)
7390     * @see #setRotationY(float)
7391     * @see #setCameraDistance(float)
7392     *
7393     * @attr ref android.R.styleable#View_rotationX
7394     */
7395    public void setRotationX(float rotationX) {
7396        ensureTransformationInfo();
7397        final TransformationInfo info = mTransformationInfo;
7398        if (info.mRotationX != rotationX) {
7399            invalidateParentCaches();
7400            // Double-invalidation is necessary to capture view's old and new areas
7401            invalidate(false);
7402            info.mRotationX = rotationX;
7403            info.mMatrixDirty = true;
7404            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7405            invalidate(false);
7406        }
7407    }
7408
7409    /**
7410     * The amount that the view is scaled in x around the pivot point, as a proportion of
7411     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7412     *
7413     * <p>By default, this is 1.0f.
7414     *
7415     * @see #getPivotX()
7416     * @see #getPivotY()
7417     * @return The scaling factor.
7418     */
7419    @ViewDebug.ExportedProperty(category = "drawing")
7420    public float getScaleX() {
7421        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7422    }
7423
7424    /**
7425     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7426     * the view's unscaled width. A value of 1 means that no scaling is applied.
7427     *
7428     * @param scaleX The scaling factor.
7429     * @see #getPivotX()
7430     * @see #getPivotY()
7431     *
7432     * @attr ref android.R.styleable#View_scaleX
7433     */
7434    public void setScaleX(float scaleX) {
7435        ensureTransformationInfo();
7436        final TransformationInfo info = mTransformationInfo;
7437        if (info.mScaleX != scaleX) {
7438            invalidateParentCaches();
7439            // Double-invalidation is necessary to capture view's old and new areas
7440            invalidate(false);
7441            info.mScaleX = scaleX;
7442            info.mMatrixDirty = true;
7443            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7444            invalidate(false);
7445        }
7446    }
7447
7448    /**
7449     * The amount that the view is scaled in y around the pivot point, as a proportion of
7450     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7451     *
7452     * <p>By default, this is 1.0f.
7453     *
7454     * @see #getPivotX()
7455     * @see #getPivotY()
7456     * @return The scaling factor.
7457     */
7458    @ViewDebug.ExportedProperty(category = "drawing")
7459    public float getScaleY() {
7460        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7461    }
7462
7463    /**
7464     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7465     * the view's unscaled width. A value of 1 means that no scaling is applied.
7466     *
7467     * @param scaleY The scaling factor.
7468     * @see #getPivotX()
7469     * @see #getPivotY()
7470     *
7471     * @attr ref android.R.styleable#View_scaleY
7472     */
7473    public void setScaleY(float scaleY) {
7474        ensureTransformationInfo();
7475        final TransformationInfo info = mTransformationInfo;
7476        if (info.mScaleY != scaleY) {
7477            invalidateParentCaches();
7478            // Double-invalidation is necessary to capture view's old and new areas
7479            invalidate(false);
7480            info.mScaleY = scaleY;
7481            info.mMatrixDirty = true;
7482            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7483            invalidate(false);
7484        }
7485    }
7486
7487    /**
7488     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7489     * and {@link #setScaleX(float) scaled}.
7490     *
7491     * @see #getRotation()
7492     * @see #getScaleX()
7493     * @see #getScaleY()
7494     * @see #getPivotY()
7495     * @return The x location of the pivot point.
7496     */
7497    @ViewDebug.ExportedProperty(category = "drawing")
7498    public float getPivotX() {
7499        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7500    }
7501
7502    /**
7503     * Sets the x location of the point around which the view is
7504     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7505     * By default, the pivot point is centered on the object.
7506     * Setting this property disables this behavior and causes the view to use only the
7507     * explicitly set pivotX and pivotY values.
7508     *
7509     * @param pivotX The x location of the pivot point.
7510     * @see #getRotation()
7511     * @see #getScaleX()
7512     * @see #getScaleY()
7513     * @see #getPivotY()
7514     *
7515     * @attr ref android.R.styleable#View_transformPivotX
7516     */
7517    public void setPivotX(float pivotX) {
7518        ensureTransformationInfo();
7519        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7520        final TransformationInfo info = mTransformationInfo;
7521        if (info.mPivotX != pivotX) {
7522            invalidateParentCaches();
7523            // Double-invalidation is necessary to capture view's old and new areas
7524            invalidate(false);
7525            info.mPivotX = pivotX;
7526            info.mMatrixDirty = true;
7527            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7528            invalidate(false);
7529        }
7530    }
7531
7532    /**
7533     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7534     * and {@link #setScaleY(float) scaled}.
7535     *
7536     * @see #getRotation()
7537     * @see #getScaleX()
7538     * @see #getScaleY()
7539     * @see #getPivotY()
7540     * @return The y location of the pivot point.
7541     */
7542    @ViewDebug.ExportedProperty(category = "drawing")
7543    public float getPivotY() {
7544        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7545    }
7546
7547    /**
7548     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7549     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7550     * Setting this property disables this behavior and causes the view to use only the
7551     * explicitly set pivotX and pivotY values.
7552     *
7553     * @param pivotY The y location of the pivot point.
7554     * @see #getRotation()
7555     * @see #getScaleX()
7556     * @see #getScaleY()
7557     * @see #getPivotY()
7558     *
7559     * @attr ref android.R.styleable#View_transformPivotY
7560     */
7561    public void setPivotY(float pivotY) {
7562        ensureTransformationInfo();
7563        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7564        final TransformationInfo info = mTransformationInfo;
7565        if (info.mPivotY != pivotY) {
7566            invalidateParentCaches();
7567            // Double-invalidation is necessary to capture view's old and new areas
7568            invalidate(false);
7569            info.mPivotY = pivotY;
7570            info.mMatrixDirty = true;
7571            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7572            invalidate(false);
7573        }
7574    }
7575
7576    /**
7577     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7578     * completely transparent and 1 means the view is completely opaque.
7579     *
7580     * <p>By default this is 1.0f.
7581     * @return The opacity of the view.
7582     */
7583    @ViewDebug.ExportedProperty(category = "drawing")
7584    public float getAlpha() {
7585        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7586    }
7587
7588    /**
7589     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7590     * completely transparent and 1 means the view is completely opaque.</p>
7591     *
7592     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7593     * responsible for applying the opacity itself. Otherwise, calling this method is
7594     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7595     * setting a hardware layer.</p>
7596     *
7597     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7598     * performance implications. It is generally best to use the alpha property sparingly and
7599     * transiently, as in the case of fading animations.</p>
7600     *
7601     * @param alpha The opacity of the view.
7602     *
7603     * @see #setLayerType(int, android.graphics.Paint)
7604     *
7605     * @attr ref android.R.styleable#View_alpha
7606     */
7607    public void setAlpha(float alpha) {
7608        ensureTransformationInfo();
7609        if (mTransformationInfo.mAlpha != alpha) {
7610            mTransformationInfo.mAlpha = alpha;
7611            invalidateParentCaches();
7612            if (onSetAlpha((int) (alpha * 255))) {
7613                mPrivateFlags |= ALPHA_SET;
7614                // subclass is handling alpha - don't optimize rendering cache invalidation
7615                invalidate(true);
7616            } else {
7617                mPrivateFlags &= ~ALPHA_SET;
7618                invalidate(false);
7619            }
7620        }
7621    }
7622
7623    /**
7624     * Faster version of setAlpha() which performs the same steps except there are
7625     * no calls to invalidate(). The caller of this function should perform proper invalidation
7626     * on the parent and this object. The return value indicates whether the subclass handles
7627     * alpha (the return value for onSetAlpha()).
7628     *
7629     * @param alpha The new value for the alpha property
7630     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7631     *         the new value for the alpha property is different from the old value
7632     */
7633    boolean setAlphaNoInvalidation(float alpha) {
7634        ensureTransformationInfo();
7635        if (mTransformationInfo.mAlpha != alpha) {
7636            mTransformationInfo.mAlpha = alpha;
7637            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7638            if (subclassHandlesAlpha) {
7639                mPrivateFlags |= ALPHA_SET;
7640                return true;
7641            } else {
7642                mPrivateFlags &= ~ALPHA_SET;
7643            }
7644        }
7645        return false;
7646    }
7647
7648    /**
7649     * Top position of this view relative to its parent.
7650     *
7651     * @return The top of this view, in pixels.
7652     */
7653    @ViewDebug.CapturedViewProperty
7654    public final int getTop() {
7655        return mTop;
7656    }
7657
7658    /**
7659     * Sets the top position of this view relative to its parent. This method is meant to be called
7660     * by the layout system and should not generally be called otherwise, because the property
7661     * may be changed at any time by the layout.
7662     *
7663     * @param top The top of this view, in pixels.
7664     */
7665    public final void setTop(int top) {
7666        if (top != mTop) {
7667            updateMatrix();
7668            final boolean matrixIsIdentity = mTransformationInfo == null
7669                    || mTransformationInfo.mMatrixIsIdentity;
7670            if (matrixIsIdentity) {
7671                if (mAttachInfo != null) {
7672                    int minTop;
7673                    int yLoc;
7674                    if (top < mTop) {
7675                        minTop = top;
7676                        yLoc = top - mTop;
7677                    } else {
7678                        minTop = mTop;
7679                        yLoc = 0;
7680                    }
7681                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7682                }
7683            } else {
7684                // Double-invalidation is necessary to capture view's old and new areas
7685                invalidate(true);
7686            }
7687
7688            int width = mRight - mLeft;
7689            int oldHeight = mBottom - mTop;
7690
7691            mTop = top;
7692
7693            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7694
7695            if (!matrixIsIdentity) {
7696                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7697                    // A change in dimension means an auto-centered pivot point changes, too
7698                    mTransformationInfo.mMatrixDirty = true;
7699                }
7700                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7701                invalidate(true);
7702            }
7703            mBackgroundSizeChanged = true;
7704            invalidateParentIfNeeded();
7705        }
7706    }
7707
7708    /**
7709     * Bottom position of this view relative to its parent.
7710     *
7711     * @return The bottom of this view, in pixels.
7712     */
7713    @ViewDebug.CapturedViewProperty
7714    public final int getBottom() {
7715        return mBottom;
7716    }
7717
7718    /**
7719     * True if this view has changed since the last time being drawn.
7720     *
7721     * @return The dirty state of this view.
7722     */
7723    public boolean isDirty() {
7724        return (mPrivateFlags & DIRTY_MASK) != 0;
7725    }
7726
7727    /**
7728     * Sets the bottom position of this view relative to its parent. This method is meant to be
7729     * called by the layout system and should not generally be called otherwise, because the
7730     * property may be changed at any time by the layout.
7731     *
7732     * @param bottom The bottom of this view, in pixels.
7733     */
7734    public final void setBottom(int bottom) {
7735        if (bottom != mBottom) {
7736            updateMatrix();
7737            final boolean matrixIsIdentity = mTransformationInfo == null
7738                    || mTransformationInfo.mMatrixIsIdentity;
7739            if (matrixIsIdentity) {
7740                if (mAttachInfo != null) {
7741                    int maxBottom;
7742                    if (bottom < mBottom) {
7743                        maxBottom = mBottom;
7744                    } else {
7745                        maxBottom = bottom;
7746                    }
7747                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7748                }
7749            } else {
7750                // Double-invalidation is necessary to capture view's old and new areas
7751                invalidate(true);
7752            }
7753
7754            int width = mRight - mLeft;
7755            int oldHeight = mBottom - mTop;
7756
7757            mBottom = bottom;
7758
7759            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7760
7761            if (!matrixIsIdentity) {
7762                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7763                    // A change in dimension means an auto-centered pivot point changes, too
7764                    mTransformationInfo.mMatrixDirty = true;
7765                }
7766                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7767                invalidate(true);
7768            }
7769            mBackgroundSizeChanged = true;
7770            invalidateParentIfNeeded();
7771        }
7772    }
7773
7774    /**
7775     * Left position of this view relative to its parent.
7776     *
7777     * @return The left edge of this view, in pixels.
7778     */
7779    @ViewDebug.CapturedViewProperty
7780    public final int getLeft() {
7781        return mLeft;
7782    }
7783
7784    /**
7785     * Sets the left position of this view relative to its parent. This method is meant to be called
7786     * by the layout system and should not generally be called otherwise, because the property
7787     * may be changed at any time by the layout.
7788     *
7789     * @param left The bottom of this view, in pixels.
7790     */
7791    public final void setLeft(int left) {
7792        if (left != mLeft) {
7793            updateMatrix();
7794            final boolean matrixIsIdentity = mTransformationInfo == null
7795                    || mTransformationInfo.mMatrixIsIdentity;
7796            if (matrixIsIdentity) {
7797                if (mAttachInfo != null) {
7798                    int minLeft;
7799                    int xLoc;
7800                    if (left < mLeft) {
7801                        minLeft = left;
7802                        xLoc = left - mLeft;
7803                    } else {
7804                        minLeft = mLeft;
7805                        xLoc = 0;
7806                    }
7807                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7808                }
7809            } else {
7810                // Double-invalidation is necessary to capture view's old and new areas
7811                invalidate(true);
7812            }
7813
7814            int oldWidth = mRight - mLeft;
7815            int height = mBottom - mTop;
7816
7817            mLeft = left;
7818
7819            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7820
7821            if (!matrixIsIdentity) {
7822                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7823                    // A change in dimension means an auto-centered pivot point changes, too
7824                    mTransformationInfo.mMatrixDirty = true;
7825                }
7826                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7827                invalidate(true);
7828            }
7829            mBackgroundSizeChanged = true;
7830            invalidateParentIfNeeded();
7831        }
7832    }
7833
7834    /**
7835     * Right position of this view relative to its parent.
7836     *
7837     * @return The right edge of this view, in pixels.
7838     */
7839    @ViewDebug.CapturedViewProperty
7840    public final int getRight() {
7841        return mRight;
7842    }
7843
7844    /**
7845     * Sets the right position of this view relative to its parent. This method is meant to be called
7846     * by the layout system and should not generally be called otherwise, because the property
7847     * may be changed at any time by the layout.
7848     *
7849     * @param right The bottom of this view, in pixels.
7850     */
7851    public final void setRight(int right) {
7852        if (right != mRight) {
7853            updateMatrix();
7854            final boolean matrixIsIdentity = mTransformationInfo == null
7855                    || mTransformationInfo.mMatrixIsIdentity;
7856            if (matrixIsIdentity) {
7857                if (mAttachInfo != null) {
7858                    int maxRight;
7859                    if (right < mRight) {
7860                        maxRight = mRight;
7861                    } else {
7862                        maxRight = right;
7863                    }
7864                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7865                }
7866            } else {
7867                // Double-invalidation is necessary to capture view's old and new areas
7868                invalidate(true);
7869            }
7870
7871            int oldWidth = mRight - mLeft;
7872            int height = mBottom - mTop;
7873
7874            mRight = right;
7875
7876            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7877
7878            if (!matrixIsIdentity) {
7879                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7880                    // A change in dimension means an auto-centered pivot point changes, too
7881                    mTransformationInfo.mMatrixDirty = true;
7882                }
7883                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7884                invalidate(true);
7885            }
7886            mBackgroundSizeChanged = true;
7887            invalidateParentIfNeeded();
7888        }
7889    }
7890
7891    /**
7892     * The visual x position of this view, in pixels. This is equivalent to the
7893     * {@link #setTranslationX(float) translationX} property plus the current
7894     * {@link #getLeft() left} property.
7895     *
7896     * @return The visual x position of this view, in pixels.
7897     */
7898    @ViewDebug.ExportedProperty(category = "drawing")
7899    public float getX() {
7900        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7901    }
7902
7903    /**
7904     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7905     * {@link #setTranslationX(float) translationX} property to be the difference between
7906     * the x value passed in and the current {@link #getLeft() left} property.
7907     *
7908     * @param x The visual x position of this view, in pixels.
7909     */
7910    public void setX(float x) {
7911        setTranslationX(x - mLeft);
7912    }
7913
7914    /**
7915     * The visual y position of this view, in pixels. This is equivalent to the
7916     * {@link #setTranslationY(float) translationY} property plus the current
7917     * {@link #getTop() top} property.
7918     *
7919     * @return The visual y position of this view, in pixels.
7920     */
7921    @ViewDebug.ExportedProperty(category = "drawing")
7922    public float getY() {
7923        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7924    }
7925
7926    /**
7927     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7928     * {@link #setTranslationY(float) translationY} property to be the difference between
7929     * the y value passed in and the current {@link #getTop() top} property.
7930     *
7931     * @param y The visual y position of this view, in pixels.
7932     */
7933    public void setY(float y) {
7934        setTranslationY(y - mTop);
7935    }
7936
7937
7938    /**
7939     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7940     * This position is post-layout, in addition to wherever the object's
7941     * layout placed it.
7942     *
7943     * @return The horizontal position of this view relative to its left position, in pixels.
7944     */
7945    @ViewDebug.ExportedProperty(category = "drawing")
7946    public float getTranslationX() {
7947        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7948    }
7949
7950    /**
7951     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7952     * This effectively positions the object post-layout, in addition to wherever the object's
7953     * layout placed it.
7954     *
7955     * @param translationX The horizontal position of this view relative to its left position,
7956     * in pixels.
7957     *
7958     * @attr ref android.R.styleable#View_translationX
7959     */
7960    public void setTranslationX(float translationX) {
7961        ensureTransformationInfo();
7962        final TransformationInfo info = mTransformationInfo;
7963        if (info.mTranslationX != translationX) {
7964            invalidateParentCaches();
7965            // Double-invalidation is necessary to capture view's old and new areas
7966            invalidate(false);
7967            info.mTranslationX = translationX;
7968            info.mMatrixDirty = true;
7969            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7970            invalidate(false);
7971        }
7972    }
7973
7974    /**
7975     * The horizontal location of this view relative to its {@link #getTop() top} position.
7976     * This position is post-layout, in addition to wherever the object's
7977     * layout placed it.
7978     *
7979     * @return The vertical position of this view relative to its top position,
7980     * in pixels.
7981     */
7982    @ViewDebug.ExportedProperty(category = "drawing")
7983    public float getTranslationY() {
7984        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7985    }
7986
7987    /**
7988     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7989     * This effectively positions the object post-layout, in addition to wherever the object's
7990     * layout placed it.
7991     *
7992     * @param translationY The vertical position of this view relative to its top position,
7993     * in pixels.
7994     *
7995     * @attr ref android.R.styleable#View_translationY
7996     */
7997    public void setTranslationY(float translationY) {
7998        ensureTransformationInfo();
7999        final TransformationInfo info = mTransformationInfo;
8000        if (info.mTranslationY != translationY) {
8001            invalidateParentCaches();
8002            // Double-invalidation is necessary to capture view's old and new areas
8003            invalidate(false);
8004            info.mTranslationY = translationY;
8005            info.mMatrixDirty = true;
8006            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8007            invalidate(false);
8008        }
8009    }
8010
8011    /**
8012     * Hit rectangle in parent's coordinates
8013     *
8014     * @param outRect The hit rectangle of the view.
8015     */
8016    public void getHitRect(Rect outRect) {
8017        updateMatrix();
8018        final TransformationInfo info = mTransformationInfo;
8019        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8020            outRect.set(mLeft, mTop, mRight, mBottom);
8021        } else {
8022            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8023            tmpRect.set(-info.mPivotX, -info.mPivotY,
8024                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8025            info.mMatrix.mapRect(tmpRect);
8026            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8027                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8028        }
8029    }
8030
8031    /**
8032     * Determines whether the given point, in local coordinates is inside the view.
8033     */
8034    /*package*/ final boolean pointInView(float localX, float localY) {
8035        return localX >= 0 && localX < (mRight - mLeft)
8036                && localY >= 0 && localY < (mBottom - mTop);
8037    }
8038
8039    /**
8040     * Utility method to determine whether the given point, in local coordinates,
8041     * is inside the view, where the area of the view is expanded by the slop factor.
8042     * This method is called while processing touch-move events to determine if the event
8043     * is still within the view.
8044     */
8045    private boolean pointInView(float localX, float localY, float slop) {
8046        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8047                localY < ((mBottom - mTop) + slop);
8048    }
8049
8050    /**
8051     * When a view has focus and the user navigates away from it, the next view is searched for
8052     * starting from the rectangle filled in by this method.
8053     *
8054     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8055     * of the view.  However, if your view maintains some idea of internal selection,
8056     * such as a cursor, or a selected row or column, you should override this method and
8057     * fill in a more specific rectangle.
8058     *
8059     * @param r The rectangle to fill in, in this view's coordinates.
8060     */
8061    public void getFocusedRect(Rect r) {
8062        getDrawingRect(r);
8063    }
8064
8065    /**
8066     * If some part of this view is not clipped by any of its parents, then
8067     * return that area in r in global (root) coordinates. To convert r to local
8068     * coordinates (without taking possible View rotations into account), offset
8069     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8070     * If the view is completely clipped or translated out, return false.
8071     *
8072     * @param r If true is returned, r holds the global coordinates of the
8073     *        visible portion of this view.
8074     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8075     *        between this view and its root. globalOffet may be null.
8076     * @return true if r is non-empty (i.e. part of the view is visible at the
8077     *         root level.
8078     */
8079    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8080        int width = mRight - mLeft;
8081        int height = mBottom - mTop;
8082        if (width > 0 && height > 0) {
8083            r.set(0, 0, width, height);
8084            if (globalOffset != null) {
8085                globalOffset.set(-mScrollX, -mScrollY);
8086            }
8087            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8088        }
8089        return false;
8090    }
8091
8092    public final boolean getGlobalVisibleRect(Rect r) {
8093        return getGlobalVisibleRect(r, null);
8094    }
8095
8096    public final boolean getLocalVisibleRect(Rect r) {
8097        Point offset = new Point();
8098        if (getGlobalVisibleRect(r, offset)) {
8099            r.offset(-offset.x, -offset.y); // make r local
8100            return true;
8101        }
8102        return false;
8103    }
8104
8105    /**
8106     * Offset this view's vertical location by the specified number of pixels.
8107     *
8108     * @param offset the number of pixels to offset the view by
8109     */
8110    public void offsetTopAndBottom(int offset) {
8111        if (offset != 0) {
8112            updateMatrix();
8113            final boolean matrixIsIdentity = mTransformationInfo == null
8114                    || mTransformationInfo.mMatrixIsIdentity;
8115            if (matrixIsIdentity) {
8116                final ViewParent p = mParent;
8117                if (p != null && mAttachInfo != null) {
8118                    final Rect r = mAttachInfo.mTmpInvalRect;
8119                    int minTop;
8120                    int maxBottom;
8121                    int yLoc;
8122                    if (offset < 0) {
8123                        minTop = mTop + offset;
8124                        maxBottom = mBottom;
8125                        yLoc = offset;
8126                    } else {
8127                        minTop = mTop;
8128                        maxBottom = mBottom + offset;
8129                        yLoc = 0;
8130                    }
8131                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8132                    p.invalidateChild(this, r);
8133                }
8134            } else {
8135                invalidate(false);
8136            }
8137
8138            mTop += offset;
8139            mBottom += offset;
8140
8141            if (!matrixIsIdentity) {
8142                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8143                invalidate(false);
8144            }
8145            invalidateParentIfNeeded();
8146        }
8147    }
8148
8149    /**
8150     * Offset this view's horizontal location by the specified amount of pixels.
8151     *
8152     * @param offset the numer of pixels to offset the view by
8153     */
8154    public void offsetLeftAndRight(int offset) {
8155        if (offset != 0) {
8156            updateMatrix();
8157            final boolean matrixIsIdentity = mTransformationInfo == null
8158                    || mTransformationInfo.mMatrixIsIdentity;
8159            if (matrixIsIdentity) {
8160                final ViewParent p = mParent;
8161                if (p != null && mAttachInfo != null) {
8162                    final Rect r = mAttachInfo.mTmpInvalRect;
8163                    int minLeft;
8164                    int maxRight;
8165                    if (offset < 0) {
8166                        minLeft = mLeft + offset;
8167                        maxRight = mRight;
8168                    } else {
8169                        minLeft = mLeft;
8170                        maxRight = mRight + offset;
8171                    }
8172                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8173                    p.invalidateChild(this, r);
8174                }
8175            } else {
8176                invalidate(false);
8177            }
8178
8179            mLeft += offset;
8180            mRight += offset;
8181
8182            if (!matrixIsIdentity) {
8183                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8184                invalidate(false);
8185            }
8186            invalidateParentIfNeeded();
8187        }
8188    }
8189
8190    /**
8191     * Get the LayoutParams associated with this view. All views should have
8192     * layout parameters. These supply parameters to the <i>parent</i> of this
8193     * view specifying how it should be arranged. There are many subclasses of
8194     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8195     * of ViewGroup that are responsible for arranging their children.
8196     *
8197     * This method may return null if this View is not attached to a parent
8198     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8199     * was not invoked successfully. When a View is attached to a parent
8200     * ViewGroup, this method must not return null.
8201     *
8202     * @return The LayoutParams associated with this view, or null if no
8203     *         parameters have been set yet
8204     */
8205    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8206    public ViewGroup.LayoutParams getLayoutParams() {
8207        return mLayoutParams;
8208    }
8209
8210    /**
8211     * Set the layout parameters associated with this view. These supply
8212     * parameters to the <i>parent</i> of this view specifying how it should be
8213     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8214     * correspond to the different subclasses of ViewGroup that are responsible
8215     * for arranging their children.
8216     *
8217     * @param params The layout parameters for this view, cannot be null
8218     */
8219    public void setLayoutParams(ViewGroup.LayoutParams params) {
8220        if (params == null) {
8221            throw new NullPointerException("Layout parameters cannot be null");
8222        }
8223        mLayoutParams = params;
8224        if (mParent instanceof ViewGroup) {
8225            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8226        }
8227        requestLayout();
8228    }
8229
8230    /**
8231     * Set the scrolled position of your view. This will cause a call to
8232     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8233     * invalidated.
8234     * @param x the x position to scroll to
8235     * @param y the y position to scroll to
8236     */
8237    public void scrollTo(int x, int y) {
8238        if (mScrollX != x || mScrollY != y) {
8239            int oldX = mScrollX;
8240            int oldY = mScrollY;
8241            mScrollX = x;
8242            mScrollY = y;
8243            invalidateParentCaches();
8244            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8245            if (!awakenScrollBars()) {
8246                invalidate(true);
8247            }
8248        }
8249    }
8250
8251    /**
8252     * Move the scrolled position of your view. This will cause a call to
8253     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8254     * invalidated.
8255     * @param x the amount of pixels to scroll by horizontally
8256     * @param y the amount of pixels to scroll by vertically
8257     */
8258    public void scrollBy(int x, int y) {
8259        scrollTo(mScrollX + x, mScrollY + y);
8260    }
8261
8262    /**
8263     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8264     * animation to fade the scrollbars out after a default delay. If a subclass
8265     * provides animated scrolling, the start delay should equal the duration
8266     * of the scrolling animation.</p>
8267     *
8268     * <p>The animation starts only if at least one of the scrollbars is
8269     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8270     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8271     * this method returns true, and false otherwise. If the animation is
8272     * started, this method calls {@link #invalidate()}; in that case the
8273     * caller should not call {@link #invalidate()}.</p>
8274     *
8275     * <p>This method should be invoked every time a subclass directly updates
8276     * the scroll parameters.</p>
8277     *
8278     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8279     * and {@link #scrollTo(int, int)}.</p>
8280     *
8281     * @return true if the animation is played, false otherwise
8282     *
8283     * @see #awakenScrollBars(int)
8284     * @see #scrollBy(int, int)
8285     * @see #scrollTo(int, int)
8286     * @see #isHorizontalScrollBarEnabled()
8287     * @see #isVerticalScrollBarEnabled()
8288     * @see #setHorizontalScrollBarEnabled(boolean)
8289     * @see #setVerticalScrollBarEnabled(boolean)
8290     */
8291    protected boolean awakenScrollBars() {
8292        return mScrollCache != null &&
8293                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8294    }
8295
8296    /**
8297     * Trigger the scrollbars to draw.
8298     * This method differs from awakenScrollBars() only in its default duration.
8299     * initialAwakenScrollBars() will show the scroll bars for longer than
8300     * usual to give the user more of a chance to notice them.
8301     *
8302     * @return true if the animation is played, false otherwise.
8303     */
8304    private boolean initialAwakenScrollBars() {
8305        return mScrollCache != null &&
8306                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8307    }
8308
8309    /**
8310     * <p>
8311     * Trigger the scrollbars to draw. When invoked this method starts an
8312     * animation to fade the scrollbars out after a fixed delay. If a subclass
8313     * provides animated scrolling, the start delay should equal the duration of
8314     * the scrolling animation.
8315     * </p>
8316     *
8317     * <p>
8318     * The animation starts only if at least one of the scrollbars is enabled,
8319     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8320     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8321     * this method returns true, and false otherwise. If the animation is
8322     * started, this method calls {@link #invalidate()}; in that case the caller
8323     * should not call {@link #invalidate()}.
8324     * </p>
8325     *
8326     * <p>
8327     * This method should be invoked everytime a subclass directly updates the
8328     * scroll parameters.
8329     * </p>
8330     *
8331     * @param startDelay the delay, in milliseconds, after which the animation
8332     *        should start; when the delay is 0, the animation starts
8333     *        immediately
8334     * @return true if the animation is played, false otherwise
8335     *
8336     * @see #scrollBy(int, int)
8337     * @see #scrollTo(int, int)
8338     * @see #isHorizontalScrollBarEnabled()
8339     * @see #isVerticalScrollBarEnabled()
8340     * @see #setHorizontalScrollBarEnabled(boolean)
8341     * @see #setVerticalScrollBarEnabled(boolean)
8342     */
8343    protected boolean awakenScrollBars(int startDelay) {
8344        return awakenScrollBars(startDelay, true);
8345    }
8346
8347    /**
8348     * <p>
8349     * Trigger the scrollbars to draw. When invoked this method starts an
8350     * animation to fade the scrollbars out after a fixed delay. If a subclass
8351     * provides animated scrolling, the start delay should equal the duration of
8352     * the scrolling animation.
8353     * </p>
8354     *
8355     * <p>
8356     * The animation starts only if at least one of the scrollbars is enabled,
8357     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8358     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8359     * this method returns true, and false otherwise. If the animation is
8360     * started, this method calls {@link #invalidate()} if the invalidate parameter
8361     * is set to true; in that case the caller
8362     * should not call {@link #invalidate()}.
8363     * </p>
8364     *
8365     * <p>
8366     * This method should be invoked everytime a subclass directly updates the
8367     * scroll parameters.
8368     * </p>
8369     *
8370     * @param startDelay the delay, in milliseconds, after which the animation
8371     *        should start; when the delay is 0, the animation starts
8372     *        immediately
8373     *
8374     * @param invalidate Wheter this method should call invalidate
8375     *
8376     * @return true if the animation is played, false otherwise
8377     *
8378     * @see #scrollBy(int, int)
8379     * @see #scrollTo(int, int)
8380     * @see #isHorizontalScrollBarEnabled()
8381     * @see #isVerticalScrollBarEnabled()
8382     * @see #setHorizontalScrollBarEnabled(boolean)
8383     * @see #setVerticalScrollBarEnabled(boolean)
8384     */
8385    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8386        final ScrollabilityCache scrollCache = mScrollCache;
8387
8388        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8389            return false;
8390        }
8391
8392        if (scrollCache.scrollBar == null) {
8393            scrollCache.scrollBar = new ScrollBarDrawable();
8394        }
8395
8396        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8397
8398            if (invalidate) {
8399                // Invalidate to show the scrollbars
8400                invalidate(true);
8401            }
8402
8403            if (scrollCache.state == ScrollabilityCache.OFF) {
8404                // FIXME: this is copied from WindowManagerService.
8405                // We should get this value from the system when it
8406                // is possible to do so.
8407                final int KEY_REPEAT_FIRST_DELAY = 750;
8408                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8409            }
8410
8411            // Tell mScrollCache when we should start fading. This may
8412            // extend the fade start time if one was already scheduled
8413            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8414            scrollCache.fadeStartTime = fadeStartTime;
8415            scrollCache.state = ScrollabilityCache.ON;
8416
8417            // Schedule our fader to run, unscheduling any old ones first
8418            if (mAttachInfo != null) {
8419                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8420                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8421            }
8422
8423            return true;
8424        }
8425
8426        return false;
8427    }
8428
8429    /**
8430     * Do not invalidate views which are not visible and which are not running an animation. They
8431     * will not get drawn and they should not set dirty flags as if they will be drawn
8432     */
8433    private boolean skipInvalidate() {
8434        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8435                (!(mParent instanceof ViewGroup) ||
8436                        !((ViewGroup) mParent).isViewTransitioning(this));
8437    }
8438    /**
8439     * Mark the area defined by dirty as needing to be drawn. If the view is
8440     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8441     * in the future. This must be called from a UI thread. To call from a non-UI
8442     * thread, call {@link #postInvalidate()}.
8443     *
8444     * WARNING: This method is destructive to dirty.
8445     * @param dirty the rectangle representing the bounds of the dirty region
8446     */
8447    public void invalidate(Rect dirty) {
8448        if (ViewDebug.TRACE_HIERARCHY) {
8449            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8450        }
8451
8452        if (skipInvalidate()) {
8453            return;
8454        }
8455        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8456                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8457                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8458            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8459            mPrivateFlags |= INVALIDATED;
8460            mPrivateFlags |= DIRTY;
8461            final ViewParent p = mParent;
8462            final AttachInfo ai = mAttachInfo;
8463            //noinspection PointlessBooleanExpression,ConstantConditions
8464            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8465                if (p != null && ai != null && ai.mHardwareAccelerated) {
8466                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8467                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8468                    p.invalidateChild(this, null);
8469                    return;
8470                }
8471            }
8472            if (p != null && ai != null) {
8473                final int scrollX = mScrollX;
8474                final int scrollY = mScrollY;
8475                final Rect r = ai.mTmpInvalRect;
8476                r.set(dirty.left - scrollX, dirty.top - scrollY,
8477                        dirty.right - scrollX, dirty.bottom - scrollY);
8478                mParent.invalidateChild(this, r);
8479            }
8480        }
8481    }
8482
8483    /**
8484     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8485     * The coordinates of the dirty rect are relative to the view.
8486     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8487     * will be called at some point in the future. This must be called from
8488     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8489     * @param l the left position of the dirty region
8490     * @param t the top position of the dirty region
8491     * @param r the right position of the dirty region
8492     * @param b the bottom position of the dirty region
8493     */
8494    public void invalidate(int l, int t, int r, int b) {
8495        if (ViewDebug.TRACE_HIERARCHY) {
8496            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8497        }
8498
8499        if (skipInvalidate()) {
8500            return;
8501        }
8502        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8503                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8504                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8505            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8506            mPrivateFlags |= INVALIDATED;
8507            mPrivateFlags |= DIRTY;
8508            final ViewParent p = mParent;
8509            final AttachInfo ai = mAttachInfo;
8510            //noinspection PointlessBooleanExpression,ConstantConditions
8511            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8512                if (p != null && ai != null && ai.mHardwareAccelerated) {
8513                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8514                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8515                    p.invalidateChild(this, null);
8516                    return;
8517                }
8518            }
8519            if (p != null && ai != null && l < r && t < b) {
8520                final int scrollX = mScrollX;
8521                final int scrollY = mScrollY;
8522                final Rect tmpr = ai.mTmpInvalRect;
8523                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8524                p.invalidateChild(this, tmpr);
8525            }
8526        }
8527    }
8528
8529    /**
8530     * Invalidate the whole view. If the view is visible,
8531     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8532     * the future. This must be called from a UI thread. To call from a non-UI thread,
8533     * call {@link #postInvalidate()}.
8534     */
8535    public void invalidate() {
8536        invalidate(true);
8537    }
8538
8539    /**
8540     * This is where the invalidate() work actually happens. A full invalidate()
8541     * causes the drawing cache to be invalidated, but this function can be called with
8542     * invalidateCache set to false to skip that invalidation step for cases that do not
8543     * need it (for example, a component that remains at the same dimensions with the same
8544     * content).
8545     *
8546     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8547     * well. This is usually true for a full invalidate, but may be set to false if the
8548     * View's contents or dimensions have not changed.
8549     */
8550    void invalidate(boolean invalidateCache) {
8551        if (ViewDebug.TRACE_HIERARCHY) {
8552            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8553        }
8554
8555        if (skipInvalidate()) {
8556            return;
8557        }
8558        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8559                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8560                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8561            mLastIsOpaque = isOpaque();
8562            mPrivateFlags &= ~DRAWN;
8563            mPrivateFlags |= DIRTY;
8564            if (invalidateCache) {
8565                mPrivateFlags |= INVALIDATED;
8566                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8567            }
8568            final AttachInfo ai = mAttachInfo;
8569            final ViewParent p = mParent;
8570            //noinspection PointlessBooleanExpression,ConstantConditions
8571            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8572                if (p != null && ai != null && ai.mHardwareAccelerated) {
8573                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8574                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8575                    p.invalidateChild(this, null);
8576                    return;
8577                }
8578            }
8579
8580            if (p != null && ai != null) {
8581                final Rect r = ai.mTmpInvalRect;
8582                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8583                // Don't call invalidate -- we don't want to internally scroll
8584                // our own bounds
8585                p.invalidateChild(this, r);
8586            }
8587        }
8588    }
8589
8590    /**
8591     * Used to indicate that the parent of this view should clear its caches. This functionality
8592     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8593     * which is necessary when various parent-managed properties of the view change, such as
8594     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8595     * clears the parent caches and does not causes an invalidate event.
8596     *
8597     * @hide
8598     */
8599    protected void invalidateParentCaches() {
8600        if (mParent instanceof View) {
8601            ((View) mParent).mPrivateFlags |= INVALIDATED;
8602        }
8603    }
8604
8605    /**
8606     * Used to indicate that the parent of this view should be invalidated. This functionality
8607     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8608     * which is necessary when various parent-managed properties of the view change, such as
8609     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8610     * an invalidation event to the parent.
8611     *
8612     * @hide
8613     */
8614    protected void invalidateParentIfNeeded() {
8615        if (isHardwareAccelerated() && mParent instanceof View) {
8616            ((View) mParent).invalidate(true);
8617        }
8618    }
8619
8620    /**
8621     * Indicates whether this View is opaque. An opaque View guarantees that it will
8622     * draw all the pixels overlapping its bounds using a fully opaque color.
8623     *
8624     * Subclasses of View should override this method whenever possible to indicate
8625     * whether an instance is opaque. Opaque Views are treated in a special way by
8626     * the View hierarchy, possibly allowing it to perform optimizations during
8627     * invalidate/draw passes.
8628     *
8629     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8630     */
8631    @ViewDebug.ExportedProperty(category = "drawing")
8632    public boolean isOpaque() {
8633        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8634                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8635                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8636    }
8637
8638    /**
8639     * @hide
8640     */
8641    protected void computeOpaqueFlags() {
8642        // Opaque if:
8643        //   - Has a background
8644        //   - Background is opaque
8645        //   - Doesn't have scrollbars or scrollbars are inside overlay
8646
8647        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8648            mPrivateFlags |= OPAQUE_BACKGROUND;
8649        } else {
8650            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8651        }
8652
8653        final int flags = mViewFlags;
8654        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8655                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8656            mPrivateFlags |= OPAQUE_SCROLLBARS;
8657        } else {
8658            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8659        }
8660    }
8661
8662    /**
8663     * @hide
8664     */
8665    protected boolean hasOpaqueScrollbars() {
8666        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8667    }
8668
8669    /**
8670     * @return A handler associated with the thread running the View. This
8671     * handler can be used to pump events in the UI events queue.
8672     */
8673    public Handler getHandler() {
8674        if (mAttachInfo != null) {
8675            return mAttachInfo.mHandler;
8676        }
8677        return null;
8678    }
8679
8680    /**
8681     * <p>Causes the Runnable to be added to the message queue.
8682     * The runnable will be run on the user interface thread.</p>
8683     *
8684     * <p>This method can be invoked from outside of the UI thread
8685     * only when this View is attached to a window.</p>
8686     *
8687     * @param action The Runnable that will be executed.
8688     *
8689     * @return Returns true if the Runnable was successfully placed in to the
8690     *         message queue.  Returns false on failure, usually because the
8691     *         looper processing the message queue is exiting.
8692     */
8693    public boolean post(Runnable action) {
8694        Handler handler;
8695        AttachInfo attachInfo = mAttachInfo;
8696        if (attachInfo != null) {
8697            handler = attachInfo.mHandler;
8698        } else {
8699            // Assume that post will succeed later
8700            ViewRootImpl.getRunQueue().post(action);
8701            return true;
8702        }
8703
8704        return handler.post(action);
8705    }
8706
8707    /**
8708     * <p>Causes the Runnable to be added to the message queue, to be run
8709     * after the specified amount of time elapses.
8710     * The runnable will be run on the user interface thread.</p>
8711     *
8712     * <p>This method can be invoked from outside of the UI thread
8713     * only when this View is attached to a window.</p>
8714     *
8715     * @param action The Runnable that will be executed.
8716     * @param delayMillis The delay (in milliseconds) until the Runnable
8717     *        will be executed.
8718     *
8719     * @return true if the Runnable was successfully placed in to the
8720     *         message queue.  Returns false on failure, usually because the
8721     *         looper processing the message queue is exiting.  Note that a
8722     *         result of true does not mean the Runnable will be processed --
8723     *         if the looper is quit before the delivery time of the message
8724     *         occurs then the message will be dropped.
8725     */
8726    public boolean postDelayed(Runnable action, long delayMillis) {
8727        Handler handler;
8728        AttachInfo attachInfo = mAttachInfo;
8729        if (attachInfo != null) {
8730            handler = attachInfo.mHandler;
8731        } else {
8732            // Assume that post will succeed later
8733            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8734            return true;
8735        }
8736
8737        return handler.postDelayed(action, delayMillis);
8738    }
8739
8740    /**
8741     * <p>Removes the specified Runnable from the message queue.</p>
8742     *
8743     * <p>This method can be invoked from outside of the UI thread
8744     * only when this View is attached to a window.</p>
8745     *
8746     * @param action The Runnable to remove from the message handling queue
8747     *
8748     * @return true if this view could ask the Handler to remove the Runnable,
8749     *         false otherwise. When the returned value is true, the Runnable
8750     *         may or may not have been actually removed from the message queue
8751     *         (for instance, if the Runnable was not in the queue already.)
8752     */
8753    public boolean removeCallbacks(Runnable action) {
8754        Handler handler;
8755        AttachInfo attachInfo = mAttachInfo;
8756        if (attachInfo != null) {
8757            handler = attachInfo.mHandler;
8758        } else {
8759            // Assume that post will succeed later
8760            ViewRootImpl.getRunQueue().removeCallbacks(action);
8761            return true;
8762        }
8763
8764        handler.removeCallbacks(action);
8765        return true;
8766    }
8767
8768    /**
8769     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8770     * Use this to invalidate the View from a non-UI thread.</p>
8771     *
8772     * <p>This method can be invoked from outside of the UI thread
8773     * only when this View is attached to a window.</p>
8774     *
8775     * @see #invalidate()
8776     */
8777    public void postInvalidate() {
8778        postInvalidateDelayed(0);
8779    }
8780
8781    /**
8782     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8783     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8784     *
8785     * <p>This method can be invoked from outside of the UI thread
8786     * only when this View is attached to a window.</p>
8787     *
8788     * @param left The left coordinate of the rectangle to invalidate.
8789     * @param top The top coordinate of the rectangle to invalidate.
8790     * @param right The right coordinate of the rectangle to invalidate.
8791     * @param bottom The bottom coordinate of the rectangle to invalidate.
8792     *
8793     * @see #invalidate(int, int, int, int)
8794     * @see #invalidate(Rect)
8795     */
8796    public void postInvalidate(int left, int top, int right, int bottom) {
8797        postInvalidateDelayed(0, left, top, right, bottom);
8798    }
8799
8800    /**
8801     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8802     * loop. Waits for the specified amount of time.</p>
8803     *
8804     * <p>This method can be invoked from outside of the UI thread
8805     * only when this View is attached to a window.</p>
8806     *
8807     * @param delayMilliseconds the duration in milliseconds to delay the
8808     *         invalidation by
8809     */
8810    public void postInvalidateDelayed(long delayMilliseconds) {
8811        // We try only with the AttachInfo because there's no point in invalidating
8812        // if we are not attached to our window
8813        AttachInfo attachInfo = mAttachInfo;
8814        if (attachInfo != null) {
8815            Message msg = Message.obtain();
8816            msg.what = AttachInfo.INVALIDATE_MSG;
8817            msg.obj = this;
8818            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8819        }
8820    }
8821
8822    /**
8823     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8824     * through the event loop. Waits for the specified amount of time.</p>
8825     *
8826     * <p>This method can be invoked from outside of the UI thread
8827     * only when this View is attached to a window.</p>
8828     *
8829     * @param delayMilliseconds the duration in milliseconds to delay the
8830     *         invalidation by
8831     * @param left The left coordinate of the rectangle to invalidate.
8832     * @param top The top coordinate of the rectangle to invalidate.
8833     * @param right The right coordinate of the rectangle to invalidate.
8834     * @param bottom The bottom coordinate of the rectangle to invalidate.
8835     */
8836    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8837            int right, int bottom) {
8838
8839        // We try only with the AttachInfo because there's no point in invalidating
8840        // if we are not attached to our window
8841        AttachInfo attachInfo = mAttachInfo;
8842        if (attachInfo != null) {
8843            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8844            info.target = this;
8845            info.left = left;
8846            info.top = top;
8847            info.right = right;
8848            info.bottom = bottom;
8849
8850            final Message msg = Message.obtain();
8851            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8852            msg.obj = info;
8853            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8854        }
8855    }
8856
8857    /**
8858     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8859     * This event is sent at most once every
8860     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8861     */
8862    private void postSendViewScrolledAccessibilityEventCallback() {
8863        if (mSendViewScrolledAccessibilityEvent == null) {
8864            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8865        }
8866        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8867            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8868            postDelayed(mSendViewScrolledAccessibilityEvent,
8869                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8870        }
8871    }
8872
8873    /**
8874     * Called by a parent to request that a child update its values for mScrollX
8875     * and mScrollY if necessary. This will typically be done if the child is
8876     * animating a scroll using a {@link android.widget.Scroller Scroller}
8877     * object.
8878     */
8879    public void computeScroll() {
8880    }
8881
8882    /**
8883     * <p>Indicate whether the horizontal edges are faded when the view is
8884     * scrolled horizontally.</p>
8885     *
8886     * @return true if the horizontal edges should are faded on scroll, false
8887     *         otherwise
8888     *
8889     * @see #setHorizontalFadingEdgeEnabled(boolean)
8890     * @attr ref android.R.styleable#View_requiresFadingEdge
8891     */
8892    public boolean isHorizontalFadingEdgeEnabled() {
8893        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8894    }
8895
8896    /**
8897     * <p>Define whether the horizontal edges should be faded when this view
8898     * is scrolled horizontally.</p>
8899     *
8900     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8901     *                                    be faded when the view is scrolled
8902     *                                    horizontally
8903     *
8904     * @see #isHorizontalFadingEdgeEnabled()
8905     * @attr ref android.R.styleable#View_requiresFadingEdge
8906     */
8907    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8908        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8909            if (horizontalFadingEdgeEnabled) {
8910                initScrollCache();
8911            }
8912
8913            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8914        }
8915    }
8916
8917    /**
8918     * <p>Indicate whether the vertical edges are faded when the view is
8919     * scrolled horizontally.</p>
8920     *
8921     * @return true if the vertical edges should are faded on scroll, false
8922     *         otherwise
8923     *
8924     * @see #setVerticalFadingEdgeEnabled(boolean)
8925     * @attr ref android.R.styleable#View_requiresFadingEdge
8926     */
8927    public boolean isVerticalFadingEdgeEnabled() {
8928        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8929    }
8930
8931    /**
8932     * <p>Define whether the vertical edges should be faded when this view
8933     * is scrolled vertically.</p>
8934     *
8935     * @param verticalFadingEdgeEnabled true if the vertical edges should
8936     *                                  be faded when the view is scrolled
8937     *                                  vertically
8938     *
8939     * @see #isVerticalFadingEdgeEnabled()
8940     * @attr ref android.R.styleable#View_requiresFadingEdge
8941     */
8942    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8943        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8944            if (verticalFadingEdgeEnabled) {
8945                initScrollCache();
8946            }
8947
8948            mViewFlags ^= FADING_EDGE_VERTICAL;
8949        }
8950    }
8951
8952    /**
8953     * Returns the strength, or intensity, of the top faded edge. The strength is
8954     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8955     * returns 0.0 or 1.0 but no value in between.
8956     *
8957     * Subclasses should override this method to provide a smoother fade transition
8958     * when scrolling occurs.
8959     *
8960     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8961     */
8962    protected float getTopFadingEdgeStrength() {
8963        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8964    }
8965
8966    /**
8967     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8968     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8969     * returns 0.0 or 1.0 but no value in between.
8970     *
8971     * Subclasses should override this method to provide a smoother fade transition
8972     * when scrolling occurs.
8973     *
8974     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8975     */
8976    protected float getBottomFadingEdgeStrength() {
8977        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8978                computeVerticalScrollRange() ? 1.0f : 0.0f;
8979    }
8980
8981    /**
8982     * Returns the strength, or intensity, of the left faded edge. The strength is
8983     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8984     * returns 0.0 or 1.0 but no value in between.
8985     *
8986     * Subclasses should override this method to provide a smoother fade transition
8987     * when scrolling occurs.
8988     *
8989     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8990     */
8991    protected float getLeftFadingEdgeStrength() {
8992        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8993    }
8994
8995    /**
8996     * Returns the strength, or intensity, of the right faded edge. The strength is
8997     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8998     * returns 0.0 or 1.0 but no value in between.
8999     *
9000     * Subclasses should override this method to provide a smoother fade transition
9001     * when scrolling occurs.
9002     *
9003     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9004     */
9005    protected float getRightFadingEdgeStrength() {
9006        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9007                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9008    }
9009
9010    /**
9011     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9012     * scrollbar is not drawn by default.</p>
9013     *
9014     * @return true if the horizontal scrollbar should be painted, false
9015     *         otherwise
9016     *
9017     * @see #setHorizontalScrollBarEnabled(boolean)
9018     */
9019    public boolean isHorizontalScrollBarEnabled() {
9020        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9021    }
9022
9023    /**
9024     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9025     * scrollbar is not drawn by default.</p>
9026     *
9027     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9028     *                                   be painted
9029     *
9030     * @see #isHorizontalScrollBarEnabled()
9031     */
9032    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9033        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9034            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9035            computeOpaqueFlags();
9036            resolvePadding();
9037        }
9038    }
9039
9040    /**
9041     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9042     * scrollbar is not drawn by default.</p>
9043     *
9044     * @return true if the vertical scrollbar should be painted, false
9045     *         otherwise
9046     *
9047     * @see #setVerticalScrollBarEnabled(boolean)
9048     */
9049    public boolean isVerticalScrollBarEnabled() {
9050        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9051    }
9052
9053    /**
9054     * <p>Define whether the vertical scrollbar should be drawn or not. The
9055     * scrollbar is not drawn by default.</p>
9056     *
9057     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9058     *                                 be painted
9059     *
9060     * @see #isVerticalScrollBarEnabled()
9061     */
9062    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9063        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9064            mViewFlags ^= SCROLLBARS_VERTICAL;
9065            computeOpaqueFlags();
9066            resolvePadding();
9067        }
9068    }
9069
9070    /**
9071     * @hide
9072     */
9073    protected void recomputePadding() {
9074        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9075    }
9076
9077    /**
9078     * Define whether scrollbars will fade when the view is not scrolling.
9079     *
9080     * @param fadeScrollbars wheter to enable fading
9081     *
9082     */
9083    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9084        initScrollCache();
9085        final ScrollabilityCache scrollabilityCache = mScrollCache;
9086        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9087        if (fadeScrollbars) {
9088            scrollabilityCache.state = ScrollabilityCache.OFF;
9089        } else {
9090            scrollabilityCache.state = ScrollabilityCache.ON;
9091        }
9092    }
9093
9094    /**
9095     *
9096     * Returns true if scrollbars will fade when this view is not scrolling
9097     *
9098     * @return true if scrollbar fading is enabled
9099     */
9100    public boolean isScrollbarFadingEnabled() {
9101        return mScrollCache != null && mScrollCache.fadeScrollBars;
9102    }
9103
9104    /**
9105     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9106     * inset. When inset, they add to the padding of the view. And the scrollbars
9107     * can be drawn inside the padding area or on the edge of the view. For example,
9108     * if a view has a background drawable and you want to draw the scrollbars
9109     * inside the padding specified by the drawable, you can use
9110     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9111     * appear at the edge of the view, ignoring the padding, then you can use
9112     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9113     * @param style the style of the scrollbars. Should be one of
9114     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9115     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9116     * @see #SCROLLBARS_INSIDE_OVERLAY
9117     * @see #SCROLLBARS_INSIDE_INSET
9118     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9119     * @see #SCROLLBARS_OUTSIDE_INSET
9120     */
9121    public void setScrollBarStyle(int style) {
9122        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9123            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9124            computeOpaqueFlags();
9125            resolvePadding();
9126        }
9127    }
9128
9129    /**
9130     * <p>Returns the current scrollbar style.</p>
9131     * @return the current scrollbar style
9132     * @see #SCROLLBARS_INSIDE_OVERLAY
9133     * @see #SCROLLBARS_INSIDE_INSET
9134     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9135     * @see #SCROLLBARS_OUTSIDE_INSET
9136     */
9137    @ViewDebug.ExportedProperty(mapping = {
9138            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9139            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9140            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9141            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9142    })
9143    public int getScrollBarStyle() {
9144        return mViewFlags & SCROLLBARS_STYLE_MASK;
9145    }
9146
9147    /**
9148     * <p>Compute the horizontal range that the horizontal scrollbar
9149     * represents.</p>
9150     *
9151     * <p>The range is expressed in arbitrary units that must be the same as the
9152     * units used by {@link #computeHorizontalScrollExtent()} and
9153     * {@link #computeHorizontalScrollOffset()}.</p>
9154     *
9155     * <p>The default range is the drawing width of this view.</p>
9156     *
9157     * @return the total horizontal range represented by the horizontal
9158     *         scrollbar
9159     *
9160     * @see #computeHorizontalScrollExtent()
9161     * @see #computeHorizontalScrollOffset()
9162     * @see android.widget.ScrollBarDrawable
9163     */
9164    protected int computeHorizontalScrollRange() {
9165        return getWidth();
9166    }
9167
9168    /**
9169     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9170     * within the horizontal range. This value is used to compute the position
9171     * of the thumb within the scrollbar's track.</p>
9172     *
9173     * <p>The range is expressed in arbitrary units that must be the same as the
9174     * units used by {@link #computeHorizontalScrollRange()} and
9175     * {@link #computeHorizontalScrollExtent()}.</p>
9176     *
9177     * <p>The default offset is the scroll offset of this view.</p>
9178     *
9179     * @return the horizontal offset of the scrollbar's thumb
9180     *
9181     * @see #computeHorizontalScrollRange()
9182     * @see #computeHorizontalScrollExtent()
9183     * @see android.widget.ScrollBarDrawable
9184     */
9185    protected int computeHorizontalScrollOffset() {
9186        return mScrollX;
9187    }
9188
9189    /**
9190     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9191     * within the horizontal range. This value is used to compute the length
9192     * of the thumb within the scrollbar's track.</p>
9193     *
9194     * <p>The range is expressed in arbitrary units that must be the same as the
9195     * units used by {@link #computeHorizontalScrollRange()} and
9196     * {@link #computeHorizontalScrollOffset()}.</p>
9197     *
9198     * <p>The default extent is the drawing width of this view.</p>
9199     *
9200     * @return the horizontal extent of the scrollbar's thumb
9201     *
9202     * @see #computeHorizontalScrollRange()
9203     * @see #computeHorizontalScrollOffset()
9204     * @see android.widget.ScrollBarDrawable
9205     */
9206    protected int computeHorizontalScrollExtent() {
9207        return getWidth();
9208    }
9209
9210    /**
9211     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9212     *
9213     * <p>The range is expressed in arbitrary units that must be the same as the
9214     * units used by {@link #computeVerticalScrollExtent()} and
9215     * {@link #computeVerticalScrollOffset()}.</p>
9216     *
9217     * @return the total vertical range represented by the vertical scrollbar
9218     *
9219     * <p>The default range is the drawing height of this view.</p>
9220     *
9221     * @see #computeVerticalScrollExtent()
9222     * @see #computeVerticalScrollOffset()
9223     * @see android.widget.ScrollBarDrawable
9224     */
9225    protected int computeVerticalScrollRange() {
9226        return getHeight();
9227    }
9228
9229    /**
9230     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9231     * within the horizontal range. This value is used to compute the position
9232     * of the thumb within the scrollbar's track.</p>
9233     *
9234     * <p>The range is expressed in arbitrary units that must be the same as the
9235     * units used by {@link #computeVerticalScrollRange()} and
9236     * {@link #computeVerticalScrollExtent()}.</p>
9237     *
9238     * <p>The default offset is the scroll offset of this view.</p>
9239     *
9240     * @return the vertical offset of the scrollbar's thumb
9241     *
9242     * @see #computeVerticalScrollRange()
9243     * @see #computeVerticalScrollExtent()
9244     * @see android.widget.ScrollBarDrawable
9245     */
9246    protected int computeVerticalScrollOffset() {
9247        return mScrollY;
9248    }
9249
9250    /**
9251     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9252     * within the vertical range. This value is used to compute the length
9253     * of the thumb within the scrollbar's track.</p>
9254     *
9255     * <p>The range is expressed in arbitrary units that must be the same as the
9256     * units used by {@link #computeVerticalScrollRange()} and
9257     * {@link #computeVerticalScrollOffset()}.</p>
9258     *
9259     * <p>The default extent is the drawing height of this view.</p>
9260     *
9261     * @return the vertical extent of the scrollbar's thumb
9262     *
9263     * @see #computeVerticalScrollRange()
9264     * @see #computeVerticalScrollOffset()
9265     * @see android.widget.ScrollBarDrawable
9266     */
9267    protected int computeVerticalScrollExtent() {
9268        return getHeight();
9269    }
9270
9271    /**
9272     * Check if this view can be scrolled horizontally in a certain direction.
9273     *
9274     * @param direction Negative to check scrolling left, positive to check scrolling right.
9275     * @return true if this view can be scrolled in the specified direction, false otherwise.
9276     */
9277    public boolean canScrollHorizontally(int direction) {
9278        final int offset = computeHorizontalScrollOffset();
9279        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9280        if (range == 0) return false;
9281        if (direction < 0) {
9282            return offset > 0;
9283        } else {
9284            return offset < range - 1;
9285        }
9286    }
9287
9288    /**
9289     * Check if this view can be scrolled vertically in a certain direction.
9290     *
9291     * @param direction Negative to check scrolling up, positive to check scrolling down.
9292     * @return true if this view can be scrolled in the specified direction, false otherwise.
9293     */
9294    public boolean canScrollVertically(int direction) {
9295        final int offset = computeVerticalScrollOffset();
9296        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9297        if (range == 0) return false;
9298        if (direction < 0) {
9299            return offset > 0;
9300        } else {
9301            return offset < range - 1;
9302        }
9303    }
9304
9305    /**
9306     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9307     * scrollbars are painted only if they have been awakened first.</p>
9308     *
9309     * @param canvas the canvas on which to draw the scrollbars
9310     *
9311     * @see #awakenScrollBars(int)
9312     */
9313    protected final void onDrawScrollBars(Canvas canvas) {
9314        // scrollbars are drawn only when the animation is running
9315        final ScrollabilityCache cache = mScrollCache;
9316        if (cache != null) {
9317
9318            int state = cache.state;
9319
9320            if (state == ScrollabilityCache.OFF) {
9321                return;
9322            }
9323
9324            boolean invalidate = false;
9325
9326            if (state == ScrollabilityCache.FADING) {
9327                // We're fading -- get our fade interpolation
9328                if (cache.interpolatorValues == null) {
9329                    cache.interpolatorValues = new float[1];
9330                }
9331
9332                float[] values = cache.interpolatorValues;
9333
9334                // Stops the animation if we're done
9335                if (cache.scrollBarInterpolator.timeToValues(values) ==
9336                        Interpolator.Result.FREEZE_END) {
9337                    cache.state = ScrollabilityCache.OFF;
9338                } else {
9339                    cache.scrollBar.setAlpha(Math.round(values[0]));
9340                }
9341
9342                // This will make the scroll bars inval themselves after
9343                // drawing. We only want this when we're fading so that
9344                // we prevent excessive redraws
9345                invalidate = true;
9346            } else {
9347                // We're just on -- but we may have been fading before so
9348                // reset alpha
9349                cache.scrollBar.setAlpha(255);
9350            }
9351
9352
9353            final int viewFlags = mViewFlags;
9354
9355            final boolean drawHorizontalScrollBar =
9356                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9357            final boolean drawVerticalScrollBar =
9358                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9359                && !isVerticalScrollBarHidden();
9360
9361            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9362                final int width = mRight - mLeft;
9363                final int height = mBottom - mTop;
9364
9365                final ScrollBarDrawable scrollBar = cache.scrollBar;
9366
9367                final int scrollX = mScrollX;
9368                final int scrollY = mScrollY;
9369                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9370
9371                int left, top, right, bottom;
9372
9373                if (drawHorizontalScrollBar) {
9374                    int size = scrollBar.getSize(false);
9375                    if (size <= 0) {
9376                        size = cache.scrollBarSize;
9377                    }
9378
9379                    scrollBar.setParameters(computeHorizontalScrollRange(),
9380                                            computeHorizontalScrollOffset(),
9381                                            computeHorizontalScrollExtent(), false);
9382                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9383                            getVerticalScrollbarWidth() : 0;
9384                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9385                    left = scrollX + (mPaddingLeft & inside);
9386                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9387                    bottom = top + size;
9388                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9389                    if (invalidate) {
9390                        invalidate(left, top, right, bottom);
9391                    }
9392                }
9393
9394                if (drawVerticalScrollBar) {
9395                    int size = scrollBar.getSize(true);
9396                    if (size <= 0) {
9397                        size = cache.scrollBarSize;
9398                    }
9399
9400                    scrollBar.setParameters(computeVerticalScrollRange(),
9401                                            computeVerticalScrollOffset(),
9402                                            computeVerticalScrollExtent(), true);
9403                    switch (mVerticalScrollbarPosition) {
9404                        default:
9405                        case SCROLLBAR_POSITION_DEFAULT:
9406                        case SCROLLBAR_POSITION_RIGHT:
9407                            left = scrollX + width - size - (mUserPaddingRight & inside);
9408                            break;
9409                        case SCROLLBAR_POSITION_LEFT:
9410                            left = scrollX + (mUserPaddingLeft & inside);
9411                            break;
9412                    }
9413                    top = scrollY + (mPaddingTop & inside);
9414                    right = left + size;
9415                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9416                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9417                    if (invalidate) {
9418                        invalidate(left, top, right, bottom);
9419                    }
9420                }
9421            }
9422        }
9423    }
9424
9425    /**
9426     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9427     * FastScroller is visible.
9428     * @return whether to temporarily hide the vertical scrollbar
9429     * @hide
9430     */
9431    protected boolean isVerticalScrollBarHidden() {
9432        return false;
9433    }
9434
9435    /**
9436     * <p>Draw the horizontal scrollbar if
9437     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9438     *
9439     * @param canvas the canvas on which to draw the scrollbar
9440     * @param scrollBar the scrollbar's drawable
9441     *
9442     * @see #isHorizontalScrollBarEnabled()
9443     * @see #computeHorizontalScrollRange()
9444     * @see #computeHorizontalScrollExtent()
9445     * @see #computeHorizontalScrollOffset()
9446     * @see android.widget.ScrollBarDrawable
9447     * @hide
9448     */
9449    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9450            int l, int t, int r, int b) {
9451        scrollBar.setBounds(l, t, r, b);
9452        scrollBar.draw(canvas);
9453    }
9454
9455    /**
9456     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9457     * returns true.</p>
9458     *
9459     * @param canvas the canvas on which to draw the scrollbar
9460     * @param scrollBar the scrollbar's drawable
9461     *
9462     * @see #isVerticalScrollBarEnabled()
9463     * @see #computeVerticalScrollRange()
9464     * @see #computeVerticalScrollExtent()
9465     * @see #computeVerticalScrollOffset()
9466     * @see android.widget.ScrollBarDrawable
9467     * @hide
9468     */
9469    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9470            int l, int t, int r, int b) {
9471        scrollBar.setBounds(l, t, r, b);
9472        scrollBar.draw(canvas);
9473    }
9474
9475    /**
9476     * Implement this to do your drawing.
9477     *
9478     * @param canvas the canvas on which the background will be drawn
9479     */
9480    protected void onDraw(Canvas canvas) {
9481    }
9482
9483    /*
9484     * Caller is responsible for calling requestLayout if necessary.
9485     * (This allows addViewInLayout to not request a new layout.)
9486     */
9487    void assignParent(ViewParent parent) {
9488        if (mParent == null) {
9489            mParent = parent;
9490        } else if (parent == null) {
9491            mParent = null;
9492        } else {
9493            throw new RuntimeException("view " + this + " being added, but"
9494                    + " it already has a parent");
9495        }
9496    }
9497
9498    /**
9499     * This is called when the view is attached to a window.  At this point it
9500     * has a Surface and will start drawing.  Note that this function is
9501     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9502     * however it may be called any time before the first onDraw -- including
9503     * before or after {@link #onMeasure(int, int)}.
9504     *
9505     * @see #onDetachedFromWindow()
9506     */
9507    protected void onAttachedToWindow() {
9508        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9509            mParent.requestTransparentRegion(this);
9510        }
9511        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9512            initialAwakenScrollBars();
9513            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9514        }
9515        jumpDrawablesToCurrentState();
9516        // Order is important here: LayoutDirection MUST be resolved before Padding
9517        // and TextDirection
9518        resolveLayoutDirectionIfNeeded();
9519        resolvePadding();
9520        resolveTextDirection();
9521        if (isFocused()) {
9522            InputMethodManager imm = InputMethodManager.peekInstance();
9523            imm.focusIn(this);
9524        }
9525    }
9526
9527    /**
9528     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9529     * that the parent directionality can and will be resolved before its children.
9530     */
9531    private void resolveLayoutDirectionIfNeeded() {
9532        // Do not resolve if it is not needed
9533        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9534
9535        // Clear any previous layout direction resolution
9536        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9537
9538        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9539        // TextDirectionHeuristic
9540        resetResolvedTextDirection();
9541
9542        // Set resolved depending on layout direction
9543        switch (getLayoutDirection()) {
9544            case LAYOUT_DIRECTION_INHERIT:
9545                // We cannot do the resolution if there is no parent
9546                if (mParent == null) return;
9547
9548                // If this is root view, no need to look at parent's layout dir.
9549                if (mParent instanceof ViewGroup) {
9550                    ViewGroup viewGroup = ((ViewGroup) mParent);
9551
9552                    // Check if the parent view group can resolve
9553                    if (! viewGroup.canResolveLayoutDirection()) {
9554                        return;
9555                    }
9556                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9557                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9558                    }
9559                }
9560                break;
9561            case LAYOUT_DIRECTION_RTL:
9562                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9563                break;
9564            case LAYOUT_DIRECTION_LOCALE:
9565                if(isLayoutDirectionRtl(Locale.getDefault())) {
9566                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9567                }
9568                break;
9569            default:
9570                // Nothing to do, LTR by default
9571        }
9572
9573        // Set to resolved
9574        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9575    }
9576
9577    /**
9578     * @hide
9579     */
9580    protected void resolvePadding() {
9581        // If the user specified the absolute padding (either with android:padding or
9582        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9583        // use the default padding or the padding from the background drawable
9584        // (stored at this point in mPadding*)
9585        switch (getResolvedLayoutDirection()) {
9586            case LAYOUT_DIRECTION_RTL:
9587                // Start user padding override Right user padding. Otherwise, if Right user
9588                // padding is not defined, use the default Right padding. If Right user padding
9589                // is defined, just use it.
9590                if (mUserPaddingStart >= 0) {
9591                    mUserPaddingRight = mUserPaddingStart;
9592                } else if (mUserPaddingRight < 0) {
9593                    mUserPaddingRight = mPaddingRight;
9594                }
9595                if (mUserPaddingEnd >= 0) {
9596                    mUserPaddingLeft = mUserPaddingEnd;
9597                } else if (mUserPaddingLeft < 0) {
9598                    mUserPaddingLeft = mPaddingLeft;
9599                }
9600                break;
9601            case LAYOUT_DIRECTION_LTR:
9602            default:
9603                // Start user padding override Left user padding. Otherwise, if Left user
9604                // padding is not defined, use the default left padding. If Left user padding
9605                // is defined, just use it.
9606                if (mUserPaddingStart >= 0) {
9607                    mUserPaddingLeft = mUserPaddingStart;
9608                } else if (mUserPaddingLeft < 0) {
9609                    mUserPaddingLeft = mPaddingLeft;
9610                }
9611                if (mUserPaddingEnd >= 0) {
9612                    mUserPaddingRight = mUserPaddingEnd;
9613                } else if (mUserPaddingRight < 0) {
9614                    mUserPaddingRight = mPaddingRight;
9615                }
9616        }
9617
9618        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9619
9620        recomputePadding();
9621    }
9622
9623    /**
9624     * Return true if layout direction resolution can be done
9625     *
9626     * @hide
9627     */
9628    protected boolean canResolveLayoutDirection() {
9629        switch (getLayoutDirection()) {
9630            case LAYOUT_DIRECTION_INHERIT:
9631                return (mParent != null);
9632            default:
9633                return true;
9634        }
9635    }
9636
9637    /**
9638     * Reset the resolved layout direction.
9639     *
9640     * Subclasses need to override this method to clear cached information that depends on the
9641     * resolved layout direction, or to inform child views that inherit their layout direction.
9642     * Overrides must also call the superclass implementation at the start of their implementation.
9643     *
9644     * @hide
9645     */
9646    protected void resetResolvedLayoutDirection() {
9647        // Reset the current View resolution
9648        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9649    }
9650
9651    /**
9652     * Check if a Locale is corresponding to a RTL script.
9653     *
9654     * @param locale Locale to check
9655     * @return true if a Locale is corresponding to a RTL script.
9656     *
9657     * @hide
9658     */
9659    protected static boolean isLayoutDirectionRtl(Locale locale) {
9660        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9661                LocaleUtil.getLayoutDirectionFromLocale(locale));
9662    }
9663
9664    /**
9665     * This is called when the view is detached from a window.  At this point it
9666     * no longer has a surface for drawing.
9667     *
9668     * @see #onAttachedToWindow()
9669     */
9670    protected void onDetachedFromWindow() {
9671        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9672
9673        removeUnsetPressCallback();
9674        removeLongPressCallback();
9675        removePerformClickCallback();
9676        removeSendViewScrolledAccessibilityEventCallback();
9677
9678        destroyDrawingCache();
9679
9680        destroyLayer();
9681
9682        if (mDisplayList != null) {
9683            mDisplayList.invalidate();
9684        }
9685
9686        if (mAttachInfo != null) {
9687            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9688        }
9689
9690        mCurrentAnimation = null;
9691
9692        resetResolvedLayoutDirection();
9693        resetResolvedTextDirection();
9694    }
9695
9696    /**
9697     * @return The number of times this view has been attached to a window
9698     */
9699    protected int getWindowAttachCount() {
9700        return mWindowAttachCount;
9701    }
9702
9703    /**
9704     * Retrieve a unique token identifying the window this view is attached to.
9705     * @return Return the window's token for use in
9706     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9707     */
9708    public IBinder getWindowToken() {
9709        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9710    }
9711
9712    /**
9713     * Retrieve a unique token identifying the top-level "real" window of
9714     * the window that this view is attached to.  That is, this is like
9715     * {@link #getWindowToken}, except if the window this view in is a panel
9716     * window (attached to another containing window), then the token of
9717     * the containing window is returned instead.
9718     *
9719     * @return Returns the associated window token, either
9720     * {@link #getWindowToken()} or the containing window's token.
9721     */
9722    public IBinder getApplicationWindowToken() {
9723        AttachInfo ai = mAttachInfo;
9724        if (ai != null) {
9725            IBinder appWindowToken = ai.mPanelParentWindowToken;
9726            if (appWindowToken == null) {
9727                appWindowToken = ai.mWindowToken;
9728            }
9729            return appWindowToken;
9730        }
9731        return null;
9732    }
9733
9734    /**
9735     * Retrieve private session object this view hierarchy is using to
9736     * communicate with the window manager.
9737     * @return the session object to communicate with the window manager
9738     */
9739    /*package*/ IWindowSession getWindowSession() {
9740        return mAttachInfo != null ? mAttachInfo.mSession : null;
9741    }
9742
9743    /**
9744     * @param info the {@link android.view.View.AttachInfo} to associated with
9745     *        this view
9746     */
9747    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9748        //System.out.println("Attached! " + this);
9749        mAttachInfo = info;
9750        mWindowAttachCount++;
9751        // We will need to evaluate the drawable state at least once.
9752        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9753        if (mFloatingTreeObserver != null) {
9754            info.mTreeObserver.merge(mFloatingTreeObserver);
9755            mFloatingTreeObserver = null;
9756        }
9757        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9758            mAttachInfo.mScrollContainers.add(this);
9759            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9760        }
9761        performCollectViewAttributes(visibility);
9762        onAttachedToWindow();
9763
9764        ListenerInfo li = mListenerInfo;
9765        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9766                li != null ? li.mOnAttachStateChangeListeners : null;
9767        if (listeners != null && listeners.size() > 0) {
9768            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9769            // perform the dispatching. The iterator is a safe guard against listeners that
9770            // could mutate the list by calling the various add/remove methods. This prevents
9771            // the array from being modified while we iterate it.
9772            for (OnAttachStateChangeListener listener : listeners) {
9773                listener.onViewAttachedToWindow(this);
9774            }
9775        }
9776
9777        int vis = info.mWindowVisibility;
9778        if (vis != GONE) {
9779            onWindowVisibilityChanged(vis);
9780        }
9781        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9782            // If nobody has evaluated the drawable state yet, then do it now.
9783            refreshDrawableState();
9784        }
9785    }
9786
9787    void dispatchDetachedFromWindow() {
9788        AttachInfo info = mAttachInfo;
9789        if (info != null) {
9790            int vis = info.mWindowVisibility;
9791            if (vis != GONE) {
9792                onWindowVisibilityChanged(GONE);
9793            }
9794        }
9795
9796        onDetachedFromWindow();
9797
9798        ListenerInfo li = mListenerInfo;
9799        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9800                li != null ? li.mOnAttachStateChangeListeners : null;
9801        if (listeners != null && listeners.size() > 0) {
9802            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9803            // perform the dispatching. The iterator is a safe guard against listeners that
9804            // could mutate the list by calling the various add/remove methods. This prevents
9805            // the array from being modified while we iterate it.
9806            for (OnAttachStateChangeListener listener : listeners) {
9807                listener.onViewDetachedFromWindow(this);
9808            }
9809        }
9810
9811        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9812            mAttachInfo.mScrollContainers.remove(this);
9813            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9814        }
9815
9816        mAttachInfo = null;
9817    }
9818
9819    /**
9820     * Store this view hierarchy's frozen state into the given container.
9821     *
9822     * @param container The SparseArray in which to save the view's state.
9823     *
9824     * @see #restoreHierarchyState(android.util.SparseArray)
9825     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9826     * @see #onSaveInstanceState()
9827     */
9828    public void saveHierarchyState(SparseArray<Parcelable> container) {
9829        dispatchSaveInstanceState(container);
9830    }
9831
9832    /**
9833     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9834     * this view and its children. May be overridden to modify how freezing happens to a
9835     * view's children; for example, some views may want to not store state for their children.
9836     *
9837     * @param container The SparseArray in which to save the view's state.
9838     *
9839     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9840     * @see #saveHierarchyState(android.util.SparseArray)
9841     * @see #onSaveInstanceState()
9842     */
9843    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9844        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9845            mPrivateFlags &= ~SAVE_STATE_CALLED;
9846            Parcelable state = onSaveInstanceState();
9847            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9848                throw new IllegalStateException(
9849                        "Derived class did not call super.onSaveInstanceState()");
9850            }
9851            if (state != null) {
9852                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9853                // + ": " + state);
9854                container.put(mID, state);
9855            }
9856        }
9857    }
9858
9859    /**
9860     * Hook allowing a view to generate a representation of its internal state
9861     * that can later be used to create a new instance with that same state.
9862     * This state should only contain information that is not persistent or can
9863     * not be reconstructed later. For example, you will never store your
9864     * current position on screen because that will be computed again when a
9865     * new instance of the view is placed in its view hierarchy.
9866     * <p>
9867     * Some examples of things you may store here: the current cursor position
9868     * in a text view (but usually not the text itself since that is stored in a
9869     * content provider or other persistent storage), the currently selected
9870     * item in a list view.
9871     *
9872     * @return Returns a Parcelable object containing the view's current dynamic
9873     *         state, or null if there is nothing interesting to save. The
9874     *         default implementation returns null.
9875     * @see #onRestoreInstanceState(android.os.Parcelable)
9876     * @see #saveHierarchyState(android.util.SparseArray)
9877     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9878     * @see #setSaveEnabled(boolean)
9879     */
9880    protected Parcelable onSaveInstanceState() {
9881        mPrivateFlags |= SAVE_STATE_CALLED;
9882        return BaseSavedState.EMPTY_STATE;
9883    }
9884
9885    /**
9886     * Restore this view hierarchy's frozen state from the given container.
9887     *
9888     * @param container The SparseArray which holds previously frozen states.
9889     *
9890     * @see #saveHierarchyState(android.util.SparseArray)
9891     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9892     * @see #onRestoreInstanceState(android.os.Parcelable)
9893     */
9894    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9895        dispatchRestoreInstanceState(container);
9896    }
9897
9898    /**
9899     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9900     * state for this view and its children. May be overridden to modify how restoring
9901     * happens to a view's children; for example, some views may want to not store state
9902     * for their children.
9903     *
9904     * @param container The SparseArray which holds previously saved state.
9905     *
9906     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9907     * @see #restoreHierarchyState(android.util.SparseArray)
9908     * @see #onRestoreInstanceState(android.os.Parcelable)
9909     */
9910    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9911        if (mID != NO_ID) {
9912            Parcelable state = container.get(mID);
9913            if (state != null) {
9914                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9915                // + ": " + state);
9916                mPrivateFlags &= ~SAVE_STATE_CALLED;
9917                onRestoreInstanceState(state);
9918                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9919                    throw new IllegalStateException(
9920                            "Derived class did not call super.onRestoreInstanceState()");
9921                }
9922            }
9923        }
9924    }
9925
9926    /**
9927     * Hook allowing a view to re-apply a representation of its internal state that had previously
9928     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9929     * null state.
9930     *
9931     * @param state The frozen state that had previously been returned by
9932     *        {@link #onSaveInstanceState}.
9933     *
9934     * @see #onSaveInstanceState()
9935     * @see #restoreHierarchyState(android.util.SparseArray)
9936     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9937     */
9938    protected void onRestoreInstanceState(Parcelable state) {
9939        mPrivateFlags |= SAVE_STATE_CALLED;
9940        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9941            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9942                    + "received " + state.getClass().toString() + " instead. This usually happens "
9943                    + "when two views of different type have the same id in the same hierarchy. "
9944                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9945                    + "other views do not use the same id.");
9946        }
9947    }
9948
9949    /**
9950     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9951     *
9952     * @return the drawing start time in milliseconds
9953     */
9954    public long getDrawingTime() {
9955        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9956    }
9957
9958    /**
9959     * <p>Enables or disables the duplication of the parent's state into this view. When
9960     * duplication is enabled, this view gets its drawable state from its parent rather
9961     * than from its own internal properties.</p>
9962     *
9963     * <p>Note: in the current implementation, setting this property to true after the
9964     * view was added to a ViewGroup might have no effect at all. This property should
9965     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9966     *
9967     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9968     * property is enabled, an exception will be thrown.</p>
9969     *
9970     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9971     * parent, these states should not be affected by this method.</p>
9972     *
9973     * @param enabled True to enable duplication of the parent's drawable state, false
9974     *                to disable it.
9975     *
9976     * @see #getDrawableState()
9977     * @see #isDuplicateParentStateEnabled()
9978     */
9979    public void setDuplicateParentStateEnabled(boolean enabled) {
9980        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9981    }
9982
9983    /**
9984     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9985     *
9986     * @return True if this view's drawable state is duplicated from the parent,
9987     *         false otherwise
9988     *
9989     * @see #getDrawableState()
9990     * @see #setDuplicateParentStateEnabled(boolean)
9991     */
9992    public boolean isDuplicateParentStateEnabled() {
9993        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9994    }
9995
9996    /**
9997     * <p>Specifies the type of layer backing this view. The layer can be
9998     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9999     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10000     *
10001     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10002     * instance that controls how the layer is composed on screen. The following
10003     * properties of the paint are taken into account when composing the layer:</p>
10004     * <ul>
10005     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10006     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10007     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10008     * </ul>
10009     *
10010     * <p>If this view has an alpha value set to < 1.0 by calling
10011     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10012     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10013     * equivalent to setting a hardware layer on this view and providing a paint with
10014     * the desired alpha value.<p>
10015     *
10016     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10017     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10018     * for more information on when and how to use layers.</p>
10019     *
10020     * @param layerType The ype of layer to use with this view, must be one of
10021     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10022     *        {@link #LAYER_TYPE_HARDWARE}
10023     * @param paint The paint used to compose the layer. This argument is optional
10024     *        and can be null. It is ignored when the layer type is
10025     *        {@link #LAYER_TYPE_NONE}
10026     *
10027     * @see #getLayerType()
10028     * @see #LAYER_TYPE_NONE
10029     * @see #LAYER_TYPE_SOFTWARE
10030     * @see #LAYER_TYPE_HARDWARE
10031     * @see #setAlpha(float)
10032     *
10033     * @attr ref android.R.styleable#View_layerType
10034     */
10035    public void setLayerType(int layerType, Paint paint) {
10036        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10037            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10038                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10039        }
10040
10041        if (layerType == mLayerType) {
10042            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10043                mLayerPaint = paint == null ? new Paint() : paint;
10044                invalidateParentCaches();
10045                invalidate(true);
10046            }
10047            return;
10048        }
10049
10050        // Destroy any previous software drawing cache if needed
10051        switch (mLayerType) {
10052            case LAYER_TYPE_HARDWARE:
10053                destroyLayer();
10054                // fall through - non-accelerated views may use software layer mechanism instead
10055            case LAYER_TYPE_SOFTWARE:
10056                destroyDrawingCache();
10057                break;
10058            default:
10059                break;
10060        }
10061
10062        mLayerType = layerType;
10063        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10064        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10065        mLocalDirtyRect = layerDisabled ? null : new Rect();
10066
10067        invalidateParentCaches();
10068        invalidate(true);
10069    }
10070
10071    /**
10072     * Indicates whether this view has a static layer. A view with layer type
10073     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10074     * dynamic.
10075     */
10076    boolean hasStaticLayer() {
10077        return mLayerType == LAYER_TYPE_NONE;
10078    }
10079
10080    /**
10081     * Indicates what type of layer is currently associated with this view. By default
10082     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10083     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10084     * for more information on the different types of layers.
10085     *
10086     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10087     *         {@link #LAYER_TYPE_HARDWARE}
10088     *
10089     * @see #setLayerType(int, android.graphics.Paint)
10090     * @see #buildLayer()
10091     * @see #LAYER_TYPE_NONE
10092     * @see #LAYER_TYPE_SOFTWARE
10093     * @see #LAYER_TYPE_HARDWARE
10094     */
10095    public int getLayerType() {
10096        return mLayerType;
10097    }
10098
10099    /**
10100     * Forces this view's layer to be created and this view to be rendered
10101     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10102     * invoking this method will have no effect.
10103     *
10104     * This method can for instance be used to render a view into its layer before
10105     * starting an animation. If this view is complex, rendering into the layer
10106     * before starting the animation will avoid skipping frames.
10107     *
10108     * @throws IllegalStateException If this view is not attached to a window
10109     *
10110     * @see #setLayerType(int, android.graphics.Paint)
10111     */
10112    public void buildLayer() {
10113        if (mLayerType == LAYER_TYPE_NONE) return;
10114
10115        if (mAttachInfo == null) {
10116            throw new IllegalStateException("This view must be attached to a window first");
10117        }
10118
10119        switch (mLayerType) {
10120            case LAYER_TYPE_HARDWARE:
10121                if (mAttachInfo.mHardwareRenderer != null &&
10122                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10123                        mAttachInfo.mHardwareRenderer.validate()) {
10124                    getHardwareLayer();
10125                }
10126                break;
10127            case LAYER_TYPE_SOFTWARE:
10128                buildDrawingCache(true);
10129                break;
10130        }
10131    }
10132
10133    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10134    void flushLayer() {
10135        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10136            mHardwareLayer.flush();
10137        }
10138    }
10139
10140    /**
10141     * <p>Returns a hardware layer that can be used to draw this view again
10142     * without executing its draw method.</p>
10143     *
10144     * @return A HardwareLayer ready to render, or null if an error occurred.
10145     */
10146    HardwareLayer getHardwareLayer() {
10147        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10148                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10149            return null;
10150        }
10151
10152        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10153
10154        final int width = mRight - mLeft;
10155        final int height = mBottom - mTop;
10156
10157        if (width == 0 || height == 0) {
10158            return null;
10159        }
10160
10161        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10162            if (mHardwareLayer == null) {
10163                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10164                        width, height, isOpaque());
10165                mLocalDirtyRect.setEmpty();
10166            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10167                mHardwareLayer.resize(width, height);
10168                mLocalDirtyRect.setEmpty();
10169            }
10170
10171            // The layer is not valid if the underlying GPU resources cannot be allocated
10172            if (!mHardwareLayer.isValid()) {
10173                return null;
10174            }
10175
10176            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10177            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10178
10179            // Make sure all the GPU resources have been properly allocated
10180            if (canvas == null) {
10181                mHardwareLayer.end(currentCanvas);
10182                return null;
10183            }
10184
10185            mAttachInfo.mHardwareCanvas = canvas;
10186            try {
10187                canvas.setViewport(width, height);
10188                canvas.onPreDraw(mLocalDirtyRect);
10189                mLocalDirtyRect.setEmpty();
10190
10191                final int restoreCount = canvas.save();
10192
10193                computeScroll();
10194                canvas.translate(-mScrollX, -mScrollY);
10195
10196                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10197
10198                // Fast path for layouts with no backgrounds
10199                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10200                    mPrivateFlags &= ~DIRTY_MASK;
10201                    dispatchDraw(canvas);
10202                } else {
10203                    draw(canvas);
10204                }
10205
10206                canvas.restoreToCount(restoreCount);
10207            } finally {
10208                canvas.onPostDraw();
10209                mHardwareLayer.end(currentCanvas);
10210                mAttachInfo.mHardwareCanvas = currentCanvas;
10211            }
10212        }
10213
10214        return mHardwareLayer;
10215    }
10216
10217    /**
10218     * Destroys this View's hardware layer if possible.
10219     *
10220     * @return True if the layer was destroyed, false otherwise.
10221     *
10222     * @see #setLayerType(int, android.graphics.Paint)
10223     * @see #LAYER_TYPE_HARDWARE
10224     */
10225    boolean destroyLayer() {
10226        if (mHardwareLayer != null) {
10227            AttachInfo info = mAttachInfo;
10228            if (info != null && info.mHardwareRenderer != null &&
10229                    info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) {
10230                mHardwareLayer.destroy();
10231                mHardwareLayer = null;
10232
10233                invalidate(true);
10234                invalidateParentCaches();
10235            }
10236            return true;
10237        }
10238        return false;
10239    }
10240
10241    /**
10242     * Destroys all hardware rendering resources. This method is invoked
10243     * when the system needs to reclaim resources. Upon execution of this
10244     * method, you should free any OpenGL resources created by the view.
10245     *
10246     * Note: you <strong>must</strong> call
10247     * <code>super.destroyHardwareResources()</code> when overriding
10248     * this method.
10249     *
10250     * @hide
10251     */
10252    protected void destroyHardwareResources() {
10253        destroyLayer();
10254    }
10255
10256    /**
10257     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10258     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10259     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10260     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10261     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10262     * null.</p>
10263     *
10264     * <p>Enabling the drawing cache is similar to
10265     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10266     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10267     * drawing cache has no effect on rendering because the system uses a different mechanism
10268     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10269     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10270     * for information on how to enable software and hardware layers.</p>
10271     *
10272     * <p>This API can be used to manually generate
10273     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10274     * {@link #getDrawingCache()}.</p>
10275     *
10276     * @param enabled true to enable the drawing cache, false otherwise
10277     *
10278     * @see #isDrawingCacheEnabled()
10279     * @see #getDrawingCache()
10280     * @see #buildDrawingCache()
10281     * @see #setLayerType(int, android.graphics.Paint)
10282     */
10283    public void setDrawingCacheEnabled(boolean enabled) {
10284        mCachingFailed = false;
10285        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10286    }
10287
10288    /**
10289     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10290     *
10291     * @return true if the drawing cache is enabled
10292     *
10293     * @see #setDrawingCacheEnabled(boolean)
10294     * @see #getDrawingCache()
10295     */
10296    @ViewDebug.ExportedProperty(category = "drawing")
10297    public boolean isDrawingCacheEnabled() {
10298        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10299    }
10300
10301    /**
10302     * Debugging utility which recursively outputs the dirty state of a view and its
10303     * descendants.
10304     *
10305     * @hide
10306     */
10307    @SuppressWarnings({"UnusedDeclaration"})
10308    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10309        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10310                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10311                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10312                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10313        if (clear) {
10314            mPrivateFlags &= clearMask;
10315        }
10316        if (this instanceof ViewGroup) {
10317            ViewGroup parent = (ViewGroup) this;
10318            final int count = parent.getChildCount();
10319            for (int i = 0; i < count; i++) {
10320                final View child = parent.getChildAt(i);
10321                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10322            }
10323        }
10324    }
10325
10326    /**
10327     * This method is used by ViewGroup to cause its children to restore or recreate their
10328     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10329     * to recreate its own display list, which would happen if it went through the normal
10330     * draw/dispatchDraw mechanisms.
10331     *
10332     * @hide
10333     */
10334    protected void dispatchGetDisplayList() {}
10335
10336    /**
10337     * A view that is not attached or hardware accelerated cannot create a display list.
10338     * This method checks these conditions and returns the appropriate result.
10339     *
10340     * @return true if view has the ability to create a display list, false otherwise.
10341     *
10342     * @hide
10343     */
10344    public boolean canHaveDisplayList() {
10345        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10346    }
10347
10348    /**
10349     * @return The HardwareRenderer associated with that view or null if hardware rendering
10350     * is not supported or this this has not been attached to a window.
10351     *
10352     * @hide
10353     */
10354    public HardwareRenderer getHardwareRenderer() {
10355        if (mAttachInfo != null) {
10356            return mAttachInfo.mHardwareRenderer;
10357        }
10358        return null;
10359    }
10360
10361    /**
10362     * <p>Returns a display list that can be used to draw this view again
10363     * without executing its draw method.</p>
10364     *
10365     * @return A DisplayList ready to replay, or null if caching is not enabled.
10366     *
10367     * @hide
10368     */
10369    public DisplayList getDisplayList() {
10370        if (!canHaveDisplayList()) {
10371            return null;
10372        }
10373
10374        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10375                mDisplayList == null || !mDisplayList.isValid() ||
10376                mRecreateDisplayList)) {
10377            // Don't need to recreate the display list, just need to tell our
10378            // children to restore/recreate theirs
10379            if (mDisplayList != null && mDisplayList.isValid() &&
10380                    !mRecreateDisplayList) {
10381                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10382                mPrivateFlags &= ~DIRTY_MASK;
10383                dispatchGetDisplayList();
10384
10385                return mDisplayList;
10386            }
10387
10388            // If we got here, we're recreating it. Mark it as such to ensure that
10389            // we copy in child display lists into ours in drawChild()
10390            mRecreateDisplayList = true;
10391            if (mDisplayList == null) {
10392                final String name = getClass().getSimpleName();
10393                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10394                // If we're creating a new display list, make sure our parent gets invalidated
10395                // since they will need to recreate their display list to account for this
10396                // new child display list.
10397                invalidateParentCaches();
10398            }
10399
10400            final HardwareCanvas canvas = mDisplayList.start();
10401            int restoreCount = 0;
10402            try {
10403                int width = mRight - mLeft;
10404                int height = mBottom - mTop;
10405
10406                canvas.setViewport(width, height);
10407                // The dirty rect should always be null for a display list
10408                canvas.onPreDraw(null);
10409
10410                computeScroll();
10411
10412                restoreCount = canvas.save();
10413                canvas.translate(-mScrollX, -mScrollY);
10414                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10415                mPrivateFlags &= ~DIRTY_MASK;
10416
10417                // Fast path for layouts with no backgrounds
10418                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10419                    dispatchDraw(canvas);
10420                } else {
10421                    draw(canvas);
10422                }
10423            } finally {
10424                canvas.restoreToCount(restoreCount);
10425                canvas.onPostDraw();
10426
10427                mDisplayList.end();
10428            }
10429        } else {
10430            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10431            mPrivateFlags &= ~DIRTY_MASK;
10432        }
10433
10434        return mDisplayList;
10435    }
10436
10437    /**
10438     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10439     *
10440     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10441     *
10442     * @see #getDrawingCache(boolean)
10443     */
10444    public Bitmap getDrawingCache() {
10445        return getDrawingCache(false);
10446    }
10447
10448    /**
10449     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10450     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10451     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10452     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10453     * request the drawing cache by calling this method and draw it on screen if the
10454     * returned bitmap is not null.</p>
10455     *
10456     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10457     * this method will create a bitmap of the same size as this view. Because this bitmap
10458     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10459     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10460     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10461     * size than the view. This implies that your application must be able to handle this
10462     * size.</p>
10463     *
10464     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10465     *        the current density of the screen when the application is in compatibility
10466     *        mode.
10467     *
10468     * @return A bitmap representing this view or null if cache is disabled.
10469     *
10470     * @see #setDrawingCacheEnabled(boolean)
10471     * @see #isDrawingCacheEnabled()
10472     * @see #buildDrawingCache(boolean)
10473     * @see #destroyDrawingCache()
10474     */
10475    public Bitmap getDrawingCache(boolean autoScale) {
10476        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10477            return null;
10478        }
10479        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10480            buildDrawingCache(autoScale);
10481        }
10482        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10483    }
10484
10485    /**
10486     * <p>Frees the resources used by the drawing cache. If you call
10487     * {@link #buildDrawingCache()} manually without calling
10488     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10489     * should cleanup the cache with this method afterwards.</p>
10490     *
10491     * @see #setDrawingCacheEnabled(boolean)
10492     * @see #buildDrawingCache()
10493     * @see #getDrawingCache()
10494     */
10495    public void destroyDrawingCache() {
10496        if (mDrawingCache != null) {
10497            mDrawingCache.recycle();
10498            mDrawingCache = null;
10499        }
10500        if (mUnscaledDrawingCache != null) {
10501            mUnscaledDrawingCache.recycle();
10502            mUnscaledDrawingCache = null;
10503        }
10504    }
10505
10506    /**
10507     * Setting a solid background color for the drawing cache's bitmaps will improve
10508     * performance and memory usage. Note, though that this should only be used if this
10509     * view will always be drawn on top of a solid color.
10510     *
10511     * @param color The background color to use for the drawing cache's bitmap
10512     *
10513     * @see #setDrawingCacheEnabled(boolean)
10514     * @see #buildDrawingCache()
10515     * @see #getDrawingCache()
10516     */
10517    public void setDrawingCacheBackgroundColor(int color) {
10518        if (color != mDrawingCacheBackgroundColor) {
10519            mDrawingCacheBackgroundColor = color;
10520            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10521        }
10522    }
10523
10524    /**
10525     * @see #setDrawingCacheBackgroundColor(int)
10526     *
10527     * @return The background color to used for the drawing cache's bitmap
10528     */
10529    public int getDrawingCacheBackgroundColor() {
10530        return mDrawingCacheBackgroundColor;
10531    }
10532
10533    /**
10534     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10535     *
10536     * @see #buildDrawingCache(boolean)
10537     */
10538    public void buildDrawingCache() {
10539        buildDrawingCache(false);
10540    }
10541
10542    /**
10543     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10544     *
10545     * <p>If you call {@link #buildDrawingCache()} manually without calling
10546     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10547     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10548     *
10549     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10550     * this method will create a bitmap of the same size as this view. Because this bitmap
10551     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10552     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10553     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10554     * size than the view. This implies that your application must be able to handle this
10555     * size.</p>
10556     *
10557     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10558     * you do not need the drawing cache bitmap, calling this method will increase memory
10559     * usage and cause the view to be rendered in software once, thus negatively impacting
10560     * performance.</p>
10561     *
10562     * @see #getDrawingCache()
10563     * @see #destroyDrawingCache()
10564     */
10565    public void buildDrawingCache(boolean autoScale) {
10566        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10567                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10568            mCachingFailed = false;
10569
10570            if (ViewDebug.TRACE_HIERARCHY) {
10571                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10572            }
10573
10574            int width = mRight - mLeft;
10575            int height = mBottom - mTop;
10576
10577            final AttachInfo attachInfo = mAttachInfo;
10578            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10579
10580            if (autoScale && scalingRequired) {
10581                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10582                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10583            }
10584
10585            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10586            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10587            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10588
10589            if (width <= 0 || height <= 0 ||
10590                     // Projected bitmap size in bytes
10591                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10592                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10593                destroyDrawingCache();
10594                mCachingFailed = true;
10595                return;
10596            }
10597
10598            boolean clear = true;
10599            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10600
10601            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10602                Bitmap.Config quality;
10603                if (!opaque) {
10604                    // Never pick ARGB_4444 because it looks awful
10605                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10606                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10607                        case DRAWING_CACHE_QUALITY_AUTO:
10608                            quality = Bitmap.Config.ARGB_8888;
10609                            break;
10610                        case DRAWING_CACHE_QUALITY_LOW:
10611                            quality = Bitmap.Config.ARGB_8888;
10612                            break;
10613                        case DRAWING_CACHE_QUALITY_HIGH:
10614                            quality = Bitmap.Config.ARGB_8888;
10615                            break;
10616                        default:
10617                            quality = Bitmap.Config.ARGB_8888;
10618                            break;
10619                    }
10620                } else {
10621                    // Optimization for translucent windows
10622                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10623                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10624                }
10625
10626                // Try to cleanup memory
10627                if (bitmap != null) bitmap.recycle();
10628
10629                try {
10630                    bitmap = Bitmap.createBitmap(width, height, quality);
10631                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10632                    if (autoScale) {
10633                        mDrawingCache = bitmap;
10634                    } else {
10635                        mUnscaledDrawingCache = bitmap;
10636                    }
10637                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10638                } catch (OutOfMemoryError e) {
10639                    // If there is not enough memory to create the bitmap cache, just
10640                    // ignore the issue as bitmap caches are not required to draw the
10641                    // view hierarchy
10642                    if (autoScale) {
10643                        mDrawingCache = null;
10644                    } else {
10645                        mUnscaledDrawingCache = null;
10646                    }
10647                    mCachingFailed = true;
10648                    return;
10649                }
10650
10651                clear = drawingCacheBackgroundColor != 0;
10652            }
10653
10654            Canvas canvas;
10655            if (attachInfo != null) {
10656                canvas = attachInfo.mCanvas;
10657                if (canvas == null) {
10658                    canvas = new Canvas();
10659                }
10660                canvas.setBitmap(bitmap);
10661                // Temporarily clobber the cached Canvas in case one of our children
10662                // is also using a drawing cache. Without this, the children would
10663                // steal the canvas by attaching their own bitmap to it and bad, bad
10664                // thing would happen (invisible views, corrupted drawings, etc.)
10665                attachInfo.mCanvas = null;
10666            } else {
10667                // This case should hopefully never or seldom happen
10668                canvas = new Canvas(bitmap);
10669            }
10670
10671            if (clear) {
10672                bitmap.eraseColor(drawingCacheBackgroundColor);
10673            }
10674
10675            computeScroll();
10676            final int restoreCount = canvas.save();
10677
10678            if (autoScale && scalingRequired) {
10679                final float scale = attachInfo.mApplicationScale;
10680                canvas.scale(scale, scale);
10681            }
10682
10683            canvas.translate(-mScrollX, -mScrollY);
10684
10685            mPrivateFlags |= DRAWN;
10686            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10687                    mLayerType != LAYER_TYPE_NONE) {
10688                mPrivateFlags |= DRAWING_CACHE_VALID;
10689            }
10690
10691            // Fast path for layouts with no backgrounds
10692            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10693                if (ViewDebug.TRACE_HIERARCHY) {
10694                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10695                }
10696                mPrivateFlags &= ~DIRTY_MASK;
10697                dispatchDraw(canvas);
10698            } else {
10699                draw(canvas);
10700            }
10701
10702            canvas.restoreToCount(restoreCount);
10703            canvas.setBitmap(null);
10704
10705            if (attachInfo != null) {
10706                // Restore the cached Canvas for our siblings
10707                attachInfo.mCanvas = canvas;
10708            }
10709        }
10710    }
10711
10712    /**
10713     * Create a snapshot of the view into a bitmap.  We should probably make
10714     * some form of this public, but should think about the API.
10715     */
10716    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10717        int width = mRight - mLeft;
10718        int height = mBottom - mTop;
10719
10720        final AttachInfo attachInfo = mAttachInfo;
10721        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10722        width = (int) ((width * scale) + 0.5f);
10723        height = (int) ((height * scale) + 0.5f);
10724
10725        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10726        if (bitmap == null) {
10727            throw new OutOfMemoryError();
10728        }
10729
10730        Resources resources = getResources();
10731        if (resources != null) {
10732            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10733        }
10734
10735        Canvas canvas;
10736        if (attachInfo != null) {
10737            canvas = attachInfo.mCanvas;
10738            if (canvas == null) {
10739                canvas = new Canvas();
10740            }
10741            canvas.setBitmap(bitmap);
10742            // Temporarily clobber the cached Canvas in case one of our children
10743            // is also using a drawing cache. Without this, the children would
10744            // steal the canvas by attaching their own bitmap to it and bad, bad
10745            // things would happen (invisible views, corrupted drawings, etc.)
10746            attachInfo.mCanvas = null;
10747        } else {
10748            // This case should hopefully never or seldom happen
10749            canvas = new Canvas(bitmap);
10750        }
10751
10752        if ((backgroundColor & 0xff000000) != 0) {
10753            bitmap.eraseColor(backgroundColor);
10754        }
10755
10756        computeScroll();
10757        final int restoreCount = canvas.save();
10758        canvas.scale(scale, scale);
10759        canvas.translate(-mScrollX, -mScrollY);
10760
10761        // Temporarily remove the dirty mask
10762        int flags = mPrivateFlags;
10763        mPrivateFlags &= ~DIRTY_MASK;
10764
10765        // Fast path for layouts with no backgrounds
10766        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10767            dispatchDraw(canvas);
10768        } else {
10769            draw(canvas);
10770        }
10771
10772        mPrivateFlags = flags;
10773
10774        canvas.restoreToCount(restoreCount);
10775        canvas.setBitmap(null);
10776
10777        if (attachInfo != null) {
10778            // Restore the cached Canvas for our siblings
10779            attachInfo.mCanvas = canvas;
10780        }
10781
10782        return bitmap;
10783    }
10784
10785    /**
10786     * Indicates whether this View is currently in edit mode. A View is usually
10787     * in edit mode when displayed within a developer tool. For instance, if
10788     * this View is being drawn by a visual user interface builder, this method
10789     * should return true.
10790     *
10791     * Subclasses should check the return value of this method to provide
10792     * different behaviors if their normal behavior might interfere with the
10793     * host environment. For instance: the class spawns a thread in its
10794     * constructor, the drawing code relies on device-specific features, etc.
10795     *
10796     * This method is usually checked in the drawing code of custom widgets.
10797     *
10798     * @return True if this View is in edit mode, false otherwise.
10799     */
10800    public boolean isInEditMode() {
10801        return false;
10802    }
10803
10804    /**
10805     * If the View draws content inside its padding and enables fading edges,
10806     * it needs to support padding offsets. Padding offsets are added to the
10807     * fading edges to extend the length of the fade so that it covers pixels
10808     * drawn inside the padding.
10809     *
10810     * Subclasses of this class should override this method if they need
10811     * to draw content inside the padding.
10812     *
10813     * @return True if padding offset must be applied, false otherwise.
10814     *
10815     * @see #getLeftPaddingOffset()
10816     * @see #getRightPaddingOffset()
10817     * @see #getTopPaddingOffset()
10818     * @see #getBottomPaddingOffset()
10819     *
10820     * @since CURRENT
10821     */
10822    protected boolean isPaddingOffsetRequired() {
10823        return false;
10824    }
10825
10826    /**
10827     * Amount by which to extend the left fading region. Called only when
10828     * {@link #isPaddingOffsetRequired()} returns true.
10829     *
10830     * @return The left padding offset in pixels.
10831     *
10832     * @see #isPaddingOffsetRequired()
10833     *
10834     * @since CURRENT
10835     */
10836    protected int getLeftPaddingOffset() {
10837        return 0;
10838    }
10839
10840    /**
10841     * Amount by which to extend the right fading region. Called only when
10842     * {@link #isPaddingOffsetRequired()} returns true.
10843     *
10844     * @return The right padding offset in pixels.
10845     *
10846     * @see #isPaddingOffsetRequired()
10847     *
10848     * @since CURRENT
10849     */
10850    protected int getRightPaddingOffset() {
10851        return 0;
10852    }
10853
10854    /**
10855     * Amount by which to extend the top fading region. Called only when
10856     * {@link #isPaddingOffsetRequired()} returns true.
10857     *
10858     * @return The top padding offset in pixels.
10859     *
10860     * @see #isPaddingOffsetRequired()
10861     *
10862     * @since CURRENT
10863     */
10864    protected int getTopPaddingOffset() {
10865        return 0;
10866    }
10867
10868    /**
10869     * Amount by which to extend the bottom fading region. Called only when
10870     * {@link #isPaddingOffsetRequired()} returns true.
10871     *
10872     * @return The bottom padding offset in pixels.
10873     *
10874     * @see #isPaddingOffsetRequired()
10875     *
10876     * @since CURRENT
10877     */
10878    protected int getBottomPaddingOffset() {
10879        return 0;
10880    }
10881
10882    /**
10883     * @hide
10884     * @param offsetRequired
10885     */
10886    protected int getFadeTop(boolean offsetRequired) {
10887        int top = mPaddingTop;
10888        if (offsetRequired) top += getTopPaddingOffset();
10889        return top;
10890    }
10891
10892    /**
10893     * @hide
10894     * @param offsetRequired
10895     */
10896    protected int getFadeHeight(boolean offsetRequired) {
10897        int padding = mPaddingTop;
10898        if (offsetRequired) padding += getTopPaddingOffset();
10899        return mBottom - mTop - mPaddingBottom - padding;
10900    }
10901
10902    /**
10903     * <p>Indicates whether this view is attached to an hardware accelerated
10904     * window or not.</p>
10905     *
10906     * <p>Even if this method returns true, it does not mean that every call
10907     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10908     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10909     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10910     * window is hardware accelerated,
10911     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10912     * return false, and this method will return true.</p>
10913     *
10914     * @return True if the view is attached to a window and the window is
10915     *         hardware accelerated; false in any other case.
10916     */
10917    public boolean isHardwareAccelerated() {
10918        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10919    }
10920
10921    /**
10922     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
10923     * case of an active Animation being run on the view.
10924     */
10925    private boolean drawAnimation(ViewGroup parent, long drawingTime,
10926            Animation a, boolean scalingRequired) {
10927        Transformation invalidationTransform;
10928        final int flags = parent.mGroupFlags;
10929        final boolean initialized = a.isInitialized();
10930        if (!initialized) {
10931            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
10932            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
10933            onAnimationStart();
10934        }
10935
10936        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
10937        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
10938            if (parent.mInvalidationTransformation == null) {
10939                parent.mInvalidationTransformation = new Transformation();
10940            }
10941            invalidationTransform = parent.mInvalidationTransformation;
10942            a.getTransformation(drawingTime, invalidationTransform, 1f);
10943        } else {
10944            invalidationTransform = parent.mChildTransformation;
10945        }
10946        if (more) {
10947            if (!a.willChangeBounds()) {
10948                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
10949                        parent.FLAG_OPTIMIZE_INVALIDATE) {
10950                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
10951                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
10952                    // The child need to draw an animation, potentially offscreen, so
10953                    // make sure we do not cancel invalidate requests
10954                    parent.mPrivateFlags |= DRAW_ANIMATION;
10955                    parent.invalidate(mLeft, mTop, mRight, mBottom);
10956                }
10957            } else {
10958                if (parent.mInvalidateRegion == null) {
10959                    parent.mInvalidateRegion = new RectF();
10960                }
10961                final RectF region = parent.mInvalidateRegion;
10962                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
10963                        invalidationTransform);
10964
10965                // The child need to draw an animation, potentially offscreen, so
10966                // make sure we do not cancel invalidate requests
10967                parent.mPrivateFlags |= DRAW_ANIMATION;
10968
10969                final int left = mLeft + (int) region.left;
10970                final int top = mTop + (int) region.top;
10971                parent.invalidate(left, top, left + (int) (region.width() + .5f),
10972                        top + (int) (region.height() + .5f));
10973            }
10974        }
10975        return more;
10976    }
10977
10978    /**
10979     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
10980     * This draw() method is an implementation detail and is not intended to be overridden or
10981     * to be called from anywhere else other than ViewGroup.drawChild().
10982     */
10983    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
10984        boolean more = false;
10985        final boolean childHasIdentityMatrix = hasIdentityMatrix();
10986        final int flags = parent.mGroupFlags;
10987
10988        if ((flags & parent.FLAG_CLEAR_TRANSFORMATION) == parent.FLAG_CLEAR_TRANSFORMATION) {
10989            parent.mChildTransformation.clear();
10990            parent.mGroupFlags &= ~parent.FLAG_CLEAR_TRANSFORMATION;
10991        }
10992
10993        Transformation transformToApply = null;
10994        boolean concatMatrix = false;
10995
10996        boolean scalingRequired = false;
10997        boolean caching;
10998        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
10999
11000        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11001        if ((flags & parent.FLAG_CHILDREN_DRAWN_WITH_CACHE) == parent.FLAG_CHILDREN_DRAWN_WITH_CACHE ||
11002                (flags & parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) == parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) {
11003            caching = true;
11004            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11005        } else {
11006            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11007        }
11008
11009        final Animation a = getAnimation();
11010        if (a != null) {
11011            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11012            concatMatrix = a.willChangeTransformationMatrix();
11013            transformToApply = parent.mChildTransformation;
11014        } else if ((flags & parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
11015                parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
11016            final boolean hasTransform =
11017                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11018            if (hasTransform) {
11019                final int transformType = parent.mChildTransformation.getTransformationType();
11020                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11021                        parent.mChildTransformation : null;
11022                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11023            }
11024        }
11025
11026        concatMatrix |= !childHasIdentityMatrix;
11027
11028        // Sets the flag as early as possible to allow draw() implementations
11029        // to call invalidate() successfully when doing animations
11030        mPrivateFlags |= DRAWN;
11031
11032        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11033                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11034            return more;
11035        }
11036
11037        if (hardwareAccelerated) {
11038            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11039            // retain the flag's value temporarily in the mRecreateDisplayList flag
11040            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11041            mPrivateFlags &= ~INVALIDATED;
11042        }
11043
11044        computeScroll();
11045
11046        final int sx = mScrollX;
11047        final int sy = mScrollY;
11048
11049        DisplayList displayList = null;
11050        Bitmap cache = null;
11051        boolean hasDisplayList = false;
11052        if (caching) {
11053            if (!hardwareAccelerated) {
11054                if (layerType != LAYER_TYPE_NONE) {
11055                    layerType = LAYER_TYPE_SOFTWARE;
11056                    buildDrawingCache(true);
11057                }
11058                cache = getDrawingCache(true);
11059            } else {
11060                switch (layerType) {
11061                    case LAYER_TYPE_SOFTWARE:
11062                        buildDrawingCache(true);
11063                        cache = getDrawingCache(true);
11064                        break;
11065                    case LAYER_TYPE_NONE:
11066                        // Delay getting the display list until animation-driven alpha values are
11067                        // set up and possibly passed on to the view
11068                        hasDisplayList = canHaveDisplayList();
11069                        break;
11070                }
11071            }
11072        }
11073
11074        final boolean hasNoCache = cache == null || hasDisplayList;
11075        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11076                layerType != LAYER_TYPE_HARDWARE;
11077
11078        final int restoreTo = canvas.save();
11079        if (offsetForScroll) {
11080            canvas.translate(mLeft - sx, mTop - sy);
11081        } else {
11082            canvas.translate(mLeft, mTop);
11083            if (scalingRequired) {
11084                // mAttachInfo cannot be null, otherwise scalingRequired == false
11085                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11086                canvas.scale(scale, scale);
11087            }
11088        }
11089
11090        float alpha = getAlpha();
11091        if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) {
11092            if (transformToApply != null || !childHasIdentityMatrix) {
11093                int transX = 0;
11094                int transY = 0;
11095
11096                if (offsetForScroll) {
11097                    transX = -sx;
11098                    transY = -sy;
11099                }
11100
11101                if (transformToApply != null) {
11102                    if (concatMatrix) {
11103                        // Undo the scroll translation, apply the transformation matrix,
11104                        // then redo the scroll translate to get the correct result.
11105                        canvas.translate(-transX, -transY);
11106                        canvas.concat(transformToApply.getMatrix());
11107                        canvas.translate(transX, transY);
11108                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11109                    }
11110
11111                    float transformAlpha = transformToApply.getAlpha();
11112                    if (transformAlpha < 1.0f) {
11113                        alpha *= transformToApply.getAlpha();
11114                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11115                    }
11116                }
11117
11118                if (!childHasIdentityMatrix) {
11119                    canvas.translate(-transX, -transY);
11120                    canvas.concat(getMatrix());
11121                    canvas.translate(transX, transY);
11122                }
11123            }
11124
11125            if (alpha < 1.0f) {
11126                parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11127                if (hasNoCache) {
11128                    final int multipliedAlpha = (int) (255 * alpha);
11129                    if (!onSetAlpha(multipliedAlpha)) {
11130                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11131                        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN ||
11132                                layerType != LAYER_TYPE_NONE) {
11133                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11134                        }
11135                        if (layerType == LAYER_TYPE_NONE) {
11136                            final int scrollX = hasDisplayList ? 0 : sx;
11137                            final int scrollY = hasDisplayList ? 0 : sy;
11138                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11139                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11140                        }
11141                    } else {
11142                        // Alpha is handled by the child directly, clobber the layer's alpha
11143                        mPrivateFlags |= ALPHA_SET;
11144                    }
11145                }
11146            }
11147        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11148            onSetAlpha(255);
11149            mPrivateFlags &= ~ALPHA_SET;
11150        }
11151
11152        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN) {
11153            if (offsetForScroll) {
11154                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11155            } else {
11156                if (!scalingRequired || cache == null) {
11157                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11158                } else {
11159                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11160                }
11161            }
11162        }
11163
11164        if (hasDisplayList) {
11165            displayList = getDisplayList();
11166            if (!displayList.isValid()) {
11167                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11168                // to getDisplayList(), the display list will be marked invalid and we should not
11169                // try to use it again.
11170                displayList = null;
11171                hasDisplayList = false;
11172            }
11173        }
11174
11175        if (hasNoCache) {
11176            boolean layerRendered = false;
11177            if (layerType == LAYER_TYPE_HARDWARE) {
11178                final HardwareLayer layer = getHardwareLayer();
11179                if (layer != null && layer.isValid()) {
11180                    mLayerPaint.setAlpha((int) (alpha * 255));
11181                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11182                    layerRendered = true;
11183                } else {
11184                    final int scrollX = hasDisplayList ? 0 : sx;
11185                    final int scrollY = hasDisplayList ? 0 : sy;
11186                    canvas.saveLayer(scrollX, scrollY,
11187                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11188                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11189                }
11190            }
11191
11192            if (!layerRendered) {
11193                if (!hasDisplayList) {
11194                    // Fast path for layouts with no backgrounds
11195                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11196                        if (ViewDebug.TRACE_HIERARCHY) {
11197                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11198                        }
11199                        mPrivateFlags &= ~DIRTY_MASK;
11200                        dispatchDraw(canvas);
11201                    } else {
11202                        draw(canvas);
11203                    }
11204                } else {
11205                    mPrivateFlags &= ~DIRTY_MASK;
11206                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11207                            mRight - mLeft, mBottom - mTop, null);
11208                }
11209            }
11210        } else if (cache != null) {
11211            mPrivateFlags &= ~DIRTY_MASK;
11212            Paint cachePaint;
11213
11214            if (layerType == LAYER_TYPE_NONE) {
11215                cachePaint = parent.mCachePaint;
11216                if (cachePaint == null) {
11217                    cachePaint = new Paint();
11218                    cachePaint.setDither(false);
11219                    parent.mCachePaint = cachePaint;
11220                }
11221                if (alpha < 1.0f) {
11222                    cachePaint.setAlpha((int) (alpha * 255));
11223                    parent.mGroupFlags |= parent.FLAG_ALPHA_LOWER_THAN_ONE;
11224                } else if  ((flags & parent.FLAG_ALPHA_LOWER_THAN_ONE) ==
11225                        parent.FLAG_ALPHA_LOWER_THAN_ONE) {
11226                    cachePaint.setAlpha(255);
11227                    parent.mGroupFlags &= ~parent.FLAG_ALPHA_LOWER_THAN_ONE;
11228                }
11229            } else {
11230                cachePaint = mLayerPaint;
11231                cachePaint.setAlpha((int) (alpha * 255));
11232            }
11233            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11234        }
11235
11236        canvas.restoreToCount(restoreTo);
11237
11238        if (a != null && !more) {
11239            if (!hardwareAccelerated && !a.getFillAfter()) {
11240                onSetAlpha(255);
11241            }
11242            parent.finishAnimatingView(this, a);
11243        }
11244
11245        if (more && hardwareAccelerated) {
11246            // invalidation is the trigger to recreate display lists, so if we're using
11247            // display lists to render, force an invalidate to allow the animation to
11248            // continue drawing another frame
11249            parent.invalidate(true);
11250            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11251                // alpha animations should cause the child to recreate its display list
11252                invalidate(true);
11253            }
11254        }
11255
11256        mRecreateDisplayList = false;
11257
11258        return more;
11259    }
11260
11261    /**
11262     * Manually render this view (and all of its children) to the given Canvas.
11263     * The view must have already done a full layout before this function is
11264     * called.  When implementing a view, implement
11265     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11266     * If you do need to override this method, call the superclass version.
11267     *
11268     * @param canvas The Canvas to which the View is rendered.
11269     */
11270    public void draw(Canvas canvas) {
11271        if (ViewDebug.TRACE_HIERARCHY) {
11272            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11273        }
11274
11275        final int privateFlags = mPrivateFlags;
11276        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11277                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11278        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11279
11280        /*
11281         * Draw traversal performs several drawing steps which must be executed
11282         * in the appropriate order:
11283         *
11284         *      1. Draw the background
11285         *      2. If necessary, save the canvas' layers to prepare for fading
11286         *      3. Draw view's content
11287         *      4. Draw children
11288         *      5. If necessary, draw the fading edges and restore layers
11289         *      6. Draw decorations (scrollbars for instance)
11290         */
11291
11292        // Step 1, draw the background, if needed
11293        int saveCount;
11294
11295        if (!dirtyOpaque) {
11296            final Drawable background = mBGDrawable;
11297            if (background != null) {
11298                final int scrollX = mScrollX;
11299                final int scrollY = mScrollY;
11300
11301                if (mBackgroundSizeChanged) {
11302                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11303                    mBackgroundSizeChanged = false;
11304                }
11305
11306                if ((scrollX | scrollY) == 0) {
11307                    background.draw(canvas);
11308                } else {
11309                    canvas.translate(scrollX, scrollY);
11310                    background.draw(canvas);
11311                    canvas.translate(-scrollX, -scrollY);
11312                }
11313            }
11314        }
11315
11316        // skip step 2 & 5 if possible (common case)
11317        final int viewFlags = mViewFlags;
11318        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11319        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11320        if (!verticalEdges && !horizontalEdges) {
11321            // Step 3, draw the content
11322            if (!dirtyOpaque) onDraw(canvas);
11323
11324            // Step 4, draw the children
11325            dispatchDraw(canvas);
11326
11327            // Step 6, draw decorations (scrollbars)
11328            onDrawScrollBars(canvas);
11329
11330            // we're done...
11331            return;
11332        }
11333
11334        /*
11335         * Here we do the full fledged routine...
11336         * (this is an uncommon case where speed matters less,
11337         * this is why we repeat some of the tests that have been
11338         * done above)
11339         */
11340
11341        boolean drawTop = false;
11342        boolean drawBottom = false;
11343        boolean drawLeft = false;
11344        boolean drawRight = false;
11345
11346        float topFadeStrength = 0.0f;
11347        float bottomFadeStrength = 0.0f;
11348        float leftFadeStrength = 0.0f;
11349        float rightFadeStrength = 0.0f;
11350
11351        // Step 2, save the canvas' layers
11352        int paddingLeft = mPaddingLeft;
11353
11354        final boolean offsetRequired = isPaddingOffsetRequired();
11355        if (offsetRequired) {
11356            paddingLeft += getLeftPaddingOffset();
11357        }
11358
11359        int left = mScrollX + paddingLeft;
11360        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11361        int top = mScrollY + getFadeTop(offsetRequired);
11362        int bottom = top + getFadeHeight(offsetRequired);
11363
11364        if (offsetRequired) {
11365            right += getRightPaddingOffset();
11366            bottom += getBottomPaddingOffset();
11367        }
11368
11369        final ScrollabilityCache scrollabilityCache = mScrollCache;
11370        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11371        int length = (int) fadeHeight;
11372
11373        // clip the fade length if top and bottom fades overlap
11374        // overlapping fades produce odd-looking artifacts
11375        if (verticalEdges && (top + length > bottom - length)) {
11376            length = (bottom - top) / 2;
11377        }
11378
11379        // also clip horizontal fades if necessary
11380        if (horizontalEdges && (left + length > right - length)) {
11381            length = (right - left) / 2;
11382        }
11383
11384        if (verticalEdges) {
11385            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11386            drawTop = topFadeStrength * fadeHeight > 1.0f;
11387            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11388            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11389        }
11390
11391        if (horizontalEdges) {
11392            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11393            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11394            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11395            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11396        }
11397
11398        saveCount = canvas.getSaveCount();
11399
11400        int solidColor = getSolidColor();
11401        if (solidColor == 0) {
11402            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11403
11404            if (drawTop) {
11405                canvas.saveLayer(left, top, right, top + length, null, flags);
11406            }
11407
11408            if (drawBottom) {
11409                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11410            }
11411
11412            if (drawLeft) {
11413                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11414            }
11415
11416            if (drawRight) {
11417                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11418            }
11419        } else {
11420            scrollabilityCache.setFadeColor(solidColor);
11421        }
11422
11423        // Step 3, draw the content
11424        if (!dirtyOpaque) onDraw(canvas);
11425
11426        // Step 4, draw the children
11427        dispatchDraw(canvas);
11428
11429        // Step 5, draw the fade effect and restore layers
11430        final Paint p = scrollabilityCache.paint;
11431        final Matrix matrix = scrollabilityCache.matrix;
11432        final Shader fade = scrollabilityCache.shader;
11433
11434        if (drawTop) {
11435            matrix.setScale(1, fadeHeight * topFadeStrength);
11436            matrix.postTranslate(left, top);
11437            fade.setLocalMatrix(matrix);
11438            canvas.drawRect(left, top, right, top + length, p);
11439        }
11440
11441        if (drawBottom) {
11442            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11443            matrix.postRotate(180);
11444            matrix.postTranslate(left, bottom);
11445            fade.setLocalMatrix(matrix);
11446            canvas.drawRect(left, bottom - length, right, bottom, p);
11447        }
11448
11449        if (drawLeft) {
11450            matrix.setScale(1, fadeHeight * leftFadeStrength);
11451            matrix.postRotate(-90);
11452            matrix.postTranslate(left, top);
11453            fade.setLocalMatrix(matrix);
11454            canvas.drawRect(left, top, left + length, bottom, p);
11455        }
11456
11457        if (drawRight) {
11458            matrix.setScale(1, fadeHeight * rightFadeStrength);
11459            matrix.postRotate(90);
11460            matrix.postTranslate(right, top);
11461            fade.setLocalMatrix(matrix);
11462            canvas.drawRect(right - length, top, right, bottom, p);
11463        }
11464
11465        canvas.restoreToCount(saveCount);
11466
11467        // Step 6, draw decorations (scrollbars)
11468        onDrawScrollBars(canvas);
11469    }
11470
11471    /**
11472     * Override this if your view is known to always be drawn on top of a solid color background,
11473     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11474     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11475     * should be set to 0xFF.
11476     *
11477     * @see #setVerticalFadingEdgeEnabled(boolean)
11478     * @see #setHorizontalFadingEdgeEnabled(boolean)
11479     *
11480     * @return The known solid color background for this view, or 0 if the color may vary
11481     */
11482    @ViewDebug.ExportedProperty(category = "drawing")
11483    public int getSolidColor() {
11484        return 0;
11485    }
11486
11487    /**
11488     * Build a human readable string representation of the specified view flags.
11489     *
11490     * @param flags the view flags to convert to a string
11491     * @return a String representing the supplied flags
11492     */
11493    private static String printFlags(int flags) {
11494        String output = "";
11495        int numFlags = 0;
11496        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11497            output += "TAKES_FOCUS";
11498            numFlags++;
11499        }
11500
11501        switch (flags & VISIBILITY_MASK) {
11502        case INVISIBLE:
11503            if (numFlags > 0) {
11504                output += " ";
11505            }
11506            output += "INVISIBLE";
11507            // USELESS HERE numFlags++;
11508            break;
11509        case GONE:
11510            if (numFlags > 0) {
11511                output += " ";
11512            }
11513            output += "GONE";
11514            // USELESS HERE numFlags++;
11515            break;
11516        default:
11517            break;
11518        }
11519        return output;
11520    }
11521
11522    /**
11523     * Build a human readable string representation of the specified private
11524     * view flags.
11525     *
11526     * @param privateFlags the private view flags to convert to a string
11527     * @return a String representing the supplied flags
11528     */
11529    private static String printPrivateFlags(int privateFlags) {
11530        String output = "";
11531        int numFlags = 0;
11532
11533        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11534            output += "WANTS_FOCUS";
11535            numFlags++;
11536        }
11537
11538        if ((privateFlags & FOCUSED) == FOCUSED) {
11539            if (numFlags > 0) {
11540                output += " ";
11541            }
11542            output += "FOCUSED";
11543            numFlags++;
11544        }
11545
11546        if ((privateFlags & SELECTED) == SELECTED) {
11547            if (numFlags > 0) {
11548                output += " ";
11549            }
11550            output += "SELECTED";
11551            numFlags++;
11552        }
11553
11554        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11555            if (numFlags > 0) {
11556                output += " ";
11557            }
11558            output += "IS_ROOT_NAMESPACE";
11559            numFlags++;
11560        }
11561
11562        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11563            if (numFlags > 0) {
11564                output += " ";
11565            }
11566            output += "HAS_BOUNDS";
11567            numFlags++;
11568        }
11569
11570        if ((privateFlags & DRAWN) == DRAWN) {
11571            if (numFlags > 0) {
11572                output += " ";
11573            }
11574            output += "DRAWN";
11575            // USELESS HERE numFlags++;
11576        }
11577        return output;
11578    }
11579
11580    /**
11581     * <p>Indicates whether or not this view's layout will be requested during
11582     * the next hierarchy layout pass.</p>
11583     *
11584     * @return true if the layout will be forced during next layout pass
11585     */
11586    public boolean isLayoutRequested() {
11587        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11588    }
11589
11590    /**
11591     * Assign a size and position to a view and all of its
11592     * descendants
11593     *
11594     * <p>This is the second phase of the layout mechanism.
11595     * (The first is measuring). In this phase, each parent calls
11596     * layout on all of its children to position them.
11597     * This is typically done using the child measurements
11598     * that were stored in the measure pass().</p>
11599     *
11600     * <p>Derived classes should not override this method.
11601     * Derived classes with children should override
11602     * onLayout. In that method, they should
11603     * call layout on each of their children.</p>
11604     *
11605     * @param l Left position, relative to parent
11606     * @param t Top position, relative to parent
11607     * @param r Right position, relative to parent
11608     * @param b Bottom position, relative to parent
11609     */
11610    @SuppressWarnings({"unchecked"})
11611    public void layout(int l, int t, int r, int b) {
11612        int oldL = mLeft;
11613        int oldT = mTop;
11614        int oldB = mBottom;
11615        int oldR = mRight;
11616        boolean changed = setFrame(l, t, r, b);
11617        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11618            if (ViewDebug.TRACE_HIERARCHY) {
11619                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11620            }
11621
11622            onLayout(changed, l, t, r, b);
11623            mPrivateFlags &= ~LAYOUT_REQUIRED;
11624
11625            ListenerInfo li = mListenerInfo;
11626            if (li != null && li.mOnLayoutChangeListeners != null) {
11627                ArrayList<OnLayoutChangeListener> listenersCopy =
11628                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
11629                int numListeners = listenersCopy.size();
11630                for (int i = 0; i < numListeners; ++i) {
11631                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11632                }
11633            }
11634        }
11635        mPrivateFlags &= ~FORCE_LAYOUT;
11636    }
11637
11638    /**
11639     * Called from layout when this view should
11640     * assign a size and position to each of its children.
11641     *
11642     * Derived classes with children should override
11643     * this method and call layout on each of
11644     * their children.
11645     * @param changed This is a new size or position for this view
11646     * @param left Left position, relative to parent
11647     * @param top Top position, relative to parent
11648     * @param right Right position, relative to parent
11649     * @param bottom Bottom position, relative to parent
11650     */
11651    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11652    }
11653
11654    /**
11655     * Assign a size and position to this view.
11656     *
11657     * This is called from layout.
11658     *
11659     * @param left Left position, relative to parent
11660     * @param top Top position, relative to parent
11661     * @param right Right position, relative to parent
11662     * @param bottom Bottom position, relative to parent
11663     * @return true if the new size and position are different than the
11664     *         previous ones
11665     * {@hide}
11666     */
11667    protected boolean setFrame(int left, int top, int right, int bottom) {
11668        boolean changed = false;
11669
11670        if (DBG) {
11671            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11672                    + right + "," + bottom + ")");
11673        }
11674
11675        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11676            changed = true;
11677
11678            // Remember our drawn bit
11679            int drawn = mPrivateFlags & DRAWN;
11680
11681            int oldWidth = mRight - mLeft;
11682            int oldHeight = mBottom - mTop;
11683            int newWidth = right - left;
11684            int newHeight = bottom - top;
11685            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11686
11687            // Invalidate our old position
11688            invalidate(sizeChanged);
11689
11690            mLeft = left;
11691            mTop = top;
11692            mRight = right;
11693            mBottom = bottom;
11694
11695            mPrivateFlags |= HAS_BOUNDS;
11696
11697
11698            if (sizeChanged) {
11699                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11700                    // A change in dimension means an auto-centered pivot point changes, too
11701                    if (mTransformationInfo != null) {
11702                        mTransformationInfo.mMatrixDirty = true;
11703                    }
11704                }
11705                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11706            }
11707
11708            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11709                // If we are visible, force the DRAWN bit to on so that
11710                // this invalidate will go through (at least to our parent).
11711                // This is because someone may have invalidated this view
11712                // before this call to setFrame came in, thereby clearing
11713                // the DRAWN bit.
11714                mPrivateFlags |= DRAWN;
11715                invalidate(sizeChanged);
11716                // parent display list may need to be recreated based on a change in the bounds
11717                // of any child
11718                invalidateParentCaches();
11719            }
11720
11721            // Reset drawn bit to original value (invalidate turns it off)
11722            mPrivateFlags |= drawn;
11723
11724            mBackgroundSizeChanged = true;
11725        }
11726        return changed;
11727    }
11728
11729    /**
11730     * Finalize inflating a view from XML.  This is called as the last phase
11731     * of inflation, after all child views have been added.
11732     *
11733     * <p>Even if the subclass overrides onFinishInflate, they should always be
11734     * sure to call the super method, so that we get called.
11735     */
11736    protected void onFinishInflate() {
11737    }
11738
11739    /**
11740     * Returns the resources associated with this view.
11741     *
11742     * @return Resources object.
11743     */
11744    public Resources getResources() {
11745        return mResources;
11746    }
11747
11748    /**
11749     * Invalidates the specified Drawable.
11750     *
11751     * @param drawable the drawable to invalidate
11752     */
11753    public void invalidateDrawable(Drawable drawable) {
11754        if (verifyDrawable(drawable)) {
11755            final Rect dirty = drawable.getBounds();
11756            final int scrollX = mScrollX;
11757            final int scrollY = mScrollY;
11758
11759            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11760                    dirty.right + scrollX, dirty.bottom + scrollY);
11761        }
11762    }
11763
11764    /**
11765     * Schedules an action on a drawable to occur at a specified time.
11766     *
11767     * @param who the recipient of the action
11768     * @param what the action to run on the drawable
11769     * @param when the time at which the action must occur. Uses the
11770     *        {@link SystemClock#uptimeMillis} timebase.
11771     */
11772    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11773        if (verifyDrawable(who) && what != null) {
11774            if (mAttachInfo != null) {
11775                mAttachInfo.mHandler.postAtTime(what, who, when);
11776            } else {
11777                ViewRootImpl.getRunQueue().postDelayed(what, when - SystemClock.uptimeMillis());
11778            }
11779        }
11780    }
11781
11782    /**
11783     * Cancels a scheduled action on a drawable.
11784     *
11785     * @param who the recipient of the action
11786     * @param what the action to cancel
11787     */
11788    public void unscheduleDrawable(Drawable who, Runnable what) {
11789        if (verifyDrawable(who) && what != null) {
11790            if (mAttachInfo != null) {
11791                mAttachInfo.mHandler.removeCallbacks(what, who);
11792            } else {
11793                ViewRootImpl.getRunQueue().removeCallbacks(what);
11794            }
11795        }
11796    }
11797
11798    /**
11799     * Unschedule any events associated with the given Drawable.  This can be
11800     * used when selecting a new Drawable into a view, so that the previous
11801     * one is completely unscheduled.
11802     *
11803     * @param who The Drawable to unschedule.
11804     *
11805     * @see #drawableStateChanged
11806     */
11807    public void unscheduleDrawable(Drawable who) {
11808        if (mAttachInfo != null) {
11809            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11810        }
11811    }
11812
11813    /**
11814    * Return the layout direction of a given Drawable.
11815    *
11816    * @param who the Drawable to query
11817    *
11818    * @hide
11819    */
11820    public int getResolvedLayoutDirection(Drawable who) {
11821        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11822    }
11823
11824    /**
11825     * If your view subclass is displaying its own Drawable objects, it should
11826     * override this function and return true for any Drawable it is
11827     * displaying.  This allows animations for those drawables to be
11828     * scheduled.
11829     *
11830     * <p>Be sure to call through to the super class when overriding this
11831     * function.
11832     *
11833     * @param who The Drawable to verify.  Return true if it is one you are
11834     *            displaying, else return the result of calling through to the
11835     *            super class.
11836     *
11837     * @return boolean If true than the Drawable is being displayed in the
11838     *         view; else false and it is not allowed to animate.
11839     *
11840     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11841     * @see #drawableStateChanged()
11842     */
11843    protected boolean verifyDrawable(Drawable who) {
11844        return who == mBGDrawable;
11845    }
11846
11847    /**
11848     * This function is called whenever the state of the view changes in such
11849     * a way that it impacts the state of drawables being shown.
11850     *
11851     * <p>Be sure to call through to the superclass when overriding this
11852     * function.
11853     *
11854     * @see Drawable#setState(int[])
11855     */
11856    protected void drawableStateChanged() {
11857        Drawable d = mBGDrawable;
11858        if (d != null && d.isStateful()) {
11859            d.setState(getDrawableState());
11860        }
11861    }
11862
11863    /**
11864     * Call this to force a view to update its drawable state. This will cause
11865     * drawableStateChanged to be called on this view. Views that are interested
11866     * in the new state should call getDrawableState.
11867     *
11868     * @see #drawableStateChanged
11869     * @see #getDrawableState
11870     */
11871    public void refreshDrawableState() {
11872        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11873        drawableStateChanged();
11874
11875        ViewParent parent = mParent;
11876        if (parent != null) {
11877            parent.childDrawableStateChanged(this);
11878        }
11879    }
11880
11881    /**
11882     * Return an array of resource IDs of the drawable states representing the
11883     * current state of the view.
11884     *
11885     * @return The current drawable state
11886     *
11887     * @see Drawable#setState(int[])
11888     * @see #drawableStateChanged()
11889     * @see #onCreateDrawableState(int)
11890     */
11891    public final int[] getDrawableState() {
11892        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11893            return mDrawableState;
11894        } else {
11895            mDrawableState = onCreateDrawableState(0);
11896            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11897            return mDrawableState;
11898        }
11899    }
11900
11901    /**
11902     * Generate the new {@link android.graphics.drawable.Drawable} state for
11903     * this view. This is called by the view
11904     * system when the cached Drawable state is determined to be invalid.  To
11905     * retrieve the current state, you should use {@link #getDrawableState}.
11906     *
11907     * @param extraSpace if non-zero, this is the number of extra entries you
11908     * would like in the returned array in which you can place your own
11909     * states.
11910     *
11911     * @return Returns an array holding the current {@link Drawable} state of
11912     * the view.
11913     *
11914     * @see #mergeDrawableStates(int[], int[])
11915     */
11916    protected int[] onCreateDrawableState(int extraSpace) {
11917        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11918                mParent instanceof View) {
11919            return ((View) mParent).onCreateDrawableState(extraSpace);
11920        }
11921
11922        int[] drawableState;
11923
11924        int privateFlags = mPrivateFlags;
11925
11926        int viewStateIndex = 0;
11927        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11928        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11929        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11930        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11931        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11932        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11933        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11934                HardwareRenderer.isAvailable()) {
11935            // This is set if HW acceleration is requested, even if the current
11936            // process doesn't allow it.  This is just to allow app preview
11937            // windows to better match their app.
11938            viewStateIndex |= VIEW_STATE_ACCELERATED;
11939        }
11940        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11941
11942        final int privateFlags2 = mPrivateFlags2;
11943        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11944        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11945
11946        drawableState = VIEW_STATE_SETS[viewStateIndex];
11947
11948        //noinspection ConstantIfStatement
11949        if (false) {
11950            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11951            Log.i("View", toString()
11952                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11953                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11954                    + " fo=" + hasFocus()
11955                    + " sl=" + ((privateFlags & SELECTED) != 0)
11956                    + " wf=" + hasWindowFocus()
11957                    + ": " + Arrays.toString(drawableState));
11958        }
11959
11960        if (extraSpace == 0) {
11961            return drawableState;
11962        }
11963
11964        final int[] fullState;
11965        if (drawableState != null) {
11966            fullState = new int[drawableState.length + extraSpace];
11967            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11968        } else {
11969            fullState = new int[extraSpace];
11970        }
11971
11972        return fullState;
11973    }
11974
11975    /**
11976     * Merge your own state values in <var>additionalState</var> into the base
11977     * state values <var>baseState</var> that were returned by
11978     * {@link #onCreateDrawableState(int)}.
11979     *
11980     * @param baseState The base state values returned by
11981     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11982     * own additional state values.
11983     *
11984     * @param additionalState The additional state values you would like
11985     * added to <var>baseState</var>; this array is not modified.
11986     *
11987     * @return As a convenience, the <var>baseState</var> array you originally
11988     * passed into the function is returned.
11989     *
11990     * @see #onCreateDrawableState(int)
11991     */
11992    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11993        final int N = baseState.length;
11994        int i = N - 1;
11995        while (i >= 0 && baseState[i] == 0) {
11996            i--;
11997        }
11998        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11999        return baseState;
12000    }
12001
12002    /**
12003     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12004     * on all Drawable objects associated with this view.
12005     */
12006    public void jumpDrawablesToCurrentState() {
12007        if (mBGDrawable != null) {
12008            mBGDrawable.jumpToCurrentState();
12009        }
12010    }
12011
12012    /**
12013     * Sets the background color for this view.
12014     * @param color the color of the background
12015     */
12016    @RemotableViewMethod
12017    public void setBackgroundColor(int color) {
12018        if (mBGDrawable instanceof ColorDrawable) {
12019            ((ColorDrawable) mBGDrawable).setColor(color);
12020        } else {
12021            setBackgroundDrawable(new ColorDrawable(color));
12022        }
12023    }
12024
12025    /**
12026     * Set the background to a given resource. The resource should refer to
12027     * a Drawable object or 0 to remove the background.
12028     * @param resid The identifier of the resource.
12029     * @attr ref android.R.styleable#View_background
12030     */
12031    @RemotableViewMethod
12032    public void setBackgroundResource(int resid) {
12033        if (resid != 0 && resid == mBackgroundResource) {
12034            return;
12035        }
12036
12037        Drawable d= null;
12038        if (resid != 0) {
12039            d = mResources.getDrawable(resid);
12040        }
12041        setBackgroundDrawable(d);
12042
12043        mBackgroundResource = resid;
12044    }
12045
12046    /**
12047     * Set the background to a given Drawable, or remove the background. If the
12048     * background has padding, this View's padding is set to the background's
12049     * padding. However, when a background is removed, this View's padding isn't
12050     * touched. If setting the padding is desired, please use
12051     * {@link #setPadding(int, int, int, int)}.
12052     *
12053     * @param d The Drawable to use as the background, or null to remove the
12054     *        background
12055     */
12056    public void setBackgroundDrawable(Drawable d) {
12057        if (d == mBGDrawable) {
12058            return;
12059        }
12060
12061        boolean requestLayout = false;
12062
12063        mBackgroundResource = 0;
12064
12065        /*
12066         * Regardless of whether we're setting a new background or not, we want
12067         * to clear the previous drawable.
12068         */
12069        if (mBGDrawable != null) {
12070            mBGDrawable.setCallback(null);
12071            unscheduleDrawable(mBGDrawable);
12072        }
12073
12074        if (d != null) {
12075            Rect padding = sThreadLocal.get();
12076            if (padding == null) {
12077                padding = new Rect();
12078                sThreadLocal.set(padding);
12079            }
12080            if (d.getPadding(padding)) {
12081                switch (d.getResolvedLayoutDirectionSelf()) {
12082                    case LAYOUT_DIRECTION_RTL:
12083                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12084                        break;
12085                    case LAYOUT_DIRECTION_LTR:
12086                    default:
12087                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12088                }
12089            }
12090
12091            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12092            // if it has a different minimum size, we should layout again
12093            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12094                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12095                requestLayout = true;
12096            }
12097
12098            d.setCallback(this);
12099            if (d.isStateful()) {
12100                d.setState(getDrawableState());
12101            }
12102            d.setVisible(getVisibility() == VISIBLE, false);
12103            mBGDrawable = d;
12104
12105            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12106                mPrivateFlags &= ~SKIP_DRAW;
12107                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12108                requestLayout = true;
12109            }
12110        } else {
12111            /* Remove the background */
12112            mBGDrawable = null;
12113
12114            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12115                /*
12116                 * This view ONLY drew the background before and we're removing
12117                 * the background, so now it won't draw anything
12118                 * (hence we SKIP_DRAW)
12119                 */
12120                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12121                mPrivateFlags |= SKIP_DRAW;
12122            }
12123
12124            /*
12125             * When the background is set, we try to apply its padding to this
12126             * View. When the background is removed, we don't touch this View's
12127             * padding. This is noted in the Javadocs. Hence, we don't need to
12128             * requestLayout(), the invalidate() below is sufficient.
12129             */
12130
12131            // The old background's minimum size could have affected this
12132            // View's layout, so let's requestLayout
12133            requestLayout = true;
12134        }
12135
12136        computeOpaqueFlags();
12137
12138        if (requestLayout) {
12139            requestLayout();
12140        }
12141
12142        mBackgroundSizeChanged = true;
12143        invalidate(true);
12144    }
12145
12146    /**
12147     * Gets the background drawable
12148     * @return The drawable used as the background for this view, if any.
12149     */
12150    public Drawable getBackground() {
12151        return mBGDrawable;
12152    }
12153
12154    /**
12155     * Sets the padding. The view may add on the space required to display
12156     * the scrollbars, depending on the style and visibility of the scrollbars.
12157     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12158     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12159     * from the values set in this call.
12160     *
12161     * @attr ref android.R.styleable#View_padding
12162     * @attr ref android.R.styleable#View_paddingBottom
12163     * @attr ref android.R.styleable#View_paddingLeft
12164     * @attr ref android.R.styleable#View_paddingRight
12165     * @attr ref android.R.styleable#View_paddingTop
12166     * @param left the left padding in pixels
12167     * @param top the top padding in pixels
12168     * @param right the right padding in pixels
12169     * @param bottom the bottom padding in pixels
12170     */
12171    public void setPadding(int left, int top, int right, int bottom) {
12172        boolean changed = false;
12173
12174        mUserPaddingRelative = false;
12175
12176        mUserPaddingLeft = left;
12177        mUserPaddingRight = right;
12178        mUserPaddingBottom = bottom;
12179
12180        final int viewFlags = mViewFlags;
12181
12182        // Common case is there are no scroll bars.
12183        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12184            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12185                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12186                        ? 0 : getVerticalScrollbarWidth();
12187                switch (mVerticalScrollbarPosition) {
12188                    case SCROLLBAR_POSITION_DEFAULT:
12189                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12190                            left += offset;
12191                        } else {
12192                            right += offset;
12193                        }
12194                        break;
12195                    case SCROLLBAR_POSITION_RIGHT:
12196                        right += offset;
12197                        break;
12198                    case SCROLLBAR_POSITION_LEFT:
12199                        left += offset;
12200                        break;
12201                }
12202            }
12203            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12204                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12205                        ? 0 : getHorizontalScrollbarHeight();
12206            }
12207        }
12208
12209        if (mPaddingLeft != left) {
12210            changed = true;
12211            mPaddingLeft = left;
12212        }
12213        if (mPaddingTop != top) {
12214            changed = true;
12215            mPaddingTop = top;
12216        }
12217        if (mPaddingRight != right) {
12218            changed = true;
12219            mPaddingRight = right;
12220        }
12221        if (mPaddingBottom != bottom) {
12222            changed = true;
12223            mPaddingBottom = bottom;
12224        }
12225
12226        if (changed) {
12227            requestLayout();
12228        }
12229    }
12230
12231    /**
12232     * Sets the relative padding. The view may add on the space required to display
12233     * the scrollbars, depending on the style and visibility of the scrollbars.
12234     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12235     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12236     * from the values set in this call.
12237     *
12238     * @attr ref android.R.styleable#View_padding
12239     * @attr ref android.R.styleable#View_paddingBottom
12240     * @attr ref android.R.styleable#View_paddingStart
12241     * @attr ref android.R.styleable#View_paddingEnd
12242     * @attr ref android.R.styleable#View_paddingTop
12243     * @param start the start padding in pixels
12244     * @param top the top padding in pixels
12245     * @param end the end padding in pixels
12246     * @param bottom the bottom padding in pixels
12247     *
12248     * @hide
12249     */
12250    public void setPaddingRelative(int start, int top, int end, int bottom) {
12251        mUserPaddingRelative = true;
12252
12253        mUserPaddingStart = start;
12254        mUserPaddingEnd = end;
12255
12256        switch(getResolvedLayoutDirection()) {
12257            case LAYOUT_DIRECTION_RTL:
12258                setPadding(end, top, start, bottom);
12259                break;
12260            case LAYOUT_DIRECTION_LTR:
12261            default:
12262                setPadding(start, top, end, bottom);
12263        }
12264    }
12265
12266    /**
12267     * Returns the top padding of this view.
12268     *
12269     * @return the top padding in pixels
12270     */
12271    public int getPaddingTop() {
12272        return mPaddingTop;
12273    }
12274
12275    /**
12276     * Returns the bottom padding of this view. If there are inset and enabled
12277     * scrollbars, this value may include the space required to display the
12278     * scrollbars as well.
12279     *
12280     * @return the bottom padding in pixels
12281     */
12282    public int getPaddingBottom() {
12283        return mPaddingBottom;
12284    }
12285
12286    /**
12287     * Returns the left padding of this view. If there are inset and enabled
12288     * scrollbars, this value may include the space required to display the
12289     * scrollbars as well.
12290     *
12291     * @return the left padding in pixels
12292     */
12293    public int getPaddingLeft() {
12294        return mPaddingLeft;
12295    }
12296
12297    /**
12298     * Returns the start padding of this view. If there are inset and enabled
12299     * scrollbars, this value may include the space required to display the
12300     * scrollbars as well.
12301     *
12302     * @return the start padding in pixels
12303     *
12304     * @hide
12305     */
12306    public int getPaddingStart() {
12307        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12308                mPaddingRight : mPaddingLeft;
12309    }
12310
12311    /**
12312     * Returns the right padding of this view. If there are inset and enabled
12313     * scrollbars, this value may include the space required to display the
12314     * scrollbars as well.
12315     *
12316     * @return the right padding in pixels
12317     */
12318    public int getPaddingRight() {
12319        return mPaddingRight;
12320    }
12321
12322    /**
12323     * Returns the end padding of this view. If there are inset and enabled
12324     * scrollbars, this value may include the space required to display the
12325     * scrollbars as well.
12326     *
12327     * @return the end padding in pixels
12328     *
12329     * @hide
12330     */
12331    public int getPaddingEnd() {
12332        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12333                mPaddingLeft : mPaddingRight;
12334    }
12335
12336    /**
12337     * Return if the padding as been set thru relative values
12338     * {@link #setPaddingRelative(int, int, int, int)} or thru
12339     * @attr ref android.R.styleable#View_paddingStart or
12340     * @attr ref android.R.styleable#View_paddingEnd
12341     *
12342     * @return true if the padding is relative or false if it is not.
12343     *
12344     * @hide
12345     */
12346    public boolean isPaddingRelative() {
12347        return mUserPaddingRelative;
12348    }
12349
12350    /**
12351     * Changes the selection state of this view. A view can be selected or not.
12352     * Note that selection is not the same as focus. Views are typically
12353     * selected in the context of an AdapterView like ListView or GridView;
12354     * the selected view is the view that is highlighted.
12355     *
12356     * @param selected true if the view must be selected, false otherwise
12357     */
12358    public void setSelected(boolean selected) {
12359        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12360            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12361            if (!selected) resetPressedState();
12362            invalidate(true);
12363            refreshDrawableState();
12364            dispatchSetSelected(selected);
12365        }
12366    }
12367
12368    /**
12369     * Dispatch setSelected to all of this View's children.
12370     *
12371     * @see #setSelected(boolean)
12372     *
12373     * @param selected The new selected state
12374     */
12375    protected void dispatchSetSelected(boolean selected) {
12376    }
12377
12378    /**
12379     * Indicates the selection state of this view.
12380     *
12381     * @return true if the view is selected, false otherwise
12382     */
12383    @ViewDebug.ExportedProperty
12384    public boolean isSelected() {
12385        return (mPrivateFlags & SELECTED) != 0;
12386    }
12387
12388    /**
12389     * Changes the activated state of this view. A view can be activated or not.
12390     * Note that activation is not the same as selection.  Selection is
12391     * a transient property, representing the view (hierarchy) the user is
12392     * currently interacting with.  Activation is a longer-term state that the
12393     * user can move views in and out of.  For example, in a list view with
12394     * single or multiple selection enabled, the views in the current selection
12395     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12396     * here.)  The activated state is propagated down to children of the view it
12397     * is set on.
12398     *
12399     * @param activated true if the view must be activated, false otherwise
12400     */
12401    public void setActivated(boolean activated) {
12402        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12403            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12404            invalidate(true);
12405            refreshDrawableState();
12406            dispatchSetActivated(activated);
12407        }
12408    }
12409
12410    /**
12411     * Dispatch setActivated to all of this View's children.
12412     *
12413     * @see #setActivated(boolean)
12414     *
12415     * @param activated The new activated state
12416     */
12417    protected void dispatchSetActivated(boolean activated) {
12418    }
12419
12420    /**
12421     * Indicates the activation state of this view.
12422     *
12423     * @return true if the view is activated, false otherwise
12424     */
12425    @ViewDebug.ExportedProperty
12426    public boolean isActivated() {
12427        return (mPrivateFlags & ACTIVATED) != 0;
12428    }
12429
12430    /**
12431     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12432     * observer can be used to get notifications when global events, like
12433     * layout, happen.
12434     *
12435     * The returned ViewTreeObserver observer is not guaranteed to remain
12436     * valid for the lifetime of this View. If the caller of this method keeps
12437     * a long-lived reference to ViewTreeObserver, it should always check for
12438     * the return value of {@link ViewTreeObserver#isAlive()}.
12439     *
12440     * @return The ViewTreeObserver for this view's hierarchy.
12441     */
12442    public ViewTreeObserver getViewTreeObserver() {
12443        if (mAttachInfo != null) {
12444            return mAttachInfo.mTreeObserver;
12445        }
12446        if (mFloatingTreeObserver == null) {
12447            mFloatingTreeObserver = new ViewTreeObserver();
12448        }
12449        return mFloatingTreeObserver;
12450    }
12451
12452    /**
12453     * <p>Finds the topmost view in the current view hierarchy.</p>
12454     *
12455     * @return the topmost view containing this view
12456     */
12457    public View getRootView() {
12458        if (mAttachInfo != null) {
12459            final View v = mAttachInfo.mRootView;
12460            if (v != null) {
12461                return v;
12462            }
12463        }
12464
12465        View parent = this;
12466
12467        while (parent.mParent != null && parent.mParent instanceof View) {
12468            parent = (View) parent.mParent;
12469        }
12470
12471        return parent;
12472    }
12473
12474    /**
12475     * <p>Computes the coordinates of this view on the screen. The argument
12476     * must be an array of two integers. After the method returns, the array
12477     * contains the x and y location in that order.</p>
12478     *
12479     * @param location an array of two integers in which to hold the coordinates
12480     */
12481    public void getLocationOnScreen(int[] location) {
12482        getLocationInWindow(location);
12483
12484        final AttachInfo info = mAttachInfo;
12485        if (info != null) {
12486            location[0] += info.mWindowLeft;
12487            location[1] += info.mWindowTop;
12488        }
12489    }
12490
12491    /**
12492     * <p>Computes the coordinates of this view in its window. The argument
12493     * must be an array of two integers. After the method returns, the array
12494     * contains the x and y location in that order.</p>
12495     *
12496     * @param location an array of two integers in which to hold the coordinates
12497     */
12498    public void getLocationInWindow(int[] location) {
12499        if (location == null || location.length < 2) {
12500            throw new IllegalArgumentException("location must be an array of two integers");
12501        }
12502
12503        if (mAttachInfo == null) {
12504            // When the view is not attached to a window, this method does not make sense
12505            location[0] = location[1] = 0;
12506            return;
12507        }
12508
12509        float[] position = mAttachInfo.mTmpTransformLocation;
12510        position[0] = position[1] = 0.0f;
12511
12512        if (!hasIdentityMatrix()) {
12513            getMatrix().mapPoints(position);
12514        }
12515
12516        position[0] += mLeft;
12517        position[1] += mTop;
12518
12519        ViewParent viewParent = mParent;
12520        while (viewParent instanceof View) {
12521            final View view = (View) viewParent;
12522
12523            position[0] -= view.mScrollX;
12524            position[1] -= view.mScrollY;
12525
12526            if (!view.hasIdentityMatrix()) {
12527                view.getMatrix().mapPoints(position);
12528            }
12529
12530            position[0] += view.mLeft;
12531            position[1] += view.mTop;
12532
12533            viewParent = view.mParent;
12534        }
12535
12536        if (viewParent instanceof ViewRootImpl) {
12537            // *cough*
12538            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12539            position[1] -= vr.mCurScrollY;
12540        }
12541
12542        location[0] = (int) (position[0] + 0.5f);
12543        location[1] = (int) (position[1] + 0.5f);
12544    }
12545
12546    /**
12547     * {@hide}
12548     * @param id the id of the view to be found
12549     * @return the view of the specified id, null if cannot be found
12550     */
12551    protected View findViewTraversal(int id) {
12552        if (id == mID) {
12553            return this;
12554        }
12555        return null;
12556    }
12557
12558    /**
12559     * {@hide}
12560     * @param tag the tag of the view to be found
12561     * @return the view of specified tag, null if cannot be found
12562     */
12563    protected View findViewWithTagTraversal(Object tag) {
12564        if (tag != null && tag.equals(mTag)) {
12565            return this;
12566        }
12567        return null;
12568    }
12569
12570    /**
12571     * {@hide}
12572     * @param predicate The predicate to evaluate.
12573     * @param childToSkip If not null, ignores this child during the recursive traversal.
12574     * @return The first view that matches the predicate or null.
12575     */
12576    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12577        if (predicate.apply(this)) {
12578            return this;
12579        }
12580        return null;
12581    }
12582
12583    /**
12584     * Look for a child view with the given id.  If this view has the given
12585     * id, return this view.
12586     *
12587     * @param id The id to search for.
12588     * @return The view that has the given id in the hierarchy or null
12589     */
12590    public final View findViewById(int id) {
12591        if (id < 0) {
12592            return null;
12593        }
12594        return findViewTraversal(id);
12595    }
12596
12597    /**
12598     * Finds a view by its unuque and stable accessibility id.
12599     *
12600     * @param accessibilityId The searched accessibility id.
12601     * @return The found view.
12602     */
12603    final View findViewByAccessibilityId(int accessibilityId) {
12604        if (accessibilityId < 0) {
12605            return null;
12606        }
12607        return findViewByAccessibilityIdTraversal(accessibilityId);
12608    }
12609
12610    /**
12611     * Performs the traversal to find a view by its unuque and stable accessibility id.
12612     *
12613     * <strong>Note:</strong>This method does not stop at the root namespace
12614     * boundary since the user can touch the screen at an arbitrary location
12615     * potentially crossing the root namespace bounday which will send an
12616     * accessibility event to accessibility services and they should be able
12617     * to obtain the event source. Also accessibility ids are guaranteed to be
12618     * unique in the window.
12619     *
12620     * @param accessibilityId The accessibility id.
12621     * @return The found view.
12622     */
12623    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12624        if (getAccessibilityViewId() == accessibilityId) {
12625            return this;
12626        }
12627        return null;
12628    }
12629
12630    /**
12631     * Look for a child view with the given tag.  If this view has the given
12632     * tag, return this view.
12633     *
12634     * @param tag The tag to search for, using "tag.equals(getTag())".
12635     * @return The View that has the given tag in the hierarchy or null
12636     */
12637    public final View findViewWithTag(Object tag) {
12638        if (tag == null) {
12639            return null;
12640        }
12641        return findViewWithTagTraversal(tag);
12642    }
12643
12644    /**
12645     * {@hide}
12646     * Look for a child view that matches the specified predicate.
12647     * If this view matches the predicate, return this view.
12648     *
12649     * @param predicate The predicate to evaluate.
12650     * @return The first view that matches the predicate or null.
12651     */
12652    public final View findViewByPredicate(Predicate<View> predicate) {
12653        return findViewByPredicateTraversal(predicate, null);
12654    }
12655
12656    /**
12657     * {@hide}
12658     * Look for a child view that matches the specified predicate,
12659     * starting with the specified view and its descendents and then
12660     * recusively searching the ancestors and siblings of that view
12661     * until this view is reached.
12662     *
12663     * This method is useful in cases where the predicate does not match
12664     * a single unique view (perhaps multiple views use the same id)
12665     * and we are trying to find the view that is "closest" in scope to the
12666     * starting view.
12667     *
12668     * @param start The view to start from.
12669     * @param predicate The predicate to evaluate.
12670     * @return The first view that matches the predicate or null.
12671     */
12672    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12673        View childToSkip = null;
12674        for (;;) {
12675            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12676            if (view != null || start == this) {
12677                return view;
12678            }
12679
12680            ViewParent parent = start.getParent();
12681            if (parent == null || !(parent instanceof View)) {
12682                return null;
12683            }
12684
12685            childToSkip = start;
12686            start = (View) parent;
12687        }
12688    }
12689
12690    /**
12691     * Sets the identifier for this view. The identifier does not have to be
12692     * unique in this view's hierarchy. The identifier should be a positive
12693     * number.
12694     *
12695     * @see #NO_ID
12696     * @see #getId()
12697     * @see #findViewById(int)
12698     *
12699     * @param id a number used to identify the view
12700     *
12701     * @attr ref android.R.styleable#View_id
12702     */
12703    public void setId(int id) {
12704        mID = id;
12705    }
12706
12707    /**
12708     * {@hide}
12709     *
12710     * @param isRoot true if the view belongs to the root namespace, false
12711     *        otherwise
12712     */
12713    public void setIsRootNamespace(boolean isRoot) {
12714        if (isRoot) {
12715            mPrivateFlags |= IS_ROOT_NAMESPACE;
12716        } else {
12717            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12718        }
12719    }
12720
12721    /**
12722     * {@hide}
12723     *
12724     * @return true if the view belongs to the root namespace, false otherwise
12725     */
12726    public boolean isRootNamespace() {
12727        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12728    }
12729
12730    /**
12731     * Returns this view's identifier.
12732     *
12733     * @return a positive integer used to identify the view or {@link #NO_ID}
12734     *         if the view has no ID
12735     *
12736     * @see #setId(int)
12737     * @see #findViewById(int)
12738     * @attr ref android.R.styleable#View_id
12739     */
12740    @ViewDebug.CapturedViewProperty
12741    public int getId() {
12742        return mID;
12743    }
12744
12745    /**
12746     * Returns this view's tag.
12747     *
12748     * @return the Object stored in this view as a tag
12749     *
12750     * @see #setTag(Object)
12751     * @see #getTag(int)
12752     */
12753    @ViewDebug.ExportedProperty
12754    public Object getTag() {
12755        return mTag;
12756    }
12757
12758    /**
12759     * Sets the tag associated with this view. A tag can be used to mark
12760     * a view in its hierarchy and does not have to be unique within the
12761     * hierarchy. Tags can also be used to store data within a view without
12762     * resorting to another data structure.
12763     *
12764     * @param tag an Object to tag the view with
12765     *
12766     * @see #getTag()
12767     * @see #setTag(int, Object)
12768     */
12769    public void setTag(final Object tag) {
12770        mTag = tag;
12771    }
12772
12773    /**
12774     * Returns the tag associated with this view and the specified key.
12775     *
12776     * @param key The key identifying the tag
12777     *
12778     * @return the Object stored in this view as a tag
12779     *
12780     * @see #setTag(int, Object)
12781     * @see #getTag()
12782     */
12783    public Object getTag(int key) {
12784        if (mKeyedTags != null) return mKeyedTags.get(key);
12785        return null;
12786    }
12787
12788    /**
12789     * Sets a tag associated with this view and a key. A tag can be used
12790     * to mark a view in its hierarchy and does not have to be unique within
12791     * the hierarchy. Tags can also be used to store data within a view
12792     * without resorting to another data structure.
12793     *
12794     * The specified key should be an id declared in the resources of the
12795     * application to ensure it is unique (see the <a
12796     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12797     * Keys identified as belonging to
12798     * the Android framework or not associated with any package will cause
12799     * an {@link IllegalArgumentException} to be thrown.
12800     *
12801     * @param key The key identifying the tag
12802     * @param tag An Object to tag the view with
12803     *
12804     * @throws IllegalArgumentException If they specified key is not valid
12805     *
12806     * @see #setTag(Object)
12807     * @see #getTag(int)
12808     */
12809    public void setTag(int key, final Object tag) {
12810        // If the package id is 0x00 or 0x01, it's either an undefined package
12811        // or a framework id
12812        if ((key >>> 24) < 2) {
12813            throw new IllegalArgumentException("The key must be an application-specific "
12814                    + "resource id.");
12815        }
12816
12817        setKeyedTag(key, tag);
12818    }
12819
12820    /**
12821     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12822     * framework id.
12823     *
12824     * @hide
12825     */
12826    public void setTagInternal(int key, Object tag) {
12827        if ((key >>> 24) != 0x1) {
12828            throw new IllegalArgumentException("The key must be a framework-specific "
12829                    + "resource id.");
12830        }
12831
12832        setKeyedTag(key, tag);
12833    }
12834
12835    private void setKeyedTag(int key, Object tag) {
12836        if (mKeyedTags == null) {
12837            mKeyedTags = new SparseArray<Object>();
12838        }
12839
12840        mKeyedTags.put(key, tag);
12841    }
12842
12843    /**
12844     * @param consistency The type of consistency. See ViewDebug for more information.
12845     *
12846     * @hide
12847     */
12848    protected boolean dispatchConsistencyCheck(int consistency) {
12849        return onConsistencyCheck(consistency);
12850    }
12851
12852    /**
12853     * Method that subclasses should implement to check their consistency. The type of
12854     * consistency check is indicated by the bit field passed as a parameter.
12855     *
12856     * @param consistency The type of consistency. See ViewDebug for more information.
12857     *
12858     * @throws IllegalStateException if the view is in an inconsistent state.
12859     *
12860     * @hide
12861     */
12862    protected boolean onConsistencyCheck(int consistency) {
12863        boolean result = true;
12864
12865        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12866        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12867
12868        if (checkLayout) {
12869            if (getParent() == null) {
12870                result = false;
12871                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12872                        "View " + this + " does not have a parent.");
12873            }
12874
12875            if (mAttachInfo == null) {
12876                result = false;
12877                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12878                        "View " + this + " is not attached to a window.");
12879            }
12880        }
12881
12882        if (checkDrawing) {
12883            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12884            // from their draw() method
12885
12886            if ((mPrivateFlags & DRAWN) != DRAWN &&
12887                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12888                result = false;
12889                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12890                        "View " + this + " was invalidated but its drawing cache is valid.");
12891            }
12892        }
12893
12894        return result;
12895    }
12896
12897    /**
12898     * Prints information about this view in the log output, with the tag
12899     * {@link #VIEW_LOG_TAG}.
12900     *
12901     * @hide
12902     */
12903    public void debug() {
12904        debug(0);
12905    }
12906
12907    /**
12908     * Prints information about this view in the log output, with the tag
12909     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12910     * indentation defined by the <code>depth</code>.
12911     *
12912     * @param depth the indentation level
12913     *
12914     * @hide
12915     */
12916    protected void debug(int depth) {
12917        String output = debugIndent(depth - 1);
12918
12919        output += "+ " + this;
12920        int id = getId();
12921        if (id != -1) {
12922            output += " (id=" + id + ")";
12923        }
12924        Object tag = getTag();
12925        if (tag != null) {
12926            output += " (tag=" + tag + ")";
12927        }
12928        Log.d(VIEW_LOG_TAG, output);
12929
12930        if ((mPrivateFlags & FOCUSED) != 0) {
12931            output = debugIndent(depth) + " FOCUSED";
12932            Log.d(VIEW_LOG_TAG, output);
12933        }
12934
12935        output = debugIndent(depth);
12936        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12937                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12938                + "} ";
12939        Log.d(VIEW_LOG_TAG, output);
12940
12941        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12942                || mPaddingBottom != 0) {
12943            output = debugIndent(depth);
12944            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12945                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12946            Log.d(VIEW_LOG_TAG, output);
12947        }
12948
12949        output = debugIndent(depth);
12950        output += "mMeasureWidth=" + mMeasuredWidth +
12951                " mMeasureHeight=" + mMeasuredHeight;
12952        Log.d(VIEW_LOG_TAG, output);
12953
12954        output = debugIndent(depth);
12955        if (mLayoutParams == null) {
12956            output += "BAD! no layout params";
12957        } else {
12958            output = mLayoutParams.debug(output);
12959        }
12960        Log.d(VIEW_LOG_TAG, output);
12961
12962        output = debugIndent(depth);
12963        output += "flags={";
12964        output += View.printFlags(mViewFlags);
12965        output += "}";
12966        Log.d(VIEW_LOG_TAG, output);
12967
12968        output = debugIndent(depth);
12969        output += "privateFlags={";
12970        output += View.printPrivateFlags(mPrivateFlags);
12971        output += "}";
12972        Log.d(VIEW_LOG_TAG, output);
12973    }
12974
12975    /**
12976     * Creates an string of whitespaces used for indentation.
12977     *
12978     * @param depth the indentation level
12979     * @return a String containing (depth * 2 + 3) * 2 white spaces
12980     *
12981     * @hide
12982     */
12983    protected static String debugIndent(int depth) {
12984        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12985        for (int i = 0; i < (depth * 2) + 3; i++) {
12986            spaces.append(' ').append(' ');
12987        }
12988        return spaces.toString();
12989    }
12990
12991    /**
12992     * <p>Return the offset of the widget's text baseline from the widget's top
12993     * boundary. If this widget does not support baseline alignment, this
12994     * method returns -1. </p>
12995     *
12996     * @return the offset of the baseline within the widget's bounds or -1
12997     *         if baseline alignment is not supported
12998     */
12999    @ViewDebug.ExportedProperty(category = "layout")
13000    public int getBaseline() {
13001        return -1;
13002    }
13003
13004    /**
13005     * Call this when something has changed which has invalidated the
13006     * layout of this view. This will schedule a layout pass of the view
13007     * tree.
13008     */
13009    public void requestLayout() {
13010        if (ViewDebug.TRACE_HIERARCHY) {
13011            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13012        }
13013
13014        if (getAccessibilityNodeProvider() != null) {
13015            throw new IllegalStateException("Views with AccessibilityNodeProvider"
13016                    + " can't have children.");
13017        }
13018
13019        mPrivateFlags |= FORCE_LAYOUT;
13020        mPrivateFlags |= INVALIDATED;
13021
13022        if (mParent != null) {
13023            if (mLayoutParams != null) {
13024                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
13025            }
13026            if (!mParent.isLayoutRequested()) {
13027                mParent.requestLayout();
13028            }
13029        }
13030    }
13031
13032    /**
13033     * Forces this view to be laid out during the next layout pass.
13034     * This method does not call requestLayout() or forceLayout()
13035     * on the parent.
13036     */
13037    public void forceLayout() {
13038        mPrivateFlags |= FORCE_LAYOUT;
13039        mPrivateFlags |= INVALIDATED;
13040    }
13041
13042    /**
13043     * <p>
13044     * This is called to find out how big a view should be. The parent
13045     * supplies constraint information in the width and height parameters.
13046     * </p>
13047     *
13048     * <p>
13049     * The actual measurement work of a view is performed in
13050     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13051     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13052     * </p>
13053     *
13054     *
13055     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13056     *        parent
13057     * @param heightMeasureSpec Vertical space requirements as imposed by the
13058     *        parent
13059     *
13060     * @see #onMeasure(int, int)
13061     */
13062    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13063        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13064                widthMeasureSpec != mOldWidthMeasureSpec ||
13065                heightMeasureSpec != mOldHeightMeasureSpec) {
13066
13067            // first clears the measured dimension flag
13068            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13069
13070            if (ViewDebug.TRACE_HIERARCHY) {
13071                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13072            }
13073
13074            // measure ourselves, this should set the measured dimension flag back
13075            onMeasure(widthMeasureSpec, heightMeasureSpec);
13076
13077            // flag not set, setMeasuredDimension() was not invoked, we raise
13078            // an exception to warn the developer
13079            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13080                throw new IllegalStateException("onMeasure() did not set the"
13081                        + " measured dimension by calling"
13082                        + " setMeasuredDimension()");
13083            }
13084
13085            mPrivateFlags |= LAYOUT_REQUIRED;
13086        }
13087
13088        mOldWidthMeasureSpec = widthMeasureSpec;
13089        mOldHeightMeasureSpec = heightMeasureSpec;
13090    }
13091
13092    /**
13093     * <p>
13094     * Measure the view and its content to determine the measured width and the
13095     * measured height. This method is invoked by {@link #measure(int, int)} and
13096     * should be overriden by subclasses to provide accurate and efficient
13097     * measurement of their contents.
13098     * </p>
13099     *
13100     * <p>
13101     * <strong>CONTRACT:</strong> When overriding this method, you
13102     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13103     * measured width and height of this view. Failure to do so will trigger an
13104     * <code>IllegalStateException</code>, thrown by
13105     * {@link #measure(int, int)}. Calling the superclass'
13106     * {@link #onMeasure(int, int)} is a valid use.
13107     * </p>
13108     *
13109     * <p>
13110     * The base class implementation of measure defaults to the background size,
13111     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13112     * override {@link #onMeasure(int, int)} to provide better measurements of
13113     * their content.
13114     * </p>
13115     *
13116     * <p>
13117     * If this method is overridden, it is the subclass's responsibility to make
13118     * sure the measured height and width are at least the view's minimum height
13119     * and width ({@link #getSuggestedMinimumHeight()} and
13120     * {@link #getSuggestedMinimumWidth()}).
13121     * </p>
13122     *
13123     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13124     *                         The requirements are encoded with
13125     *                         {@link android.view.View.MeasureSpec}.
13126     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13127     *                         The requirements are encoded with
13128     *                         {@link android.view.View.MeasureSpec}.
13129     *
13130     * @see #getMeasuredWidth()
13131     * @see #getMeasuredHeight()
13132     * @see #setMeasuredDimension(int, int)
13133     * @see #getSuggestedMinimumHeight()
13134     * @see #getSuggestedMinimumWidth()
13135     * @see android.view.View.MeasureSpec#getMode(int)
13136     * @see android.view.View.MeasureSpec#getSize(int)
13137     */
13138    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13139        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13140                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13141    }
13142
13143    /**
13144     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13145     * measured width and measured height. Failing to do so will trigger an
13146     * exception at measurement time.</p>
13147     *
13148     * @param measuredWidth The measured width of this view.  May be a complex
13149     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13150     * {@link #MEASURED_STATE_TOO_SMALL}.
13151     * @param measuredHeight The measured height of this view.  May be a complex
13152     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13153     * {@link #MEASURED_STATE_TOO_SMALL}.
13154     */
13155    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13156        mMeasuredWidth = measuredWidth;
13157        mMeasuredHeight = measuredHeight;
13158
13159        mPrivateFlags |= MEASURED_DIMENSION_SET;
13160    }
13161
13162    /**
13163     * Merge two states as returned by {@link #getMeasuredState()}.
13164     * @param curState The current state as returned from a view or the result
13165     * of combining multiple views.
13166     * @param newState The new view state to combine.
13167     * @return Returns a new integer reflecting the combination of the two
13168     * states.
13169     */
13170    public static int combineMeasuredStates(int curState, int newState) {
13171        return curState | newState;
13172    }
13173
13174    /**
13175     * Version of {@link #resolveSizeAndState(int, int, int)}
13176     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13177     */
13178    public static int resolveSize(int size, int measureSpec) {
13179        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13180    }
13181
13182    /**
13183     * Utility to reconcile a desired size and state, with constraints imposed
13184     * by a MeasureSpec.  Will take the desired size, unless a different size
13185     * is imposed by the constraints.  The returned value is a compound integer,
13186     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13187     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13188     * size is smaller than the size the view wants to be.
13189     *
13190     * @param size How big the view wants to be
13191     * @param measureSpec Constraints imposed by the parent
13192     * @return Size information bit mask as defined by
13193     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13194     */
13195    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13196        int result = size;
13197        int specMode = MeasureSpec.getMode(measureSpec);
13198        int specSize =  MeasureSpec.getSize(measureSpec);
13199        switch (specMode) {
13200        case MeasureSpec.UNSPECIFIED:
13201            result = size;
13202            break;
13203        case MeasureSpec.AT_MOST:
13204            if (specSize < size) {
13205                result = specSize | MEASURED_STATE_TOO_SMALL;
13206            } else {
13207                result = size;
13208            }
13209            break;
13210        case MeasureSpec.EXACTLY:
13211            result = specSize;
13212            break;
13213        }
13214        return result | (childMeasuredState&MEASURED_STATE_MASK);
13215    }
13216
13217    /**
13218     * Utility to return a default size. Uses the supplied size if the
13219     * MeasureSpec imposed no constraints. Will get larger if allowed
13220     * by the MeasureSpec.
13221     *
13222     * @param size Default size for this view
13223     * @param measureSpec Constraints imposed by the parent
13224     * @return The size this view should be.
13225     */
13226    public static int getDefaultSize(int size, int measureSpec) {
13227        int result = size;
13228        int specMode = MeasureSpec.getMode(measureSpec);
13229        int specSize = MeasureSpec.getSize(measureSpec);
13230
13231        switch (specMode) {
13232        case MeasureSpec.UNSPECIFIED:
13233            result = size;
13234            break;
13235        case MeasureSpec.AT_MOST:
13236        case MeasureSpec.EXACTLY:
13237            result = specSize;
13238            break;
13239        }
13240        return result;
13241    }
13242
13243    /**
13244     * Returns the suggested minimum height that the view should use. This
13245     * returns the maximum of the view's minimum height
13246     * and the background's minimum height
13247     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13248     * <p>
13249     * When being used in {@link #onMeasure(int, int)}, the caller should still
13250     * ensure the returned height is within the requirements of the parent.
13251     *
13252     * @return The suggested minimum height of the view.
13253     */
13254    protected int getSuggestedMinimumHeight() {
13255        int suggestedMinHeight = mMinHeight;
13256
13257        if (mBGDrawable != null) {
13258            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13259            if (suggestedMinHeight < bgMinHeight) {
13260                suggestedMinHeight = bgMinHeight;
13261            }
13262        }
13263
13264        return suggestedMinHeight;
13265    }
13266
13267    /**
13268     * Returns the suggested minimum width that the view should use. This
13269     * returns the maximum of the view's minimum width)
13270     * and the background's minimum width
13271     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13272     * <p>
13273     * When being used in {@link #onMeasure(int, int)}, the caller should still
13274     * ensure the returned width is within the requirements of the parent.
13275     *
13276     * @return The suggested minimum width of the view.
13277     */
13278    protected int getSuggestedMinimumWidth() {
13279        int suggestedMinWidth = mMinWidth;
13280
13281        if (mBGDrawable != null) {
13282            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13283            if (suggestedMinWidth < bgMinWidth) {
13284                suggestedMinWidth = bgMinWidth;
13285            }
13286        }
13287
13288        return suggestedMinWidth;
13289    }
13290
13291    /**
13292     * Sets the minimum height of the view. It is not guaranteed the view will
13293     * be able to achieve this minimum height (for example, if its parent layout
13294     * constrains it with less available height).
13295     *
13296     * @param minHeight The minimum height the view will try to be.
13297     */
13298    public void setMinimumHeight(int minHeight) {
13299        mMinHeight = minHeight;
13300    }
13301
13302    /**
13303     * Sets the minimum width of the view. It is not guaranteed the view will
13304     * be able to achieve this minimum width (for example, if its parent layout
13305     * constrains it with less available width).
13306     *
13307     * @param minWidth The minimum width the view will try to be.
13308     */
13309    public void setMinimumWidth(int minWidth) {
13310        mMinWidth = minWidth;
13311    }
13312
13313    /**
13314     * Get the animation currently associated with this view.
13315     *
13316     * @return The animation that is currently playing or
13317     *         scheduled to play for this view.
13318     */
13319    public Animation getAnimation() {
13320        return mCurrentAnimation;
13321    }
13322
13323    /**
13324     * Start the specified animation now.
13325     *
13326     * @param animation the animation to start now
13327     */
13328    public void startAnimation(Animation animation) {
13329        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13330        setAnimation(animation);
13331        invalidateParentCaches();
13332        invalidate(true);
13333    }
13334
13335    /**
13336     * Cancels any animations for this view.
13337     */
13338    public void clearAnimation() {
13339        if (mCurrentAnimation != null) {
13340            mCurrentAnimation.detach();
13341        }
13342        mCurrentAnimation = null;
13343        invalidateParentIfNeeded();
13344    }
13345
13346    /**
13347     * Sets the next animation to play for this view.
13348     * If you want the animation to play immediately, use
13349     * startAnimation. This method provides allows fine-grained
13350     * control over the start time and invalidation, but you
13351     * must make sure that 1) the animation has a start time set, and
13352     * 2) the view will be invalidated when the animation is supposed to
13353     * start.
13354     *
13355     * @param animation The next animation, or null.
13356     */
13357    public void setAnimation(Animation animation) {
13358        mCurrentAnimation = animation;
13359        if (animation != null) {
13360            animation.reset();
13361        }
13362    }
13363
13364    /**
13365     * Invoked by a parent ViewGroup to notify the start of the animation
13366     * currently associated with this view. If you override this method,
13367     * always call super.onAnimationStart();
13368     *
13369     * @see #setAnimation(android.view.animation.Animation)
13370     * @see #getAnimation()
13371     */
13372    protected void onAnimationStart() {
13373        mPrivateFlags |= ANIMATION_STARTED;
13374    }
13375
13376    /**
13377     * Invoked by a parent ViewGroup to notify the end of the animation
13378     * currently associated with this view. If you override this method,
13379     * always call super.onAnimationEnd();
13380     *
13381     * @see #setAnimation(android.view.animation.Animation)
13382     * @see #getAnimation()
13383     */
13384    protected void onAnimationEnd() {
13385        mPrivateFlags &= ~ANIMATION_STARTED;
13386    }
13387
13388    /**
13389     * Invoked if there is a Transform that involves alpha. Subclass that can
13390     * draw themselves with the specified alpha should return true, and then
13391     * respect that alpha when their onDraw() is called. If this returns false
13392     * then the view may be redirected to draw into an offscreen buffer to
13393     * fulfill the request, which will look fine, but may be slower than if the
13394     * subclass handles it internally. The default implementation returns false.
13395     *
13396     * @param alpha The alpha (0..255) to apply to the view's drawing
13397     * @return true if the view can draw with the specified alpha.
13398     */
13399    protected boolean onSetAlpha(int alpha) {
13400        return false;
13401    }
13402
13403    /**
13404     * This is used by the RootView to perform an optimization when
13405     * the view hierarchy contains one or several SurfaceView.
13406     * SurfaceView is always considered transparent, but its children are not,
13407     * therefore all View objects remove themselves from the global transparent
13408     * region (passed as a parameter to this function).
13409     *
13410     * @param region The transparent region for this ViewAncestor (window).
13411     *
13412     * @return Returns true if the effective visibility of the view at this
13413     * point is opaque, regardless of the transparent region; returns false
13414     * if it is possible for underlying windows to be seen behind the view.
13415     *
13416     * {@hide}
13417     */
13418    public boolean gatherTransparentRegion(Region region) {
13419        final AttachInfo attachInfo = mAttachInfo;
13420        if (region != null && attachInfo != null) {
13421            final int pflags = mPrivateFlags;
13422            if ((pflags & SKIP_DRAW) == 0) {
13423                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13424                // remove it from the transparent region.
13425                final int[] location = attachInfo.mTransparentLocation;
13426                getLocationInWindow(location);
13427                region.op(location[0], location[1], location[0] + mRight - mLeft,
13428                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13429            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13430                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13431                // exists, so we remove the background drawable's non-transparent
13432                // parts from this transparent region.
13433                applyDrawableToTransparentRegion(mBGDrawable, region);
13434            }
13435        }
13436        return true;
13437    }
13438
13439    /**
13440     * Play a sound effect for this view.
13441     *
13442     * <p>The framework will play sound effects for some built in actions, such as
13443     * clicking, but you may wish to play these effects in your widget,
13444     * for instance, for internal navigation.
13445     *
13446     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13447     * {@link #isSoundEffectsEnabled()} is true.
13448     *
13449     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13450     */
13451    public void playSoundEffect(int soundConstant) {
13452        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13453            return;
13454        }
13455        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13456    }
13457
13458    /**
13459     * BZZZTT!!1!
13460     *
13461     * <p>Provide haptic feedback to the user for this view.
13462     *
13463     * <p>The framework will provide haptic feedback for some built in actions,
13464     * such as long presses, but you may wish to provide feedback for your
13465     * own widget.
13466     *
13467     * <p>The feedback will only be performed if
13468     * {@link #isHapticFeedbackEnabled()} is true.
13469     *
13470     * @param feedbackConstant One of the constants defined in
13471     * {@link HapticFeedbackConstants}
13472     */
13473    public boolean performHapticFeedback(int feedbackConstant) {
13474        return performHapticFeedback(feedbackConstant, 0);
13475    }
13476
13477    /**
13478     * BZZZTT!!1!
13479     *
13480     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13481     *
13482     * @param feedbackConstant One of the constants defined in
13483     * {@link HapticFeedbackConstants}
13484     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13485     */
13486    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13487        if (mAttachInfo == null) {
13488            return false;
13489        }
13490        //noinspection SimplifiableIfStatement
13491        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13492                && !isHapticFeedbackEnabled()) {
13493            return false;
13494        }
13495        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13496                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13497    }
13498
13499    /**
13500     * Request that the visibility of the status bar be changed.
13501     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13502     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13503     */
13504    public void setSystemUiVisibility(int visibility) {
13505        if (visibility != mSystemUiVisibility) {
13506            mSystemUiVisibility = visibility;
13507            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13508                mParent.recomputeViewAttributes(this);
13509            }
13510        }
13511    }
13512
13513    /**
13514     * Returns the status bar visibility that this view has requested.
13515     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13516     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13517     */
13518    public int getSystemUiVisibility() {
13519        return mSystemUiVisibility;
13520    }
13521
13522    /**
13523     * Set a listener to receive callbacks when the visibility of the system bar changes.
13524     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13525     */
13526    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13527        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13528        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13529            mParent.recomputeViewAttributes(this);
13530        }
13531    }
13532
13533    /**
13534     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13535     * the view hierarchy.
13536     */
13537    public void dispatchSystemUiVisibilityChanged(int visibility) {
13538        ListenerInfo li = mListenerInfo;
13539        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13540            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13541                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13542        }
13543    }
13544
13545    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13546        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13547        if (val != mSystemUiVisibility) {
13548            setSystemUiVisibility(val);
13549        }
13550    }
13551
13552    /**
13553     * Creates an image that the system displays during the drag and drop
13554     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13555     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13556     * appearance as the given View. The default also positions the center of the drag shadow
13557     * directly under the touch point. If no View is provided (the constructor with no parameters
13558     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13559     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13560     * default is an invisible drag shadow.
13561     * <p>
13562     * You are not required to use the View you provide to the constructor as the basis of the
13563     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13564     * anything you want as the drag shadow.
13565     * </p>
13566     * <p>
13567     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13568     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13569     *  size and position of the drag shadow. It uses this data to construct a
13570     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13571     *  so that your application can draw the shadow image in the Canvas.
13572     * </p>
13573     *
13574     * <div class="special reference">
13575     * <h3>Developer Guides</h3>
13576     * <p>For a guide to implementing drag and drop features, read the
13577     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13578     * </div>
13579     */
13580    public static class DragShadowBuilder {
13581        private final WeakReference<View> mView;
13582
13583        /**
13584         * Constructs a shadow image builder based on a View. By default, the resulting drag
13585         * shadow will have the same appearance and dimensions as the View, with the touch point
13586         * over the center of the View.
13587         * @param view A View. Any View in scope can be used.
13588         */
13589        public DragShadowBuilder(View view) {
13590            mView = new WeakReference<View>(view);
13591        }
13592
13593        /**
13594         * Construct a shadow builder object with no associated View.  This
13595         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13596         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13597         * to supply the drag shadow's dimensions and appearance without
13598         * reference to any View object. If they are not overridden, then the result is an
13599         * invisible drag shadow.
13600         */
13601        public DragShadowBuilder() {
13602            mView = new WeakReference<View>(null);
13603        }
13604
13605        /**
13606         * Returns the View object that had been passed to the
13607         * {@link #View.DragShadowBuilder(View)}
13608         * constructor.  If that View parameter was {@code null} or if the
13609         * {@link #View.DragShadowBuilder()}
13610         * constructor was used to instantiate the builder object, this method will return
13611         * null.
13612         *
13613         * @return The View object associate with this builder object.
13614         */
13615        @SuppressWarnings({"JavadocReference"})
13616        final public View getView() {
13617            return mView.get();
13618        }
13619
13620        /**
13621         * Provides the metrics for the shadow image. These include the dimensions of
13622         * the shadow image, and the point within that shadow that should
13623         * be centered under the touch location while dragging.
13624         * <p>
13625         * The default implementation sets the dimensions of the shadow to be the
13626         * same as the dimensions of the View itself and centers the shadow under
13627         * the touch point.
13628         * </p>
13629         *
13630         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13631         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13632         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13633         * image.
13634         *
13635         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13636         * shadow image that should be underneath the touch point during the drag and drop
13637         * operation. Your application must set {@link android.graphics.Point#x} to the
13638         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13639         */
13640        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13641            final View view = mView.get();
13642            if (view != null) {
13643                shadowSize.set(view.getWidth(), view.getHeight());
13644                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13645            } else {
13646                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13647            }
13648        }
13649
13650        /**
13651         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13652         * based on the dimensions it received from the
13653         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13654         *
13655         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13656         */
13657        public void onDrawShadow(Canvas canvas) {
13658            final View view = mView.get();
13659            if (view != null) {
13660                view.draw(canvas);
13661            } else {
13662                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13663            }
13664        }
13665    }
13666
13667    /**
13668     * Starts a drag and drop operation. When your application calls this method, it passes a
13669     * {@link android.view.View.DragShadowBuilder} object to the system. The
13670     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13671     * to get metrics for the drag shadow, and then calls the object's
13672     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13673     * <p>
13674     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13675     *  drag events to all the View objects in your application that are currently visible. It does
13676     *  this either by calling the View object's drag listener (an implementation of
13677     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13678     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13679     *  Both are passed a {@link android.view.DragEvent} object that has a
13680     *  {@link android.view.DragEvent#getAction()} value of
13681     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13682     * </p>
13683     * <p>
13684     * Your application can invoke startDrag() on any attached View object. The View object does not
13685     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13686     * be related to the View the user selected for dragging.
13687     * </p>
13688     * @param data A {@link android.content.ClipData} object pointing to the data to be
13689     * transferred by the drag and drop operation.
13690     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13691     * drag shadow.
13692     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13693     * drop operation. This Object is put into every DragEvent object sent by the system during the
13694     * current drag.
13695     * <p>
13696     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13697     * to the target Views. For example, it can contain flags that differentiate between a
13698     * a copy operation and a move operation.
13699     * </p>
13700     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13701     * so the parameter should be set to 0.
13702     * @return {@code true} if the method completes successfully, or
13703     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13704     * do a drag, and so no drag operation is in progress.
13705     */
13706    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13707            Object myLocalState, int flags) {
13708        if (ViewDebug.DEBUG_DRAG) {
13709            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13710        }
13711        boolean okay = false;
13712
13713        Point shadowSize = new Point();
13714        Point shadowTouchPoint = new Point();
13715        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13716
13717        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13718                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13719            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13720        }
13721
13722        if (ViewDebug.DEBUG_DRAG) {
13723            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13724                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13725        }
13726        Surface surface = new Surface();
13727        try {
13728            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13729                    flags, shadowSize.x, shadowSize.y, surface);
13730            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13731                    + " surface=" + surface);
13732            if (token != null) {
13733                Canvas canvas = surface.lockCanvas(null);
13734                try {
13735                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13736                    shadowBuilder.onDrawShadow(canvas);
13737                } finally {
13738                    surface.unlockCanvasAndPost(canvas);
13739                }
13740
13741                final ViewRootImpl root = getViewRootImpl();
13742
13743                // Cache the local state object for delivery with DragEvents
13744                root.setLocalDragState(myLocalState);
13745
13746                // repurpose 'shadowSize' for the last touch point
13747                root.getLastTouchPoint(shadowSize);
13748
13749                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13750                        shadowSize.x, shadowSize.y,
13751                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13752                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13753
13754                // Off and running!  Release our local surface instance; the drag
13755                // shadow surface is now managed by the system process.
13756                surface.release();
13757            }
13758        } catch (Exception e) {
13759            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13760            surface.destroy();
13761        }
13762
13763        return okay;
13764    }
13765
13766    /**
13767     * Handles drag events sent by the system following a call to
13768     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13769     *<p>
13770     * When the system calls this method, it passes a
13771     * {@link android.view.DragEvent} object. A call to
13772     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13773     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13774     * operation.
13775     * @param event The {@link android.view.DragEvent} sent by the system.
13776     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13777     * in DragEvent, indicating the type of drag event represented by this object.
13778     * @return {@code true} if the method was successful, otherwise {@code false}.
13779     * <p>
13780     *  The method should return {@code true} in response to an action type of
13781     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13782     *  operation.
13783     * </p>
13784     * <p>
13785     *  The method should also return {@code true} in response to an action type of
13786     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13787     *  {@code false} if it didn't.
13788     * </p>
13789     */
13790    public boolean onDragEvent(DragEvent event) {
13791        return false;
13792    }
13793
13794    /**
13795     * Detects if this View is enabled and has a drag event listener.
13796     * If both are true, then it calls the drag event listener with the
13797     * {@link android.view.DragEvent} it received. If the drag event listener returns
13798     * {@code true}, then dispatchDragEvent() returns {@code true}.
13799     * <p>
13800     * For all other cases, the method calls the
13801     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13802     * method and returns its result.
13803     * </p>
13804     * <p>
13805     * This ensures that a drag event is always consumed, even if the View does not have a drag
13806     * event listener. However, if the View has a listener and the listener returns true, then
13807     * onDragEvent() is not called.
13808     * </p>
13809     */
13810    public boolean dispatchDragEvent(DragEvent event) {
13811        //noinspection SimplifiableIfStatement
13812        ListenerInfo li = mListenerInfo;
13813        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13814                && li.mOnDragListener.onDrag(this, event)) {
13815            return true;
13816        }
13817        return onDragEvent(event);
13818    }
13819
13820    boolean canAcceptDrag() {
13821        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13822    }
13823
13824    /**
13825     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13826     * it is ever exposed at all.
13827     * @hide
13828     */
13829    public void onCloseSystemDialogs(String reason) {
13830    }
13831
13832    /**
13833     * Given a Drawable whose bounds have been set to draw into this view,
13834     * update a Region being computed for
13835     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13836     * that any non-transparent parts of the Drawable are removed from the
13837     * given transparent region.
13838     *
13839     * @param dr The Drawable whose transparency is to be applied to the region.
13840     * @param region A Region holding the current transparency information,
13841     * where any parts of the region that are set are considered to be
13842     * transparent.  On return, this region will be modified to have the
13843     * transparency information reduced by the corresponding parts of the
13844     * Drawable that are not transparent.
13845     * {@hide}
13846     */
13847    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13848        if (DBG) {
13849            Log.i("View", "Getting transparent region for: " + this);
13850        }
13851        final Region r = dr.getTransparentRegion();
13852        final Rect db = dr.getBounds();
13853        final AttachInfo attachInfo = mAttachInfo;
13854        if (r != null && attachInfo != null) {
13855            final int w = getRight()-getLeft();
13856            final int h = getBottom()-getTop();
13857            if (db.left > 0) {
13858                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13859                r.op(0, 0, db.left, h, Region.Op.UNION);
13860            }
13861            if (db.right < w) {
13862                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13863                r.op(db.right, 0, w, h, Region.Op.UNION);
13864            }
13865            if (db.top > 0) {
13866                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13867                r.op(0, 0, w, db.top, Region.Op.UNION);
13868            }
13869            if (db.bottom < h) {
13870                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13871                r.op(0, db.bottom, w, h, Region.Op.UNION);
13872            }
13873            final int[] location = attachInfo.mTransparentLocation;
13874            getLocationInWindow(location);
13875            r.translate(location[0], location[1]);
13876            region.op(r, Region.Op.INTERSECT);
13877        } else {
13878            region.op(db, Region.Op.DIFFERENCE);
13879        }
13880    }
13881
13882    private void checkForLongClick(int delayOffset) {
13883        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13884            mHasPerformedLongPress = false;
13885
13886            if (mPendingCheckForLongPress == null) {
13887                mPendingCheckForLongPress = new CheckForLongPress();
13888            }
13889            mPendingCheckForLongPress.rememberWindowAttachCount();
13890            postDelayed(mPendingCheckForLongPress,
13891                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13892        }
13893    }
13894
13895    /**
13896     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13897     * LayoutInflater} class, which provides a full range of options for view inflation.
13898     *
13899     * @param context The Context object for your activity or application.
13900     * @param resource The resource ID to inflate
13901     * @param root A view group that will be the parent.  Used to properly inflate the
13902     * layout_* parameters.
13903     * @see LayoutInflater
13904     */
13905    public static View inflate(Context context, int resource, ViewGroup root) {
13906        LayoutInflater factory = LayoutInflater.from(context);
13907        return factory.inflate(resource, root);
13908    }
13909
13910    /**
13911     * Scroll the view with standard behavior for scrolling beyond the normal
13912     * content boundaries. Views that call this method should override
13913     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13914     * results of an over-scroll operation.
13915     *
13916     * Views can use this method to handle any touch or fling-based scrolling.
13917     *
13918     * @param deltaX Change in X in pixels
13919     * @param deltaY Change in Y in pixels
13920     * @param scrollX Current X scroll value in pixels before applying deltaX
13921     * @param scrollY Current Y scroll value in pixels before applying deltaY
13922     * @param scrollRangeX Maximum content scroll range along the X axis
13923     * @param scrollRangeY Maximum content scroll range along the Y axis
13924     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13925     *          along the X axis.
13926     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13927     *          along the Y axis.
13928     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13929     * @return true if scrolling was clamped to an over-scroll boundary along either
13930     *          axis, false otherwise.
13931     */
13932    @SuppressWarnings({"UnusedParameters"})
13933    protected boolean overScrollBy(int deltaX, int deltaY,
13934            int scrollX, int scrollY,
13935            int scrollRangeX, int scrollRangeY,
13936            int maxOverScrollX, int maxOverScrollY,
13937            boolean isTouchEvent) {
13938        final int overScrollMode = mOverScrollMode;
13939        final boolean canScrollHorizontal =
13940                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13941        final boolean canScrollVertical =
13942                computeVerticalScrollRange() > computeVerticalScrollExtent();
13943        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13944                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13945        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13946                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13947
13948        int newScrollX = scrollX + deltaX;
13949        if (!overScrollHorizontal) {
13950            maxOverScrollX = 0;
13951        }
13952
13953        int newScrollY = scrollY + deltaY;
13954        if (!overScrollVertical) {
13955            maxOverScrollY = 0;
13956        }
13957
13958        // Clamp values if at the limits and record
13959        final int left = -maxOverScrollX;
13960        final int right = maxOverScrollX + scrollRangeX;
13961        final int top = -maxOverScrollY;
13962        final int bottom = maxOverScrollY + scrollRangeY;
13963
13964        boolean clampedX = false;
13965        if (newScrollX > right) {
13966            newScrollX = right;
13967            clampedX = true;
13968        } else if (newScrollX < left) {
13969            newScrollX = left;
13970            clampedX = true;
13971        }
13972
13973        boolean clampedY = false;
13974        if (newScrollY > bottom) {
13975            newScrollY = bottom;
13976            clampedY = true;
13977        } else if (newScrollY < top) {
13978            newScrollY = top;
13979            clampedY = true;
13980        }
13981
13982        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13983
13984        return clampedX || clampedY;
13985    }
13986
13987    /**
13988     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13989     * respond to the results of an over-scroll operation.
13990     *
13991     * @param scrollX New X scroll value in pixels
13992     * @param scrollY New Y scroll value in pixels
13993     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13994     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13995     */
13996    protected void onOverScrolled(int scrollX, int scrollY,
13997            boolean clampedX, boolean clampedY) {
13998        // Intentionally empty.
13999    }
14000
14001    /**
14002     * Returns the over-scroll mode for this view. The result will be
14003     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14004     * (allow over-scrolling only if the view content is larger than the container),
14005     * or {@link #OVER_SCROLL_NEVER}.
14006     *
14007     * @return This view's over-scroll mode.
14008     */
14009    public int getOverScrollMode() {
14010        return mOverScrollMode;
14011    }
14012
14013    /**
14014     * Set the over-scroll mode for this view. Valid over-scroll modes are
14015     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14016     * (allow over-scrolling only if the view content is larger than the container),
14017     * or {@link #OVER_SCROLL_NEVER}.
14018     *
14019     * Setting the over-scroll mode of a view will have an effect only if the
14020     * view is capable of scrolling.
14021     *
14022     * @param overScrollMode The new over-scroll mode for this view.
14023     */
14024    public void setOverScrollMode(int overScrollMode) {
14025        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14026                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14027                overScrollMode != OVER_SCROLL_NEVER) {
14028            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14029        }
14030        mOverScrollMode = overScrollMode;
14031    }
14032
14033    /**
14034     * Gets a scale factor that determines the distance the view should scroll
14035     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14036     * @return The vertical scroll scale factor.
14037     * @hide
14038     */
14039    protected float getVerticalScrollFactor() {
14040        if (mVerticalScrollFactor == 0) {
14041            TypedValue outValue = new TypedValue();
14042            if (!mContext.getTheme().resolveAttribute(
14043                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14044                throw new IllegalStateException(
14045                        "Expected theme to define listPreferredItemHeight.");
14046            }
14047            mVerticalScrollFactor = outValue.getDimension(
14048                    mContext.getResources().getDisplayMetrics());
14049        }
14050        return mVerticalScrollFactor;
14051    }
14052
14053    /**
14054     * Gets a scale factor that determines the distance the view should scroll
14055     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14056     * @return The horizontal scroll scale factor.
14057     * @hide
14058     */
14059    protected float getHorizontalScrollFactor() {
14060        // TODO: Should use something else.
14061        return getVerticalScrollFactor();
14062    }
14063
14064    /**
14065     * Return the value specifying the text direction or policy that was set with
14066     * {@link #setTextDirection(int)}.
14067     *
14068     * @return the defined text direction. It can be one of:
14069     *
14070     * {@link #TEXT_DIRECTION_INHERIT},
14071     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14072     * {@link #TEXT_DIRECTION_ANY_RTL},
14073     * {@link #TEXT_DIRECTION_LTR},
14074     * {@link #TEXT_DIRECTION_RTL},
14075     * {@link #TEXT_DIRECTION_LOCALE},
14076     *
14077     */
14078    public int getTextDirection() {
14079        return mTextDirection;
14080    }
14081
14082    /**
14083     * Set the text direction.
14084     *
14085     * @param textDirection the direction to set. Should be one of:
14086     *
14087     * {@link #TEXT_DIRECTION_INHERIT},
14088     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14089     * {@link #TEXT_DIRECTION_ANY_RTL},
14090     * {@link #TEXT_DIRECTION_LTR},
14091     * {@link #TEXT_DIRECTION_RTL},
14092     * {@link #TEXT_DIRECTION_LOCALE},
14093     *
14094     */
14095    public void setTextDirection(int textDirection) {
14096        if (textDirection != mTextDirection) {
14097            mTextDirection = textDirection;
14098            resetResolvedTextDirection();
14099            requestLayout();
14100        }
14101    }
14102
14103    /**
14104     * Return the resolved text direction.
14105     *
14106     * @return the resolved text direction. Return one of:
14107     *
14108     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14109     * {@link #TEXT_DIRECTION_ANY_RTL},
14110     * {@link #TEXT_DIRECTION_LTR},
14111     * {@link #TEXT_DIRECTION_RTL},
14112     * {@link #TEXT_DIRECTION_LOCALE},
14113     *
14114     */
14115    public int getResolvedTextDirection() {
14116        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
14117            resolveTextDirection();
14118        }
14119        return mResolvedTextDirection;
14120    }
14121
14122    /**
14123     * Resolve the text direction.
14124     *
14125     */
14126    protected void resolveTextDirection() {
14127        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
14128            mResolvedTextDirection = mTextDirection;
14129            return;
14130        }
14131        if (mParent != null && mParent instanceof ViewGroup) {
14132            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
14133            return;
14134        }
14135        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
14136    }
14137
14138    /**
14139     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
14140     *
14141     */
14142    protected void resetResolvedTextDirection() {
14143        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
14144    }
14145
14146    //
14147    // Properties
14148    //
14149    /**
14150     * A Property wrapper around the <code>alpha</code> functionality handled by the
14151     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14152     */
14153    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14154        @Override
14155        public void setValue(View object, float value) {
14156            object.setAlpha(value);
14157        }
14158
14159        @Override
14160        public Float get(View object) {
14161            return object.getAlpha();
14162        }
14163    };
14164
14165    /**
14166     * A Property wrapper around the <code>translationX</code> functionality handled by the
14167     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14168     */
14169    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14170        @Override
14171        public void setValue(View object, float value) {
14172            object.setTranslationX(value);
14173        }
14174
14175                @Override
14176        public Float get(View object) {
14177            return object.getTranslationX();
14178        }
14179    };
14180
14181    /**
14182     * A Property wrapper around the <code>translationY</code> functionality handled by the
14183     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14184     */
14185    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14186        @Override
14187        public void setValue(View object, float value) {
14188            object.setTranslationY(value);
14189        }
14190
14191        @Override
14192        public Float get(View object) {
14193            return object.getTranslationY();
14194        }
14195    };
14196
14197    /**
14198     * A Property wrapper around the <code>x</code> functionality handled by the
14199     * {@link View#setX(float)} and {@link View#getX()} methods.
14200     */
14201    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14202        @Override
14203        public void setValue(View object, float value) {
14204            object.setX(value);
14205        }
14206
14207        @Override
14208        public Float get(View object) {
14209            return object.getX();
14210        }
14211    };
14212
14213    /**
14214     * A Property wrapper around the <code>y</code> functionality handled by the
14215     * {@link View#setY(float)} and {@link View#getY()} methods.
14216     */
14217    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
14218        @Override
14219        public void setValue(View object, float value) {
14220            object.setY(value);
14221        }
14222
14223        @Override
14224        public Float get(View object) {
14225            return object.getY();
14226        }
14227    };
14228
14229    /**
14230     * A Property wrapper around the <code>rotation</code> functionality handled by the
14231     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
14232     */
14233    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
14234        @Override
14235        public void setValue(View object, float value) {
14236            object.setRotation(value);
14237        }
14238
14239        @Override
14240        public Float get(View object) {
14241            return object.getRotation();
14242        }
14243    };
14244
14245    /**
14246     * A Property wrapper around the <code>rotationX</code> functionality handled by the
14247     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
14248     */
14249    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
14250        @Override
14251        public void setValue(View object, float value) {
14252            object.setRotationX(value);
14253        }
14254
14255        @Override
14256        public Float get(View object) {
14257            return object.getRotationX();
14258        }
14259    };
14260
14261    /**
14262     * A Property wrapper around the <code>rotationY</code> functionality handled by the
14263     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
14264     */
14265    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
14266        @Override
14267        public void setValue(View object, float value) {
14268            object.setRotationY(value);
14269        }
14270
14271        @Override
14272        public Float get(View object) {
14273            return object.getRotationY();
14274        }
14275    };
14276
14277    /**
14278     * A Property wrapper around the <code>scaleX</code> functionality handled by the
14279     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
14280     */
14281    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
14282        @Override
14283        public void setValue(View object, float value) {
14284            object.setScaleX(value);
14285        }
14286
14287        @Override
14288        public Float get(View object) {
14289            return object.getScaleX();
14290        }
14291    };
14292
14293    /**
14294     * A Property wrapper around the <code>scaleY</code> functionality handled by the
14295     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
14296     */
14297    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
14298        @Override
14299        public void setValue(View object, float value) {
14300            object.setScaleY(value);
14301        }
14302
14303        @Override
14304        public Float get(View object) {
14305            return object.getScaleY();
14306        }
14307    };
14308
14309    /**
14310     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
14311     * Each MeasureSpec represents a requirement for either the width or the height.
14312     * A MeasureSpec is comprised of a size and a mode. There are three possible
14313     * modes:
14314     * <dl>
14315     * <dt>UNSPECIFIED</dt>
14316     * <dd>
14317     * The parent has not imposed any constraint on the child. It can be whatever size
14318     * it wants.
14319     * </dd>
14320     *
14321     * <dt>EXACTLY</dt>
14322     * <dd>
14323     * The parent has determined an exact size for the child. The child is going to be
14324     * given those bounds regardless of how big it wants to be.
14325     * </dd>
14326     *
14327     * <dt>AT_MOST</dt>
14328     * <dd>
14329     * The child can be as large as it wants up to the specified size.
14330     * </dd>
14331     * </dl>
14332     *
14333     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14334     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14335     */
14336    public static class MeasureSpec {
14337        private static final int MODE_SHIFT = 30;
14338        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14339
14340        /**
14341         * Measure specification mode: The parent has not imposed any constraint
14342         * on the child. It can be whatever size it wants.
14343         */
14344        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14345
14346        /**
14347         * Measure specification mode: The parent has determined an exact size
14348         * for the child. The child is going to be given those bounds regardless
14349         * of how big it wants to be.
14350         */
14351        public static final int EXACTLY     = 1 << MODE_SHIFT;
14352
14353        /**
14354         * Measure specification mode: The child can be as large as it wants up
14355         * to the specified size.
14356         */
14357        public static final int AT_MOST     = 2 << MODE_SHIFT;
14358
14359        /**
14360         * Creates a measure specification based on the supplied size and mode.
14361         *
14362         * The mode must always be one of the following:
14363         * <ul>
14364         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14365         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14366         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14367         * </ul>
14368         *
14369         * @param size the size of the measure specification
14370         * @param mode the mode of the measure specification
14371         * @return the measure specification based on size and mode
14372         */
14373        public static int makeMeasureSpec(int size, int mode) {
14374            return size + mode;
14375        }
14376
14377        /**
14378         * Extracts the mode from the supplied measure specification.
14379         *
14380         * @param measureSpec the measure specification to extract the mode from
14381         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14382         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14383         *         {@link android.view.View.MeasureSpec#EXACTLY}
14384         */
14385        public static int getMode(int measureSpec) {
14386            return (measureSpec & MODE_MASK);
14387        }
14388
14389        /**
14390         * Extracts the size from the supplied measure specification.
14391         *
14392         * @param measureSpec the measure specification to extract the size from
14393         * @return the size in pixels defined in the supplied measure specification
14394         */
14395        public static int getSize(int measureSpec) {
14396            return (measureSpec & ~MODE_MASK);
14397        }
14398
14399        /**
14400         * Returns a String representation of the specified measure
14401         * specification.
14402         *
14403         * @param measureSpec the measure specification to convert to a String
14404         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14405         */
14406        public static String toString(int measureSpec) {
14407            int mode = getMode(measureSpec);
14408            int size = getSize(measureSpec);
14409
14410            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14411
14412            if (mode == UNSPECIFIED)
14413                sb.append("UNSPECIFIED ");
14414            else if (mode == EXACTLY)
14415                sb.append("EXACTLY ");
14416            else if (mode == AT_MOST)
14417                sb.append("AT_MOST ");
14418            else
14419                sb.append(mode).append(" ");
14420
14421            sb.append(size);
14422            return sb.toString();
14423        }
14424    }
14425
14426    class CheckForLongPress implements Runnable {
14427
14428        private int mOriginalWindowAttachCount;
14429
14430        public void run() {
14431            if (isPressed() && (mParent != null)
14432                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14433                if (performLongClick()) {
14434                    mHasPerformedLongPress = true;
14435                }
14436            }
14437        }
14438
14439        public void rememberWindowAttachCount() {
14440            mOriginalWindowAttachCount = mWindowAttachCount;
14441        }
14442    }
14443
14444    private final class CheckForTap implements Runnable {
14445        public void run() {
14446            mPrivateFlags &= ~PREPRESSED;
14447            mPrivateFlags |= PRESSED;
14448            refreshDrawableState();
14449            checkForLongClick(ViewConfiguration.getTapTimeout());
14450        }
14451    }
14452
14453    private final class PerformClick implements Runnable {
14454        public void run() {
14455            performClick();
14456        }
14457    }
14458
14459    /** @hide */
14460    public void hackTurnOffWindowResizeAnim(boolean off) {
14461        mAttachInfo.mTurnOffWindowResizeAnim = off;
14462    }
14463
14464    /**
14465     * This method returns a ViewPropertyAnimator object, which can be used to animate
14466     * specific properties on this View.
14467     *
14468     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14469     */
14470    public ViewPropertyAnimator animate() {
14471        if (mAnimator == null) {
14472            mAnimator = new ViewPropertyAnimator(this);
14473        }
14474        return mAnimator;
14475    }
14476
14477    /**
14478     * Interface definition for a callback to be invoked when a key event is
14479     * dispatched to this view. The callback will be invoked before the key
14480     * event is given to the view.
14481     */
14482    public interface OnKeyListener {
14483        /**
14484         * Called when a key is dispatched to a view. This allows listeners to
14485         * get a chance to respond before the target view.
14486         *
14487         * @param v The view the key has been dispatched to.
14488         * @param keyCode The code for the physical key that was pressed
14489         * @param event The KeyEvent object containing full information about
14490         *        the event.
14491         * @return True if the listener has consumed the event, false otherwise.
14492         */
14493        boolean onKey(View v, int keyCode, KeyEvent event);
14494    }
14495
14496    /**
14497     * Interface definition for a callback to be invoked when a touch event is
14498     * dispatched to this view. The callback will be invoked before the touch
14499     * event is given to the view.
14500     */
14501    public interface OnTouchListener {
14502        /**
14503         * Called when a touch event is dispatched to a view. This allows listeners to
14504         * get a chance to respond before the target view.
14505         *
14506         * @param v The view the touch event has been dispatched to.
14507         * @param event The MotionEvent object containing full information about
14508         *        the event.
14509         * @return True if the listener has consumed the event, false otherwise.
14510         */
14511        boolean onTouch(View v, MotionEvent event);
14512    }
14513
14514    /**
14515     * Interface definition for a callback to be invoked when a hover event is
14516     * dispatched to this view. The callback will be invoked before the hover
14517     * event is given to the view.
14518     */
14519    public interface OnHoverListener {
14520        /**
14521         * Called when a hover event is dispatched to a view. This allows listeners to
14522         * get a chance to respond before the target view.
14523         *
14524         * @param v The view the hover event has been dispatched to.
14525         * @param event The MotionEvent object containing full information about
14526         *        the event.
14527         * @return True if the listener has consumed the event, false otherwise.
14528         */
14529        boolean onHover(View v, MotionEvent event);
14530    }
14531
14532    /**
14533     * Interface definition for a callback to be invoked when a generic motion event is
14534     * dispatched to this view. The callback will be invoked before the generic motion
14535     * event is given to the view.
14536     */
14537    public interface OnGenericMotionListener {
14538        /**
14539         * Called when a generic motion event is dispatched to a view. This allows listeners to
14540         * get a chance to respond before the target view.
14541         *
14542         * @param v The view the generic motion event has been dispatched to.
14543         * @param event The MotionEvent object containing full information about
14544         *        the event.
14545         * @return True if the listener has consumed the event, false otherwise.
14546         */
14547        boolean onGenericMotion(View v, MotionEvent event);
14548    }
14549
14550    /**
14551     * Interface definition for a callback to be invoked when a view has been clicked and held.
14552     */
14553    public interface OnLongClickListener {
14554        /**
14555         * Called when a view has been clicked and held.
14556         *
14557         * @param v The view that was clicked and held.
14558         *
14559         * @return true if the callback consumed the long click, false otherwise.
14560         */
14561        boolean onLongClick(View v);
14562    }
14563
14564    /**
14565     * Interface definition for a callback to be invoked when a drag is being dispatched
14566     * to this view.  The callback will be invoked before the hosting view's own
14567     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14568     * onDrag(event) behavior, it should return 'false' from this callback.
14569     *
14570     * <div class="special reference">
14571     * <h3>Developer Guides</h3>
14572     * <p>For a guide to implementing drag and drop features, read the
14573     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14574     * </div>
14575     */
14576    public interface OnDragListener {
14577        /**
14578         * Called when a drag event is dispatched to a view. This allows listeners
14579         * to get a chance to override base View behavior.
14580         *
14581         * @param v The View that received the drag event.
14582         * @param event The {@link android.view.DragEvent} object for the drag event.
14583         * @return {@code true} if the drag event was handled successfully, or {@code false}
14584         * if the drag event was not handled. Note that {@code false} will trigger the View
14585         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14586         */
14587        boolean onDrag(View v, DragEvent event);
14588    }
14589
14590    /**
14591     * Interface definition for a callback to be invoked when the focus state of
14592     * a view changed.
14593     */
14594    public interface OnFocusChangeListener {
14595        /**
14596         * Called when the focus state of a view has changed.
14597         *
14598         * @param v The view whose state has changed.
14599         * @param hasFocus The new focus state of v.
14600         */
14601        void onFocusChange(View v, boolean hasFocus);
14602    }
14603
14604    /**
14605     * Interface definition for a callback to be invoked when a view is clicked.
14606     */
14607    public interface OnClickListener {
14608        /**
14609         * Called when a view has been clicked.
14610         *
14611         * @param v The view that was clicked.
14612         */
14613        void onClick(View v);
14614    }
14615
14616    /**
14617     * Interface definition for a callback to be invoked when the context menu
14618     * for this view is being built.
14619     */
14620    public interface OnCreateContextMenuListener {
14621        /**
14622         * Called when the context menu for this view is being built. It is not
14623         * safe to hold onto the menu after this method returns.
14624         *
14625         * @param menu The context menu that is being built
14626         * @param v The view for which the context menu is being built
14627         * @param menuInfo Extra information about the item for which the
14628         *            context menu should be shown. This information will vary
14629         *            depending on the class of v.
14630         */
14631        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14632    }
14633
14634    /**
14635     * Interface definition for a callback to be invoked when the status bar changes
14636     * visibility.  This reports <strong>global</strong> changes to the system UI
14637     * state, not just what the application is requesting.
14638     *
14639     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14640     */
14641    public interface OnSystemUiVisibilityChangeListener {
14642        /**
14643         * Called when the status bar changes visibility because of a call to
14644         * {@link View#setSystemUiVisibility(int)}.
14645         *
14646         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14647         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
14648         * <strong>global</strong> state of the UI visibility flags, not what your
14649         * app is currently applying.
14650         */
14651        public void onSystemUiVisibilityChange(int visibility);
14652    }
14653
14654    /**
14655     * Interface definition for a callback to be invoked when this view is attached
14656     * or detached from its window.
14657     */
14658    public interface OnAttachStateChangeListener {
14659        /**
14660         * Called when the view is attached to a window.
14661         * @param v The view that was attached
14662         */
14663        public void onViewAttachedToWindow(View v);
14664        /**
14665         * Called when the view is detached from a window.
14666         * @param v The view that was detached
14667         */
14668        public void onViewDetachedFromWindow(View v);
14669    }
14670
14671    private final class UnsetPressedState implements Runnable {
14672        public void run() {
14673            setPressed(false);
14674        }
14675    }
14676
14677    /**
14678     * Base class for derived classes that want to save and restore their own
14679     * state in {@link android.view.View#onSaveInstanceState()}.
14680     */
14681    public static class BaseSavedState extends AbsSavedState {
14682        /**
14683         * Constructor used when reading from a parcel. Reads the state of the superclass.
14684         *
14685         * @param source
14686         */
14687        public BaseSavedState(Parcel source) {
14688            super(source);
14689        }
14690
14691        /**
14692         * Constructor called by derived classes when creating their SavedState objects
14693         *
14694         * @param superState The state of the superclass of this view
14695         */
14696        public BaseSavedState(Parcelable superState) {
14697            super(superState);
14698        }
14699
14700        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14701                new Parcelable.Creator<BaseSavedState>() {
14702            public BaseSavedState createFromParcel(Parcel in) {
14703                return new BaseSavedState(in);
14704            }
14705
14706            public BaseSavedState[] newArray(int size) {
14707                return new BaseSavedState[size];
14708            }
14709        };
14710    }
14711
14712    /**
14713     * A set of information given to a view when it is attached to its parent
14714     * window.
14715     */
14716    static class AttachInfo {
14717        interface Callbacks {
14718            void playSoundEffect(int effectId);
14719            boolean performHapticFeedback(int effectId, boolean always);
14720        }
14721
14722        /**
14723         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14724         * to a Handler. This class contains the target (View) to invalidate and
14725         * the coordinates of the dirty rectangle.
14726         *
14727         * For performance purposes, this class also implements a pool of up to
14728         * POOL_LIMIT objects that get reused. This reduces memory allocations
14729         * whenever possible.
14730         */
14731        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14732            private static final int POOL_LIMIT = 10;
14733            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14734                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14735                        public InvalidateInfo newInstance() {
14736                            return new InvalidateInfo();
14737                        }
14738
14739                        public void onAcquired(InvalidateInfo element) {
14740                        }
14741
14742                        public void onReleased(InvalidateInfo element) {
14743                            element.target = null;
14744                        }
14745                    }, POOL_LIMIT)
14746            );
14747
14748            private InvalidateInfo mNext;
14749            private boolean mIsPooled;
14750
14751            View target;
14752
14753            int left;
14754            int top;
14755            int right;
14756            int bottom;
14757
14758            public void setNextPoolable(InvalidateInfo element) {
14759                mNext = element;
14760            }
14761
14762            public InvalidateInfo getNextPoolable() {
14763                return mNext;
14764            }
14765
14766            static InvalidateInfo acquire() {
14767                return sPool.acquire();
14768            }
14769
14770            void release() {
14771                sPool.release(this);
14772            }
14773
14774            public boolean isPooled() {
14775                return mIsPooled;
14776            }
14777
14778            public void setPooled(boolean isPooled) {
14779                mIsPooled = isPooled;
14780            }
14781        }
14782
14783        final IWindowSession mSession;
14784
14785        final IWindow mWindow;
14786
14787        final IBinder mWindowToken;
14788
14789        final Callbacks mRootCallbacks;
14790
14791        HardwareCanvas mHardwareCanvas;
14792
14793        /**
14794         * The top view of the hierarchy.
14795         */
14796        View mRootView;
14797
14798        IBinder mPanelParentWindowToken;
14799        Surface mSurface;
14800
14801        boolean mHardwareAccelerated;
14802        boolean mHardwareAccelerationRequested;
14803        HardwareRenderer mHardwareRenderer;
14804
14805        /**
14806         * Scale factor used by the compatibility mode
14807         */
14808        float mApplicationScale;
14809
14810        /**
14811         * Indicates whether the application is in compatibility mode
14812         */
14813        boolean mScalingRequired;
14814
14815        /**
14816         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14817         */
14818        boolean mTurnOffWindowResizeAnim;
14819
14820        /**
14821         * Left position of this view's window
14822         */
14823        int mWindowLeft;
14824
14825        /**
14826         * Top position of this view's window
14827         */
14828        int mWindowTop;
14829
14830        /**
14831         * Indicates whether views need to use 32-bit drawing caches
14832         */
14833        boolean mUse32BitDrawingCache;
14834
14835        /**
14836         * For windows that are full-screen but using insets to layout inside
14837         * of the screen decorations, these are the current insets for the
14838         * content of the window.
14839         */
14840        final Rect mContentInsets = new Rect();
14841
14842        /**
14843         * For windows that are full-screen but using insets to layout inside
14844         * of the screen decorations, these are the current insets for the
14845         * actual visible parts of the window.
14846         */
14847        final Rect mVisibleInsets = new Rect();
14848
14849        /**
14850         * The internal insets given by this window.  This value is
14851         * supplied by the client (through
14852         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14853         * be given to the window manager when changed to be used in laying
14854         * out windows behind it.
14855         */
14856        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14857                = new ViewTreeObserver.InternalInsetsInfo();
14858
14859        /**
14860         * All views in the window's hierarchy that serve as scroll containers,
14861         * used to determine if the window can be resized or must be panned
14862         * to adjust for a soft input area.
14863         */
14864        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14865
14866        final KeyEvent.DispatcherState mKeyDispatchState
14867                = new KeyEvent.DispatcherState();
14868
14869        /**
14870         * Indicates whether the view's window currently has the focus.
14871         */
14872        boolean mHasWindowFocus;
14873
14874        /**
14875         * The current visibility of the window.
14876         */
14877        int mWindowVisibility;
14878
14879        /**
14880         * Indicates the time at which drawing started to occur.
14881         */
14882        long mDrawingTime;
14883
14884        /**
14885         * Indicates whether or not ignoring the DIRTY_MASK flags.
14886         */
14887        boolean mIgnoreDirtyState;
14888
14889        /**
14890         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14891         * to avoid clearing that flag prematurely.
14892         */
14893        boolean mSetIgnoreDirtyState = false;
14894
14895        /**
14896         * Indicates whether the view's window is currently in touch mode.
14897         */
14898        boolean mInTouchMode;
14899
14900        /**
14901         * Indicates that ViewAncestor should trigger a global layout change
14902         * the next time it performs a traversal
14903         */
14904        boolean mRecomputeGlobalAttributes;
14905
14906        /**
14907         * Always report new attributes at next traversal.
14908         */
14909        boolean mForceReportNewAttributes;
14910
14911        /**
14912         * Set during a traveral if any views want to keep the screen on.
14913         */
14914        boolean mKeepScreenOn;
14915
14916        /**
14917         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14918         */
14919        int mSystemUiVisibility;
14920
14921        /**
14922         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14923         * attached.
14924         */
14925        boolean mHasSystemUiListeners;
14926
14927        /**
14928         * Set if the visibility of any views has changed.
14929         */
14930        boolean mViewVisibilityChanged;
14931
14932        /**
14933         * Set to true if a view has been scrolled.
14934         */
14935        boolean mViewScrollChanged;
14936
14937        /**
14938         * Global to the view hierarchy used as a temporary for dealing with
14939         * x/y points in the transparent region computations.
14940         */
14941        final int[] mTransparentLocation = new int[2];
14942
14943        /**
14944         * Global to the view hierarchy used as a temporary for dealing with
14945         * x/y points in the ViewGroup.invalidateChild implementation.
14946         */
14947        final int[] mInvalidateChildLocation = new int[2];
14948
14949
14950        /**
14951         * Global to the view hierarchy used as a temporary for dealing with
14952         * x/y location when view is transformed.
14953         */
14954        final float[] mTmpTransformLocation = new float[2];
14955
14956        /**
14957         * The view tree observer used to dispatch global events like
14958         * layout, pre-draw, touch mode change, etc.
14959         */
14960        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14961
14962        /**
14963         * A Canvas used by the view hierarchy to perform bitmap caching.
14964         */
14965        Canvas mCanvas;
14966
14967        /**
14968         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14969         * handler can be used to pump events in the UI events queue.
14970         */
14971        final Handler mHandler;
14972
14973        /**
14974         * Identifier for messages requesting the view to be invalidated.
14975         * Such messages should be sent to {@link #mHandler}.
14976         */
14977        static final int INVALIDATE_MSG = 0x1;
14978
14979        /**
14980         * Identifier for messages requesting the view to invalidate a region.
14981         * Such messages should be sent to {@link #mHandler}.
14982         */
14983        static final int INVALIDATE_RECT_MSG = 0x2;
14984
14985        /**
14986         * Temporary for use in computing invalidate rectangles while
14987         * calling up the hierarchy.
14988         */
14989        final Rect mTmpInvalRect = new Rect();
14990
14991        /**
14992         * Temporary for use in computing hit areas with transformed views
14993         */
14994        final RectF mTmpTransformRect = new RectF();
14995
14996        /**
14997         * Temporary list for use in collecting focusable descendents of a view.
14998         */
14999        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
15000
15001        /**
15002         * The id of the window for accessibility purposes.
15003         */
15004        int mAccessibilityWindowId = View.NO_ID;
15005
15006        /**
15007         * Creates a new set of attachment information with the specified
15008         * events handler and thread.
15009         *
15010         * @param handler the events handler the view must use
15011         */
15012        AttachInfo(IWindowSession session, IWindow window,
15013                Handler handler, Callbacks effectPlayer) {
15014            mSession = session;
15015            mWindow = window;
15016            mWindowToken = window.asBinder();
15017            mHandler = handler;
15018            mRootCallbacks = effectPlayer;
15019        }
15020    }
15021
15022    /**
15023     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15024     * is supported. This avoids keeping too many unused fields in most
15025     * instances of View.</p>
15026     */
15027    private static class ScrollabilityCache implements Runnable {
15028
15029        /**
15030         * Scrollbars are not visible
15031         */
15032        public static final int OFF = 0;
15033
15034        /**
15035         * Scrollbars are visible
15036         */
15037        public static final int ON = 1;
15038
15039        /**
15040         * Scrollbars are fading away
15041         */
15042        public static final int FADING = 2;
15043
15044        public boolean fadeScrollBars;
15045
15046        public int fadingEdgeLength;
15047        public int scrollBarDefaultDelayBeforeFade;
15048        public int scrollBarFadeDuration;
15049
15050        public int scrollBarSize;
15051        public ScrollBarDrawable scrollBar;
15052        public float[] interpolatorValues;
15053        public View host;
15054
15055        public final Paint paint;
15056        public final Matrix matrix;
15057        public Shader shader;
15058
15059        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15060
15061        private static final float[] OPAQUE = { 255 };
15062        private static final float[] TRANSPARENT = { 0.0f };
15063
15064        /**
15065         * When fading should start. This time moves into the future every time
15066         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15067         */
15068        public long fadeStartTime;
15069
15070
15071        /**
15072         * The current state of the scrollbars: ON, OFF, or FADING
15073         */
15074        public int state = OFF;
15075
15076        private int mLastColor;
15077
15078        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15079            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15080            scrollBarSize = configuration.getScaledScrollBarSize();
15081            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15082            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15083
15084            paint = new Paint();
15085            matrix = new Matrix();
15086            // use use a height of 1, and then wack the matrix each time we
15087            // actually use it.
15088            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15089
15090            paint.setShader(shader);
15091            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15092            this.host = host;
15093        }
15094
15095        public void setFadeColor(int color) {
15096            if (color != 0 && color != mLastColor) {
15097                mLastColor = color;
15098                color |= 0xFF000000;
15099
15100                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15101                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15102
15103                paint.setShader(shader);
15104                // Restore the default transfer mode (src_over)
15105                paint.setXfermode(null);
15106            }
15107        }
15108
15109        public void run() {
15110            long now = AnimationUtils.currentAnimationTimeMillis();
15111            if (now >= fadeStartTime) {
15112
15113                // the animation fades the scrollbars out by changing
15114                // the opacity (alpha) from fully opaque to fully
15115                // transparent
15116                int nextFrame = (int) now;
15117                int framesCount = 0;
15118
15119                Interpolator interpolator = scrollBarInterpolator;
15120
15121                // Start opaque
15122                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15123
15124                // End transparent
15125                nextFrame += scrollBarFadeDuration;
15126                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15127
15128                state = FADING;
15129
15130                // Kick off the fade animation
15131                host.invalidate(true);
15132            }
15133        }
15134    }
15135
15136    /**
15137     * Resuable callback for sending
15138     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15139     */
15140    private class SendViewScrolledAccessibilityEvent implements Runnable {
15141        public volatile boolean mIsPending;
15142
15143        public void run() {
15144            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15145            mIsPending = false;
15146        }
15147    }
15148
15149    /**
15150     * <p>
15151     * This class represents a delegate that can be registered in a {@link View}
15152     * to enhance accessibility support via composition rather via inheritance.
15153     * It is specifically targeted to widget developers that extend basic View
15154     * classes i.e. classes in package android.view, that would like their
15155     * applications to be backwards compatible.
15156     * </p>
15157     * <p>
15158     * A scenario in which a developer would like to use an accessibility delegate
15159     * is overriding a method introduced in a later API version then the minimal API
15160     * version supported by the application. For example, the method
15161     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15162     * in API version 4 when the accessibility APIs were first introduced. If a
15163     * developer would like his application to run on API version 4 devices (assuming
15164     * all other APIs used by the application are version 4 or lower) and take advantage
15165     * of this method, instead of overriding the method which would break the application's
15166     * backwards compatibility, he can override the corresponding method in this
15167     * delegate and register the delegate in the target View if the API version of
15168     * the system is high enough i.e. the API version is same or higher to the API
15169     * version that introduced
15170     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15171     * </p>
15172     * <p>
15173     * Here is an example implementation:
15174     * </p>
15175     * <code><pre><p>
15176     * if (Build.VERSION.SDK_INT >= 14) {
15177     *     // If the API version is equal of higher than the version in
15178     *     // which onInitializeAccessibilityNodeInfo was introduced we
15179     *     // register a delegate with a customized implementation.
15180     *     View view = findViewById(R.id.view_id);
15181     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15182     *         public void onInitializeAccessibilityNodeInfo(View host,
15183     *                 AccessibilityNodeInfo info) {
15184     *             // Let the default implementation populate the info.
15185     *             super.onInitializeAccessibilityNodeInfo(host, info);
15186     *             // Set some other information.
15187     *             info.setEnabled(host.isEnabled());
15188     *         }
15189     *     });
15190     * }
15191     * </code></pre></p>
15192     * <p>
15193     * This delegate contains methods that correspond to the accessibility methods
15194     * in View. If a delegate has been specified the implementation in View hands
15195     * off handling to the corresponding method in this delegate. The default
15196     * implementation the delegate methods behaves exactly as the corresponding
15197     * method in View for the case of no accessibility delegate been set. Hence,
15198     * to customize the behavior of a View method, clients can override only the
15199     * corresponding delegate method without altering the behavior of the rest
15200     * accessibility related methods of the host view.
15201     * </p>
15202     */
15203    public static class AccessibilityDelegate {
15204
15205        /**
15206         * Sends an accessibility event of the given type. If accessibility is not
15207         * enabled this method has no effect.
15208         * <p>
15209         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15210         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15211         * been set.
15212         * </p>
15213         *
15214         * @param host The View hosting the delegate.
15215         * @param eventType The type of the event to send.
15216         *
15217         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
15218         */
15219        public void sendAccessibilityEvent(View host, int eventType) {
15220            host.sendAccessibilityEventInternal(eventType);
15221        }
15222
15223        /**
15224         * Sends an accessibility event. This method behaves exactly as
15225         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
15226         * empty {@link AccessibilityEvent} and does not perform a check whether
15227         * accessibility is enabled.
15228         * <p>
15229         * The default implementation behaves as
15230         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15231         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
15232         * the case of no accessibility delegate been set.
15233         * </p>
15234         *
15235         * @param host The View hosting the delegate.
15236         * @param event The event to send.
15237         *
15238         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15239         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15240         */
15241        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
15242            host.sendAccessibilityEventUncheckedInternal(event);
15243        }
15244
15245        /**
15246         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
15247         * to its children for adding their text content to the event.
15248         * <p>
15249         * The default implementation behaves as
15250         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15251         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
15252         * the case of no accessibility delegate been set.
15253         * </p>
15254         *
15255         * @param host The View hosting the delegate.
15256         * @param event The event.
15257         * @return True if the event population was completed.
15258         *
15259         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15260         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15261         */
15262        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15263            return host.dispatchPopulateAccessibilityEventInternal(event);
15264        }
15265
15266        /**
15267         * Gives a chance to the host View to populate the accessibility event with its
15268         * text content.
15269         * <p>
15270         * The default implementation behaves as
15271         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
15272         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
15273         * the case of no accessibility delegate been set.
15274         * </p>
15275         *
15276         * @param host The View hosting the delegate.
15277         * @param event The accessibility event which to populate.
15278         *
15279         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
15280         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
15281         */
15282        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15283            host.onPopulateAccessibilityEventInternal(event);
15284        }
15285
15286        /**
15287         * Initializes an {@link AccessibilityEvent} with information about the
15288         * the host View which is the event source.
15289         * <p>
15290         * The default implementation behaves as
15291         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
15292         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
15293         * the case of no accessibility delegate been set.
15294         * </p>
15295         *
15296         * @param host The View hosting the delegate.
15297         * @param event The event to initialize.
15298         *
15299         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
15300         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
15301         */
15302        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
15303            host.onInitializeAccessibilityEventInternal(event);
15304        }
15305
15306        /**
15307         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
15308         * <p>
15309         * The default implementation behaves as
15310         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15311         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
15312         * the case of no accessibility delegate been set.
15313         * </p>
15314         *
15315         * @param host The View hosting the delegate.
15316         * @param info The instance to initialize.
15317         *
15318         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15319         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15320         */
15321        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
15322            host.onInitializeAccessibilityNodeInfoInternal(info);
15323        }
15324
15325        /**
15326         * Called when a child of the host View has requested sending an
15327         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
15328         * to augment the event.
15329         * <p>
15330         * The default implementation behaves as
15331         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15332         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15333         * the case of no accessibility delegate been set.
15334         * </p>
15335         *
15336         * @param host The View hosting the delegate.
15337         * @param child The child which requests sending the event.
15338         * @param event The event to be sent.
15339         * @return True if the event should be sent
15340         *
15341         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15342         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15343         */
15344        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15345                AccessibilityEvent event) {
15346            return host.onRequestSendAccessibilityEventInternal(child, event);
15347        }
15348
15349        /**
15350         * Gets the provider for managing a virtual view hierarchy rooted at this View
15351         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15352         * that explore the window content.
15353         * <p>
15354         * The default implementation behaves as
15355         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15356         * the case of no accessibility delegate been set.
15357         * </p>
15358         *
15359         * @return The provider.
15360         *
15361         * @see AccessibilityNodeProvider
15362         */
15363        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15364            return null;
15365        }
15366    }
15367}
15368