View.java revision a998dff5d49a423aaf7097aa8f96bf5bdc681d25
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.Parcel;
44import android.os.Parcelable;
45import android.os.RemoteException;
46import android.os.SystemClock;
47import android.text.TextUtils;
48import android.util.AttributeSet;
49import android.util.FloatProperty;
50import android.util.LocaleUtil;
51import android.util.Log;
52import android.util.Pool;
53import android.util.Poolable;
54import android.util.PoolableManager;
55import android.util.Pools;
56import android.util.Property;
57import android.util.SparseArray;
58import android.util.TypedValue;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityEventSource;
62import android.view.accessibility.AccessibilityManager;
63import android.view.accessibility.AccessibilityNodeInfo;
64import android.view.accessibility.AccessibilityNodeProvider;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.animation.Transformation;
68import android.view.inputmethod.EditorInfo;
69import android.view.inputmethod.InputConnection;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.ScrollBarDrawable;
72
73import static android.os.Build.VERSION_CODES.*;
74
75import com.android.internal.R;
76import com.android.internal.util.Predicate;
77import com.android.internal.view.menu.MenuBuilder;
78
79import java.lang.ref.WeakReference;
80import java.lang.reflect.InvocationTargetException;
81import java.lang.reflect.Method;
82import java.util.ArrayList;
83import java.util.Arrays;
84import java.util.Locale;
85import java.util.concurrent.CopyOnWriteArrayList;
86
87/**
88 * <p>
89 * This class represents the basic building block for user interface components. A View
90 * occupies a rectangular area on the screen and is responsible for drawing and
91 * event handling. View is the base class for <em>widgets</em>, which are
92 * used to create interactive UI components (buttons, text fields, etc.). The
93 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
94 * are invisible containers that hold other Views (or other ViewGroups) and define
95 * their layout properties.
96 * </p>
97 *
98 * <div class="special reference">
99 * <h3>Developer Guides</h3>
100 * <p>For information about using this class to develop your application's user interface,
101 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
102 * </div>
103 *
104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
129 * Other view subclasses offer more specialized listeners. For example, a Button
130 * exposes a listener to notify clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility(int)}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 *     <thead>
152 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 *     </thead>
154 *
155 *     <tbody>
156 *     <tr>
157 *         <td rowspan="2">Creation</td>
158 *         <td>Constructors</td>
159 *         <td>There is a form of the constructor that are called when the view
160 *         is created from code and a form that is called when the view is
161 *         inflated from a layout file. The second form should parse and apply
162 *         any attributes defined in the layout file.
163 *         </td>
164 *     </tr>
165 *     <tr>
166 *         <td><code>{@link #onFinishInflate()}</code></td>
167 *         <td>Called after a view and all of its children has been inflated
168 *         from XML.</td>
169 *     </tr>
170 *
171 *     <tr>
172 *         <td rowspan="3">Layout</td>
173 *         <td><code>{@link #onMeasure(int, int)}</code></td>
174 *         <td>Called to determine the size requirements for this view and all
175 *         of its children.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
180 *         <td>Called when this view should assign a size and position to all
181 *         of its children.
182 *         </td>
183 *     </tr>
184 *     <tr>
185 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
186 *         <td>Called when the size of this view has changed.
187 *         </td>
188 *     </tr>
189 *
190 *     <tr>
191 *         <td>Drawing</td>
192 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
193 *         <td>Called when the view should render its content.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="4">Event processing</td>
199 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
200 *         <td>Called when a new key event occurs.
201 *         </td>
202 *     </tr>
203 *     <tr>
204 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
205 *         <td>Called when a key up event occurs.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
210 *         <td>Called when a trackball motion event occurs.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
215 *         <td>Called when a touch screen motion event occurs.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td rowspan="2">Focus</td>
221 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
222 *         <td>Called when the view gains or loses focus.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
228 *         <td>Called when the window containing the view gains or loses focus.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="3">Attaching</td>
234 *         <td><code>{@link #onAttachedToWindow()}</code></td>
235 *         <td>Called when the view is attached to a window.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onDetachedFromWindow}</code></td>
241 *         <td>Called when the view is detached from its window.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
247 *         <td>Called when the visibility of the window containing the view
248 *         has changed.
249 *         </td>
250 *     </tr>
251 *     </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
264 * &lt;Button
265 *     android:id="@+id/my_button"
266 *     android:layout_width="wrap_content"
267 *     android:layout_height="wrap_content"
268 *     android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 *      Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
340 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
342 * {@link #getPaddingEnd()}.
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_paddingStart
605 * @attr ref android.R.styleable#View_paddingEnd
606 * @attr ref android.R.styleable#View_saveEnabled
607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
631 * @attr ref android.R.styleable#View_visibility
632 *
633 * @see android.view.ViewGroup
634 */
635public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
636        AccessibilityEventSource {
637    private static final boolean DBG = false;
638
639    /**
640     * The logging tag used by this class with android.util.Log.
641     */
642    protected static final String VIEW_LOG_TAG = "View";
643
644    /**
645     * Used to mark a View that has no ID.
646     */
647    public static final int NO_ID = -1;
648
649    /**
650     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
651     * calling setFlags.
652     */
653    private static final int NOT_FOCUSABLE = 0x00000000;
654
655    /**
656     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
657     * setFlags.
658     */
659    private static final int FOCUSABLE = 0x00000001;
660
661    /**
662     * Mask for use with setFlags indicating bits used for focus.
663     */
664    private static final int FOCUSABLE_MASK = 0x00000001;
665
666    /**
667     * This view will adjust its padding to fit sytem windows (e.g. status bar)
668     */
669    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
670
671    /**
672     * This view is visible.
673     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
674     * android:visibility}.
675     */
676    public static final int VISIBLE = 0x00000000;
677
678    /**
679     * This view is invisible, but it still takes up space for layout purposes.
680     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
681     * android:visibility}.
682     */
683    public static final int INVISIBLE = 0x00000004;
684
685    /**
686     * This view is invisible, and it doesn't take any space for layout
687     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
688     * android:visibility}.
689     */
690    public static final int GONE = 0x00000008;
691
692    /**
693     * Mask for use with setFlags indicating bits used for visibility.
694     * {@hide}
695     */
696    static final int VISIBILITY_MASK = 0x0000000C;
697
698    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
699
700    /**
701     * This view is enabled. Interpretation varies by subclass.
702     * Use with ENABLED_MASK when calling setFlags.
703     * {@hide}
704     */
705    static final int ENABLED = 0x00000000;
706
707    /**
708     * This view is disabled. Interpretation varies by subclass.
709     * Use with ENABLED_MASK when calling setFlags.
710     * {@hide}
711     */
712    static final int DISABLED = 0x00000020;
713
714   /**
715    * Mask for use with setFlags indicating bits used for indicating whether
716    * this view is enabled
717    * {@hide}
718    */
719    static final int ENABLED_MASK = 0x00000020;
720
721    /**
722     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
723     * called and further optimizations will be performed. It is okay to have
724     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
725     * {@hide}
726     */
727    static final int WILL_NOT_DRAW = 0x00000080;
728
729    /**
730     * Mask for use with setFlags indicating bits used for indicating whether
731     * this view is will draw
732     * {@hide}
733     */
734    static final int DRAW_MASK = 0x00000080;
735
736    /**
737     * <p>This view doesn't show scrollbars.</p>
738     * {@hide}
739     */
740    static final int SCROLLBARS_NONE = 0x00000000;
741
742    /**
743     * <p>This view shows horizontal scrollbars.</p>
744     * {@hide}
745     */
746    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
747
748    /**
749     * <p>This view shows vertical scrollbars.</p>
750     * {@hide}
751     */
752    static final int SCROLLBARS_VERTICAL = 0x00000200;
753
754    /**
755     * <p>Mask for use with setFlags indicating bits used for indicating which
756     * scrollbars are enabled.</p>
757     * {@hide}
758     */
759    static final int SCROLLBARS_MASK = 0x00000300;
760
761    /**
762     * Indicates that the view should filter touches when its window is obscured.
763     * Refer to the class comments for more information about this security feature.
764     * {@hide}
765     */
766    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
767
768    // note flag value 0x00000800 is now available for next flags...
769
770    /**
771     * <p>This view doesn't show fading edges.</p>
772     * {@hide}
773     */
774    static final int FADING_EDGE_NONE = 0x00000000;
775
776    /**
777     * <p>This view shows horizontal fading edges.</p>
778     * {@hide}
779     */
780    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
781
782    /**
783     * <p>This view shows vertical fading edges.</p>
784     * {@hide}
785     */
786    static final int FADING_EDGE_VERTICAL = 0x00002000;
787
788    /**
789     * <p>Mask for use with setFlags indicating bits used for indicating which
790     * fading edges are enabled.</p>
791     * {@hide}
792     */
793    static final int FADING_EDGE_MASK = 0x00003000;
794
795    /**
796     * <p>Indicates this view can be clicked. When clickable, a View reacts
797     * to clicks by notifying the OnClickListener.<p>
798     * {@hide}
799     */
800    static final int CLICKABLE = 0x00004000;
801
802    /**
803     * <p>Indicates this view is caching its drawing into a bitmap.</p>
804     * {@hide}
805     */
806    static final int DRAWING_CACHE_ENABLED = 0x00008000;
807
808    /**
809     * <p>Indicates that no icicle should be saved for this view.<p>
810     * {@hide}
811     */
812    static final int SAVE_DISABLED = 0x000010000;
813
814    /**
815     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
816     * property.</p>
817     * {@hide}
818     */
819    static final int SAVE_DISABLED_MASK = 0x000010000;
820
821    /**
822     * <p>Indicates that no drawing cache should ever be created for this view.<p>
823     * {@hide}
824     */
825    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
826
827    /**
828     * <p>Indicates this view can take / keep focus when int touch mode.</p>
829     * {@hide}
830     */
831    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
832
833    /**
834     * <p>Enables low quality mode for the drawing cache.</p>
835     */
836    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
837
838    /**
839     * <p>Enables high quality mode for the drawing cache.</p>
840     */
841    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
842
843    /**
844     * <p>Enables automatic quality mode for the drawing cache.</p>
845     */
846    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
847
848    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
849            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
850    };
851
852    /**
853     * <p>Mask for use with setFlags indicating bits used for the cache
854     * quality property.</p>
855     * {@hide}
856     */
857    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
858
859    /**
860     * <p>
861     * Indicates this view can be long clicked. When long clickable, a View
862     * reacts to long clicks by notifying the OnLongClickListener or showing a
863     * context menu.
864     * </p>
865     * {@hide}
866     */
867    static final int LONG_CLICKABLE = 0x00200000;
868
869    /**
870     * <p>Indicates that this view gets its drawable states from its direct parent
871     * and ignores its original internal states.</p>
872     *
873     * @hide
874     */
875    static final int DUPLICATE_PARENT_STATE = 0x00400000;
876
877    /**
878     * The scrollbar style to display the scrollbars inside the content area,
879     * without increasing the padding. The scrollbars will be overlaid with
880     * translucency on the view's content.
881     */
882    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
883
884    /**
885     * The scrollbar style to display the scrollbars inside the padded area,
886     * increasing the padding of the view. The scrollbars will not overlap the
887     * content area of the view.
888     */
889    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
890
891    /**
892     * The scrollbar style to display the scrollbars at the edge of the view,
893     * without increasing the padding. The scrollbars will be overlaid with
894     * translucency.
895     */
896    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
897
898    /**
899     * The scrollbar style to display the scrollbars at the edge of the view,
900     * increasing the padding of the view. The scrollbars will only overlap the
901     * background, if any.
902     */
903    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
904
905    /**
906     * Mask to check if the scrollbar style is overlay or inset.
907     * {@hide}
908     */
909    static final int SCROLLBARS_INSET_MASK = 0x01000000;
910
911    /**
912     * Mask to check if the scrollbar style is inside or outside.
913     * {@hide}
914     */
915    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
916
917    /**
918     * Mask for scrollbar style.
919     * {@hide}
920     */
921    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
922
923    /**
924     * View flag indicating that the screen should remain on while the
925     * window containing this view is visible to the user.  This effectively
926     * takes care of automatically setting the WindowManager's
927     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
928     */
929    public static final int KEEP_SCREEN_ON = 0x04000000;
930
931    /**
932     * View flag indicating whether this view should have sound effects enabled
933     * for events such as clicking and touching.
934     */
935    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
936
937    /**
938     * View flag indicating whether this view should have haptic feedback
939     * enabled for events such as long presses.
940     */
941    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
942
943    /**
944     * <p>Indicates that the view hierarchy should stop saving state when
945     * it reaches this view.  If state saving is initiated immediately at
946     * the view, it will be allowed.
947     * {@hide}
948     */
949    static final int PARENT_SAVE_DISABLED = 0x20000000;
950
951    /**
952     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
953     * {@hide}
954     */
955    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
956
957    /**
958     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
959     * should add all focusable Views regardless if they are focusable in touch mode.
960     */
961    public static final int FOCUSABLES_ALL = 0x00000000;
962
963    /**
964     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
965     * should add only Views focusable in touch mode.
966     */
967    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
968
969    /**
970     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
971     * item.
972     */
973    public static final int FOCUS_BACKWARD = 0x00000001;
974
975    /**
976     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
977     * item.
978     */
979    public static final int FOCUS_FORWARD = 0x00000002;
980
981    /**
982     * Use with {@link #focusSearch(int)}. Move focus to the left.
983     */
984    public static final int FOCUS_LEFT = 0x00000011;
985
986    /**
987     * Use with {@link #focusSearch(int)}. Move focus up.
988     */
989    public static final int FOCUS_UP = 0x00000021;
990
991    /**
992     * Use with {@link #focusSearch(int)}. Move focus to the right.
993     */
994    public static final int FOCUS_RIGHT = 0x00000042;
995
996    /**
997     * Use with {@link #focusSearch(int)}. Move focus down.
998     */
999    public static final int FOCUS_DOWN = 0x00000082;
1000
1001    /**
1002     * Bits of {@link #getMeasuredWidthAndState()} and
1003     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1004     */
1005    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1006
1007    /**
1008     * Bits of {@link #getMeasuredWidthAndState()} and
1009     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1010     */
1011    public static final int MEASURED_STATE_MASK = 0xff000000;
1012
1013    /**
1014     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1015     * for functions that combine both width and height into a single int,
1016     * such as {@link #getMeasuredState()} and the childState argument of
1017     * {@link #resolveSizeAndState(int, int, int)}.
1018     */
1019    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1020
1021    /**
1022     * Bit of {@link #getMeasuredWidthAndState()} and
1023     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1024     * is smaller that the space the view would like to have.
1025     */
1026    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1027
1028    /**
1029     * Base View state sets
1030     */
1031    // Singles
1032    /**
1033     * Indicates the view has no states set. States are used with
1034     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1035     * view depending on its state.
1036     *
1037     * @see android.graphics.drawable.Drawable
1038     * @see #getDrawableState()
1039     */
1040    protected static final int[] EMPTY_STATE_SET;
1041    /**
1042     * Indicates the view is enabled. States are used with
1043     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1044     * view depending on its state.
1045     *
1046     * @see android.graphics.drawable.Drawable
1047     * @see #getDrawableState()
1048     */
1049    protected static final int[] ENABLED_STATE_SET;
1050    /**
1051     * Indicates the view is focused. States are used with
1052     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1053     * view depending on its state.
1054     *
1055     * @see android.graphics.drawable.Drawable
1056     * @see #getDrawableState()
1057     */
1058    protected static final int[] FOCUSED_STATE_SET;
1059    /**
1060     * Indicates the view is selected. States are used with
1061     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1062     * view depending on its state.
1063     *
1064     * @see android.graphics.drawable.Drawable
1065     * @see #getDrawableState()
1066     */
1067    protected static final int[] SELECTED_STATE_SET;
1068    /**
1069     * Indicates the view is pressed. States are used with
1070     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1071     * view depending on its state.
1072     *
1073     * @see android.graphics.drawable.Drawable
1074     * @see #getDrawableState()
1075     * @hide
1076     */
1077    protected static final int[] PRESSED_STATE_SET;
1078    /**
1079     * Indicates the view's window has focus. 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[] WINDOW_FOCUSED_STATE_SET;
1087    // Doubles
1088    /**
1089     * Indicates the view is enabled and has the focus.
1090     *
1091     * @see #ENABLED_STATE_SET
1092     * @see #FOCUSED_STATE_SET
1093     */
1094    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1095    /**
1096     * Indicates the view is enabled and selected.
1097     *
1098     * @see #ENABLED_STATE_SET
1099     * @see #SELECTED_STATE_SET
1100     */
1101    protected static final int[] ENABLED_SELECTED_STATE_SET;
1102    /**
1103     * Indicates the view is enabled and that its window has focus.
1104     *
1105     * @see #ENABLED_STATE_SET
1106     * @see #WINDOW_FOCUSED_STATE_SET
1107     */
1108    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1109    /**
1110     * Indicates the view is focused and selected.
1111     *
1112     * @see #FOCUSED_STATE_SET
1113     * @see #SELECTED_STATE_SET
1114     */
1115    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1116    /**
1117     * Indicates the view has the focus and that its window has the focus.
1118     *
1119     * @see #FOCUSED_STATE_SET
1120     * @see #WINDOW_FOCUSED_STATE_SET
1121     */
1122    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1123    /**
1124     * Indicates the view is selected and that its window has the focus.
1125     *
1126     * @see #SELECTED_STATE_SET
1127     * @see #WINDOW_FOCUSED_STATE_SET
1128     */
1129    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1130    // Triples
1131    /**
1132     * Indicates the view is enabled, focused and selected.
1133     *
1134     * @see #ENABLED_STATE_SET
1135     * @see #FOCUSED_STATE_SET
1136     * @see #SELECTED_STATE_SET
1137     */
1138    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1139    /**
1140     * Indicates the view is enabled, focused and its window has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     * @see #WINDOW_FOCUSED_STATE_SET
1145     */
1146    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1147    /**
1148     * Indicates the view is enabled, selected and its window has the focus.
1149     *
1150     * @see #ENABLED_STATE_SET
1151     * @see #SELECTED_STATE_SET
1152     * @see #WINDOW_FOCUSED_STATE_SET
1153     */
1154    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1155    /**
1156     * Indicates the view is focused, selected and its window has the focus.
1157     *
1158     * @see #FOCUSED_STATE_SET
1159     * @see #SELECTED_STATE_SET
1160     * @see #WINDOW_FOCUSED_STATE_SET
1161     */
1162    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1163    /**
1164     * Indicates the view is enabled, focused, selected and its window
1165     * has the focus.
1166     *
1167     * @see #ENABLED_STATE_SET
1168     * @see #FOCUSED_STATE_SET
1169     * @see #SELECTED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1173    /**
1174     * Indicates the view is pressed and its window has the focus.
1175     *
1176     * @see #PRESSED_STATE_SET
1177     * @see #WINDOW_FOCUSED_STATE_SET
1178     */
1179    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1180    /**
1181     * Indicates the view is pressed and selected.
1182     *
1183     * @see #PRESSED_STATE_SET
1184     * @see #SELECTED_STATE_SET
1185     */
1186    protected static final int[] PRESSED_SELECTED_STATE_SET;
1187    /**
1188     * Indicates the view is pressed, selected and its window has the focus.
1189     *
1190     * @see #PRESSED_STATE_SET
1191     * @see #SELECTED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is pressed and focused.
1197     *
1198     * @see #PRESSED_STATE_SET
1199     * @see #FOCUSED_STATE_SET
1200     */
1201    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1202    /**
1203     * Indicates the view is pressed, focused and its window has the focus.
1204     *
1205     * @see #PRESSED_STATE_SET
1206     * @see #FOCUSED_STATE_SET
1207     * @see #WINDOW_FOCUSED_STATE_SET
1208     */
1209    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1210    /**
1211     * Indicates the view is pressed, focused and selected.
1212     *
1213     * @see #PRESSED_STATE_SET
1214     * @see #SELECTED_STATE_SET
1215     * @see #FOCUSED_STATE_SET
1216     */
1217    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1218    /**
1219     * Indicates the view is pressed, focused, selected and its window has the focus.
1220     *
1221     * @see #PRESSED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     * @see #SELECTED_STATE_SET
1224     * @see #WINDOW_FOCUSED_STATE_SET
1225     */
1226    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1227    /**
1228     * Indicates the view is pressed and enabled.
1229     *
1230     * @see #PRESSED_STATE_SET
1231     * @see #ENABLED_STATE_SET
1232     */
1233    protected static final int[] PRESSED_ENABLED_STATE_SET;
1234    /**
1235     * Indicates the view is pressed, enabled and its window has the focus.
1236     *
1237     * @see #PRESSED_STATE_SET
1238     * @see #ENABLED_STATE_SET
1239     * @see #WINDOW_FOCUSED_STATE_SET
1240     */
1241    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1242    /**
1243     * Indicates the view is pressed, enabled and selected.
1244     *
1245     * @see #PRESSED_STATE_SET
1246     * @see #ENABLED_STATE_SET
1247     * @see #SELECTED_STATE_SET
1248     */
1249    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1250    /**
1251     * Indicates the view is pressed, enabled, selected and its window has the
1252     * focus.
1253     *
1254     * @see #PRESSED_STATE_SET
1255     * @see #ENABLED_STATE_SET
1256     * @see #SELECTED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is pressed, enabled and focused.
1262     *
1263     * @see #PRESSED_STATE_SET
1264     * @see #ENABLED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, enabled, focused and its window has the
1270     * focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #ENABLED_STATE_SET
1274     * @see #FOCUSED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed, enabled, focused and selected.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     * @see #SELECTED_STATE_SET
1284     * @see #FOCUSED_STATE_SET
1285     */
1286    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1287    /**
1288     * Indicates the view is pressed, enabled, focused, selected and its window
1289     * has the focus.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #ENABLED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     * @see #FOCUSED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1298
1299    /**
1300     * The order here is very important to {@link #getDrawableState()}
1301     */
1302    private static final int[][] VIEW_STATE_SETS;
1303
1304    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1305    static final int VIEW_STATE_SELECTED = 1 << 1;
1306    static final int VIEW_STATE_FOCUSED = 1 << 2;
1307    static final int VIEW_STATE_ENABLED = 1 << 3;
1308    static final int VIEW_STATE_PRESSED = 1 << 4;
1309    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1310    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1311    static final int VIEW_STATE_HOVERED = 1 << 7;
1312    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1313    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1314
1315    static final int[] VIEW_STATE_IDS = new int[] {
1316        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1317        R.attr.state_selected,          VIEW_STATE_SELECTED,
1318        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1319        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1320        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1321        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1322        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1323        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1324        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1325        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1326    };
1327
1328    static {
1329        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1330            throw new IllegalStateException(
1331                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1332        }
1333        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1334        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1335            int viewState = R.styleable.ViewDrawableStates[i];
1336            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1337                if (VIEW_STATE_IDS[j] == viewState) {
1338                    orderedIds[i * 2] = viewState;
1339                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1340                }
1341            }
1342        }
1343        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1344        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1345        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1346            int numBits = Integer.bitCount(i);
1347            int[] set = new int[numBits];
1348            int pos = 0;
1349            for (int j = 0; j < orderedIds.length; j += 2) {
1350                if ((i & orderedIds[j+1]) != 0) {
1351                    set[pos++] = orderedIds[j];
1352                }
1353            }
1354            VIEW_STATE_SETS[i] = set;
1355        }
1356
1357        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1358        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1359        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1360        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1362        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1363        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1364                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1365        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1366                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1367        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1369                | VIEW_STATE_FOCUSED];
1370        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1371        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1372                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1373        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1374                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1375        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1377                | VIEW_STATE_ENABLED];
1378        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1379                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1380        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1382                | VIEW_STATE_ENABLED];
1383        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1384                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1385                | VIEW_STATE_ENABLED];
1386        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1387                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1388                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1389
1390        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1391        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1392                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1393        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1394                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1395        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1396                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1397                | VIEW_STATE_PRESSED];
1398        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1399                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1400        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1402                | VIEW_STATE_PRESSED];
1403        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1404                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1405                | VIEW_STATE_PRESSED];
1406        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1408                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1409        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1410                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1411        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1413                | VIEW_STATE_PRESSED];
1414        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1416                | VIEW_STATE_PRESSED];
1417        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1419                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1420        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1421                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1422                | VIEW_STATE_PRESSED];
1423        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1425                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1426        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1428                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1429        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1431                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1432                | VIEW_STATE_PRESSED];
1433    }
1434
1435    /**
1436     * Accessibility event types that are dispatched for text population.
1437     */
1438    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1439            AccessibilityEvent.TYPE_VIEW_CLICKED
1440            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1441            | AccessibilityEvent.TYPE_VIEW_SELECTED
1442            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1443            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1444            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1445            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1446            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1447            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1448
1449    /**
1450     * Temporary Rect currently for use in setBackground().  This will probably
1451     * be extended in the future to hold our own class with more than just
1452     * a Rect. :)
1453     */
1454    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1455
1456    /**
1457     * Temporary flag, used to enable processing of View properties in the native DisplayList
1458     * object instead of during draw(). Soon to be enabled by default for hardware-accelerated
1459     * apps.
1460     * @hide
1461     */
1462    public static final boolean USE_DISPLAY_LIST_PROPERTIES = false;
1463
1464    /**
1465     * Map used to store views' tags.
1466     */
1467    private SparseArray<Object> mKeyedTags;
1468
1469    /**
1470     * The next available accessiiblity id.
1471     */
1472    private static int sNextAccessibilityViewId;
1473
1474    /**
1475     * The animation currently associated with this view.
1476     * @hide
1477     */
1478    protected Animation mCurrentAnimation = null;
1479
1480    /**
1481     * Width as measured during measure pass.
1482     * {@hide}
1483     */
1484    @ViewDebug.ExportedProperty(category = "measurement")
1485    int mMeasuredWidth;
1486
1487    /**
1488     * Height as measured during measure pass.
1489     * {@hide}
1490     */
1491    @ViewDebug.ExportedProperty(category = "measurement")
1492    int mMeasuredHeight;
1493
1494    /**
1495     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1496     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1497     * its display list. This flag, used only when hw accelerated, allows us to clear the
1498     * flag while retaining this information until it's needed (at getDisplayList() time and
1499     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1500     *
1501     * {@hide}
1502     */
1503    boolean mRecreateDisplayList = false;
1504
1505    /**
1506     * The view's identifier.
1507     * {@hide}
1508     *
1509     * @see #setId(int)
1510     * @see #getId()
1511     */
1512    @ViewDebug.ExportedProperty(resolveId = true)
1513    int mID = NO_ID;
1514
1515    /**
1516     * The stable ID of this view for accessibility purposes.
1517     */
1518    int mAccessibilityViewId = NO_ID;
1519
1520    /**
1521     * The view's tag.
1522     * {@hide}
1523     *
1524     * @see #setTag(Object)
1525     * @see #getTag()
1526     */
1527    protected Object mTag;
1528
1529    // for mPrivateFlags:
1530    /** {@hide} */
1531    static final int WANTS_FOCUS                    = 0x00000001;
1532    /** {@hide} */
1533    static final int FOCUSED                        = 0x00000002;
1534    /** {@hide} */
1535    static final int SELECTED                       = 0x00000004;
1536    /** {@hide} */
1537    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1538    /** {@hide} */
1539    static final int HAS_BOUNDS                     = 0x00000010;
1540    /** {@hide} */
1541    static final int DRAWN                          = 0x00000020;
1542    /**
1543     * When this flag is set, this view is running an animation on behalf of its
1544     * children and should therefore not cancel invalidate requests, even if they
1545     * lie outside of this view's bounds.
1546     *
1547     * {@hide}
1548     */
1549    static final int DRAW_ANIMATION                 = 0x00000040;
1550    /** {@hide} */
1551    static final int SKIP_DRAW                      = 0x00000080;
1552    /** {@hide} */
1553    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1554    /** {@hide} */
1555    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1556    /** {@hide} */
1557    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1558    /** {@hide} */
1559    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1560    /** {@hide} */
1561    static final int FORCE_LAYOUT                   = 0x00001000;
1562    /** {@hide} */
1563    static final int LAYOUT_REQUIRED                = 0x00002000;
1564
1565    private static final int PRESSED                = 0x00004000;
1566
1567    /** {@hide} */
1568    static final int DRAWING_CACHE_VALID            = 0x00008000;
1569    /**
1570     * Flag used to indicate that this view should be drawn once more (and only once
1571     * more) after its animation has completed.
1572     * {@hide}
1573     */
1574    static final int ANIMATION_STARTED              = 0x00010000;
1575
1576    private static final int SAVE_STATE_CALLED      = 0x00020000;
1577
1578    /**
1579     * Indicates that the View returned true when onSetAlpha() was called and that
1580     * the alpha must be restored.
1581     * {@hide}
1582     */
1583    static final int ALPHA_SET                      = 0x00040000;
1584
1585    /**
1586     * Set by {@link #setScrollContainer(boolean)}.
1587     */
1588    static final int SCROLL_CONTAINER               = 0x00080000;
1589
1590    /**
1591     * Set by {@link #setScrollContainer(boolean)}.
1592     */
1593    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1594
1595    /**
1596     * View flag indicating whether this view was invalidated (fully or partially.)
1597     *
1598     * @hide
1599     */
1600    static final int DIRTY                          = 0x00200000;
1601
1602    /**
1603     * View flag indicating whether this view was invalidated by an opaque
1604     * invalidate request.
1605     *
1606     * @hide
1607     */
1608    static final int DIRTY_OPAQUE                   = 0x00400000;
1609
1610    /**
1611     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1612     *
1613     * @hide
1614     */
1615    static final int DIRTY_MASK                     = 0x00600000;
1616
1617    /**
1618     * Indicates whether the background is opaque.
1619     *
1620     * @hide
1621     */
1622    static final int OPAQUE_BACKGROUND              = 0x00800000;
1623
1624    /**
1625     * Indicates whether the scrollbars are opaque.
1626     *
1627     * @hide
1628     */
1629    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1630
1631    /**
1632     * Indicates whether the view is opaque.
1633     *
1634     * @hide
1635     */
1636    static final int OPAQUE_MASK                    = 0x01800000;
1637
1638    /**
1639     * Indicates a prepressed state;
1640     * the short time between ACTION_DOWN and recognizing
1641     * a 'real' press. Prepressed is used to recognize quick taps
1642     * even when they are shorter than ViewConfiguration.getTapTimeout().
1643     *
1644     * @hide
1645     */
1646    private static final int PREPRESSED             = 0x02000000;
1647
1648    /**
1649     * Indicates whether the view is temporarily detached.
1650     *
1651     * @hide
1652     */
1653    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1654
1655    /**
1656     * Indicates that we should awaken scroll bars once attached
1657     *
1658     * @hide
1659     */
1660    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1661
1662    /**
1663     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1664     * @hide
1665     */
1666    private static final int HOVERED              = 0x10000000;
1667
1668    /**
1669     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1670     * for transform operations
1671     *
1672     * @hide
1673     */
1674    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1675
1676    /** {@hide} */
1677    static final int ACTIVATED                    = 0x40000000;
1678
1679    /**
1680     * Indicates that this view was specifically invalidated, not just dirtied because some
1681     * child view was invalidated. The flag is used to determine when we need to recreate
1682     * a view's display list (as opposed to just returning a reference to its existing
1683     * display list).
1684     *
1685     * @hide
1686     */
1687    static final int INVALIDATED                  = 0x80000000;
1688
1689    /* Masks for mPrivateFlags2 */
1690
1691    /**
1692     * Indicates that this view has reported that it can accept the current drag's content.
1693     * Cleared when the drag operation concludes.
1694     * @hide
1695     */
1696    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1697
1698    /**
1699     * Indicates that this view is currently directly under the drag location in a
1700     * drag-and-drop operation involving content that it can accept.  Cleared when
1701     * the drag exits the view, or when the drag operation concludes.
1702     * @hide
1703     */
1704    static final int DRAG_HOVERED                 = 0x00000002;
1705
1706    /**
1707     * Horizontal layout direction of this view is from Left to Right.
1708     * Use with {@link #setLayoutDirection}.
1709     */
1710    public static final int LAYOUT_DIRECTION_LTR = 0x00000001;
1711
1712    /**
1713     * Horizontal layout direction of this view is from Right to Left.
1714     * Use with {@link #setLayoutDirection}.
1715     */
1716    public static final int LAYOUT_DIRECTION_RTL = 0x00000002;
1717
1718    /**
1719     * Horizontal layout direction of this view is inherited from its parent.
1720     * Use with {@link #setLayoutDirection}.
1721     */
1722    public static final int LAYOUT_DIRECTION_INHERIT = 0x00000004;
1723
1724    /**
1725     * Horizontal layout direction of this view is from deduced from the default language
1726     * script for the locale. Use with {@link #setLayoutDirection}.
1727     */
1728    public static final int LAYOUT_DIRECTION_LOCALE = 0x00000008;
1729
1730    /**
1731     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1732     * @hide
1733     */
1734    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1735
1736    /**
1737     * Mask for use with private flags indicating bits used for horizontal layout direction.
1738     * @hide
1739     */
1740    static final int LAYOUT_DIRECTION_MASK = 0x0000000F << LAYOUT_DIRECTION_MASK_SHIFT;
1741
1742    /**
1743     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1744     * right-to-left direction.
1745     * @hide
1746     */
1747    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000010 << LAYOUT_DIRECTION_MASK_SHIFT;
1748
1749    /**
1750     * Indicates whether the view horizontal layout direction has been resolved.
1751     * @hide
1752     */
1753    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000020 << LAYOUT_DIRECTION_MASK_SHIFT;
1754
1755    /**
1756     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1757     * @hide
1758     */
1759    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x00000030 << LAYOUT_DIRECTION_MASK_SHIFT;
1760
1761    /*
1762     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1763     * flag value.
1764     * @hide
1765     */
1766    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
1767            LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
1768
1769    /**
1770     * Default horizontal layout direction.
1771     * @hide
1772     */
1773    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1774
1775
1776    /**
1777     * Indicates that the view is tracking some sort of transient state
1778     * that the app should not need to be aware of, but that the framework
1779     * should take special care to preserve.
1780     *
1781     * @hide
1782     */
1783    static final int HAS_TRANSIENT_STATE = 0x00000100;
1784
1785
1786    /* End of masks for mPrivateFlags2 */
1787
1788    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1789
1790    /**
1791     * Always allow a user to over-scroll this view, provided it is a
1792     * view that can scroll.
1793     *
1794     * @see #getOverScrollMode()
1795     * @see #setOverScrollMode(int)
1796     */
1797    public static final int OVER_SCROLL_ALWAYS = 0;
1798
1799    /**
1800     * Allow a user to over-scroll this view only if the content is large
1801     * enough to meaningfully scroll, provided it is a view that can scroll.
1802     *
1803     * @see #getOverScrollMode()
1804     * @see #setOverScrollMode(int)
1805     */
1806    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1807
1808    /**
1809     * Never allow a user to over-scroll this view.
1810     *
1811     * @see #getOverScrollMode()
1812     * @see #setOverScrollMode(int)
1813     */
1814    public static final int OVER_SCROLL_NEVER = 2;
1815
1816    /**
1817     * View has requested the system UI (status bar) to be visible (the default).
1818     *
1819     * @see #setSystemUiVisibility(int)
1820     */
1821    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1822
1823    /**
1824     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1825     *
1826     * This is for use in games, book readers, video players, or any other "immersive" application
1827     * where the usual system chrome is deemed too distracting.
1828     *
1829     * In low profile mode, the status bar and/or navigation icons may dim.
1830     *
1831     * @see #setSystemUiVisibility(int)
1832     */
1833    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1834
1835    /**
1836     * View has requested that the system navigation be temporarily hidden.
1837     *
1838     * This is an even less obtrusive state than that called for by
1839     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1840     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1841     * those to disappear. This is useful (in conjunction with the
1842     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1843     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1844     * window flags) for displaying content using every last pixel on the display.
1845     *
1846     * There is a limitation: because navigation controls are so important, the least user
1847     * interaction will cause them to reappear immediately.
1848     *
1849     * @see #setSystemUiVisibility(int)
1850     */
1851    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1852
1853    /**
1854     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1855     */
1856    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1857
1858    /**
1859     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1860     */
1861    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1862
1863    /**
1864     * @hide
1865     *
1866     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1867     * out of the public fields to keep the undefined bits out of the developer's way.
1868     *
1869     * Flag to make the status bar not expandable.  Unless you also
1870     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1871     */
1872    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1873
1874    /**
1875     * @hide
1876     *
1877     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1878     * out of the public fields to keep the undefined bits out of the developer's way.
1879     *
1880     * Flag to hide notification icons and scrolling ticker text.
1881     */
1882    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1883
1884    /**
1885     * @hide
1886     *
1887     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1888     * out of the public fields to keep the undefined bits out of the developer's way.
1889     *
1890     * Flag to disable incoming notification alerts.  This will not block
1891     * icons, but it will block sound, vibrating and other visual or aural notifications.
1892     */
1893    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1894
1895    /**
1896     * @hide
1897     *
1898     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1899     * out of the public fields to keep the undefined bits out of the developer's way.
1900     *
1901     * Flag to hide only the scrolling ticker.  Note that
1902     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1903     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1904     */
1905    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1906
1907    /**
1908     * @hide
1909     *
1910     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1911     * out of the public fields to keep the undefined bits out of the developer's way.
1912     *
1913     * Flag to hide the center system info area.
1914     */
1915    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1916
1917    /**
1918     * @hide
1919     *
1920     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1921     * out of the public fields to keep the undefined bits out of the developer's way.
1922     *
1923     * Flag to hide only the home button.  Don't use this
1924     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1925     */
1926    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
1927
1928    /**
1929     * @hide
1930     *
1931     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1932     * out of the public fields to keep the undefined bits out of the developer's way.
1933     *
1934     * Flag to hide only the back button. Don't use this
1935     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1936     */
1937    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1938
1939    /**
1940     * @hide
1941     *
1942     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1943     * out of the public fields to keep the undefined bits out of the developer's way.
1944     *
1945     * Flag to hide only the clock.  You might use this if your activity has
1946     * its own clock making the status bar's clock redundant.
1947     */
1948    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1949
1950    /**
1951     * @hide
1952     *
1953     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1954     * out of the public fields to keep the undefined bits out of the developer's way.
1955     *
1956     * Flag to hide only the recent apps button. Don't use this
1957     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1958     */
1959    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
1960
1961    /**
1962     * @hide
1963     *
1964     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
1965     *
1966     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
1967     */
1968    @Deprecated
1969    public static final int STATUS_BAR_DISABLE_NAVIGATION =
1970            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
1971
1972    /**
1973     * @hide
1974     */
1975    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1976
1977    /**
1978     * These are the system UI flags that can be cleared by events outside
1979     * of an application.  Currently this is just the ability to tap on the
1980     * screen while hiding the navigation bar to have it return.
1981     * @hide
1982     */
1983    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1984            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1985
1986    /**
1987     * Find views that render the specified text.
1988     *
1989     * @see #findViewsWithText(ArrayList, CharSequence, int)
1990     */
1991    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1992
1993    /**
1994     * Find find views that contain the specified content description.
1995     *
1996     * @see #findViewsWithText(ArrayList, CharSequence, int)
1997     */
1998    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1999
2000    /**
2001     * Find views that contain {@link AccessibilityNodeProvider}. Such
2002     * a View is a root of virtual view hierarchy and may contain the searched
2003     * text. If this flag is set Views with providers are automatically
2004     * added and it is a responsibility of the client to call the APIs of
2005     * the provider to determine whether the virtual tree rooted at this View
2006     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2007     * represeting the virtual views with this text.
2008     *
2009     * @see #findViewsWithText(ArrayList, CharSequence, int)
2010     *
2011     * @hide
2012     */
2013    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2014
2015    /**
2016     * Indicates that the screen has changed state and is now off.
2017     *
2018     * @see #onScreenStateChanged(int)
2019     */
2020    public static final int SCREEN_STATE_OFF = 0x0;
2021
2022    /**
2023     * Indicates that the screen has changed state and is now on.
2024     *
2025     * @see #onScreenStateChanged(int)
2026     */
2027    public static final int SCREEN_STATE_ON = 0x1;
2028
2029    /**
2030     * Controls the over-scroll mode for this view.
2031     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2032     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2033     * and {@link #OVER_SCROLL_NEVER}.
2034     */
2035    private int mOverScrollMode;
2036
2037    /**
2038     * The parent this view is attached to.
2039     * {@hide}
2040     *
2041     * @see #getParent()
2042     */
2043    protected ViewParent mParent;
2044
2045    /**
2046     * {@hide}
2047     */
2048    AttachInfo mAttachInfo;
2049
2050    /**
2051     * {@hide}
2052     */
2053    @ViewDebug.ExportedProperty(flagMapping = {
2054        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2055                name = "FORCE_LAYOUT"),
2056        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2057                name = "LAYOUT_REQUIRED"),
2058        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2059            name = "DRAWING_CACHE_INVALID", outputIf = false),
2060        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2061        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2062        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2063        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2064    })
2065    int mPrivateFlags;
2066    int mPrivateFlags2;
2067
2068    /**
2069     * This view's request for the visibility of the status bar.
2070     * @hide
2071     */
2072    @ViewDebug.ExportedProperty(flagMapping = {
2073        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2074                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2075                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2076        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2077                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2078                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2079        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2080                                equals = SYSTEM_UI_FLAG_VISIBLE,
2081                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2082    })
2083    int mSystemUiVisibility;
2084
2085    /**
2086     * Count of how many windows this view has been attached to.
2087     */
2088    int mWindowAttachCount;
2089
2090    /**
2091     * The layout parameters associated with this view and used by the parent
2092     * {@link android.view.ViewGroup} to determine how this view should be
2093     * laid out.
2094     * {@hide}
2095     */
2096    protected ViewGroup.LayoutParams mLayoutParams;
2097
2098    /**
2099     * The view flags hold various views states.
2100     * {@hide}
2101     */
2102    @ViewDebug.ExportedProperty
2103    int mViewFlags;
2104
2105    static class TransformationInfo {
2106        /**
2107         * The transform matrix for the View. This transform is calculated internally
2108         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2109         * is used by default. Do *not* use this variable directly; instead call
2110         * getMatrix(), which will automatically recalculate the matrix if necessary
2111         * to get the correct matrix based on the latest rotation and scale properties.
2112         */
2113        private final Matrix mMatrix = new Matrix();
2114
2115        /**
2116         * The transform matrix for the View. This transform is calculated internally
2117         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2118         * is used by default. Do *not* use this variable directly; instead call
2119         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2120         * to get the correct matrix based on the latest rotation and scale properties.
2121         */
2122        private Matrix mInverseMatrix;
2123
2124        /**
2125         * An internal variable that tracks whether we need to recalculate the
2126         * transform matrix, based on whether the rotation or scaleX/Y properties
2127         * have changed since the matrix was last calculated.
2128         */
2129        boolean mMatrixDirty = false;
2130
2131        /**
2132         * An internal variable that tracks whether we need to recalculate the
2133         * transform matrix, based on whether the rotation or scaleX/Y properties
2134         * have changed since the matrix was last calculated.
2135         */
2136        private boolean mInverseMatrixDirty = true;
2137
2138        /**
2139         * A variable that tracks whether we need to recalculate the
2140         * transform matrix, based on whether the rotation or scaleX/Y properties
2141         * have changed since the matrix was last calculated. This variable
2142         * is only valid after a call to updateMatrix() or to a function that
2143         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2144         */
2145        private boolean mMatrixIsIdentity = true;
2146
2147        /**
2148         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2149         */
2150        private Camera mCamera = null;
2151
2152        /**
2153         * This matrix is used when computing the matrix for 3D rotations.
2154         */
2155        private Matrix matrix3D = null;
2156
2157        /**
2158         * These prev values are used to recalculate a centered pivot point when necessary. The
2159         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2160         * set), so thes values are only used then as well.
2161         */
2162        private int mPrevWidth = -1;
2163        private int mPrevHeight = -1;
2164
2165        /**
2166         * The degrees rotation around the vertical axis through the pivot point.
2167         */
2168        @ViewDebug.ExportedProperty
2169        float mRotationY = 0f;
2170
2171        /**
2172         * The degrees rotation around the horizontal axis through the pivot point.
2173         */
2174        @ViewDebug.ExportedProperty
2175        float mRotationX = 0f;
2176
2177        /**
2178         * The degrees rotation around the pivot point.
2179         */
2180        @ViewDebug.ExportedProperty
2181        float mRotation = 0f;
2182
2183        /**
2184         * The amount of translation of the object away from its left property (post-layout).
2185         */
2186        @ViewDebug.ExportedProperty
2187        float mTranslationX = 0f;
2188
2189        /**
2190         * The amount of translation of the object away from its top property (post-layout).
2191         */
2192        @ViewDebug.ExportedProperty
2193        float mTranslationY = 0f;
2194
2195        /**
2196         * The amount of scale in the x direction around the pivot point. A
2197         * value of 1 means no scaling is applied.
2198         */
2199        @ViewDebug.ExportedProperty
2200        float mScaleX = 1f;
2201
2202        /**
2203         * The amount of scale in the y direction around the pivot point. A
2204         * value of 1 means no scaling is applied.
2205         */
2206        @ViewDebug.ExportedProperty
2207        float mScaleY = 1f;
2208
2209        /**
2210         * The x location of the point around which the view is rotated and scaled.
2211         */
2212        @ViewDebug.ExportedProperty
2213        float mPivotX = 0f;
2214
2215        /**
2216         * The y location of the point around which the view is rotated and scaled.
2217         */
2218        @ViewDebug.ExportedProperty
2219        float mPivotY = 0f;
2220
2221        /**
2222         * The opacity of the View. This is a value from 0 to 1, where 0 means
2223         * completely transparent and 1 means completely opaque.
2224         */
2225        @ViewDebug.ExportedProperty
2226        float mAlpha = 1f;
2227    }
2228
2229    TransformationInfo mTransformationInfo;
2230
2231    private boolean mLastIsOpaque;
2232
2233    /**
2234     * Convenience value to check for float values that are close enough to zero to be considered
2235     * zero.
2236     */
2237    private static final float NONZERO_EPSILON = .001f;
2238
2239    /**
2240     * The distance in pixels from the left edge of this view's parent
2241     * to the left edge of this view.
2242     * {@hide}
2243     */
2244    @ViewDebug.ExportedProperty(category = "layout")
2245    protected int mLeft;
2246    /**
2247     * The distance in pixels from the left edge of this view's parent
2248     * to the right edge of this view.
2249     * {@hide}
2250     */
2251    @ViewDebug.ExportedProperty(category = "layout")
2252    protected int mRight;
2253    /**
2254     * The distance in pixels from the top edge of this view's parent
2255     * to the top edge of this view.
2256     * {@hide}
2257     */
2258    @ViewDebug.ExportedProperty(category = "layout")
2259    protected int mTop;
2260    /**
2261     * The distance in pixels from the top edge of this view's parent
2262     * to the bottom edge of this view.
2263     * {@hide}
2264     */
2265    @ViewDebug.ExportedProperty(category = "layout")
2266    protected int mBottom;
2267
2268    /**
2269     * The offset, in pixels, by which the content of this view is scrolled
2270     * horizontally.
2271     * {@hide}
2272     */
2273    @ViewDebug.ExportedProperty(category = "scrolling")
2274    protected int mScrollX;
2275    /**
2276     * The offset, in pixels, by which the content of this view is scrolled
2277     * vertically.
2278     * {@hide}
2279     */
2280    @ViewDebug.ExportedProperty(category = "scrolling")
2281    protected int mScrollY;
2282
2283    /**
2284     * The left padding in pixels, that is the distance in pixels between the
2285     * left edge of this view and the left edge of its content.
2286     * {@hide}
2287     */
2288    @ViewDebug.ExportedProperty(category = "padding")
2289    protected int mPaddingLeft;
2290    /**
2291     * The right padding in pixels, that is the distance in pixels between the
2292     * right edge of this view and the right edge of its content.
2293     * {@hide}
2294     */
2295    @ViewDebug.ExportedProperty(category = "padding")
2296    protected int mPaddingRight;
2297    /**
2298     * The top padding in pixels, that is the distance in pixels between the
2299     * top edge of this view and the top edge of its content.
2300     * {@hide}
2301     */
2302    @ViewDebug.ExportedProperty(category = "padding")
2303    protected int mPaddingTop;
2304    /**
2305     * The bottom padding in pixels, that is the distance in pixels between the
2306     * bottom edge of this view and the bottom edge of its content.
2307     * {@hide}
2308     */
2309    @ViewDebug.ExportedProperty(category = "padding")
2310    protected int mPaddingBottom;
2311
2312    /**
2313     * Briefly describes the view and is primarily used for accessibility support.
2314     */
2315    private CharSequence mContentDescription;
2316
2317    /**
2318     * Cache the paddingRight set by the user to append to the scrollbar's size.
2319     *
2320     * @hide
2321     */
2322    @ViewDebug.ExportedProperty(category = "padding")
2323    protected int mUserPaddingRight;
2324
2325    /**
2326     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2327     *
2328     * @hide
2329     */
2330    @ViewDebug.ExportedProperty(category = "padding")
2331    protected int mUserPaddingBottom;
2332
2333    /**
2334     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2335     *
2336     * @hide
2337     */
2338    @ViewDebug.ExportedProperty(category = "padding")
2339    protected int mUserPaddingLeft;
2340
2341    /**
2342     * Cache if the user padding is relative.
2343     *
2344     */
2345    @ViewDebug.ExportedProperty(category = "padding")
2346    boolean mUserPaddingRelative;
2347
2348    /**
2349     * Cache the paddingStart set by the user to append to the scrollbar's size.
2350     *
2351     */
2352    @ViewDebug.ExportedProperty(category = "padding")
2353    int mUserPaddingStart;
2354
2355    /**
2356     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2357     *
2358     */
2359    @ViewDebug.ExportedProperty(category = "padding")
2360    int mUserPaddingEnd;
2361
2362    /**
2363     * @hide
2364     */
2365    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2366    /**
2367     * @hide
2368     */
2369    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2370
2371    private Drawable mBGDrawable;
2372
2373    private int mBackgroundResource;
2374    private boolean mBackgroundSizeChanged;
2375
2376    static class ListenerInfo {
2377        /**
2378         * Listener used to dispatch focus change events.
2379         * This field should be made private, so it is hidden from the SDK.
2380         * {@hide}
2381         */
2382        protected OnFocusChangeListener mOnFocusChangeListener;
2383
2384        /**
2385         * Listeners for layout change events.
2386         */
2387        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2388
2389        /**
2390         * Listeners for attach events.
2391         */
2392        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2393
2394        /**
2395         * Listener used to dispatch click events.
2396         * This field should be made private, so it is hidden from the SDK.
2397         * {@hide}
2398         */
2399        public OnClickListener mOnClickListener;
2400
2401        /**
2402         * Listener used to dispatch long click events.
2403         * This field should be made private, so it is hidden from the SDK.
2404         * {@hide}
2405         */
2406        protected OnLongClickListener mOnLongClickListener;
2407
2408        /**
2409         * Listener used to build the context menu.
2410         * This field should be made private, so it is hidden from the SDK.
2411         * {@hide}
2412         */
2413        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2414
2415        private OnKeyListener mOnKeyListener;
2416
2417        private OnTouchListener mOnTouchListener;
2418
2419        private OnHoverListener mOnHoverListener;
2420
2421        private OnGenericMotionListener mOnGenericMotionListener;
2422
2423        private OnDragListener mOnDragListener;
2424
2425        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2426    }
2427
2428    ListenerInfo mListenerInfo;
2429
2430    /**
2431     * The application environment this view lives in.
2432     * This field should be made private, so it is hidden from the SDK.
2433     * {@hide}
2434     */
2435    protected Context mContext;
2436
2437    private final Resources mResources;
2438
2439    private ScrollabilityCache mScrollCache;
2440
2441    private int[] mDrawableState = null;
2442
2443    /**
2444     * Set to true when drawing cache is enabled and cannot be created.
2445     *
2446     * @hide
2447     */
2448    public boolean mCachingFailed;
2449
2450    private Bitmap mDrawingCache;
2451    private Bitmap mUnscaledDrawingCache;
2452    private HardwareLayer mHardwareLayer;
2453    DisplayList mDisplayList;
2454
2455    /**
2456     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2457     * the user may specify which view to go to next.
2458     */
2459    private int mNextFocusLeftId = View.NO_ID;
2460
2461    /**
2462     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2463     * the user may specify which view to go to next.
2464     */
2465    private int mNextFocusRightId = View.NO_ID;
2466
2467    /**
2468     * When this view has focus and the next focus is {@link #FOCUS_UP},
2469     * the user may specify which view to go to next.
2470     */
2471    private int mNextFocusUpId = View.NO_ID;
2472
2473    /**
2474     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2475     * the user may specify which view to go to next.
2476     */
2477    private int mNextFocusDownId = View.NO_ID;
2478
2479    /**
2480     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2481     * the user may specify which view to go to next.
2482     */
2483    int mNextFocusForwardId = View.NO_ID;
2484
2485    private CheckForLongPress mPendingCheckForLongPress;
2486    private CheckForTap mPendingCheckForTap = null;
2487    private PerformClick mPerformClick;
2488    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2489
2490    private UnsetPressedState mUnsetPressedState;
2491
2492    /**
2493     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2494     * up event while a long press is invoked as soon as the long press duration is reached, so
2495     * a long press could be performed before the tap is checked, in which case the tap's action
2496     * should not be invoked.
2497     */
2498    private boolean mHasPerformedLongPress;
2499
2500    /**
2501     * The minimum height of the view. We'll try our best to have the height
2502     * of this view to at least this amount.
2503     */
2504    @ViewDebug.ExportedProperty(category = "measurement")
2505    private int mMinHeight;
2506
2507    /**
2508     * The minimum width of the view. We'll try our best to have the width
2509     * of this view to at least this amount.
2510     */
2511    @ViewDebug.ExportedProperty(category = "measurement")
2512    private int mMinWidth;
2513
2514    /**
2515     * The delegate to handle touch events that are physically in this view
2516     * but should be handled by another view.
2517     */
2518    private TouchDelegate mTouchDelegate = null;
2519
2520    /**
2521     * Solid color to use as a background when creating the drawing cache. Enables
2522     * the cache to use 16 bit bitmaps instead of 32 bit.
2523     */
2524    private int mDrawingCacheBackgroundColor = 0;
2525
2526    /**
2527     * Special tree observer used when mAttachInfo is null.
2528     */
2529    private ViewTreeObserver mFloatingTreeObserver;
2530
2531    /**
2532     * Cache the touch slop from the context that created the view.
2533     */
2534    private int mTouchSlop;
2535
2536    /**
2537     * Object that handles automatic animation of view properties.
2538     */
2539    private ViewPropertyAnimator mAnimator = null;
2540
2541    /**
2542     * Flag indicating that a drag can cross window boundaries.  When
2543     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2544     * with this flag set, all visible applications will be able to participate
2545     * in the drag operation and receive the dragged content.
2546     *
2547     * @hide
2548     */
2549    public static final int DRAG_FLAG_GLOBAL = 1;
2550
2551    /**
2552     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2553     */
2554    private float mVerticalScrollFactor;
2555
2556    /**
2557     * Position of the vertical scroll bar.
2558     */
2559    private int mVerticalScrollbarPosition;
2560
2561    /**
2562     * Position the scroll bar at the default position as determined by the system.
2563     */
2564    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2565
2566    /**
2567     * Position the scroll bar along the left edge.
2568     */
2569    public static final int SCROLLBAR_POSITION_LEFT = 1;
2570
2571    /**
2572     * Position the scroll bar along the right edge.
2573     */
2574    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2575
2576    /**
2577     * Indicates that the view does not have a layer.
2578     *
2579     * @see #getLayerType()
2580     * @see #setLayerType(int, android.graphics.Paint)
2581     * @see #LAYER_TYPE_SOFTWARE
2582     * @see #LAYER_TYPE_HARDWARE
2583     */
2584    public static final int LAYER_TYPE_NONE = 0;
2585
2586    /**
2587     * <p>Indicates that the view has a software layer. A software layer is backed
2588     * by a bitmap and causes the view to be rendered using Android's software
2589     * rendering pipeline, even if hardware acceleration is enabled.</p>
2590     *
2591     * <p>Software layers have various usages:</p>
2592     * <p>When the application is not using hardware acceleration, a software layer
2593     * is useful to apply a specific color filter and/or blending mode and/or
2594     * translucency to a view and all its children.</p>
2595     * <p>When the application is using hardware acceleration, a software layer
2596     * is useful to render drawing primitives not supported by the hardware
2597     * accelerated pipeline. It can also be used to cache a complex view tree
2598     * into a texture and reduce the complexity of drawing operations. For instance,
2599     * when animating a complex view tree with a translation, a software layer can
2600     * be used to render the view tree only once.</p>
2601     * <p>Software layers should be avoided when the affected view tree updates
2602     * often. Every update will require to re-render the software layer, which can
2603     * potentially be slow (particularly when hardware acceleration is turned on
2604     * since the layer will have to be uploaded into a hardware texture after every
2605     * update.)</p>
2606     *
2607     * @see #getLayerType()
2608     * @see #setLayerType(int, android.graphics.Paint)
2609     * @see #LAYER_TYPE_NONE
2610     * @see #LAYER_TYPE_HARDWARE
2611     */
2612    public static final int LAYER_TYPE_SOFTWARE = 1;
2613
2614    /**
2615     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2616     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2617     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2618     * rendering pipeline, but only if hardware acceleration is turned on for the
2619     * view hierarchy. When hardware acceleration is turned off, hardware layers
2620     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2621     *
2622     * <p>A hardware layer is useful to apply a specific color filter and/or
2623     * blending mode and/or translucency to a view and all its children.</p>
2624     * <p>A hardware layer can be used to cache a complex view tree into a
2625     * texture and reduce the complexity of drawing operations. For instance,
2626     * when animating a complex view tree with a translation, a hardware layer can
2627     * be used to render the view tree only once.</p>
2628     * <p>A hardware layer can also be used to increase the rendering quality when
2629     * rotation transformations are applied on a view. It can also be used to
2630     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2631     *
2632     * @see #getLayerType()
2633     * @see #setLayerType(int, android.graphics.Paint)
2634     * @see #LAYER_TYPE_NONE
2635     * @see #LAYER_TYPE_SOFTWARE
2636     */
2637    public static final int LAYER_TYPE_HARDWARE = 2;
2638
2639    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2640            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2641            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2642            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2643    })
2644    int mLayerType = LAYER_TYPE_NONE;
2645    Paint mLayerPaint;
2646    Rect mLocalDirtyRect;
2647
2648    /**
2649     * Set to true when the view is sending hover accessibility events because it
2650     * is the innermost hovered view.
2651     */
2652    private boolean mSendingHoverAccessibilityEvents;
2653
2654    /**
2655     * Delegate for injecting accessiblity functionality.
2656     */
2657    AccessibilityDelegate mAccessibilityDelegate;
2658
2659    /**
2660     * Text direction is inherited thru {@link ViewGroup}
2661     */
2662    public static final int TEXT_DIRECTION_INHERIT = 0;
2663
2664    /**
2665     * Text direction is using "first strong algorithm". The first strong directional character
2666     * determines the paragraph direction. If there is no strong directional character, the
2667     * paragraph direction is the view's resolved layout direction.
2668     *
2669     */
2670    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2671
2672    /**
2673     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2674     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2675     * If there are neither, the paragraph direction is the view's resolved layout direction.
2676     *
2677     */
2678    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2679
2680    /**
2681     * Text direction is forced to LTR.
2682     *
2683     */
2684    public static final int TEXT_DIRECTION_LTR = 3;
2685
2686    /**
2687     * Text direction is forced to RTL.
2688     *
2689     */
2690    public static final int TEXT_DIRECTION_RTL = 4;
2691
2692    /**
2693     * Text direction is coming from the system Locale.
2694     *
2695     */
2696    public static final int TEXT_DIRECTION_LOCALE = 5;
2697
2698    /**
2699     * Default text direction is inherited
2700     *
2701     */
2702    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2703
2704    /**
2705     * The text direction that has been defined by {@link #setTextDirection(int)}.
2706     *
2707     */
2708    @ViewDebug.ExportedProperty(category = "text", mapping = {
2709            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2710            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2711            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2712            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2713            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2714            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2715    })
2716    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2717
2718    /**
2719     * The resolved text direction.  This needs resolution if the value is
2720     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if it is
2721     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2722     * chain of the view.
2723     *
2724     */
2725    @ViewDebug.ExportedProperty(category = "text", mapping = {
2726            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2727            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2728            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2729            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2730            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2731            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2732    })
2733    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2734
2735    /**
2736     * Consistency verifier for debugging purposes.
2737     * @hide
2738     */
2739    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2740            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2741                    new InputEventConsistencyVerifier(this, 0) : null;
2742
2743    /**
2744     * Simple constructor to use when creating a view from code.
2745     *
2746     * @param context The Context the view is running in, through which it can
2747     *        access the current theme, resources, etc.
2748     */
2749    public View(Context context) {
2750        mContext = context;
2751        mResources = context != null ? context.getResources() : null;
2752        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
2753        mPrivateFlags2 |= (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT);
2754        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2755        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2756        mUserPaddingStart = -1;
2757        mUserPaddingEnd = -1;
2758        mUserPaddingRelative = false;
2759    }
2760
2761    /**
2762     * Constructor that is called when inflating a view from XML. This is called
2763     * when a view is being constructed from an XML file, supplying attributes
2764     * that were specified in the XML file. This version uses a default style of
2765     * 0, so the only attribute values applied are those in the Context's Theme
2766     * and the given AttributeSet.
2767     *
2768     * <p>
2769     * The method onFinishInflate() will be called after all children have been
2770     * added.
2771     *
2772     * @param context The Context the view is running in, through which it can
2773     *        access the current theme, resources, etc.
2774     * @param attrs The attributes of the XML tag that is inflating the view.
2775     * @see #View(Context, AttributeSet, int)
2776     */
2777    public View(Context context, AttributeSet attrs) {
2778        this(context, attrs, 0);
2779    }
2780
2781    /**
2782     * Perform inflation from XML and apply a class-specific base style. This
2783     * constructor of View allows subclasses to use their own base style when
2784     * they are inflating. For example, a Button class's constructor would call
2785     * this version of the super class constructor and supply
2786     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2787     * the theme's button style to modify all of the base view attributes (in
2788     * particular its background) as well as the Button class's attributes.
2789     *
2790     * @param context The Context the view is running in, through which it can
2791     *        access the current theme, resources, etc.
2792     * @param attrs The attributes of the XML tag that is inflating the view.
2793     * @param defStyle The default style to apply to this view. If 0, no style
2794     *        will be applied (beyond what is included in the theme). This may
2795     *        either be an attribute resource, whose value will be retrieved
2796     *        from the current theme, or an explicit style resource.
2797     * @see #View(Context, AttributeSet)
2798     */
2799    public View(Context context, AttributeSet attrs, int defStyle) {
2800        this(context);
2801
2802        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2803                defStyle, 0);
2804
2805        Drawable background = null;
2806
2807        int leftPadding = -1;
2808        int topPadding = -1;
2809        int rightPadding = -1;
2810        int bottomPadding = -1;
2811        int startPadding = -1;
2812        int endPadding = -1;
2813
2814        int padding = -1;
2815
2816        int viewFlagValues = 0;
2817        int viewFlagMasks = 0;
2818
2819        boolean setScrollContainer = false;
2820
2821        int x = 0;
2822        int y = 0;
2823
2824        float tx = 0;
2825        float ty = 0;
2826        float rotation = 0;
2827        float rotationX = 0;
2828        float rotationY = 0;
2829        float sx = 1f;
2830        float sy = 1f;
2831        boolean transformSet = false;
2832
2833        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2834
2835        int overScrollMode = mOverScrollMode;
2836        final int N = a.getIndexCount();
2837        for (int i = 0; i < N; i++) {
2838            int attr = a.getIndex(i);
2839            switch (attr) {
2840                case com.android.internal.R.styleable.View_background:
2841                    background = a.getDrawable(attr);
2842                    break;
2843                case com.android.internal.R.styleable.View_padding:
2844                    padding = a.getDimensionPixelSize(attr, -1);
2845                    break;
2846                 case com.android.internal.R.styleable.View_paddingLeft:
2847                    leftPadding = a.getDimensionPixelSize(attr, -1);
2848                    break;
2849                case com.android.internal.R.styleable.View_paddingTop:
2850                    topPadding = a.getDimensionPixelSize(attr, -1);
2851                    break;
2852                case com.android.internal.R.styleable.View_paddingRight:
2853                    rightPadding = a.getDimensionPixelSize(attr, -1);
2854                    break;
2855                case com.android.internal.R.styleable.View_paddingBottom:
2856                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2857                    break;
2858                case com.android.internal.R.styleable.View_paddingStart:
2859                    startPadding = a.getDimensionPixelSize(attr, -1);
2860                    break;
2861                case com.android.internal.R.styleable.View_paddingEnd:
2862                    endPadding = a.getDimensionPixelSize(attr, -1);
2863                    break;
2864                case com.android.internal.R.styleable.View_scrollX:
2865                    x = a.getDimensionPixelOffset(attr, 0);
2866                    break;
2867                case com.android.internal.R.styleable.View_scrollY:
2868                    y = a.getDimensionPixelOffset(attr, 0);
2869                    break;
2870                case com.android.internal.R.styleable.View_alpha:
2871                    setAlpha(a.getFloat(attr, 1f));
2872                    break;
2873                case com.android.internal.R.styleable.View_transformPivotX:
2874                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2875                    break;
2876                case com.android.internal.R.styleable.View_transformPivotY:
2877                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2878                    break;
2879                case com.android.internal.R.styleable.View_translationX:
2880                    tx = a.getDimensionPixelOffset(attr, 0);
2881                    transformSet = true;
2882                    break;
2883                case com.android.internal.R.styleable.View_translationY:
2884                    ty = a.getDimensionPixelOffset(attr, 0);
2885                    transformSet = true;
2886                    break;
2887                case com.android.internal.R.styleable.View_rotation:
2888                    rotation = a.getFloat(attr, 0);
2889                    transformSet = true;
2890                    break;
2891                case com.android.internal.R.styleable.View_rotationX:
2892                    rotationX = a.getFloat(attr, 0);
2893                    transformSet = true;
2894                    break;
2895                case com.android.internal.R.styleable.View_rotationY:
2896                    rotationY = a.getFloat(attr, 0);
2897                    transformSet = true;
2898                    break;
2899                case com.android.internal.R.styleable.View_scaleX:
2900                    sx = a.getFloat(attr, 1f);
2901                    transformSet = true;
2902                    break;
2903                case com.android.internal.R.styleable.View_scaleY:
2904                    sy = a.getFloat(attr, 1f);
2905                    transformSet = true;
2906                    break;
2907                case com.android.internal.R.styleable.View_id:
2908                    mID = a.getResourceId(attr, NO_ID);
2909                    break;
2910                case com.android.internal.R.styleable.View_tag:
2911                    mTag = a.getText(attr);
2912                    break;
2913                case com.android.internal.R.styleable.View_fitsSystemWindows:
2914                    if (a.getBoolean(attr, false)) {
2915                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2916                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2917                    }
2918                    break;
2919                case com.android.internal.R.styleable.View_focusable:
2920                    if (a.getBoolean(attr, false)) {
2921                        viewFlagValues |= FOCUSABLE;
2922                        viewFlagMasks |= FOCUSABLE_MASK;
2923                    }
2924                    break;
2925                case com.android.internal.R.styleable.View_focusableInTouchMode:
2926                    if (a.getBoolean(attr, false)) {
2927                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2928                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2929                    }
2930                    break;
2931                case com.android.internal.R.styleable.View_clickable:
2932                    if (a.getBoolean(attr, false)) {
2933                        viewFlagValues |= CLICKABLE;
2934                        viewFlagMasks |= CLICKABLE;
2935                    }
2936                    break;
2937                case com.android.internal.R.styleable.View_longClickable:
2938                    if (a.getBoolean(attr, false)) {
2939                        viewFlagValues |= LONG_CLICKABLE;
2940                        viewFlagMasks |= LONG_CLICKABLE;
2941                    }
2942                    break;
2943                case com.android.internal.R.styleable.View_saveEnabled:
2944                    if (!a.getBoolean(attr, true)) {
2945                        viewFlagValues |= SAVE_DISABLED;
2946                        viewFlagMasks |= SAVE_DISABLED_MASK;
2947                    }
2948                    break;
2949                case com.android.internal.R.styleable.View_duplicateParentState:
2950                    if (a.getBoolean(attr, false)) {
2951                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2952                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2953                    }
2954                    break;
2955                case com.android.internal.R.styleable.View_visibility:
2956                    final int visibility = a.getInt(attr, 0);
2957                    if (visibility != 0) {
2958                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2959                        viewFlagMasks |= VISIBILITY_MASK;
2960                    }
2961                    break;
2962                case com.android.internal.R.styleable.View_layoutDirection:
2963                    // Clear any layout direction flags (included resolved bits) already set
2964                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
2965                    // Set the layout direction flags depending on the value of the attribute
2966                    final int layoutDirection = a.getInt(attr, -1);
2967                    final int value = (layoutDirection != -1) ?
2968                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
2969                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
2970                    break;
2971                case com.android.internal.R.styleable.View_drawingCacheQuality:
2972                    final int cacheQuality = a.getInt(attr, 0);
2973                    if (cacheQuality != 0) {
2974                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2975                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2976                    }
2977                    break;
2978                case com.android.internal.R.styleable.View_contentDescription:
2979                    mContentDescription = a.getString(attr);
2980                    break;
2981                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2982                    if (!a.getBoolean(attr, true)) {
2983                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2984                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2985                    }
2986                    break;
2987                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2988                    if (!a.getBoolean(attr, true)) {
2989                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2990                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2991                    }
2992                    break;
2993                case R.styleable.View_scrollbars:
2994                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2995                    if (scrollbars != SCROLLBARS_NONE) {
2996                        viewFlagValues |= scrollbars;
2997                        viewFlagMasks |= SCROLLBARS_MASK;
2998                        initializeScrollbars(a);
2999                    }
3000                    break;
3001                //noinspection deprecation
3002                case R.styleable.View_fadingEdge:
3003                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3004                        // Ignore the attribute starting with ICS
3005                        break;
3006                    }
3007                    // With builds < ICS, fall through and apply fading edges
3008                case R.styleable.View_requiresFadingEdge:
3009                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3010                    if (fadingEdge != FADING_EDGE_NONE) {
3011                        viewFlagValues |= fadingEdge;
3012                        viewFlagMasks |= FADING_EDGE_MASK;
3013                        initializeFadingEdge(a);
3014                    }
3015                    break;
3016                case R.styleable.View_scrollbarStyle:
3017                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3018                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3019                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3020                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3021                    }
3022                    break;
3023                case R.styleable.View_isScrollContainer:
3024                    setScrollContainer = true;
3025                    if (a.getBoolean(attr, false)) {
3026                        setScrollContainer(true);
3027                    }
3028                    break;
3029                case com.android.internal.R.styleable.View_keepScreenOn:
3030                    if (a.getBoolean(attr, false)) {
3031                        viewFlagValues |= KEEP_SCREEN_ON;
3032                        viewFlagMasks |= KEEP_SCREEN_ON;
3033                    }
3034                    break;
3035                case R.styleable.View_filterTouchesWhenObscured:
3036                    if (a.getBoolean(attr, false)) {
3037                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3038                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3039                    }
3040                    break;
3041                case R.styleable.View_nextFocusLeft:
3042                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3043                    break;
3044                case R.styleable.View_nextFocusRight:
3045                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3046                    break;
3047                case R.styleable.View_nextFocusUp:
3048                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3049                    break;
3050                case R.styleable.View_nextFocusDown:
3051                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3052                    break;
3053                case R.styleable.View_nextFocusForward:
3054                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3055                    break;
3056                case R.styleable.View_minWidth:
3057                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3058                    break;
3059                case R.styleable.View_minHeight:
3060                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3061                    break;
3062                case R.styleable.View_onClick:
3063                    if (context.isRestricted()) {
3064                        throw new IllegalStateException("The android:onClick attribute cannot "
3065                                + "be used within a restricted context");
3066                    }
3067
3068                    final String handlerName = a.getString(attr);
3069                    if (handlerName != null) {
3070                        setOnClickListener(new OnClickListener() {
3071                            private Method mHandler;
3072
3073                            public void onClick(View v) {
3074                                if (mHandler == null) {
3075                                    try {
3076                                        mHandler = getContext().getClass().getMethod(handlerName,
3077                                                View.class);
3078                                    } catch (NoSuchMethodException e) {
3079                                        int id = getId();
3080                                        String idText = id == NO_ID ? "" : " with id '"
3081                                                + getContext().getResources().getResourceEntryName(
3082                                                    id) + "'";
3083                                        throw new IllegalStateException("Could not find a method " +
3084                                                handlerName + "(View) in the activity "
3085                                                + getContext().getClass() + " for onClick handler"
3086                                                + " on view " + View.this.getClass() + idText, e);
3087                                    }
3088                                }
3089
3090                                try {
3091                                    mHandler.invoke(getContext(), View.this);
3092                                } catch (IllegalAccessException e) {
3093                                    throw new IllegalStateException("Could not execute non "
3094                                            + "public method of the activity", e);
3095                                } catch (InvocationTargetException e) {
3096                                    throw new IllegalStateException("Could not execute "
3097                                            + "method of the activity", e);
3098                                }
3099                            }
3100                        });
3101                    }
3102                    break;
3103                case R.styleable.View_overScrollMode:
3104                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3105                    break;
3106                case R.styleable.View_verticalScrollbarPosition:
3107                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3108                    break;
3109                case R.styleable.View_layerType:
3110                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3111                    break;
3112                case R.styleable.View_textDirection:
3113                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3114                    break;
3115            }
3116        }
3117
3118        a.recycle();
3119
3120        setOverScrollMode(overScrollMode);
3121
3122        if (background != null) {
3123            setBackgroundDrawable(background);
3124        }
3125
3126        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3127        // layout direction). Those cached values will be used later during padding resolution.
3128        mUserPaddingStart = startPadding;
3129        mUserPaddingEnd = endPadding;
3130
3131        updateUserPaddingRelative();
3132
3133        if (padding >= 0) {
3134            leftPadding = padding;
3135            topPadding = padding;
3136            rightPadding = padding;
3137            bottomPadding = padding;
3138        }
3139
3140        // If the user specified the padding (either with android:padding or
3141        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3142        // use the default padding or the padding from the background drawable
3143        // (stored at this point in mPadding*)
3144        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3145                topPadding >= 0 ? topPadding : mPaddingTop,
3146                rightPadding >= 0 ? rightPadding : mPaddingRight,
3147                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3148
3149        if (viewFlagMasks != 0) {
3150            setFlags(viewFlagValues, viewFlagMasks);
3151        }
3152
3153        // Needs to be called after mViewFlags is set
3154        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3155            recomputePadding();
3156        }
3157
3158        if (x != 0 || y != 0) {
3159            scrollTo(x, y);
3160        }
3161
3162        if (transformSet) {
3163            setTranslationX(tx);
3164            setTranslationY(ty);
3165            setRotation(rotation);
3166            setRotationX(rotationX);
3167            setRotationY(rotationY);
3168            setScaleX(sx);
3169            setScaleY(sy);
3170        }
3171
3172        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3173            setScrollContainer(true);
3174        }
3175
3176        computeOpaqueFlags();
3177    }
3178
3179    private void updateUserPaddingRelative() {
3180        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3181    }
3182
3183    /**
3184     * Non-public constructor for use in testing
3185     */
3186    View() {
3187        mResources = null;
3188    }
3189
3190    /**
3191     * <p>
3192     * Initializes the fading edges from a given set of styled attributes. This
3193     * method should be called by subclasses that need fading edges and when an
3194     * instance of these subclasses is created programmatically rather than
3195     * being inflated from XML. This method is automatically called when the XML
3196     * is inflated.
3197     * </p>
3198     *
3199     * @param a the styled attributes set to initialize the fading edges from
3200     */
3201    protected void initializeFadingEdge(TypedArray a) {
3202        initScrollCache();
3203
3204        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3205                R.styleable.View_fadingEdgeLength,
3206                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3207    }
3208
3209    /**
3210     * Returns the size of the vertical faded edges used to indicate that more
3211     * content in this view is visible.
3212     *
3213     * @return The size in pixels of the vertical faded edge or 0 if vertical
3214     *         faded edges are not enabled for this view.
3215     * @attr ref android.R.styleable#View_fadingEdgeLength
3216     */
3217    public int getVerticalFadingEdgeLength() {
3218        if (isVerticalFadingEdgeEnabled()) {
3219            ScrollabilityCache cache = mScrollCache;
3220            if (cache != null) {
3221                return cache.fadingEdgeLength;
3222            }
3223        }
3224        return 0;
3225    }
3226
3227    /**
3228     * Set the size of the faded edge used to indicate that more content in this
3229     * view is available.  Will not change whether the fading edge is enabled; use
3230     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3231     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3232     * for the vertical or horizontal fading edges.
3233     *
3234     * @param length The size in pixels of the faded edge used to indicate that more
3235     *        content in this view is visible.
3236     */
3237    public void setFadingEdgeLength(int length) {
3238        initScrollCache();
3239        mScrollCache.fadingEdgeLength = length;
3240    }
3241
3242    /**
3243     * Returns the size of the horizontal faded edges used to indicate that more
3244     * content in this view is visible.
3245     *
3246     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3247     *         faded edges are not enabled for this view.
3248     * @attr ref android.R.styleable#View_fadingEdgeLength
3249     */
3250    public int getHorizontalFadingEdgeLength() {
3251        if (isHorizontalFadingEdgeEnabled()) {
3252            ScrollabilityCache cache = mScrollCache;
3253            if (cache != null) {
3254                return cache.fadingEdgeLength;
3255            }
3256        }
3257        return 0;
3258    }
3259
3260    /**
3261     * Returns the width of the vertical scrollbar.
3262     *
3263     * @return The width in pixels of the vertical scrollbar or 0 if there
3264     *         is no vertical scrollbar.
3265     */
3266    public int getVerticalScrollbarWidth() {
3267        ScrollabilityCache cache = mScrollCache;
3268        if (cache != null) {
3269            ScrollBarDrawable scrollBar = cache.scrollBar;
3270            if (scrollBar != null) {
3271                int size = scrollBar.getSize(true);
3272                if (size <= 0) {
3273                    size = cache.scrollBarSize;
3274                }
3275                return size;
3276            }
3277            return 0;
3278        }
3279        return 0;
3280    }
3281
3282    /**
3283     * Returns the height of the horizontal scrollbar.
3284     *
3285     * @return The height in pixels of the horizontal scrollbar or 0 if
3286     *         there is no horizontal scrollbar.
3287     */
3288    protected int getHorizontalScrollbarHeight() {
3289        ScrollabilityCache cache = mScrollCache;
3290        if (cache != null) {
3291            ScrollBarDrawable scrollBar = cache.scrollBar;
3292            if (scrollBar != null) {
3293                int size = scrollBar.getSize(false);
3294                if (size <= 0) {
3295                    size = cache.scrollBarSize;
3296                }
3297                return size;
3298            }
3299            return 0;
3300        }
3301        return 0;
3302    }
3303
3304    /**
3305     * <p>
3306     * Initializes the scrollbars from a given set of styled attributes. This
3307     * method should be called by subclasses that need scrollbars and when an
3308     * instance of these subclasses is created programmatically rather than
3309     * being inflated from XML. This method is automatically called when the XML
3310     * is inflated.
3311     * </p>
3312     *
3313     * @param a the styled attributes set to initialize the scrollbars from
3314     */
3315    protected void initializeScrollbars(TypedArray a) {
3316        initScrollCache();
3317
3318        final ScrollabilityCache scrollabilityCache = mScrollCache;
3319
3320        if (scrollabilityCache.scrollBar == null) {
3321            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3322        }
3323
3324        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3325
3326        if (!fadeScrollbars) {
3327            scrollabilityCache.state = ScrollabilityCache.ON;
3328        }
3329        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3330
3331
3332        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3333                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3334                        .getScrollBarFadeDuration());
3335        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3336                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3337                ViewConfiguration.getScrollDefaultDelay());
3338
3339
3340        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3341                com.android.internal.R.styleable.View_scrollbarSize,
3342                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3343
3344        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3345        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3346
3347        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3348        if (thumb != null) {
3349            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3350        }
3351
3352        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3353                false);
3354        if (alwaysDraw) {
3355            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3356        }
3357
3358        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3359        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3360
3361        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3362        if (thumb != null) {
3363            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3364        }
3365
3366        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3367                false);
3368        if (alwaysDraw) {
3369            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3370        }
3371
3372        // Re-apply user/background padding so that scrollbar(s) get added
3373        resolvePadding();
3374    }
3375
3376    /**
3377     * <p>
3378     * Initalizes the scrollability cache if necessary.
3379     * </p>
3380     */
3381    private void initScrollCache() {
3382        if (mScrollCache == null) {
3383            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3384        }
3385    }
3386
3387    /**
3388     * Set the position of the vertical scroll bar. Should be one of
3389     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3390     * {@link #SCROLLBAR_POSITION_RIGHT}.
3391     *
3392     * @param position Where the vertical scroll bar should be positioned.
3393     */
3394    public void setVerticalScrollbarPosition(int position) {
3395        if (mVerticalScrollbarPosition != position) {
3396            mVerticalScrollbarPosition = position;
3397            computeOpaqueFlags();
3398            resolvePadding();
3399        }
3400    }
3401
3402    /**
3403     * @return The position where the vertical scroll bar will show, if applicable.
3404     * @see #setVerticalScrollbarPosition(int)
3405     */
3406    public int getVerticalScrollbarPosition() {
3407        return mVerticalScrollbarPosition;
3408    }
3409
3410    ListenerInfo getListenerInfo() {
3411        if (mListenerInfo != null) {
3412            return mListenerInfo;
3413        }
3414        mListenerInfo = new ListenerInfo();
3415        return mListenerInfo;
3416    }
3417
3418    /**
3419     * Register a callback to be invoked when focus of this view changed.
3420     *
3421     * @param l The callback that will run.
3422     */
3423    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3424        getListenerInfo().mOnFocusChangeListener = l;
3425    }
3426
3427    /**
3428     * Add a listener that will be called when the bounds of the view change due to
3429     * layout processing.
3430     *
3431     * @param listener The listener that will be called when layout bounds change.
3432     */
3433    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3434        ListenerInfo li = getListenerInfo();
3435        if (li.mOnLayoutChangeListeners == null) {
3436            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3437        }
3438        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3439            li.mOnLayoutChangeListeners.add(listener);
3440        }
3441    }
3442
3443    /**
3444     * Remove a listener for layout changes.
3445     *
3446     * @param listener The listener for layout bounds change.
3447     */
3448    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3449        ListenerInfo li = mListenerInfo;
3450        if (li == null || li.mOnLayoutChangeListeners == null) {
3451            return;
3452        }
3453        li.mOnLayoutChangeListeners.remove(listener);
3454    }
3455
3456    /**
3457     * Add a listener for attach state changes.
3458     *
3459     * This listener will be called whenever this view is attached or detached
3460     * from a window. Remove the listener using
3461     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3462     *
3463     * @param listener Listener to attach
3464     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3465     */
3466    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3467        ListenerInfo li = getListenerInfo();
3468        if (li.mOnAttachStateChangeListeners == null) {
3469            li.mOnAttachStateChangeListeners
3470                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3471        }
3472        li.mOnAttachStateChangeListeners.add(listener);
3473    }
3474
3475    /**
3476     * Remove a listener for attach state changes. The listener will receive no further
3477     * notification of window attach/detach events.
3478     *
3479     * @param listener Listener to remove
3480     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3481     */
3482    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3483        ListenerInfo li = mListenerInfo;
3484        if (li == null || li.mOnAttachStateChangeListeners == null) {
3485            return;
3486        }
3487        li.mOnAttachStateChangeListeners.remove(listener);
3488    }
3489
3490    /**
3491     * Returns the focus-change callback registered for this view.
3492     *
3493     * @return The callback, or null if one is not registered.
3494     */
3495    public OnFocusChangeListener getOnFocusChangeListener() {
3496        ListenerInfo li = mListenerInfo;
3497        return li != null ? li.mOnFocusChangeListener : null;
3498    }
3499
3500    /**
3501     * Register a callback to be invoked when this view is clicked. If this view is not
3502     * clickable, it becomes clickable.
3503     *
3504     * @param l The callback that will run
3505     *
3506     * @see #setClickable(boolean)
3507     */
3508    public void setOnClickListener(OnClickListener l) {
3509        if (!isClickable()) {
3510            setClickable(true);
3511        }
3512        getListenerInfo().mOnClickListener = l;
3513    }
3514
3515    /**
3516     * Return whether this view has an attached OnClickListener.  Returns
3517     * true if there is a listener, false if there is none.
3518     */
3519    public boolean hasOnClickListeners() {
3520        ListenerInfo li = mListenerInfo;
3521        return (li != null && li.mOnClickListener != null);
3522    }
3523
3524    /**
3525     * Register a callback to be invoked when this view is clicked and held. If this view is not
3526     * long clickable, it becomes long clickable.
3527     *
3528     * @param l The callback that will run
3529     *
3530     * @see #setLongClickable(boolean)
3531     */
3532    public void setOnLongClickListener(OnLongClickListener l) {
3533        if (!isLongClickable()) {
3534            setLongClickable(true);
3535        }
3536        getListenerInfo().mOnLongClickListener = l;
3537    }
3538
3539    /**
3540     * Register a callback to be invoked when the context menu for this view is
3541     * being built. If this view is not long clickable, it becomes long clickable.
3542     *
3543     * @param l The callback that will run
3544     *
3545     */
3546    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3547        if (!isLongClickable()) {
3548            setLongClickable(true);
3549        }
3550        getListenerInfo().mOnCreateContextMenuListener = l;
3551    }
3552
3553    /**
3554     * Call this view's OnClickListener, if it is defined.  Performs all normal
3555     * actions associated with clicking: reporting accessibility event, playing
3556     * a sound, etc.
3557     *
3558     * @return True there was an assigned OnClickListener that was called, false
3559     *         otherwise is returned.
3560     */
3561    public boolean performClick() {
3562        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3563
3564        ListenerInfo li = mListenerInfo;
3565        if (li != null && li.mOnClickListener != null) {
3566            playSoundEffect(SoundEffectConstants.CLICK);
3567            li.mOnClickListener.onClick(this);
3568            return true;
3569        }
3570
3571        return false;
3572    }
3573
3574    /**
3575     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3576     * this only calls the listener, and does not do any associated clicking
3577     * actions like reporting an accessibility event.
3578     *
3579     * @return True there was an assigned OnClickListener that was called, false
3580     *         otherwise is returned.
3581     */
3582    public boolean callOnClick() {
3583        ListenerInfo li = mListenerInfo;
3584        if (li != null && li.mOnClickListener != null) {
3585            li.mOnClickListener.onClick(this);
3586            return true;
3587        }
3588        return false;
3589    }
3590
3591    /**
3592     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3593     * OnLongClickListener did not consume the event.
3594     *
3595     * @return True if one of the above receivers consumed the event, false otherwise.
3596     */
3597    public boolean performLongClick() {
3598        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3599
3600        boolean handled = false;
3601        ListenerInfo li = mListenerInfo;
3602        if (li != null && li.mOnLongClickListener != null) {
3603            handled = li.mOnLongClickListener.onLongClick(View.this);
3604        }
3605        if (!handled) {
3606            handled = showContextMenu();
3607        }
3608        if (handled) {
3609            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3610        }
3611        return handled;
3612    }
3613
3614    /**
3615     * Performs button-related actions during a touch down event.
3616     *
3617     * @param event The event.
3618     * @return True if the down was consumed.
3619     *
3620     * @hide
3621     */
3622    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3623        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3624            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3625                return true;
3626            }
3627        }
3628        return false;
3629    }
3630
3631    /**
3632     * Bring up the context menu for this view.
3633     *
3634     * @return Whether a context menu was displayed.
3635     */
3636    public boolean showContextMenu() {
3637        return getParent().showContextMenuForChild(this);
3638    }
3639
3640    /**
3641     * Bring up the context menu for this view, referring to the item under the specified point.
3642     *
3643     * @param x The referenced x coordinate.
3644     * @param y The referenced y coordinate.
3645     * @param metaState The keyboard modifiers that were pressed.
3646     * @return Whether a context menu was displayed.
3647     *
3648     * @hide
3649     */
3650    public boolean showContextMenu(float x, float y, int metaState) {
3651        return showContextMenu();
3652    }
3653
3654    /**
3655     * Start an action mode.
3656     *
3657     * @param callback Callback that will control the lifecycle of the action mode
3658     * @return The new action mode if it is started, null otherwise
3659     *
3660     * @see ActionMode
3661     */
3662    public ActionMode startActionMode(ActionMode.Callback callback) {
3663        ViewParent parent = getParent();
3664        if (parent == null) return null;
3665        return parent.startActionModeForChild(this, callback);
3666    }
3667
3668    /**
3669     * Register a callback to be invoked when a key is pressed in this view.
3670     * @param l the key listener to attach to this view
3671     */
3672    public void setOnKeyListener(OnKeyListener l) {
3673        getListenerInfo().mOnKeyListener = l;
3674    }
3675
3676    /**
3677     * Register a callback to be invoked when a touch event is sent to this view.
3678     * @param l the touch listener to attach to this view
3679     */
3680    public void setOnTouchListener(OnTouchListener l) {
3681        getListenerInfo().mOnTouchListener = l;
3682    }
3683
3684    /**
3685     * Register a callback to be invoked when a generic motion event is sent to this view.
3686     * @param l the generic motion listener to attach to this view
3687     */
3688    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3689        getListenerInfo().mOnGenericMotionListener = l;
3690    }
3691
3692    /**
3693     * Register a callback to be invoked when a hover event is sent to this view.
3694     * @param l the hover listener to attach to this view
3695     */
3696    public void setOnHoverListener(OnHoverListener l) {
3697        getListenerInfo().mOnHoverListener = l;
3698    }
3699
3700    /**
3701     * Register a drag event listener callback object for this View. The parameter is
3702     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3703     * View, the system calls the
3704     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3705     * @param l An implementation of {@link android.view.View.OnDragListener}.
3706     */
3707    public void setOnDragListener(OnDragListener l) {
3708        getListenerInfo().mOnDragListener = l;
3709    }
3710
3711    /**
3712     * Give this view focus. This will cause
3713     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3714     *
3715     * Note: this does not check whether this {@link View} should get focus, it just
3716     * gives it focus no matter what.  It should only be called internally by framework
3717     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3718     *
3719     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3720     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3721     *        focus moved when requestFocus() is called. It may not always
3722     *        apply, in which case use the default View.FOCUS_DOWN.
3723     * @param previouslyFocusedRect The rectangle of the view that had focus
3724     *        prior in this View's coordinate system.
3725     */
3726    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3727        if (DBG) {
3728            System.out.println(this + " requestFocus()");
3729        }
3730
3731        if ((mPrivateFlags & FOCUSED) == 0) {
3732            mPrivateFlags |= FOCUSED;
3733
3734            if (mParent != null) {
3735                mParent.requestChildFocus(this, this);
3736            }
3737
3738            onFocusChanged(true, direction, previouslyFocusedRect);
3739            refreshDrawableState();
3740        }
3741    }
3742
3743    /**
3744     * Request that a rectangle of this view be visible on the screen,
3745     * scrolling if necessary just enough.
3746     *
3747     * <p>A View should call this if it maintains some notion of which part
3748     * of its content is interesting.  For example, a text editing view
3749     * should call this when its cursor moves.
3750     *
3751     * @param rectangle The rectangle.
3752     * @return Whether any parent scrolled.
3753     */
3754    public boolean requestRectangleOnScreen(Rect rectangle) {
3755        return requestRectangleOnScreen(rectangle, false);
3756    }
3757
3758    /**
3759     * Request that a rectangle of this view be visible on the screen,
3760     * scrolling if necessary just enough.
3761     *
3762     * <p>A View should call this if it maintains some notion of which part
3763     * of its content is interesting.  For example, a text editing view
3764     * should call this when its cursor moves.
3765     *
3766     * <p>When <code>immediate</code> is set to true, scrolling will not be
3767     * animated.
3768     *
3769     * @param rectangle The rectangle.
3770     * @param immediate True to forbid animated scrolling, false otherwise
3771     * @return Whether any parent scrolled.
3772     */
3773    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3774        View child = this;
3775        ViewParent parent = mParent;
3776        boolean scrolled = false;
3777        while (parent != null) {
3778            scrolled |= parent.requestChildRectangleOnScreen(child,
3779                    rectangle, immediate);
3780
3781            // offset rect so next call has the rectangle in the
3782            // coordinate system of its direct child.
3783            rectangle.offset(child.getLeft(), child.getTop());
3784            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3785
3786            if (!(parent instanceof View)) {
3787                break;
3788            }
3789
3790            child = (View) parent;
3791            parent = child.getParent();
3792        }
3793        return scrolled;
3794    }
3795
3796    /**
3797     * Called when this view wants to give up focus. If focus is cleared
3798     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3799     * <p>
3800     * <strong>Note:</strong> When a View clears focus the framework is trying
3801     * to give focus to the first focusable View from the top. Hence, if this
3802     * View is the first from the top that can take focus, then its focus will
3803     * not be cleared nor will the focus change callback be invoked.
3804     * </p>
3805     */
3806    public void clearFocus() {
3807        if (DBG) {
3808            System.out.println(this + " clearFocus()");
3809        }
3810
3811        if ((mPrivateFlags & FOCUSED) != 0) {
3812            mPrivateFlags &= ~FOCUSED;
3813
3814            if (mParent != null) {
3815                mParent.clearChildFocus(this);
3816            }
3817
3818            onFocusChanged(false, 0, null);
3819            refreshDrawableState();
3820        }
3821    }
3822
3823    /**
3824     * Called to clear the focus of a view that is about to be removed.
3825     * Doesn't call clearChildFocus, which prevents this view from taking
3826     * focus again before it has been removed from the parent
3827     */
3828    void clearFocusForRemoval() {
3829        if ((mPrivateFlags & FOCUSED) != 0) {
3830            mPrivateFlags &= ~FOCUSED;
3831
3832            onFocusChanged(false, 0, null);
3833            refreshDrawableState();
3834
3835            // The view cleared focus and invoked the callbacks, so  now is the
3836            // time to give focus to the the first focusable from the top to
3837            // ensure that the gain focus is announced after clear focus.
3838            getRootView().requestFocus(FOCUS_FORWARD);
3839        }
3840    }
3841
3842    /**
3843     * Called internally by the view system when a new view is getting focus.
3844     * This is what clears the old focus.
3845     */
3846    void unFocus() {
3847        if (DBG) {
3848            System.out.println(this + " unFocus()");
3849        }
3850
3851        if ((mPrivateFlags & FOCUSED) != 0) {
3852            mPrivateFlags &= ~FOCUSED;
3853
3854            onFocusChanged(false, 0, null);
3855            refreshDrawableState();
3856        }
3857    }
3858
3859    /**
3860     * Returns true if this view has focus iteself, or is the ancestor of the
3861     * view that has focus.
3862     *
3863     * @return True if this view has or contains focus, false otherwise.
3864     */
3865    @ViewDebug.ExportedProperty(category = "focus")
3866    public boolean hasFocus() {
3867        return (mPrivateFlags & FOCUSED) != 0;
3868    }
3869
3870    /**
3871     * Returns true if this view is focusable or if it contains a reachable View
3872     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3873     * is a View whose parents do not block descendants focus.
3874     *
3875     * Only {@link #VISIBLE} views are considered focusable.
3876     *
3877     * @return True if the view is focusable or if the view contains a focusable
3878     *         View, false otherwise.
3879     *
3880     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3881     */
3882    public boolean hasFocusable() {
3883        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3884    }
3885
3886    /**
3887     * Called by the view system when the focus state of this view changes.
3888     * When the focus change event is caused by directional navigation, direction
3889     * and previouslyFocusedRect provide insight into where the focus is coming from.
3890     * When overriding, be sure to call up through to the super class so that
3891     * the standard focus handling will occur.
3892     *
3893     * @param gainFocus True if the View has focus; false otherwise.
3894     * @param direction The direction focus has moved when requestFocus()
3895     *                  is called to give this view focus. Values are
3896     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3897     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3898     *                  It may not always apply, in which case use the default.
3899     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3900     *        system, of the previously focused view.  If applicable, this will be
3901     *        passed in as finer grained information about where the focus is coming
3902     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3903     */
3904    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3905        if (gainFocus) {
3906            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3907        }
3908
3909        InputMethodManager imm = InputMethodManager.peekInstance();
3910        if (!gainFocus) {
3911            if (isPressed()) {
3912                setPressed(false);
3913            }
3914            if (imm != null && mAttachInfo != null
3915                    && mAttachInfo.mHasWindowFocus) {
3916                imm.focusOut(this);
3917            }
3918            onFocusLost();
3919        } else if (imm != null && mAttachInfo != null
3920                && mAttachInfo.mHasWindowFocus) {
3921            imm.focusIn(this);
3922        }
3923
3924        invalidate(true);
3925        ListenerInfo li = mListenerInfo;
3926        if (li != null && li.mOnFocusChangeListener != null) {
3927            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3928        }
3929
3930        if (mAttachInfo != null) {
3931            mAttachInfo.mKeyDispatchState.reset(this);
3932        }
3933    }
3934
3935    /**
3936     * Sends an accessibility event of the given type. If accessiiblity is
3937     * not enabled this method has no effect. The default implementation calls
3938     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3939     * to populate information about the event source (this View), then calls
3940     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3941     * populate the text content of the event source including its descendants,
3942     * and last calls
3943     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3944     * on its parent to resuest sending of the event to interested parties.
3945     * <p>
3946     * If an {@link AccessibilityDelegate} has been specified via calling
3947     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3948     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3949     * responsible for handling this call.
3950     * </p>
3951     *
3952     * @param eventType The type of the event to send, as defined by several types from
3953     * {@link android.view.accessibility.AccessibilityEvent}, such as
3954     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3955     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3956     *
3957     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3958     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3959     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3960     * @see AccessibilityDelegate
3961     */
3962    public void sendAccessibilityEvent(int eventType) {
3963        if (mAccessibilityDelegate != null) {
3964            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3965        } else {
3966            sendAccessibilityEventInternal(eventType);
3967        }
3968    }
3969
3970    /**
3971     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
3972     * {@link AccessibilityEvent} to make an announcement which is related to some
3973     * sort of a context change for which none of the events representing UI transitions
3974     * is a good fit. For example, announcing a new page in a book. If accessibility
3975     * is not enabled this method does nothing.
3976     *
3977     * @param text The announcement text.
3978     */
3979    public void announceForAccessibility(CharSequence text) {
3980        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3981            AccessibilityEvent event = AccessibilityEvent.obtain(
3982                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
3983            event.getText().add(text);
3984            sendAccessibilityEventUnchecked(event);
3985        }
3986    }
3987
3988    /**
3989     * @see #sendAccessibilityEvent(int)
3990     *
3991     * Note: Called from the default {@link AccessibilityDelegate}.
3992     */
3993    void sendAccessibilityEventInternal(int eventType) {
3994        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3995            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3996        }
3997    }
3998
3999    /**
4000     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4001     * takes as an argument an empty {@link AccessibilityEvent} and does not
4002     * perform a check whether accessibility is enabled.
4003     * <p>
4004     * If an {@link AccessibilityDelegate} has been specified via calling
4005     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4006     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4007     * is responsible for handling this call.
4008     * </p>
4009     *
4010     * @param event The event to send.
4011     *
4012     * @see #sendAccessibilityEvent(int)
4013     */
4014    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4015        if (mAccessibilityDelegate != null) {
4016           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4017        } else {
4018            sendAccessibilityEventUncheckedInternal(event);
4019        }
4020    }
4021
4022    /**
4023     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4024     *
4025     * Note: Called from the default {@link AccessibilityDelegate}.
4026     */
4027    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4028        if (!isShown()) {
4029            return;
4030        }
4031        onInitializeAccessibilityEvent(event);
4032        // Only a subset of accessibility events populates text content.
4033        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4034            dispatchPopulateAccessibilityEvent(event);
4035        }
4036        // In the beginning we called #isShown(), so we know that getParent() is not null.
4037        getParent().requestSendAccessibilityEvent(this, event);
4038    }
4039
4040    /**
4041     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4042     * to its children for adding their text content to the event. Note that the
4043     * event text is populated in a separate dispatch path since we add to the
4044     * event not only the text of the source but also the text of all its descendants.
4045     * A typical implementation will call
4046     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4047     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4048     * on each child. Override this method if custom population of the event text
4049     * content is required.
4050     * <p>
4051     * If an {@link AccessibilityDelegate} has been specified via calling
4052     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4053     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4054     * is responsible for handling this call.
4055     * </p>
4056     * <p>
4057     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4058     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4059     * </p>
4060     *
4061     * @param event The event.
4062     *
4063     * @return True if the event population was completed.
4064     */
4065    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4066        if (mAccessibilityDelegate != null) {
4067            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4068        } else {
4069            return dispatchPopulateAccessibilityEventInternal(event);
4070        }
4071    }
4072
4073    /**
4074     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4075     *
4076     * Note: Called from the default {@link AccessibilityDelegate}.
4077     */
4078    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4079        onPopulateAccessibilityEvent(event);
4080        return false;
4081    }
4082
4083    /**
4084     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4085     * giving a chance to this View to populate the accessibility event with its
4086     * text content. While this method is free to modify event
4087     * attributes other than text content, doing so should normally be performed in
4088     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4089     * <p>
4090     * Example: Adding formatted date string to an accessibility event in addition
4091     *          to the text added by the super implementation:
4092     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4093     *     super.onPopulateAccessibilityEvent(event);
4094     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4095     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4096     *         mCurrentDate.getTimeInMillis(), flags);
4097     *     event.getText().add(selectedDateUtterance);
4098     * }</pre>
4099     * <p>
4100     * If an {@link AccessibilityDelegate} has been specified via calling
4101     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4102     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4103     * is responsible for handling this call.
4104     * </p>
4105     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4106     * information to the event, in case the default implementation has basic information to add.
4107     * </p>
4108     *
4109     * @param event The accessibility event which to populate.
4110     *
4111     * @see #sendAccessibilityEvent(int)
4112     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4113     */
4114    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4115        if (mAccessibilityDelegate != null) {
4116            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4117        } else {
4118            onPopulateAccessibilityEventInternal(event);
4119        }
4120    }
4121
4122    /**
4123     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4124     *
4125     * Note: Called from the default {@link AccessibilityDelegate}.
4126     */
4127    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4128
4129    }
4130
4131    /**
4132     * Initializes an {@link AccessibilityEvent} with information about
4133     * this View which is the event source. In other words, the source of
4134     * an accessibility event is the view whose state change triggered firing
4135     * the event.
4136     * <p>
4137     * Example: Setting the password property of an event in addition
4138     *          to properties set by the super implementation:
4139     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4140     *     super.onInitializeAccessibilityEvent(event);
4141     *     event.setPassword(true);
4142     * }</pre>
4143     * <p>
4144     * If an {@link AccessibilityDelegate} has been specified via calling
4145     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4146     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4147     * is responsible for handling this call.
4148     * </p>
4149     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4150     * information to the event, in case the default implementation has basic information to add.
4151     * </p>
4152     * @param event The event to initialize.
4153     *
4154     * @see #sendAccessibilityEvent(int)
4155     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4156     */
4157    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4158        if (mAccessibilityDelegate != null) {
4159            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4160        } else {
4161            onInitializeAccessibilityEventInternal(event);
4162        }
4163    }
4164
4165    /**
4166     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4167     *
4168     * Note: Called from the default {@link AccessibilityDelegate}.
4169     */
4170    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4171        event.setSource(this);
4172        event.setClassName(View.class.getName());
4173        event.setPackageName(getContext().getPackageName());
4174        event.setEnabled(isEnabled());
4175        event.setContentDescription(mContentDescription);
4176
4177        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4178            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4179            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4180                    FOCUSABLES_ALL);
4181            event.setItemCount(focusablesTempList.size());
4182            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4183            focusablesTempList.clear();
4184        }
4185    }
4186
4187    /**
4188     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4189     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4190     * This method is responsible for obtaining an accessibility node info from a
4191     * pool of reusable instances and calling
4192     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4193     * initialize the former.
4194     * <p>
4195     * Note: The client is responsible for recycling the obtained instance by calling
4196     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4197     * </p>
4198     *
4199     * @return A populated {@link AccessibilityNodeInfo}.
4200     *
4201     * @see AccessibilityNodeInfo
4202     */
4203    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4204        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4205        if (provider != null) {
4206            return provider.createAccessibilityNodeInfo(View.NO_ID);
4207        } else {
4208            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4209            onInitializeAccessibilityNodeInfo(info);
4210            return info;
4211        }
4212    }
4213
4214    /**
4215     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4216     * The base implementation sets:
4217     * <ul>
4218     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4219     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4220     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4221     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4222     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4223     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4224     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4225     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4226     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4227     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4228     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4229     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4230     * </ul>
4231     * <p>
4232     * Subclasses should override this method, call the super implementation,
4233     * and set additional attributes.
4234     * </p>
4235     * <p>
4236     * If an {@link AccessibilityDelegate} has been specified via calling
4237     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4238     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4239     * is responsible for handling this call.
4240     * </p>
4241     *
4242     * @param info The instance to initialize.
4243     */
4244    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4245        if (mAccessibilityDelegate != null) {
4246            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4247        } else {
4248            onInitializeAccessibilityNodeInfoInternal(info);
4249        }
4250    }
4251
4252    /**
4253     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4254     *
4255     * Note: Called from the default {@link AccessibilityDelegate}.
4256     */
4257    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4258        Rect bounds = mAttachInfo.mTmpInvalRect;
4259        getDrawingRect(bounds);
4260        info.setBoundsInParent(bounds);
4261
4262        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4263        getLocationOnScreen(locationOnScreen);
4264        bounds.offsetTo(0, 0);
4265        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4266        info.setBoundsInScreen(bounds);
4267
4268        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4269            ViewParent parent = getParent();
4270            if (parent instanceof View) {
4271                View parentView = (View) parent;
4272                info.setParent(parentView);
4273            }
4274        }
4275
4276        info.setPackageName(mContext.getPackageName());
4277        info.setClassName(View.class.getName());
4278        info.setContentDescription(getContentDescription());
4279
4280        info.setEnabled(isEnabled());
4281        info.setClickable(isClickable());
4282        info.setFocusable(isFocusable());
4283        info.setFocused(isFocused());
4284        info.setSelected(isSelected());
4285        info.setLongClickable(isLongClickable());
4286
4287        // TODO: These make sense only if we are in an AdapterView but all
4288        // views can be selected. Maybe from accessiiblity perspective
4289        // we should report as selectable view in an AdapterView.
4290        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4291        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4292
4293        if (isFocusable()) {
4294            if (isFocused()) {
4295                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4296            } else {
4297                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4298            }
4299        }
4300    }
4301
4302    /**
4303     * Sets a delegate for implementing accessibility support via compositon as
4304     * opposed to inheritance. The delegate's primary use is for implementing
4305     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4306     *
4307     * @param delegate The delegate instance.
4308     *
4309     * @see AccessibilityDelegate
4310     */
4311    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4312        mAccessibilityDelegate = delegate;
4313    }
4314
4315    /**
4316     * Gets the provider for managing a virtual view hierarchy rooted at this View
4317     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4318     * that explore the window content.
4319     * <p>
4320     * If this method returns an instance, this instance is responsible for managing
4321     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4322     * View including the one representing the View itself. Similarly the returned
4323     * instance is responsible for performing accessibility actions on any virtual
4324     * view or the root view itself.
4325     * </p>
4326     * <p>
4327     * If an {@link AccessibilityDelegate} has been specified via calling
4328     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4329     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4330     * is responsible for handling this call.
4331     * </p>
4332     *
4333     * @return The provider.
4334     *
4335     * @see AccessibilityNodeProvider
4336     */
4337    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4338        if (mAccessibilityDelegate != null) {
4339            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4340        } else {
4341            return null;
4342        }
4343    }
4344
4345    /**
4346     * Gets the unique identifier of this view on the screen for accessibility purposes.
4347     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4348     *
4349     * @return The view accessibility id.
4350     *
4351     * @hide
4352     */
4353    public int getAccessibilityViewId() {
4354        if (mAccessibilityViewId == NO_ID) {
4355            mAccessibilityViewId = sNextAccessibilityViewId++;
4356        }
4357        return mAccessibilityViewId;
4358    }
4359
4360    /**
4361     * Gets the unique identifier of the window in which this View reseides.
4362     *
4363     * @return The window accessibility id.
4364     *
4365     * @hide
4366     */
4367    public int getAccessibilityWindowId() {
4368        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4369    }
4370
4371    /**
4372     * Gets the {@link View} description. It briefly describes the view and is
4373     * primarily used for accessibility support. Set this property to enable
4374     * better accessibility support for your application. This is especially
4375     * true for views that do not have textual representation (For example,
4376     * ImageButton).
4377     *
4378     * @return The content descriptiopn.
4379     *
4380     * @attr ref android.R.styleable#View_contentDescription
4381     */
4382    public CharSequence getContentDescription() {
4383        return mContentDescription;
4384    }
4385
4386    /**
4387     * Sets the {@link View} description. It briefly describes the view and is
4388     * primarily used for accessibility support. Set this property to enable
4389     * better accessibility support for your application. This is especially
4390     * true for views that do not have textual representation (For example,
4391     * ImageButton).
4392     *
4393     * @param contentDescription The content description.
4394     *
4395     * @attr ref android.R.styleable#View_contentDescription
4396     */
4397    @RemotableViewMethod
4398    public void setContentDescription(CharSequence contentDescription) {
4399        mContentDescription = contentDescription;
4400    }
4401
4402    /**
4403     * Invoked whenever this view loses focus, either by losing window focus or by losing
4404     * focus within its window. This method can be used to clear any state tied to the
4405     * focus. For instance, if a button is held pressed with the trackball and the window
4406     * loses focus, this method can be used to cancel the press.
4407     *
4408     * Subclasses of View overriding this method should always call super.onFocusLost().
4409     *
4410     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4411     * @see #onWindowFocusChanged(boolean)
4412     *
4413     * @hide pending API council approval
4414     */
4415    protected void onFocusLost() {
4416        resetPressedState();
4417    }
4418
4419    private void resetPressedState() {
4420        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4421            return;
4422        }
4423
4424        if (isPressed()) {
4425            setPressed(false);
4426
4427            if (!mHasPerformedLongPress) {
4428                removeLongPressCallback();
4429            }
4430        }
4431    }
4432
4433    /**
4434     * Returns true if this view has focus
4435     *
4436     * @return True if this view has focus, false otherwise.
4437     */
4438    @ViewDebug.ExportedProperty(category = "focus")
4439    public boolean isFocused() {
4440        return (mPrivateFlags & FOCUSED) != 0;
4441    }
4442
4443    /**
4444     * Find the view in the hierarchy rooted at this view that currently has
4445     * focus.
4446     *
4447     * @return The view that currently has focus, or null if no focused view can
4448     *         be found.
4449     */
4450    public View findFocus() {
4451        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4452    }
4453
4454    /**
4455     * Change whether this view is one of the set of scrollable containers in
4456     * its window.  This will be used to determine whether the window can
4457     * resize or must pan when a soft input area is open -- scrollable
4458     * containers allow the window to use resize mode since the container
4459     * will appropriately shrink.
4460     */
4461    public void setScrollContainer(boolean isScrollContainer) {
4462        if (isScrollContainer) {
4463            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4464                mAttachInfo.mScrollContainers.add(this);
4465                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4466            }
4467            mPrivateFlags |= SCROLL_CONTAINER;
4468        } else {
4469            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4470                mAttachInfo.mScrollContainers.remove(this);
4471            }
4472            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4473        }
4474    }
4475
4476    /**
4477     * Returns the quality of the drawing cache.
4478     *
4479     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4480     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4481     *
4482     * @see #setDrawingCacheQuality(int)
4483     * @see #setDrawingCacheEnabled(boolean)
4484     * @see #isDrawingCacheEnabled()
4485     *
4486     * @attr ref android.R.styleable#View_drawingCacheQuality
4487     */
4488    public int getDrawingCacheQuality() {
4489        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4490    }
4491
4492    /**
4493     * Set the drawing cache quality of this view. This value is used only when the
4494     * drawing cache is enabled
4495     *
4496     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4497     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4498     *
4499     * @see #getDrawingCacheQuality()
4500     * @see #setDrawingCacheEnabled(boolean)
4501     * @see #isDrawingCacheEnabled()
4502     *
4503     * @attr ref android.R.styleable#View_drawingCacheQuality
4504     */
4505    public void setDrawingCacheQuality(int quality) {
4506        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4507    }
4508
4509    /**
4510     * Returns whether the screen should remain on, corresponding to the current
4511     * value of {@link #KEEP_SCREEN_ON}.
4512     *
4513     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4514     *
4515     * @see #setKeepScreenOn(boolean)
4516     *
4517     * @attr ref android.R.styleable#View_keepScreenOn
4518     */
4519    public boolean getKeepScreenOn() {
4520        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4521    }
4522
4523    /**
4524     * Controls whether the screen should remain on, modifying the
4525     * value of {@link #KEEP_SCREEN_ON}.
4526     *
4527     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4528     *
4529     * @see #getKeepScreenOn()
4530     *
4531     * @attr ref android.R.styleable#View_keepScreenOn
4532     */
4533    public void setKeepScreenOn(boolean keepScreenOn) {
4534        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4535    }
4536
4537    /**
4538     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4539     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4540     *
4541     * @attr ref android.R.styleable#View_nextFocusLeft
4542     */
4543    public int getNextFocusLeftId() {
4544        return mNextFocusLeftId;
4545    }
4546
4547    /**
4548     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4549     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4550     * decide automatically.
4551     *
4552     * @attr ref android.R.styleable#View_nextFocusLeft
4553     */
4554    public void setNextFocusLeftId(int nextFocusLeftId) {
4555        mNextFocusLeftId = nextFocusLeftId;
4556    }
4557
4558    /**
4559     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4560     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4561     *
4562     * @attr ref android.R.styleable#View_nextFocusRight
4563     */
4564    public int getNextFocusRightId() {
4565        return mNextFocusRightId;
4566    }
4567
4568    /**
4569     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4570     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4571     * decide automatically.
4572     *
4573     * @attr ref android.R.styleable#View_nextFocusRight
4574     */
4575    public void setNextFocusRightId(int nextFocusRightId) {
4576        mNextFocusRightId = nextFocusRightId;
4577    }
4578
4579    /**
4580     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4581     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4582     *
4583     * @attr ref android.R.styleable#View_nextFocusUp
4584     */
4585    public int getNextFocusUpId() {
4586        return mNextFocusUpId;
4587    }
4588
4589    /**
4590     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4591     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4592     * decide automatically.
4593     *
4594     * @attr ref android.R.styleable#View_nextFocusUp
4595     */
4596    public void setNextFocusUpId(int nextFocusUpId) {
4597        mNextFocusUpId = nextFocusUpId;
4598    }
4599
4600    /**
4601     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4602     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4603     *
4604     * @attr ref android.R.styleable#View_nextFocusDown
4605     */
4606    public int getNextFocusDownId() {
4607        return mNextFocusDownId;
4608    }
4609
4610    /**
4611     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4612     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4613     * decide automatically.
4614     *
4615     * @attr ref android.R.styleable#View_nextFocusDown
4616     */
4617    public void setNextFocusDownId(int nextFocusDownId) {
4618        mNextFocusDownId = nextFocusDownId;
4619    }
4620
4621    /**
4622     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4623     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4624     *
4625     * @attr ref android.R.styleable#View_nextFocusForward
4626     */
4627    public int getNextFocusForwardId() {
4628        return mNextFocusForwardId;
4629    }
4630
4631    /**
4632     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4633     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4634     * decide automatically.
4635     *
4636     * @attr ref android.R.styleable#View_nextFocusForward
4637     */
4638    public void setNextFocusForwardId(int nextFocusForwardId) {
4639        mNextFocusForwardId = nextFocusForwardId;
4640    }
4641
4642    /**
4643     * Returns the visibility of this view and all of its ancestors
4644     *
4645     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4646     */
4647    public boolean isShown() {
4648        View current = this;
4649        //noinspection ConstantConditions
4650        do {
4651            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4652                return false;
4653            }
4654            ViewParent parent = current.mParent;
4655            if (parent == null) {
4656                return false; // We are not attached to the view root
4657            }
4658            if (!(parent instanceof View)) {
4659                return true;
4660            }
4661            current = (View) parent;
4662        } while (current != null);
4663
4664        return false;
4665    }
4666
4667    /**
4668     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4669     * is set
4670     *
4671     * @param insets Insets for system windows
4672     *
4673     * @return True if this view applied the insets, false otherwise
4674     */
4675    protected boolean fitSystemWindows(Rect insets) {
4676        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4677            mPaddingLeft = insets.left;
4678            mPaddingTop = insets.top;
4679            mPaddingRight = insets.right;
4680            mPaddingBottom = insets.bottom;
4681            requestLayout();
4682            return true;
4683        }
4684        return false;
4685    }
4686
4687    /**
4688     * Set whether or not this view should account for system screen decorations
4689     * such as the status bar and inset its content. This allows this view to be
4690     * positioned in absolute screen coordinates and remain visible to the user.
4691     *
4692     * <p>This should only be used by top-level window decor views.
4693     *
4694     * @param fitSystemWindows true to inset content for system screen decorations, false for
4695     *                         default behavior.
4696     *
4697     * @attr ref android.R.styleable#View_fitsSystemWindows
4698     */
4699    public void setFitsSystemWindows(boolean fitSystemWindows) {
4700        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4701    }
4702
4703    /**
4704     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4705     * will account for system screen decorations such as the status bar and inset its
4706     * content. This allows the view to be positioned in absolute screen coordinates
4707     * and remain visible to the user.
4708     *
4709     * @return true if this view will adjust its content bounds for system screen decorations.
4710     *
4711     * @attr ref android.R.styleable#View_fitsSystemWindows
4712     */
4713    public boolean fitsSystemWindows() {
4714        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4715    }
4716
4717    /**
4718     * Returns the visibility status for this view.
4719     *
4720     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4721     * @attr ref android.R.styleable#View_visibility
4722     */
4723    @ViewDebug.ExportedProperty(mapping = {
4724        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4725        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4726        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4727    })
4728    public int getVisibility() {
4729        return mViewFlags & VISIBILITY_MASK;
4730    }
4731
4732    /**
4733     * Set the enabled state of this view.
4734     *
4735     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4736     * @attr ref android.R.styleable#View_visibility
4737     */
4738    @RemotableViewMethod
4739    public void setVisibility(int visibility) {
4740        setFlags(visibility, VISIBILITY_MASK);
4741        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4742    }
4743
4744    /**
4745     * Returns the enabled status for this view. The interpretation of the
4746     * enabled state varies by subclass.
4747     *
4748     * @return True if this view is enabled, false otherwise.
4749     */
4750    @ViewDebug.ExportedProperty
4751    public boolean isEnabled() {
4752        return (mViewFlags & ENABLED_MASK) == ENABLED;
4753    }
4754
4755    /**
4756     * Set the enabled state of this view. The interpretation of the enabled
4757     * state varies by subclass.
4758     *
4759     * @param enabled True if this view is enabled, false otherwise.
4760     */
4761    @RemotableViewMethod
4762    public void setEnabled(boolean enabled) {
4763        if (enabled == isEnabled()) return;
4764
4765        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4766
4767        /*
4768         * The View most likely has to change its appearance, so refresh
4769         * the drawable state.
4770         */
4771        refreshDrawableState();
4772
4773        // Invalidate too, since the default behavior for views is to be
4774        // be drawn at 50% alpha rather than to change the drawable.
4775        invalidate(true);
4776    }
4777
4778    /**
4779     * Set whether this view can receive the focus.
4780     *
4781     * Setting this to false will also ensure that this view is not focusable
4782     * in touch mode.
4783     *
4784     * @param focusable If true, this view can receive the focus.
4785     *
4786     * @see #setFocusableInTouchMode(boolean)
4787     * @attr ref android.R.styleable#View_focusable
4788     */
4789    public void setFocusable(boolean focusable) {
4790        if (!focusable) {
4791            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4792        }
4793        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4794    }
4795
4796    /**
4797     * Set whether this view can receive focus while in touch mode.
4798     *
4799     * Setting this to true will also ensure that this view is focusable.
4800     *
4801     * @param focusableInTouchMode If true, this view can receive the focus while
4802     *   in touch mode.
4803     *
4804     * @see #setFocusable(boolean)
4805     * @attr ref android.R.styleable#View_focusableInTouchMode
4806     */
4807    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4808        // Focusable in touch mode should always be set before the focusable flag
4809        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4810        // which, in touch mode, will not successfully request focus on this view
4811        // because the focusable in touch mode flag is not set
4812        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4813        if (focusableInTouchMode) {
4814            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4815        }
4816    }
4817
4818    /**
4819     * Set whether this view should have sound effects enabled for events such as
4820     * clicking and touching.
4821     *
4822     * <p>You may wish to disable sound effects for a view if you already play sounds,
4823     * for instance, a dial key that plays dtmf tones.
4824     *
4825     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4826     * @see #isSoundEffectsEnabled()
4827     * @see #playSoundEffect(int)
4828     * @attr ref android.R.styleable#View_soundEffectsEnabled
4829     */
4830    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4831        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4832    }
4833
4834    /**
4835     * @return whether this view should have sound effects enabled for events such as
4836     *     clicking and touching.
4837     *
4838     * @see #setSoundEffectsEnabled(boolean)
4839     * @see #playSoundEffect(int)
4840     * @attr ref android.R.styleable#View_soundEffectsEnabled
4841     */
4842    @ViewDebug.ExportedProperty
4843    public boolean isSoundEffectsEnabled() {
4844        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4845    }
4846
4847    /**
4848     * Set whether this view should have haptic feedback for events such as
4849     * long presses.
4850     *
4851     * <p>You may wish to disable haptic feedback if your view already controls
4852     * its own haptic feedback.
4853     *
4854     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4855     * @see #isHapticFeedbackEnabled()
4856     * @see #performHapticFeedback(int)
4857     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4858     */
4859    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4860        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4861    }
4862
4863    /**
4864     * @return whether this view should have haptic feedback enabled for events
4865     * long presses.
4866     *
4867     * @see #setHapticFeedbackEnabled(boolean)
4868     * @see #performHapticFeedback(int)
4869     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4870     */
4871    @ViewDebug.ExportedProperty
4872    public boolean isHapticFeedbackEnabled() {
4873        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4874    }
4875
4876    /**
4877     * Returns the layout direction for this view.
4878     *
4879     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4880     *   {@link #LAYOUT_DIRECTION_RTL},
4881     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4882     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4883     * @attr ref android.R.styleable#View_layoutDirection
4884     */
4885    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4886        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4887        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4888        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4889        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4890    })
4891    public int getLayoutDirection() {
4892        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
4893    }
4894
4895    /**
4896     * Set the layout direction for this view. This will propagate a reset of layout direction
4897     * resolution to the view's children and resolve layout direction for this view.
4898     *
4899     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4900     *   {@link #LAYOUT_DIRECTION_RTL},
4901     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4902     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4903     *
4904     * @attr ref android.R.styleable#View_layoutDirection
4905     */
4906    @RemotableViewMethod
4907    public void setLayoutDirection(int layoutDirection) {
4908        if (getLayoutDirection() != layoutDirection) {
4909            // Reset the current layout direction
4910            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
4911            // Reset the current resolved layout direction
4912            resetResolvedLayoutDirection();
4913            // Set the new layout direction (filtered) and ask for a layout pass
4914            mPrivateFlags2 |=
4915                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
4916            requestLayout();
4917        }
4918    }
4919
4920    /**
4921     * Returns the resolved layout direction for this view.
4922     *
4923     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4924     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
4925     */
4926    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4927        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
4928        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
4929    })
4930    public int getResolvedLayoutDirection() {
4931        resolveLayoutDirectionIfNeeded();
4932        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4933                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4934    }
4935
4936    /**
4937     * Indicates whether or not this view's layout is right-to-left. This is resolved from
4938     * layout attribute and/or the inherited value from the parent
4939     *
4940     * @return true if the layout is right-to-left.
4941     */
4942    @ViewDebug.ExportedProperty(category = "layout")
4943    public boolean isLayoutRtl() {
4944        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4945    }
4946
4947    /**
4948     * Indicates whether the view is currently tracking transient state that the
4949     * app should not need to concern itself with saving and restoring, but that
4950     * the framework should take special note to preserve when possible.
4951     *
4952     * @return true if the view has transient state
4953     */
4954    @ViewDebug.ExportedProperty(category = "layout")
4955    public boolean hasTransientState() {
4956        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
4957    }
4958
4959    /**
4960     * Set whether this view is currently tracking transient state that the
4961     * framework should attempt to preserve when possible.
4962     *
4963     * @param hasTransientState true if this view has transient state
4964     */
4965    public void setHasTransientState(boolean hasTransientState) {
4966        if (hasTransientState() == hasTransientState) return;
4967
4968        mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
4969                (hasTransientState ? HAS_TRANSIENT_STATE : 0);
4970        if (mParent != null) {
4971            try {
4972                mParent.childHasTransientStateChanged(this, hasTransientState);
4973            } catch (AbstractMethodError e) {
4974                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
4975                        " does not fully implement ViewParent", e);
4976            }
4977        }
4978    }
4979
4980    /**
4981     * If this view doesn't do any drawing on its own, set this flag to
4982     * allow further optimizations. By default, this flag is not set on
4983     * View, but could be set on some View subclasses such as ViewGroup.
4984     *
4985     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4986     * you should clear this flag.
4987     *
4988     * @param willNotDraw whether or not this View draw on its own
4989     */
4990    public void setWillNotDraw(boolean willNotDraw) {
4991        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4992    }
4993
4994    /**
4995     * Returns whether or not this View draws on its own.
4996     *
4997     * @return true if this view has nothing to draw, false otherwise
4998     */
4999    @ViewDebug.ExportedProperty(category = "drawing")
5000    public boolean willNotDraw() {
5001        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5002    }
5003
5004    /**
5005     * When a View's drawing cache is enabled, drawing is redirected to an
5006     * offscreen bitmap. Some views, like an ImageView, must be able to
5007     * bypass this mechanism if they already draw a single bitmap, to avoid
5008     * unnecessary usage of the memory.
5009     *
5010     * @param willNotCacheDrawing true if this view does not cache its
5011     *        drawing, false otherwise
5012     */
5013    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5014        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5015    }
5016
5017    /**
5018     * Returns whether or not this View can cache its drawing or not.
5019     *
5020     * @return true if this view does not cache its drawing, false otherwise
5021     */
5022    @ViewDebug.ExportedProperty(category = "drawing")
5023    public boolean willNotCacheDrawing() {
5024        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5025    }
5026
5027    /**
5028     * Indicates whether this view reacts to click events or not.
5029     *
5030     * @return true if the view is clickable, false otherwise
5031     *
5032     * @see #setClickable(boolean)
5033     * @attr ref android.R.styleable#View_clickable
5034     */
5035    @ViewDebug.ExportedProperty
5036    public boolean isClickable() {
5037        return (mViewFlags & CLICKABLE) == CLICKABLE;
5038    }
5039
5040    /**
5041     * Enables or disables click events for this view. When a view
5042     * is clickable it will change its state to "pressed" on every click.
5043     * Subclasses should set the view clickable to visually react to
5044     * user's clicks.
5045     *
5046     * @param clickable true to make the view clickable, false otherwise
5047     *
5048     * @see #isClickable()
5049     * @attr ref android.R.styleable#View_clickable
5050     */
5051    public void setClickable(boolean clickable) {
5052        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5053    }
5054
5055    /**
5056     * Indicates whether this view reacts to long click events or not.
5057     *
5058     * @return true if the view is long clickable, false otherwise
5059     *
5060     * @see #setLongClickable(boolean)
5061     * @attr ref android.R.styleable#View_longClickable
5062     */
5063    public boolean isLongClickable() {
5064        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5065    }
5066
5067    /**
5068     * Enables or disables long click events for this view. When a view is long
5069     * clickable it reacts to the user holding down the button for a longer
5070     * duration than a tap. This event can either launch the listener or a
5071     * context menu.
5072     *
5073     * @param longClickable true to make the view long clickable, false otherwise
5074     * @see #isLongClickable()
5075     * @attr ref android.R.styleable#View_longClickable
5076     */
5077    public void setLongClickable(boolean longClickable) {
5078        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5079    }
5080
5081    /**
5082     * Sets the pressed state for this view.
5083     *
5084     * @see #isClickable()
5085     * @see #setClickable(boolean)
5086     *
5087     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5088     *        the View's internal state from a previously set "pressed" state.
5089     */
5090    public void setPressed(boolean pressed) {
5091        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5092
5093        if (pressed) {
5094            mPrivateFlags |= PRESSED;
5095        } else {
5096            mPrivateFlags &= ~PRESSED;
5097        }
5098
5099        if (needsRefresh) {
5100            refreshDrawableState();
5101        }
5102        dispatchSetPressed(pressed);
5103    }
5104
5105    /**
5106     * Dispatch setPressed to all of this View's children.
5107     *
5108     * @see #setPressed(boolean)
5109     *
5110     * @param pressed The new pressed state
5111     */
5112    protected void dispatchSetPressed(boolean pressed) {
5113    }
5114
5115    /**
5116     * Indicates whether the view is currently in pressed state. Unless
5117     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5118     * the pressed state.
5119     *
5120     * @see #setPressed(boolean)
5121     * @see #isClickable()
5122     * @see #setClickable(boolean)
5123     *
5124     * @return true if the view is currently pressed, false otherwise
5125     */
5126    public boolean isPressed() {
5127        return (mPrivateFlags & PRESSED) == PRESSED;
5128    }
5129
5130    /**
5131     * Indicates whether this view will save its state (that is,
5132     * whether its {@link #onSaveInstanceState} method will be called).
5133     *
5134     * @return Returns true if the view state saving is enabled, else false.
5135     *
5136     * @see #setSaveEnabled(boolean)
5137     * @attr ref android.R.styleable#View_saveEnabled
5138     */
5139    public boolean isSaveEnabled() {
5140        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5141    }
5142
5143    /**
5144     * Controls whether the saving of this view's state is
5145     * enabled (that is, whether its {@link #onSaveInstanceState} method
5146     * will be called).  Note that even if freezing is enabled, the
5147     * view still must have an id assigned to it (via {@link #setId(int)})
5148     * for its state to be saved.  This flag can only disable the
5149     * saving of this view; any child views may still have their state saved.
5150     *
5151     * @param enabled Set to false to <em>disable</em> state saving, or true
5152     * (the default) to allow it.
5153     *
5154     * @see #isSaveEnabled()
5155     * @see #setId(int)
5156     * @see #onSaveInstanceState()
5157     * @attr ref android.R.styleable#View_saveEnabled
5158     */
5159    public void setSaveEnabled(boolean enabled) {
5160        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5161    }
5162
5163    /**
5164     * Gets whether the framework should discard touches when the view's
5165     * window is obscured by another visible window.
5166     * Refer to the {@link View} security documentation for more details.
5167     *
5168     * @return True if touch filtering is enabled.
5169     *
5170     * @see #setFilterTouchesWhenObscured(boolean)
5171     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5172     */
5173    @ViewDebug.ExportedProperty
5174    public boolean getFilterTouchesWhenObscured() {
5175        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5176    }
5177
5178    /**
5179     * Sets whether the framework should discard touches when the view's
5180     * window is obscured by another visible window.
5181     * Refer to the {@link View} security documentation for more details.
5182     *
5183     * @param enabled True if touch filtering should be enabled.
5184     *
5185     * @see #getFilterTouchesWhenObscured
5186     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5187     */
5188    public void setFilterTouchesWhenObscured(boolean enabled) {
5189        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5190                FILTER_TOUCHES_WHEN_OBSCURED);
5191    }
5192
5193    /**
5194     * Indicates whether the entire hierarchy under this view will save its
5195     * state when a state saving traversal occurs from its parent.  The default
5196     * is true; if false, these views will not be saved unless
5197     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5198     *
5199     * @return Returns true if the view state saving from parent is enabled, else false.
5200     *
5201     * @see #setSaveFromParentEnabled(boolean)
5202     */
5203    public boolean isSaveFromParentEnabled() {
5204        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5205    }
5206
5207    /**
5208     * Controls whether the entire hierarchy under this view will save its
5209     * state when a state saving traversal occurs from its parent.  The default
5210     * is true; if false, these views will not be saved unless
5211     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5212     *
5213     * @param enabled Set to false to <em>disable</em> state saving, or true
5214     * (the default) to allow it.
5215     *
5216     * @see #isSaveFromParentEnabled()
5217     * @see #setId(int)
5218     * @see #onSaveInstanceState()
5219     */
5220    public void setSaveFromParentEnabled(boolean enabled) {
5221        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5222    }
5223
5224
5225    /**
5226     * Returns whether this View is able to take focus.
5227     *
5228     * @return True if this view can take focus, or false otherwise.
5229     * @attr ref android.R.styleable#View_focusable
5230     */
5231    @ViewDebug.ExportedProperty(category = "focus")
5232    public final boolean isFocusable() {
5233        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5234    }
5235
5236    /**
5237     * When a view is focusable, it may not want to take focus when in touch mode.
5238     * For example, a button would like focus when the user is navigating via a D-pad
5239     * so that the user can click on it, but once the user starts touching the screen,
5240     * the button shouldn't take focus
5241     * @return Whether the view is focusable in touch mode.
5242     * @attr ref android.R.styleable#View_focusableInTouchMode
5243     */
5244    @ViewDebug.ExportedProperty
5245    public final boolean isFocusableInTouchMode() {
5246        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5247    }
5248
5249    /**
5250     * Find the nearest view in the specified direction that can take focus.
5251     * This does not actually give focus to that view.
5252     *
5253     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5254     *
5255     * @return The nearest focusable in the specified direction, or null if none
5256     *         can be found.
5257     */
5258    public View focusSearch(int direction) {
5259        if (mParent != null) {
5260            return mParent.focusSearch(this, direction);
5261        } else {
5262            return null;
5263        }
5264    }
5265
5266    /**
5267     * This method is the last chance for the focused view and its ancestors to
5268     * respond to an arrow key. This is called when the focused view did not
5269     * consume the key internally, nor could the view system find a new view in
5270     * the requested direction to give focus to.
5271     *
5272     * @param focused The currently focused view.
5273     * @param direction The direction focus wants to move. One of FOCUS_UP,
5274     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5275     * @return True if the this view consumed this unhandled move.
5276     */
5277    public boolean dispatchUnhandledMove(View focused, int direction) {
5278        return false;
5279    }
5280
5281    /**
5282     * If a user manually specified the next view id for a particular direction,
5283     * use the root to look up the view.
5284     * @param root The root view of the hierarchy containing this view.
5285     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5286     * or FOCUS_BACKWARD.
5287     * @return The user specified next view, or null if there is none.
5288     */
5289    View findUserSetNextFocus(View root, int direction) {
5290        switch (direction) {
5291            case FOCUS_LEFT:
5292                if (mNextFocusLeftId == View.NO_ID) return null;
5293                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5294            case FOCUS_RIGHT:
5295                if (mNextFocusRightId == View.NO_ID) return null;
5296                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5297            case FOCUS_UP:
5298                if (mNextFocusUpId == View.NO_ID) return null;
5299                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5300            case FOCUS_DOWN:
5301                if (mNextFocusDownId == View.NO_ID) return null;
5302                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5303            case FOCUS_FORWARD:
5304                if (mNextFocusForwardId == View.NO_ID) return null;
5305                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5306            case FOCUS_BACKWARD: {
5307                if (mID == View.NO_ID) return null;
5308                final int id = mID;
5309                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5310                    @Override
5311                    public boolean apply(View t) {
5312                        return t.mNextFocusForwardId == id;
5313                    }
5314                });
5315            }
5316        }
5317        return null;
5318    }
5319
5320    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5321        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5322            @Override
5323            public boolean apply(View t) {
5324                return t.mID == childViewId;
5325            }
5326        });
5327
5328        if (result == null) {
5329            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5330                    + "by user for id " + childViewId);
5331        }
5332        return result;
5333    }
5334
5335    /**
5336     * Find and return all focusable views that are descendants of this view,
5337     * possibly including this view if it is focusable itself.
5338     *
5339     * @param direction The direction of the focus
5340     * @return A list of focusable views
5341     */
5342    public ArrayList<View> getFocusables(int direction) {
5343        ArrayList<View> result = new ArrayList<View>(24);
5344        addFocusables(result, direction);
5345        return result;
5346    }
5347
5348    /**
5349     * Add any focusable views that are descendants of this view (possibly
5350     * including this view if it is focusable itself) to views.  If we are in touch mode,
5351     * only add views that are also focusable in touch mode.
5352     *
5353     * @param views Focusable views found so far
5354     * @param direction The direction of the focus
5355     */
5356    public void addFocusables(ArrayList<View> views, int direction) {
5357        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5358    }
5359
5360    /**
5361     * Adds any focusable views that are descendants of this view (possibly
5362     * including this view if it is focusable itself) to views. This method
5363     * adds all focusable views regardless if we are in touch mode or
5364     * only views focusable in touch mode if we are in touch mode depending on
5365     * the focusable mode paramater.
5366     *
5367     * @param views Focusable views found so far or null if all we are interested is
5368     *        the number of focusables.
5369     * @param direction The direction of the focus.
5370     * @param focusableMode The type of focusables to be added.
5371     *
5372     * @see #FOCUSABLES_ALL
5373     * @see #FOCUSABLES_TOUCH_MODE
5374     */
5375    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5376        if (!isFocusable()) {
5377            return;
5378        }
5379
5380        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5381                isInTouchMode() && !isFocusableInTouchMode()) {
5382            return;
5383        }
5384
5385        if (views != null) {
5386            views.add(this);
5387        }
5388    }
5389
5390    /**
5391     * Finds the Views that contain given text. The containment is case insensitive.
5392     * The search is performed by either the text that the View renders or the content
5393     * description that describes the view for accessibility purposes and the view does
5394     * not render or both. Clients can specify how the search is to be performed via
5395     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5396     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5397     *
5398     * @param outViews The output list of matching Views.
5399     * @param searched The text to match against.
5400     *
5401     * @see #FIND_VIEWS_WITH_TEXT
5402     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5403     * @see #setContentDescription(CharSequence)
5404     */
5405    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5406        if (getAccessibilityNodeProvider() != null) {
5407            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5408                outViews.add(this);
5409            }
5410        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5411                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5412            String searchedLowerCase = searched.toString().toLowerCase();
5413            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5414            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5415                outViews.add(this);
5416            }
5417        }
5418    }
5419
5420    /**
5421     * Find and return all touchable views that are descendants of this view,
5422     * possibly including this view if it is touchable itself.
5423     *
5424     * @return A list of touchable views
5425     */
5426    public ArrayList<View> getTouchables() {
5427        ArrayList<View> result = new ArrayList<View>();
5428        addTouchables(result);
5429        return result;
5430    }
5431
5432    /**
5433     * Add any touchable views that are descendants of this view (possibly
5434     * including this view if it is touchable itself) to views.
5435     *
5436     * @param views Touchable views found so far
5437     */
5438    public void addTouchables(ArrayList<View> views) {
5439        final int viewFlags = mViewFlags;
5440
5441        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5442                && (viewFlags & ENABLED_MASK) == ENABLED) {
5443            views.add(this);
5444        }
5445    }
5446
5447    /**
5448     * Call this to try to give focus to a specific view or to one of its
5449     * descendants.
5450     *
5451     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5452     * false), or if it is focusable and it is not focusable in touch mode
5453     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5454     *
5455     * See also {@link #focusSearch(int)}, which is what you call to say that you
5456     * have focus, and you want your parent to look for the next one.
5457     *
5458     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5459     * {@link #FOCUS_DOWN} and <code>null</code>.
5460     *
5461     * @return Whether this view or one of its descendants actually took focus.
5462     */
5463    public final boolean requestFocus() {
5464        return requestFocus(View.FOCUS_DOWN);
5465    }
5466
5467
5468    /**
5469     * Call this to try to give focus to a specific view or to one of its
5470     * descendants and give it a hint about what direction focus is heading.
5471     *
5472     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5473     * false), or if it is focusable and it is not focusable in touch mode
5474     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5475     *
5476     * See also {@link #focusSearch(int)}, which is what you call to say that you
5477     * have focus, and you want your parent to look for the next one.
5478     *
5479     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5480     * <code>null</code> set for the previously focused rectangle.
5481     *
5482     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5483     * @return Whether this view or one of its descendants actually took focus.
5484     */
5485    public final boolean requestFocus(int direction) {
5486        return requestFocus(direction, null);
5487    }
5488
5489    /**
5490     * Call this to try to give focus to a specific view or to one of its descendants
5491     * and give it hints about the direction and a specific rectangle that the focus
5492     * is coming from.  The rectangle can help give larger views a finer grained hint
5493     * about where focus is coming from, and therefore, where to show selection, or
5494     * forward focus change internally.
5495     *
5496     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5497     * false), or if it is focusable and it is not focusable in touch mode
5498     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5499     *
5500     * A View will not take focus if it is not visible.
5501     *
5502     * A View will not take focus if one of its parents has
5503     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5504     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5505     *
5506     * See also {@link #focusSearch(int)}, which is what you call to say that you
5507     * have focus, and you want your parent to look for the next one.
5508     *
5509     * You may wish to override this method if your custom {@link View} has an internal
5510     * {@link View} that it wishes to forward the request to.
5511     *
5512     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5513     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5514     *        to give a finer grained hint about where focus is coming from.  May be null
5515     *        if there is no hint.
5516     * @return Whether this view or one of its descendants actually took focus.
5517     */
5518    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5519        // need to be focusable
5520        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5521                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5522            return false;
5523        }
5524
5525        // need to be focusable in touch mode if in touch mode
5526        if (isInTouchMode() &&
5527            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5528               return false;
5529        }
5530
5531        // need to not have any parents blocking us
5532        if (hasAncestorThatBlocksDescendantFocus()) {
5533            return false;
5534        }
5535
5536        handleFocusGainInternal(direction, previouslyFocusedRect);
5537        return true;
5538    }
5539
5540    /**
5541     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5542     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5543     * touch mode to request focus when they are touched.
5544     *
5545     * @return Whether this view or one of its descendants actually took focus.
5546     *
5547     * @see #isInTouchMode()
5548     *
5549     */
5550    public final boolean requestFocusFromTouch() {
5551        // Leave touch mode if we need to
5552        if (isInTouchMode()) {
5553            ViewRootImpl viewRoot = getViewRootImpl();
5554            if (viewRoot != null) {
5555                viewRoot.ensureTouchMode(false);
5556            }
5557        }
5558        return requestFocus(View.FOCUS_DOWN);
5559    }
5560
5561    /**
5562     * @return Whether any ancestor of this view blocks descendant focus.
5563     */
5564    private boolean hasAncestorThatBlocksDescendantFocus() {
5565        ViewParent ancestor = mParent;
5566        while (ancestor instanceof ViewGroup) {
5567            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5568            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5569                return true;
5570            } else {
5571                ancestor = vgAncestor.getParent();
5572            }
5573        }
5574        return false;
5575    }
5576
5577    /**
5578     * @hide
5579     */
5580    public void dispatchStartTemporaryDetach() {
5581        onStartTemporaryDetach();
5582    }
5583
5584    /**
5585     * This is called when a container is going to temporarily detach a child, with
5586     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5587     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5588     * {@link #onDetachedFromWindow()} when the container is done.
5589     */
5590    public void onStartTemporaryDetach() {
5591        removeUnsetPressCallback();
5592        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5593    }
5594
5595    /**
5596     * @hide
5597     */
5598    public void dispatchFinishTemporaryDetach() {
5599        onFinishTemporaryDetach();
5600    }
5601
5602    /**
5603     * Called after {@link #onStartTemporaryDetach} when the container is done
5604     * changing the view.
5605     */
5606    public void onFinishTemporaryDetach() {
5607    }
5608
5609    /**
5610     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5611     * for this view's window.  Returns null if the view is not currently attached
5612     * to the window.  Normally you will not need to use this directly, but
5613     * just use the standard high-level event callbacks like
5614     * {@link #onKeyDown(int, KeyEvent)}.
5615     */
5616    public KeyEvent.DispatcherState getKeyDispatcherState() {
5617        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5618    }
5619
5620    /**
5621     * Dispatch a key event before it is processed by any input method
5622     * associated with the view hierarchy.  This can be used to intercept
5623     * key events in special situations before the IME consumes them; a
5624     * typical example would be handling the BACK key to update the application's
5625     * UI instead of allowing the IME to see it and close itself.
5626     *
5627     * @param event The key event to be dispatched.
5628     * @return True if the event was handled, false otherwise.
5629     */
5630    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5631        return onKeyPreIme(event.getKeyCode(), event);
5632    }
5633
5634    /**
5635     * Dispatch a key event to the next view on the focus path. This path runs
5636     * from the top of the view tree down to the currently focused view. If this
5637     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5638     * the next node down the focus path. This method also fires any key
5639     * listeners.
5640     *
5641     * @param event The key event to be dispatched.
5642     * @return True if the event was handled, false otherwise.
5643     */
5644    public boolean dispatchKeyEvent(KeyEvent event) {
5645        if (mInputEventConsistencyVerifier != null) {
5646            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5647        }
5648
5649        // Give any attached key listener a first crack at the event.
5650        //noinspection SimplifiableIfStatement
5651        ListenerInfo li = mListenerInfo;
5652        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5653                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5654            return true;
5655        }
5656
5657        if (event.dispatch(this, mAttachInfo != null
5658                ? mAttachInfo.mKeyDispatchState : null, this)) {
5659            return true;
5660        }
5661
5662        if (mInputEventConsistencyVerifier != null) {
5663            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5664        }
5665        return false;
5666    }
5667
5668    /**
5669     * Dispatches a key shortcut event.
5670     *
5671     * @param event The key event to be dispatched.
5672     * @return True if the event was handled by the view, false otherwise.
5673     */
5674    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5675        return onKeyShortcut(event.getKeyCode(), event);
5676    }
5677
5678    /**
5679     * Pass the touch screen motion event down to the target view, or this
5680     * view if it is the target.
5681     *
5682     * @param event The motion event to be dispatched.
5683     * @return True if the event was handled by the view, false otherwise.
5684     */
5685    public boolean dispatchTouchEvent(MotionEvent event) {
5686        if (mInputEventConsistencyVerifier != null) {
5687            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5688        }
5689
5690        if (onFilterTouchEventForSecurity(event)) {
5691            //noinspection SimplifiableIfStatement
5692            ListenerInfo li = mListenerInfo;
5693            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5694                    && li.mOnTouchListener.onTouch(this, event)) {
5695                return true;
5696            }
5697
5698            if (onTouchEvent(event)) {
5699                return true;
5700            }
5701        }
5702
5703        if (mInputEventConsistencyVerifier != null) {
5704            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5705        }
5706        return false;
5707    }
5708
5709    /**
5710     * Filter the touch event to apply security policies.
5711     *
5712     * @param event The motion event to be filtered.
5713     * @return True if the event should be dispatched, false if the event should be dropped.
5714     *
5715     * @see #getFilterTouchesWhenObscured
5716     */
5717    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5718        //noinspection RedundantIfStatement
5719        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5720                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5721            // Window is obscured, drop this touch.
5722            return false;
5723        }
5724        return true;
5725    }
5726
5727    /**
5728     * Pass a trackball motion event down to the focused view.
5729     *
5730     * @param event The motion event to be dispatched.
5731     * @return True if the event was handled by the view, false otherwise.
5732     */
5733    public boolean dispatchTrackballEvent(MotionEvent event) {
5734        if (mInputEventConsistencyVerifier != null) {
5735            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5736        }
5737
5738        return onTrackballEvent(event);
5739    }
5740
5741    /**
5742     * Dispatch a generic motion event.
5743     * <p>
5744     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5745     * are delivered to the view under the pointer.  All other generic motion events are
5746     * delivered to the focused view.  Hover events are handled specially and are delivered
5747     * to {@link #onHoverEvent(MotionEvent)}.
5748     * </p>
5749     *
5750     * @param event The motion event to be dispatched.
5751     * @return True if the event was handled by the view, false otherwise.
5752     */
5753    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5754        if (mInputEventConsistencyVerifier != null) {
5755            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5756        }
5757
5758        final int source = event.getSource();
5759        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5760            final int action = event.getAction();
5761            if (action == MotionEvent.ACTION_HOVER_ENTER
5762                    || action == MotionEvent.ACTION_HOVER_MOVE
5763                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5764                if (dispatchHoverEvent(event)) {
5765                    return true;
5766                }
5767            } else if (dispatchGenericPointerEvent(event)) {
5768                return true;
5769            }
5770        } else if (dispatchGenericFocusedEvent(event)) {
5771            return true;
5772        }
5773
5774        if (dispatchGenericMotionEventInternal(event)) {
5775            return true;
5776        }
5777
5778        if (mInputEventConsistencyVerifier != null) {
5779            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5780        }
5781        return false;
5782    }
5783
5784    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5785        //noinspection SimplifiableIfStatement
5786        ListenerInfo li = mListenerInfo;
5787        if (li != null && li.mOnGenericMotionListener != null
5788                && (mViewFlags & ENABLED_MASK) == ENABLED
5789                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5790            return true;
5791        }
5792
5793        if (onGenericMotionEvent(event)) {
5794            return true;
5795        }
5796
5797        if (mInputEventConsistencyVerifier != null) {
5798            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5799        }
5800        return false;
5801    }
5802
5803    /**
5804     * Dispatch a hover event.
5805     * <p>
5806     * Do not call this method directly.
5807     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5808     * </p>
5809     *
5810     * @param event The motion event to be dispatched.
5811     * @return True if the event was handled by the view, false otherwise.
5812     */
5813    protected boolean dispatchHoverEvent(MotionEvent event) {
5814        //noinspection SimplifiableIfStatement
5815        ListenerInfo li = mListenerInfo;
5816        if (li != null && li.mOnHoverListener != null
5817                && (mViewFlags & ENABLED_MASK) == ENABLED
5818                && li.mOnHoverListener.onHover(this, event)) {
5819            return true;
5820        }
5821
5822        return onHoverEvent(event);
5823    }
5824
5825    /**
5826     * Returns true if the view has a child to which it has recently sent
5827     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5828     * it does not have a hovered child, then it must be the innermost hovered view.
5829     * @hide
5830     */
5831    protected boolean hasHoveredChild() {
5832        return false;
5833    }
5834
5835    /**
5836     * Dispatch a generic motion event to the view under the first pointer.
5837     * <p>
5838     * Do not call this method directly.
5839     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5840     * </p>
5841     *
5842     * @param event The motion event to be dispatched.
5843     * @return True if the event was handled by the view, false otherwise.
5844     */
5845    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5846        return false;
5847    }
5848
5849    /**
5850     * Dispatch a generic motion event to the currently focused view.
5851     * <p>
5852     * Do not call this method directly.
5853     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5854     * </p>
5855     *
5856     * @param event The motion event to be dispatched.
5857     * @return True if the event was handled by the view, false otherwise.
5858     */
5859    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5860        return false;
5861    }
5862
5863    /**
5864     * Dispatch a pointer event.
5865     * <p>
5866     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5867     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5868     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5869     * and should not be expected to handle other pointing device features.
5870     * </p>
5871     *
5872     * @param event The motion event to be dispatched.
5873     * @return True if the event was handled by the view, false otherwise.
5874     * @hide
5875     */
5876    public final boolean dispatchPointerEvent(MotionEvent event) {
5877        if (event.isTouchEvent()) {
5878            return dispatchTouchEvent(event);
5879        } else {
5880            return dispatchGenericMotionEvent(event);
5881        }
5882    }
5883
5884    /**
5885     * Called when the window containing this view gains or loses window focus.
5886     * ViewGroups should override to route to their children.
5887     *
5888     * @param hasFocus True if the window containing this view now has focus,
5889     *        false otherwise.
5890     */
5891    public void dispatchWindowFocusChanged(boolean hasFocus) {
5892        onWindowFocusChanged(hasFocus);
5893    }
5894
5895    /**
5896     * Called when the window containing this view gains or loses focus.  Note
5897     * that this is separate from view focus: to receive key events, both
5898     * your view and its window must have focus.  If a window is displayed
5899     * on top of yours that takes input focus, then your own window will lose
5900     * focus but the view focus will remain unchanged.
5901     *
5902     * @param hasWindowFocus True if the window containing this view now has
5903     *        focus, false otherwise.
5904     */
5905    public void onWindowFocusChanged(boolean hasWindowFocus) {
5906        InputMethodManager imm = InputMethodManager.peekInstance();
5907        if (!hasWindowFocus) {
5908            if (isPressed()) {
5909                setPressed(false);
5910            }
5911            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5912                imm.focusOut(this);
5913            }
5914            removeLongPressCallback();
5915            removeTapCallback();
5916            onFocusLost();
5917        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5918            imm.focusIn(this);
5919        }
5920        refreshDrawableState();
5921    }
5922
5923    /**
5924     * Returns true if this view is in a window that currently has window focus.
5925     * Note that this is not the same as the view itself having focus.
5926     *
5927     * @return True if this view is in a window that currently has window focus.
5928     */
5929    public boolean hasWindowFocus() {
5930        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5931    }
5932
5933    /**
5934     * Dispatch a view visibility change down the view hierarchy.
5935     * ViewGroups should override to route to their children.
5936     * @param changedView The view whose visibility changed. Could be 'this' or
5937     * an ancestor view.
5938     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5939     * {@link #INVISIBLE} or {@link #GONE}.
5940     */
5941    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5942        onVisibilityChanged(changedView, visibility);
5943    }
5944
5945    /**
5946     * Called when the visibility of the view or an ancestor of the view is changed.
5947     * @param changedView The view whose visibility changed. Could be 'this' or
5948     * an ancestor view.
5949     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5950     * {@link #INVISIBLE} or {@link #GONE}.
5951     */
5952    protected void onVisibilityChanged(View changedView, int visibility) {
5953        if (visibility == VISIBLE) {
5954            if (mAttachInfo != null) {
5955                initialAwakenScrollBars();
5956            } else {
5957                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5958            }
5959        }
5960    }
5961
5962    /**
5963     * Dispatch a hint about whether this view is displayed. For instance, when
5964     * a View moves out of the screen, it might receives a display hint indicating
5965     * the view is not displayed. Applications should not <em>rely</em> on this hint
5966     * as there is no guarantee that they will receive one.
5967     *
5968     * @param hint A hint about whether or not this view is displayed:
5969     * {@link #VISIBLE} or {@link #INVISIBLE}.
5970     */
5971    public void dispatchDisplayHint(int hint) {
5972        onDisplayHint(hint);
5973    }
5974
5975    /**
5976     * Gives this view a hint about whether is displayed or not. For instance, when
5977     * a View moves out of the screen, it might receives a display hint indicating
5978     * the view is not displayed. Applications should not <em>rely</em> on this hint
5979     * as there is no guarantee that they will receive one.
5980     *
5981     * @param hint A hint about whether or not this view is displayed:
5982     * {@link #VISIBLE} or {@link #INVISIBLE}.
5983     */
5984    protected void onDisplayHint(int hint) {
5985    }
5986
5987    /**
5988     * Dispatch a window visibility change down the view hierarchy.
5989     * ViewGroups should override to route to their children.
5990     *
5991     * @param visibility The new visibility of the window.
5992     *
5993     * @see #onWindowVisibilityChanged(int)
5994     */
5995    public void dispatchWindowVisibilityChanged(int visibility) {
5996        onWindowVisibilityChanged(visibility);
5997    }
5998
5999    /**
6000     * Called when the window containing has change its visibility
6001     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6002     * that this tells you whether or not your window is being made visible
6003     * to the window manager; this does <em>not</em> tell you whether or not
6004     * your window is obscured by other windows on the screen, even if it
6005     * is itself visible.
6006     *
6007     * @param visibility The new visibility of the window.
6008     */
6009    protected void onWindowVisibilityChanged(int visibility) {
6010        if (visibility == VISIBLE) {
6011            initialAwakenScrollBars();
6012        }
6013    }
6014
6015    /**
6016     * Returns the current visibility of the window this view is attached to
6017     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6018     *
6019     * @return Returns the current visibility of the view's window.
6020     */
6021    public int getWindowVisibility() {
6022        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6023    }
6024
6025    /**
6026     * Retrieve the overall visible display size in which the window this view is
6027     * attached to has been positioned in.  This takes into account screen
6028     * decorations above the window, for both cases where the window itself
6029     * is being position inside of them or the window is being placed under
6030     * then and covered insets are used for the window to position its content
6031     * inside.  In effect, this tells you the available area where content can
6032     * be placed and remain visible to users.
6033     *
6034     * <p>This function requires an IPC back to the window manager to retrieve
6035     * the requested information, so should not be used in performance critical
6036     * code like drawing.
6037     *
6038     * @param outRect Filled in with the visible display frame.  If the view
6039     * is not attached to a window, this is simply the raw display size.
6040     */
6041    public void getWindowVisibleDisplayFrame(Rect outRect) {
6042        if (mAttachInfo != null) {
6043            try {
6044                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6045            } catch (RemoteException e) {
6046                return;
6047            }
6048            // XXX This is really broken, and probably all needs to be done
6049            // in the window manager, and we need to know more about whether
6050            // we want the area behind or in front of the IME.
6051            final Rect insets = mAttachInfo.mVisibleInsets;
6052            outRect.left += insets.left;
6053            outRect.top += insets.top;
6054            outRect.right -= insets.right;
6055            outRect.bottom -= insets.bottom;
6056            return;
6057        }
6058        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6059        d.getRectSize(outRect);
6060    }
6061
6062    /**
6063     * Dispatch a notification about a resource configuration change down
6064     * the view hierarchy.
6065     * ViewGroups should override to route to their children.
6066     *
6067     * @param newConfig The new resource configuration.
6068     *
6069     * @see #onConfigurationChanged(android.content.res.Configuration)
6070     */
6071    public void dispatchConfigurationChanged(Configuration newConfig) {
6072        onConfigurationChanged(newConfig);
6073    }
6074
6075    /**
6076     * Called when the current configuration of the resources being used
6077     * by the application have changed.  You can use this to decide when
6078     * to reload resources that can changed based on orientation and other
6079     * configuration characterstics.  You only need to use this if you are
6080     * not relying on the normal {@link android.app.Activity} mechanism of
6081     * recreating the activity instance upon a configuration change.
6082     *
6083     * @param newConfig The new resource configuration.
6084     */
6085    protected void onConfigurationChanged(Configuration newConfig) {
6086    }
6087
6088    /**
6089     * Private function to aggregate all per-view attributes in to the view
6090     * root.
6091     */
6092    void dispatchCollectViewAttributes(int visibility) {
6093        performCollectViewAttributes(visibility);
6094    }
6095
6096    void performCollectViewAttributes(int visibility) {
6097        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6098            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6099                mAttachInfo.mKeepScreenOn = true;
6100            }
6101            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6102            ListenerInfo li = mListenerInfo;
6103            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6104                mAttachInfo.mHasSystemUiListeners = true;
6105            }
6106        }
6107    }
6108
6109    void needGlobalAttributesUpdate(boolean force) {
6110        final AttachInfo ai = mAttachInfo;
6111        if (ai != null) {
6112            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6113                    || ai.mHasSystemUiListeners) {
6114                ai.mRecomputeGlobalAttributes = true;
6115            }
6116        }
6117    }
6118
6119    /**
6120     * Returns whether the device is currently in touch mode.  Touch mode is entered
6121     * once the user begins interacting with the device by touch, and affects various
6122     * things like whether focus is always visible to the user.
6123     *
6124     * @return Whether the device is in touch mode.
6125     */
6126    @ViewDebug.ExportedProperty
6127    public boolean isInTouchMode() {
6128        if (mAttachInfo != null) {
6129            return mAttachInfo.mInTouchMode;
6130        } else {
6131            return ViewRootImpl.isInTouchMode();
6132        }
6133    }
6134
6135    /**
6136     * Returns the context the view is running in, through which it can
6137     * access the current theme, resources, etc.
6138     *
6139     * @return The view's Context.
6140     */
6141    @ViewDebug.CapturedViewProperty
6142    public final Context getContext() {
6143        return mContext;
6144    }
6145
6146    /**
6147     * Handle a key event before it is processed by any input method
6148     * associated with the view hierarchy.  This can be used to intercept
6149     * key events in special situations before the IME consumes them; a
6150     * typical example would be handling the BACK key to update the application's
6151     * UI instead of allowing the IME to see it and close itself.
6152     *
6153     * @param keyCode The value in event.getKeyCode().
6154     * @param event Description of the key event.
6155     * @return If you handled the event, return true. If you want to allow the
6156     *         event to be handled by the next receiver, return false.
6157     */
6158    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6159        return false;
6160    }
6161
6162    /**
6163     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6164     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6165     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6166     * is released, if the view is enabled and clickable.
6167     *
6168     * @param keyCode A key code that represents the button pressed, from
6169     *                {@link android.view.KeyEvent}.
6170     * @param event   The KeyEvent object that defines the button action.
6171     */
6172    public boolean onKeyDown(int keyCode, KeyEvent event) {
6173        boolean result = false;
6174
6175        switch (keyCode) {
6176            case KeyEvent.KEYCODE_DPAD_CENTER:
6177            case KeyEvent.KEYCODE_ENTER: {
6178                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6179                    return true;
6180                }
6181                // Long clickable items don't necessarily have to be clickable
6182                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6183                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6184                        (event.getRepeatCount() == 0)) {
6185                    setPressed(true);
6186                    checkForLongClick(0);
6187                    return true;
6188                }
6189                break;
6190            }
6191        }
6192        return result;
6193    }
6194
6195    /**
6196     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6197     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6198     * the event).
6199     */
6200    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6201        return false;
6202    }
6203
6204    /**
6205     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6206     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6207     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6208     * {@link KeyEvent#KEYCODE_ENTER} is released.
6209     *
6210     * @param keyCode A key code that represents the button pressed, from
6211     *                {@link android.view.KeyEvent}.
6212     * @param event   The KeyEvent object that defines the button action.
6213     */
6214    public boolean onKeyUp(int keyCode, KeyEvent event) {
6215        boolean result = false;
6216
6217        switch (keyCode) {
6218            case KeyEvent.KEYCODE_DPAD_CENTER:
6219            case KeyEvent.KEYCODE_ENTER: {
6220                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6221                    return true;
6222                }
6223                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6224                    setPressed(false);
6225
6226                    if (!mHasPerformedLongPress) {
6227                        // This is a tap, so remove the longpress check
6228                        removeLongPressCallback();
6229
6230                        result = performClick();
6231                    }
6232                }
6233                break;
6234            }
6235        }
6236        return result;
6237    }
6238
6239    /**
6240     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6241     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6242     * the event).
6243     *
6244     * @param keyCode     A key code that represents the button pressed, from
6245     *                    {@link android.view.KeyEvent}.
6246     * @param repeatCount The number of times the action was made.
6247     * @param event       The KeyEvent object that defines the button action.
6248     */
6249    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6250        return false;
6251    }
6252
6253    /**
6254     * Called on the focused view when a key shortcut event is not handled.
6255     * Override this method to implement local key shortcuts for the View.
6256     * Key shortcuts can also be implemented by setting the
6257     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6258     *
6259     * @param keyCode The value in event.getKeyCode().
6260     * @param event Description of the key event.
6261     * @return If you handled the event, return true. If you want to allow the
6262     *         event to be handled by the next receiver, return false.
6263     */
6264    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6265        return false;
6266    }
6267
6268    /**
6269     * Check whether the called view is a text editor, in which case it
6270     * would make sense to automatically display a soft input window for
6271     * it.  Subclasses should override this if they implement
6272     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6273     * a call on that method would return a non-null InputConnection, and
6274     * they are really a first-class editor that the user would normally
6275     * start typing on when the go into a window containing your view.
6276     *
6277     * <p>The default implementation always returns false.  This does
6278     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6279     * will not be called or the user can not otherwise perform edits on your
6280     * view; it is just a hint to the system that this is not the primary
6281     * purpose of this view.
6282     *
6283     * @return Returns true if this view is a text editor, else false.
6284     */
6285    public boolean onCheckIsTextEditor() {
6286        return false;
6287    }
6288
6289    /**
6290     * Create a new InputConnection for an InputMethod to interact
6291     * with the view.  The default implementation returns null, since it doesn't
6292     * support input methods.  You can override this to implement such support.
6293     * This is only needed for views that take focus and text input.
6294     *
6295     * <p>When implementing this, you probably also want to implement
6296     * {@link #onCheckIsTextEditor()} to indicate you will return a
6297     * non-null InputConnection.
6298     *
6299     * @param outAttrs Fill in with attribute information about the connection.
6300     */
6301    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6302        return null;
6303    }
6304
6305    /**
6306     * Called by the {@link android.view.inputmethod.InputMethodManager}
6307     * when a view who is not the current
6308     * input connection target is trying to make a call on the manager.  The
6309     * default implementation returns false; you can override this to return
6310     * true for certain views if you are performing InputConnection proxying
6311     * to them.
6312     * @param view The View that is making the InputMethodManager call.
6313     * @return Return true to allow the call, false to reject.
6314     */
6315    public boolean checkInputConnectionProxy(View view) {
6316        return false;
6317    }
6318
6319    /**
6320     * Show the context menu for this view. It is not safe to hold on to the
6321     * menu after returning from this method.
6322     *
6323     * You should normally not overload this method. Overload
6324     * {@link #onCreateContextMenu(ContextMenu)} or define an
6325     * {@link OnCreateContextMenuListener} to add items to the context menu.
6326     *
6327     * @param menu The context menu to populate
6328     */
6329    public void createContextMenu(ContextMenu menu) {
6330        ContextMenuInfo menuInfo = getContextMenuInfo();
6331
6332        // Sets the current menu info so all items added to menu will have
6333        // my extra info set.
6334        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6335
6336        onCreateContextMenu(menu);
6337        ListenerInfo li = mListenerInfo;
6338        if (li != null && li.mOnCreateContextMenuListener != null) {
6339            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6340        }
6341
6342        // Clear the extra information so subsequent items that aren't mine don't
6343        // have my extra info.
6344        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6345
6346        if (mParent != null) {
6347            mParent.createContextMenu(menu);
6348        }
6349    }
6350
6351    /**
6352     * Views should implement this if they have extra information to associate
6353     * with the context menu. The return result is supplied as a parameter to
6354     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6355     * callback.
6356     *
6357     * @return Extra information about the item for which the context menu
6358     *         should be shown. This information will vary across different
6359     *         subclasses of View.
6360     */
6361    protected ContextMenuInfo getContextMenuInfo() {
6362        return null;
6363    }
6364
6365    /**
6366     * Views should implement this if the view itself is going to add items to
6367     * the context menu.
6368     *
6369     * @param menu the context menu to populate
6370     */
6371    protected void onCreateContextMenu(ContextMenu menu) {
6372    }
6373
6374    /**
6375     * Implement this method to handle trackball motion events.  The
6376     * <em>relative</em> movement of the trackball since the last event
6377     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6378     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6379     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6380     * they will often be fractional values, representing the more fine-grained
6381     * movement information available from a trackball).
6382     *
6383     * @param event The motion event.
6384     * @return True if the event was handled, false otherwise.
6385     */
6386    public boolean onTrackballEvent(MotionEvent event) {
6387        return false;
6388    }
6389
6390    /**
6391     * Implement this method to handle generic motion events.
6392     * <p>
6393     * Generic motion events describe joystick movements, mouse hovers, track pad
6394     * touches, scroll wheel movements and other input events.  The
6395     * {@link MotionEvent#getSource() source} of the motion event specifies
6396     * the class of input that was received.  Implementations of this method
6397     * must examine the bits in the source before processing the event.
6398     * The following code example shows how this is done.
6399     * </p><p>
6400     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6401     * are delivered to the view under the pointer.  All other generic motion events are
6402     * delivered to the focused view.
6403     * </p>
6404     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6405     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6406     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6407     *             // process the joystick movement...
6408     *             return true;
6409     *         }
6410     *     }
6411     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6412     *         switch (event.getAction()) {
6413     *             case MotionEvent.ACTION_HOVER_MOVE:
6414     *                 // process the mouse hover movement...
6415     *                 return true;
6416     *             case MotionEvent.ACTION_SCROLL:
6417     *                 // process the scroll wheel movement...
6418     *                 return true;
6419     *         }
6420     *     }
6421     *     return super.onGenericMotionEvent(event);
6422     * }</pre>
6423     *
6424     * @param event The generic motion event being processed.
6425     * @return True if the event was handled, false otherwise.
6426     */
6427    public boolean onGenericMotionEvent(MotionEvent event) {
6428        return false;
6429    }
6430
6431    /**
6432     * Implement this method to handle hover events.
6433     * <p>
6434     * This method is called whenever a pointer is hovering into, over, or out of the
6435     * bounds of a view and the view is not currently being touched.
6436     * Hover events are represented as pointer events with action
6437     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6438     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6439     * </p>
6440     * <ul>
6441     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6442     * when the pointer enters the bounds of the view.</li>
6443     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6444     * when the pointer has already entered the bounds of the view and has moved.</li>
6445     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6446     * when the pointer has exited the bounds of the view or when the pointer is
6447     * about to go down due to a button click, tap, or similar user action that
6448     * causes the view to be touched.</li>
6449     * </ul>
6450     * <p>
6451     * The view should implement this method to return true to indicate that it is
6452     * handling the hover event, such as by changing its drawable state.
6453     * </p><p>
6454     * The default implementation calls {@link #setHovered} to update the hovered state
6455     * of the view when a hover enter or hover exit event is received, if the view
6456     * is enabled and is clickable.  The default implementation also sends hover
6457     * accessibility events.
6458     * </p>
6459     *
6460     * @param event The motion event that describes the hover.
6461     * @return True if the view handled the hover event.
6462     *
6463     * @see #isHovered
6464     * @see #setHovered
6465     * @see #onHoverChanged
6466     */
6467    public boolean onHoverEvent(MotionEvent event) {
6468        // The root view may receive hover (or touch) events that are outside the bounds of
6469        // the window.  This code ensures that we only send accessibility events for
6470        // hovers that are actually within the bounds of the root view.
6471        final int action = event.getAction();
6472        if (!mSendingHoverAccessibilityEvents) {
6473            if ((action == MotionEvent.ACTION_HOVER_ENTER
6474                    || action == MotionEvent.ACTION_HOVER_MOVE)
6475                    && !hasHoveredChild()
6476                    && pointInView(event.getX(), event.getY())) {
6477                mSendingHoverAccessibilityEvents = true;
6478                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6479            }
6480        } else {
6481            if (action == MotionEvent.ACTION_HOVER_EXIT
6482                    || (action == MotionEvent.ACTION_HOVER_MOVE
6483                            && !pointInView(event.getX(), event.getY()))) {
6484                mSendingHoverAccessibilityEvents = false;
6485                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6486            }
6487        }
6488
6489        if (isHoverable()) {
6490            switch (action) {
6491                case MotionEvent.ACTION_HOVER_ENTER:
6492                    setHovered(true);
6493                    break;
6494                case MotionEvent.ACTION_HOVER_EXIT:
6495                    setHovered(false);
6496                    break;
6497            }
6498
6499            // Dispatch the event to onGenericMotionEvent before returning true.
6500            // This is to provide compatibility with existing applications that
6501            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6502            // break because of the new default handling for hoverable views
6503            // in onHoverEvent.
6504            // Note that onGenericMotionEvent will be called by default when
6505            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6506            dispatchGenericMotionEventInternal(event);
6507            return true;
6508        }
6509        return false;
6510    }
6511
6512    /**
6513     * Returns true if the view should handle {@link #onHoverEvent}
6514     * by calling {@link #setHovered} to change its hovered state.
6515     *
6516     * @return True if the view is hoverable.
6517     */
6518    private boolean isHoverable() {
6519        final int viewFlags = mViewFlags;
6520        //noinspection SimplifiableIfStatement
6521        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6522            return false;
6523        }
6524
6525        return (viewFlags & CLICKABLE) == CLICKABLE
6526                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6527    }
6528
6529    /**
6530     * Returns true if the view is currently hovered.
6531     *
6532     * @return True if the view is currently hovered.
6533     *
6534     * @see #setHovered
6535     * @see #onHoverChanged
6536     */
6537    @ViewDebug.ExportedProperty
6538    public boolean isHovered() {
6539        return (mPrivateFlags & HOVERED) != 0;
6540    }
6541
6542    /**
6543     * Sets whether the view is currently hovered.
6544     * <p>
6545     * Calling this method also changes the drawable state of the view.  This
6546     * enables the view to react to hover by using different drawable resources
6547     * to change its appearance.
6548     * </p><p>
6549     * The {@link #onHoverChanged} method is called when the hovered state changes.
6550     * </p>
6551     *
6552     * @param hovered True if the view is hovered.
6553     *
6554     * @see #isHovered
6555     * @see #onHoverChanged
6556     */
6557    public void setHovered(boolean hovered) {
6558        if (hovered) {
6559            if ((mPrivateFlags & HOVERED) == 0) {
6560                mPrivateFlags |= HOVERED;
6561                refreshDrawableState();
6562                onHoverChanged(true);
6563            }
6564        } else {
6565            if ((mPrivateFlags & HOVERED) != 0) {
6566                mPrivateFlags &= ~HOVERED;
6567                refreshDrawableState();
6568                onHoverChanged(false);
6569            }
6570        }
6571    }
6572
6573    /**
6574     * Implement this method to handle hover state changes.
6575     * <p>
6576     * This method is called whenever the hover state changes as a result of a
6577     * call to {@link #setHovered}.
6578     * </p>
6579     *
6580     * @param hovered The current hover state, as returned by {@link #isHovered}.
6581     *
6582     * @see #isHovered
6583     * @see #setHovered
6584     */
6585    public void onHoverChanged(boolean hovered) {
6586    }
6587
6588    /**
6589     * Implement this method to handle touch screen motion events.
6590     *
6591     * @param event The motion event.
6592     * @return True if the event was handled, false otherwise.
6593     */
6594    public boolean onTouchEvent(MotionEvent event) {
6595        final int viewFlags = mViewFlags;
6596
6597        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6598            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6599                setPressed(false);
6600            }
6601            // A disabled view that is clickable still consumes the touch
6602            // events, it just doesn't respond to them.
6603            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6604                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6605        }
6606
6607        if (mTouchDelegate != null) {
6608            if (mTouchDelegate.onTouchEvent(event)) {
6609                return true;
6610            }
6611        }
6612
6613        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6614                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6615            switch (event.getAction()) {
6616                case MotionEvent.ACTION_UP:
6617                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6618                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6619                        // take focus if we don't have it already and we should in
6620                        // touch mode.
6621                        boolean focusTaken = false;
6622                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6623                            focusTaken = requestFocus();
6624                        }
6625
6626                        if (prepressed) {
6627                            // The button is being released before we actually
6628                            // showed it as pressed.  Make it show the pressed
6629                            // state now (before scheduling the click) to ensure
6630                            // the user sees it.
6631                            setPressed(true);
6632                       }
6633
6634                        if (!mHasPerformedLongPress) {
6635                            // This is a tap, so remove the longpress check
6636                            removeLongPressCallback();
6637
6638                            // Only perform take click actions if we were in the pressed state
6639                            if (!focusTaken) {
6640                                // Use a Runnable and post this rather than calling
6641                                // performClick directly. This lets other visual state
6642                                // of the view update before click actions start.
6643                                if (mPerformClick == null) {
6644                                    mPerformClick = new PerformClick();
6645                                }
6646                                if (!post(mPerformClick)) {
6647                                    performClick();
6648                                }
6649                            }
6650                        }
6651
6652                        if (mUnsetPressedState == null) {
6653                            mUnsetPressedState = new UnsetPressedState();
6654                        }
6655
6656                        if (prepressed) {
6657                            postDelayed(mUnsetPressedState,
6658                                    ViewConfiguration.getPressedStateDuration());
6659                        } else if (!post(mUnsetPressedState)) {
6660                            // If the post failed, unpress right now
6661                            mUnsetPressedState.run();
6662                        }
6663                        removeTapCallback();
6664                    }
6665                    break;
6666
6667                case MotionEvent.ACTION_DOWN:
6668                    mHasPerformedLongPress = false;
6669
6670                    if (performButtonActionOnTouchDown(event)) {
6671                        break;
6672                    }
6673
6674                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6675                    boolean isInScrollingContainer = isInScrollingContainer();
6676
6677                    // For views inside a scrolling container, delay the pressed feedback for
6678                    // a short period in case this is a scroll.
6679                    if (isInScrollingContainer) {
6680                        mPrivateFlags |= PREPRESSED;
6681                        if (mPendingCheckForTap == null) {
6682                            mPendingCheckForTap = new CheckForTap();
6683                        }
6684                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6685                    } else {
6686                        // Not inside a scrolling container, so show the feedback right away
6687                        setPressed(true);
6688                        checkForLongClick(0);
6689                    }
6690                    break;
6691
6692                case MotionEvent.ACTION_CANCEL:
6693                    setPressed(false);
6694                    removeTapCallback();
6695                    break;
6696
6697                case MotionEvent.ACTION_MOVE:
6698                    final int x = (int) event.getX();
6699                    final int y = (int) event.getY();
6700
6701                    // Be lenient about moving outside of buttons
6702                    if (!pointInView(x, y, mTouchSlop)) {
6703                        // Outside button
6704                        removeTapCallback();
6705                        if ((mPrivateFlags & PRESSED) != 0) {
6706                            // Remove any future long press/tap checks
6707                            removeLongPressCallback();
6708
6709                            setPressed(false);
6710                        }
6711                    }
6712                    break;
6713            }
6714            return true;
6715        }
6716
6717        return false;
6718    }
6719
6720    /**
6721     * @hide
6722     */
6723    public boolean isInScrollingContainer() {
6724        ViewParent p = getParent();
6725        while (p != null && p instanceof ViewGroup) {
6726            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6727                return true;
6728            }
6729            p = p.getParent();
6730        }
6731        return false;
6732    }
6733
6734    /**
6735     * Remove the longpress detection timer.
6736     */
6737    private void removeLongPressCallback() {
6738        if (mPendingCheckForLongPress != null) {
6739          removeCallbacks(mPendingCheckForLongPress);
6740        }
6741    }
6742
6743    /**
6744     * Remove the pending click action
6745     */
6746    private void removePerformClickCallback() {
6747        if (mPerformClick != null) {
6748            removeCallbacks(mPerformClick);
6749        }
6750    }
6751
6752    /**
6753     * Remove the prepress detection timer.
6754     */
6755    private void removeUnsetPressCallback() {
6756        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6757            setPressed(false);
6758            removeCallbacks(mUnsetPressedState);
6759        }
6760    }
6761
6762    /**
6763     * Remove the tap detection timer.
6764     */
6765    private void removeTapCallback() {
6766        if (mPendingCheckForTap != null) {
6767            mPrivateFlags &= ~PREPRESSED;
6768            removeCallbacks(mPendingCheckForTap);
6769        }
6770    }
6771
6772    /**
6773     * Cancels a pending long press.  Your subclass can use this if you
6774     * want the context menu to come up if the user presses and holds
6775     * at the same place, but you don't want it to come up if they press
6776     * and then move around enough to cause scrolling.
6777     */
6778    public void cancelLongPress() {
6779        removeLongPressCallback();
6780
6781        /*
6782         * The prepressed state handled by the tap callback is a display
6783         * construct, but the tap callback will post a long press callback
6784         * less its own timeout. Remove it here.
6785         */
6786        removeTapCallback();
6787    }
6788
6789    /**
6790     * Remove the pending callback for sending a
6791     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6792     */
6793    private void removeSendViewScrolledAccessibilityEventCallback() {
6794        if (mSendViewScrolledAccessibilityEvent != null) {
6795            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6796        }
6797    }
6798
6799    /**
6800     * Sets the TouchDelegate for this View.
6801     */
6802    public void setTouchDelegate(TouchDelegate delegate) {
6803        mTouchDelegate = delegate;
6804    }
6805
6806    /**
6807     * Gets the TouchDelegate for this View.
6808     */
6809    public TouchDelegate getTouchDelegate() {
6810        return mTouchDelegate;
6811    }
6812
6813    /**
6814     * Set flags controlling behavior of this view.
6815     *
6816     * @param flags Constant indicating the value which should be set
6817     * @param mask Constant indicating the bit range that should be changed
6818     */
6819    void setFlags(int flags, int mask) {
6820        int old = mViewFlags;
6821        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6822
6823        int changed = mViewFlags ^ old;
6824        if (changed == 0) {
6825            return;
6826        }
6827        int privateFlags = mPrivateFlags;
6828
6829        /* Check if the FOCUSABLE bit has changed */
6830        if (((changed & FOCUSABLE_MASK) != 0) &&
6831                ((privateFlags & HAS_BOUNDS) !=0)) {
6832            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6833                    && ((privateFlags & FOCUSED) != 0)) {
6834                /* Give up focus if we are no longer focusable */
6835                clearFocus();
6836            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6837                    && ((privateFlags & FOCUSED) == 0)) {
6838                /*
6839                 * Tell the view system that we are now available to take focus
6840                 * if no one else already has it.
6841                 */
6842                if (mParent != null) mParent.focusableViewAvailable(this);
6843            }
6844        }
6845
6846        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6847            if ((changed & VISIBILITY_MASK) != 0) {
6848                /*
6849                 * If this view is becoming visible, invalidate it in case it changed while
6850                 * it was not visible. Marking it drawn ensures that the invalidation will
6851                 * go through.
6852                 */
6853                mPrivateFlags |= DRAWN;
6854                invalidate(true);
6855
6856                needGlobalAttributesUpdate(true);
6857
6858                // a view becoming visible is worth notifying the parent
6859                // about in case nothing has focus.  even if this specific view
6860                // isn't focusable, it may contain something that is, so let
6861                // the root view try to give this focus if nothing else does.
6862                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6863                    mParent.focusableViewAvailable(this);
6864                }
6865            }
6866        }
6867
6868        /* Check if the GONE bit has changed */
6869        if ((changed & GONE) != 0) {
6870            needGlobalAttributesUpdate(false);
6871            requestLayout();
6872
6873            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6874                if (hasFocus()) clearFocus();
6875                destroyDrawingCache();
6876                if (mParent instanceof View) {
6877                    // GONE views noop invalidation, so invalidate the parent
6878                    ((View) mParent).invalidate(true);
6879                }
6880                // Mark the view drawn to ensure that it gets invalidated properly the next
6881                // time it is visible and gets invalidated
6882                mPrivateFlags |= DRAWN;
6883            }
6884            if (mAttachInfo != null) {
6885                mAttachInfo.mViewVisibilityChanged = true;
6886            }
6887        }
6888
6889        /* Check if the VISIBLE bit has changed */
6890        if ((changed & INVISIBLE) != 0) {
6891            needGlobalAttributesUpdate(false);
6892            /*
6893             * If this view is becoming invisible, set the DRAWN flag so that
6894             * the next invalidate() will not be skipped.
6895             */
6896            mPrivateFlags |= DRAWN;
6897
6898            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6899                // root view becoming invisible shouldn't clear focus
6900                if (getRootView() != this) {
6901                    clearFocus();
6902                }
6903            }
6904            if (mAttachInfo != null) {
6905                mAttachInfo.mViewVisibilityChanged = true;
6906            }
6907        }
6908
6909        if ((changed & VISIBILITY_MASK) != 0) {
6910            if (mParent instanceof ViewGroup) {
6911                ((ViewGroup) mParent).onChildVisibilityChanged(this,
6912                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
6913                ((View) mParent).invalidate(true);
6914            } else if (mParent != null) {
6915                mParent.invalidateChild(this, null);
6916            }
6917            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6918        }
6919
6920        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6921            destroyDrawingCache();
6922        }
6923
6924        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6925            destroyDrawingCache();
6926            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6927            invalidateParentCaches();
6928        }
6929
6930        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6931            destroyDrawingCache();
6932            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6933        }
6934
6935        if ((changed & DRAW_MASK) != 0) {
6936            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6937                if (mBGDrawable != null) {
6938                    mPrivateFlags &= ~SKIP_DRAW;
6939                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6940                } else {
6941                    mPrivateFlags |= SKIP_DRAW;
6942                }
6943            } else {
6944                mPrivateFlags &= ~SKIP_DRAW;
6945            }
6946            requestLayout();
6947            invalidate(true);
6948        }
6949
6950        if ((changed & KEEP_SCREEN_ON) != 0) {
6951            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6952                mParent.recomputeViewAttributes(this);
6953            }
6954        }
6955    }
6956
6957    /**
6958     * Change the view's z order in the tree, so it's on top of other sibling
6959     * views
6960     */
6961    public void bringToFront() {
6962        if (mParent != null) {
6963            mParent.bringChildToFront(this);
6964        }
6965    }
6966
6967    /**
6968     * This is called in response to an internal scroll in this view (i.e., the
6969     * view scrolled its own contents). This is typically as a result of
6970     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6971     * called.
6972     *
6973     * @param l Current horizontal scroll origin.
6974     * @param t Current vertical scroll origin.
6975     * @param oldl Previous horizontal scroll origin.
6976     * @param oldt Previous vertical scroll origin.
6977     */
6978    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6979        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6980            postSendViewScrolledAccessibilityEventCallback();
6981        }
6982
6983        mBackgroundSizeChanged = true;
6984
6985        final AttachInfo ai = mAttachInfo;
6986        if (ai != null) {
6987            ai.mViewScrollChanged = true;
6988        }
6989    }
6990
6991    /**
6992     * Interface definition for a callback to be invoked when the layout bounds of a view
6993     * changes due to layout processing.
6994     */
6995    public interface OnLayoutChangeListener {
6996        /**
6997         * Called when the focus state of a view has changed.
6998         *
6999         * @param v The view whose state has changed.
7000         * @param left The new value of the view's left property.
7001         * @param top The new value of the view's top property.
7002         * @param right The new value of the view's right property.
7003         * @param bottom The new value of the view's bottom property.
7004         * @param oldLeft The previous value of the view's left property.
7005         * @param oldTop The previous value of the view's top property.
7006         * @param oldRight The previous value of the view's right property.
7007         * @param oldBottom The previous value of the view's bottom property.
7008         */
7009        void onLayoutChange(View v, int left, int top, int right, int bottom,
7010            int oldLeft, int oldTop, int oldRight, int oldBottom);
7011    }
7012
7013    /**
7014     * This is called during layout when the size of this view has changed. If
7015     * you were just added to the view hierarchy, you're called with the old
7016     * values of 0.
7017     *
7018     * @param w Current width of this view.
7019     * @param h Current height of this view.
7020     * @param oldw Old width of this view.
7021     * @param oldh Old height of this view.
7022     */
7023    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7024    }
7025
7026    /**
7027     * Called by draw to draw the child views. This may be overridden
7028     * by derived classes to gain control just before its children are drawn
7029     * (but after its own view has been drawn).
7030     * @param canvas the canvas on which to draw the view
7031     */
7032    protected void dispatchDraw(Canvas canvas) {
7033    }
7034
7035    /**
7036     * Gets the parent of this view. Note that the parent is a
7037     * ViewParent and not necessarily a View.
7038     *
7039     * @return Parent of this view.
7040     */
7041    public final ViewParent getParent() {
7042        return mParent;
7043    }
7044
7045    /**
7046     * Set the horizontal scrolled position of your view. This will cause a call to
7047     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7048     * invalidated.
7049     * @param value the x position to scroll to
7050     */
7051    public void setScrollX(int value) {
7052        scrollTo(value, mScrollY);
7053    }
7054
7055    /**
7056     * Set the vertical scrolled position of your view. This will cause a call to
7057     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7058     * invalidated.
7059     * @param value the y position to scroll to
7060     */
7061    public void setScrollY(int value) {
7062        scrollTo(mScrollX, value);
7063    }
7064
7065    /**
7066     * Return the scrolled left position of this view. This is the left edge of
7067     * the displayed part of your view. You do not need to draw any pixels
7068     * farther left, since those are outside of the frame of your view on
7069     * screen.
7070     *
7071     * @return The left edge of the displayed part of your view, in pixels.
7072     */
7073    public final int getScrollX() {
7074        return mScrollX;
7075    }
7076
7077    /**
7078     * Return the scrolled top position of this view. This is the top edge of
7079     * the displayed part of your view. You do not need to draw any pixels above
7080     * it, since those are outside of the frame of your view on screen.
7081     *
7082     * @return The top edge of the displayed part of your view, in pixels.
7083     */
7084    public final int getScrollY() {
7085        return mScrollY;
7086    }
7087
7088    /**
7089     * Return the width of the your view.
7090     *
7091     * @return The width of your view, in pixels.
7092     */
7093    @ViewDebug.ExportedProperty(category = "layout")
7094    public final int getWidth() {
7095        return mRight - mLeft;
7096    }
7097
7098    /**
7099     * Return the height of your view.
7100     *
7101     * @return The height of your view, in pixels.
7102     */
7103    @ViewDebug.ExportedProperty(category = "layout")
7104    public final int getHeight() {
7105        return mBottom - mTop;
7106    }
7107
7108    /**
7109     * Return the visible drawing bounds of your view. Fills in the output
7110     * rectangle with the values from getScrollX(), getScrollY(),
7111     * getWidth(), and getHeight().
7112     *
7113     * @param outRect The (scrolled) drawing bounds of the view.
7114     */
7115    public void getDrawingRect(Rect outRect) {
7116        outRect.left = mScrollX;
7117        outRect.top = mScrollY;
7118        outRect.right = mScrollX + (mRight - mLeft);
7119        outRect.bottom = mScrollY + (mBottom - mTop);
7120    }
7121
7122    /**
7123     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7124     * raw width component (that is the result is masked by
7125     * {@link #MEASURED_SIZE_MASK}).
7126     *
7127     * @return The raw measured width of this view.
7128     */
7129    public final int getMeasuredWidth() {
7130        return mMeasuredWidth & MEASURED_SIZE_MASK;
7131    }
7132
7133    /**
7134     * Return the full width measurement information for this view as computed
7135     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7136     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7137     * This should be used during measurement and layout calculations only. Use
7138     * {@link #getWidth()} to see how wide a view is after layout.
7139     *
7140     * @return The measured width of this view as a bit mask.
7141     */
7142    public final int getMeasuredWidthAndState() {
7143        return mMeasuredWidth;
7144    }
7145
7146    /**
7147     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7148     * raw width component (that is the result is masked by
7149     * {@link #MEASURED_SIZE_MASK}).
7150     *
7151     * @return The raw measured height of this view.
7152     */
7153    public final int getMeasuredHeight() {
7154        return mMeasuredHeight & MEASURED_SIZE_MASK;
7155    }
7156
7157    /**
7158     * Return the full height measurement information for this view as computed
7159     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7160     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7161     * This should be used during measurement and layout calculations only. Use
7162     * {@link #getHeight()} to see how wide a view is after layout.
7163     *
7164     * @return The measured width of this view as a bit mask.
7165     */
7166    public final int getMeasuredHeightAndState() {
7167        return mMeasuredHeight;
7168    }
7169
7170    /**
7171     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7172     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7173     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7174     * and the height component is at the shifted bits
7175     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7176     */
7177    public final int getMeasuredState() {
7178        return (mMeasuredWidth&MEASURED_STATE_MASK)
7179                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7180                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7181    }
7182
7183    /**
7184     * The transform matrix of this view, which is calculated based on the current
7185     * roation, scale, and pivot properties.
7186     *
7187     * @see #getRotation()
7188     * @see #getScaleX()
7189     * @see #getScaleY()
7190     * @see #getPivotX()
7191     * @see #getPivotY()
7192     * @return The current transform matrix for the view
7193     */
7194    public Matrix getMatrix() {
7195        if (mTransformationInfo != null) {
7196            updateMatrix();
7197            return mTransformationInfo.mMatrix;
7198        }
7199        return Matrix.IDENTITY_MATRIX;
7200    }
7201
7202    /**
7203     * Utility function to determine if the value is far enough away from zero to be
7204     * considered non-zero.
7205     * @param value A floating point value to check for zero-ness
7206     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7207     */
7208    private static boolean nonzero(float value) {
7209        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7210    }
7211
7212    /**
7213     * Returns true if the transform matrix is the identity matrix.
7214     * Recomputes the matrix if necessary.
7215     *
7216     * @return True if the transform matrix is the identity matrix, false otherwise.
7217     */
7218    final boolean hasIdentityMatrix() {
7219        if (mTransformationInfo != null) {
7220            updateMatrix();
7221            return mTransformationInfo.mMatrixIsIdentity;
7222        }
7223        return true;
7224    }
7225
7226    void ensureTransformationInfo() {
7227        if (mTransformationInfo == null) {
7228            mTransformationInfo = new TransformationInfo();
7229        }
7230    }
7231
7232    /**
7233     * Recomputes the transform matrix if necessary.
7234     */
7235    private void updateMatrix() {
7236        final TransformationInfo info = mTransformationInfo;
7237        if (info == null) {
7238            return;
7239        }
7240        if (info.mMatrixDirty) {
7241            // transform-related properties have changed since the last time someone
7242            // asked for the matrix; recalculate it with the current values
7243
7244            // Figure out if we need to update the pivot point
7245            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7246                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7247                    info.mPrevWidth = mRight - mLeft;
7248                    info.mPrevHeight = mBottom - mTop;
7249                    info.mPivotX = info.mPrevWidth / 2f;
7250                    info.mPivotY = info.mPrevHeight / 2f;
7251                }
7252            }
7253            info.mMatrix.reset();
7254            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7255                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7256                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7257                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7258            } else {
7259                if (info.mCamera == null) {
7260                    info.mCamera = new Camera();
7261                    info.matrix3D = new Matrix();
7262                }
7263                info.mCamera.save();
7264                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7265                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7266                info.mCamera.getMatrix(info.matrix3D);
7267                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7268                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7269                        info.mPivotY + info.mTranslationY);
7270                info.mMatrix.postConcat(info.matrix3D);
7271                info.mCamera.restore();
7272            }
7273            info.mMatrixDirty = false;
7274            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7275            info.mInverseMatrixDirty = true;
7276        }
7277    }
7278
7279    /**
7280     * Utility method to retrieve the inverse of the current mMatrix property.
7281     * We cache the matrix to avoid recalculating it when transform properties
7282     * have not changed.
7283     *
7284     * @return The inverse of the current matrix of this view.
7285     */
7286    final Matrix getInverseMatrix() {
7287        final TransformationInfo info = mTransformationInfo;
7288        if (info != null) {
7289            updateMatrix();
7290            if (info.mInverseMatrixDirty) {
7291                if (info.mInverseMatrix == null) {
7292                    info.mInverseMatrix = new Matrix();
7293                }
7294                info.mMatrix.invert(info.mInverseMatrix);
7295                info.mInverseMatrixDirty = false;
7296            }
7297            return info.mInverseMatrix;
7298        }
7299        return Matrix.IDENTITY_MATRIX;
7300    }
7301
7302    /**
7303     * Gets the distance along the Z axis from the camera to this view.
7304     *
7305     * @see #setCameraDistance(float)
7306     *
7307     * @return The distance along the Z axis.
7308     */
7309    public float getCameraDistance() {
7310        ensureTransformationInfo();
7311        final float dpi = mResources.getDisplayMetrics().densityDpi;
7312        final TransformationInfo info = mTransformationInfo;
7313        if (info.mCamera == null) {
7314            info.mCamera = new Camera();
7315            info.matrix3D = new Matrix();
7316        }
7317        return -(info.mCamera.getLocationZ() * dpi);
7318    }
7319
7320    /**
7321     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7322     * views are drawn) from the camera to this view. The camera's distance
7323     * affects 3D transformations, for instance rotations around the X and Y
7324     * axis. If the rotationX or rotationY properties are changed and this view is
7325     * large (more than half the size of the screen), it is recommended to always
7326     * use a camera distance that's greater than the height (X axis rotation) or
7327     * the width (Y axis rotation) of this view.</p>
7328     *
7329     * <p>The distance of the camera from the view plane can have an affect on the
7330     * perspective distortion of the view when it is rotated around the x or y axis.
7331     * For example, a large distance will result in a large viewing angle, and there
7332     * will not be much perspective distortion of the view as it rotates. A short
7333     * distance may cause much more perspective distortion upon rotation, and can
7334     * also result in some drawing artifacts if the rotated view ends up partially
7335     * behind the camera (which is why the recommendation is to use a distance at
7336     * least as far as the size of the view, if the view is to be rotated.)</p>
7337     *
7338     * <p>The distance is expressed in "depth pixels." The default distance depends
7339     * on the screen density. For instance, on a medium density display, the
7340     * default distance is 1280. On a high density display, the default distance
7341     * is 1920.</p>
7342     *
7343     * <p>If you want to specify a distance that leads to visually consistent
7344     * results across various densities, use the following formula:</p>
7345     * <pre>
7346     * float scale = context.getResources().getDisplayMetrics().density;
7347     * view.setCameraDistance(distance * scale);
7348     * </pre>
7349     *
7350     * <p>The density scale factor of a high density display is 1.5,
7351     * and 1920 = 1280 * 1.5.</p>
7352     *
7353     * @param distance The distance in "depth pixels", if negative the opposite
7354     *        value is used
7355     *
7356     * @see #setRotationX(float)
7357     * @see #setRotationY(float)
7358     */
7359    public void setCameraDistance(float distance) {
7360        invalidateViewProperty(true, false);
7361
7362        ensureTransformationInfo();
7363        final float dpi = mResources.getDisplayMetrics().densityDpi;
7364        final TransformationInfo info = mTransformationInfo;
7365        if (info.mCamera == null) {
7366            info.mCamera = new Camera();
7367            info.matrix3D = new Matrix();
7368        }
7369
7370        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7371        info.mMatrixDirty = true;
7372
7373        invalidateViewProperty(false, false);
7374        if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7375            mDisplayList.setCameraDistance(distance);
7376        }
7377    }
7378
7379    /**
7380     * The degrees that the view is rotated around the pivot point.
7381     *
7382     * @see #setRotation(float)
7383     * @see #getPivotX()
7384     * @see #getPivotY()
7385     *
7386     * @return The degrees of rotation.
7387     */
7388    @ViewDebug.ExportedProperty(category = "drawing")
7389    public float getRotation() {
7390        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7391    }
7392
7393    /**
7394     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7395     * result in clockwise rotation.
7396     *
7397     * @param rotation The degrees of rotation.
7398     *
7399     * @see #getRotation()
7400     * @see #getPivotX()
7401     * @see #getPivotY()
7402     * @see #setRotationX(float)
7403     * @see #setRotationY(float)
7404     *
7405     * @attr ref android.R.styleable#View_rotation
7406     */
7407    public void setRotation(float rotation) {
7408        ensureTransformationInfo();
7409        final TransformationInfo info = mTransformationInfo;
7410        if (info.mRotation != rotation) {
7411            // Double-invalidation is necessary to capture view's old and new areas
7412            invalidateViewProperty(true, false);
7413            info.mRotation = rotation;
7414            info.mMatrixDirty = true;
7415            invalidateViewProperty(false, true);
7416            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7417                mDisplayList.setRotation(rotation);
7418            }
7419        }
7420    }
7421
7422    /**
7423     * The degrees that the view is rotated around the vertical axis through the pivot point.
7424     *
7425     * @see #getPivotX()
7426     * @see #getPivotY()
7427     * @see #setRotationY(float)
7428     *
7429     * @return The degrees of Y rotation.
7430     */
7431    @ViewDebug.ExportedProperty(category = "drawing")
7432    public float getRotationY() {
7433        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7434    }
7435
7436    /**
7437     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7438     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7439     * down the y axis.
7440     *
7441     * When rotating large views, it is recommended to adjust the camera distance
7442     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7443     *
7444     * @param rotationY The degrees of Y rotation.
7445     *
7446     * @see #getRotationY()
7447     * @see #getPivotX()
7448     * @see #getPivotY()
7449     * @see #setRotation(float)
7450     * @see #setRotationX(float)
7451     * @see #setCameraDistance(float)
7452     *
7453     * @attr ref android.R.styleable#View_rotationY
7454     */
7455    public void setRotationY(float rotationY) {
7456        ensureTransformationInfo();
7457        final TransformationInfo info = mTransformationInfo;
7458        if (info.mRotationY != rotationY) {
7459            invalidateViewProperty(true, false);
7460            info.mRotationY = rotationY;
7461            info.mMatrixDirty = true;
7462            invalidateViewProperty(false, true);
7463            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7464                mDisplayList.setRotationY(rotationY);
7465            }
7466        }
7467    }
7468
7469    /**
7470     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7471     *
7472     * @see #getPivotX()
7473     * @see #getPivotY()
7474     * @see #setRotationX(float)
7475     *
7476     * @return The degrees of X rotation.
7477     */
7478    @ViewDebug.ExportedProperty(category = "drawing")
7479    public float getRotationX() {
7480        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7481    }
7482
7483    /**
7484     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7485     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7486     * x axis.
7487     *
7488     * When rotating large views, it is recommended to adjust the camera distance
7489     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7490     *
7491     * @param rotationX The degrees of X rotation.
7492     *
7493     * @see #getRotationX()
7494     * @see #getPivotX()
7495     * @see #getPivotY()
7496     * @see #setRotation(float)
7497     * @see #setRotationY(float)
7498     * @see #setCameraDistance(float)
7499     *
7500     * @attr ref android.R.styleable#View_rotationX
7501     */
7502    public void setRotationX(float rotationX) {
7503        ensureTransformationInfo();
7504        final TransformationInfo info = mTransformationInfo;
7505        if (info.mRotationX != rotationX) {
7506            invalidateViewProperty(true, false);
7507            info.mRotationX = rotationX;
7508            info.mMatrixDirty = true;
7509            invalidateViewProperty(false, true);
7510            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7511                mDisplayList.setRotationX(rotationX);
7512            }
7513        }
7514    }
7515
7516    /**
7517     * The amount that the view is scaled in x around the pivot point, as a proportion of
7518     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7519     *
7520     * <p>By default, this is 1.0f.
7521     *
7522     * @see #getPivotX()
7523     * @see #getPivotY()
7524     * @return The scaling factor.
7525     */
7526    @ViewDebug.ExportedProperty(category = "drawing")
7527    public float getScaleX() {
7528        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7529    }
7530
7531    /**
7532     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7533     * the view's unscaled width. A value of 1 means that no scaling is applied.
7534     *
7535     * @param scaleX The scaling factor.
7536     * @see #getPivotX()
7537     * @see #getPivotY()
7538     *
7539     * @attr ref android.R.styleable#View_scaleX
7540     */
7541    public void setScaleX(float scaleX) {
7542        ensureTransformationInfo();
7543        final TransformationInfo info = mTransformationInfo;
7544        if (info.mScaleX != scaleX) {
7545            invalidateViewProperty(true, false);
7546            info.mScaleX = scaleX;
7547            info.mMatrixDirty = true;
7548            invalidateViewProperty(false, true);
7549            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7550                mDisplayList.setScaleX(scaleX);
7551            }
7552        }
7553    }
7554
7555    /**
7556     * The amount that the view is scaled in y around the pivot point, as a proportion of
7557     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7558     *
7559     * <p>By default, this is 1.0f.
7560     *
7561     * @see #getPivotX()
7562     * @see #getPivotY()
7563     * @return The scaling factor.
7564     */
7565    @ViewDebug.ExportedProperty(category = "drawing")
7566    public float getScaleY() {
7567        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7568    }
7569
7570    /**
7571     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7572     * the view's unscaled width. A value of 1 means that no scaling is applied.
7573     *
7574     * @param scaleY The scaling factor.
7575     * @see #getPivotX()
7576     * @see #getPivotY()
7577     *
7578     * @attr ref android.R.styleable#View_scaleY
7579     */
7580    public void setScaleY(float scaleY) {
7581        ensureTransformationInfo();
7582        final TransformationInfo info = mTransformationInfo;
7583        if (info.mScaleY != scaleY) {
7584            invalidateViewProperty(true, false);
7585            info.mScaleY = scaleY;
7586            info.mMatrixDirty = true;
7587            invalidateViewProperty(false, true);
7588            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7589                mDisplayList.setScaleY(scaleY);
7590            }
7591        }
7592    }
7593
7594    /**
7595     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7596     * and {@link #setScaleX(float) scaled}.
7597     *
7598     * @see #getRotation()
7599     * @see #getScaleX()
7600     * @see #getScaleY()
7601     * @see #getPivotY()
7602     * @return The x location of the pivot point.
7603     */
7604    @ViewDebug.ExportedProperty(category = "drawing")
7605    public float getPivotX() {
7606        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7607    }
7608
7609    /**
7610     * Sets the x location of the point around which the view is
7611     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7612     * By default, the pivot point is centered on the object.
7613     * Setting this property disables this behavior and causes the view to use only the
7614     * explicitly set pivotX and pivotY values.
7615     *
7616     * @param pivotX The x location of the pivot point.
7617     * @see #getRotation()
7618     * @see #getScaleX()
7619     * @see #getScaleY()
7620     * @see #getPivotY()
7621     *
7622     * @attr ref android.R.styleable#View_transformPivotX
7623     */
7624    public void setPivotX(float pivotX) {
7625        ensureTransformationInfo();
7626        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7627        final TransformationInfo info = mTransformationInfo;
7628        if (info.mPivotX != pivotX) {
7629            invalidateViewProperty(true, false);
7630            info.mPivotX = pivotX;
7631            info.mMatrixDirty = true;
7632            invalidateViewProperty(false, true);
7633            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7634                mDisplayList.setPivotX(pivotX);
7635            }
7636        }
7637    }
7638
7639    /**
7640     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7641     * and {@link #setScaleY(float) scaled}.
7642     *
7643     * @see #getRotation()
7644     * @see #getScaleX()
7645     * @see #getScaleY()
7646     * @see #getPivotY()
7647     * @return The y location of the pivot point.
7648     */
7649    @ViewDebug.ExportedProperty(category = "drawing")
7650    public float getPivotY() {
7651        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7652    }
7653
7654    /**
7655     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7656     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7657     * Setting this property disables this behavior and causes the view to use only the
7658     * explicitly set pivotX and pivotY values.
7659     *
7660     * @param pivotY The y location of the pivot point.
7661     * @see #getRotation()
7662     * @see #getScaleX()
7663     * @see #getScaleY()
7664     * @see #getPivotY()
7665     *
7666     * @attr ref android.R.styleable#View_transformPivotY
7667     */
7668    public void setPivotY(float pivotY) {
7669        ensureTransformationInfo();
7670        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7671        final TransformationInfo info = mTransformationInfo;
7672        if (info.mPivotY != pivotY) {
7673            invalidateViewProperty(true, false);
7674            info.mPivotY = pivotY;
7675            info.mMatrixDirty = true;
7676            invalidateViewProperty(false, true);
7677            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7678                mDisplayList.setPivotY(pivotY);
7679            }
7680        }
7681    }
7682
7683    /**
7684     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7685     * completely transparent and 1 means the view is completely opaque.
7686     *
7687     * <p>By default this is 1.0f.
7688     * @return The opacity of the view.
7689     */
7690    @ViewDebug.ExportedProperty(category = "drawing")
7691    public float getAlpha() {
7692        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7693    }
7694
7695    /**
7696     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7697     * completely transparent and 1 means the view is completely opaque.</p>
7698     *
7699     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7700     * responsible for applying the opacity itself. Otherwise, calling this method is
7701     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7702     * setting a hardware layer.</p>
7703     *
7704     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7705     * performance implications. It is generally best to use the alpha property sparingly and
7706     * transiently, as in the case of fading animations.</p>
7707     *
7708     * @param alpha The opacity of the view.
7709     *
7710     * @see #setLayerType(int, android.graphics.Paint)
7711     *
7712     * @attr ref android.R.styleable#View_alpha
7713     */
7714    public void setAlpha(float alpha) {
7715        ensureTransformationInfo();
7716        if (mTransformationInfo.mAlpha != alpha) {
7717            mTransformationInfo.mAlpha = alpha;
7718            if (onSetAlpha((int) (alpha * 255))) {
7719                mPrivateFlags |= ALPHA_SET;
7720                // subclass is handling alpha - don't optimize rendering cache invalidation
7721                invalidateParentCaches();
7722                invalidate(true);
7723            } else {
7724                mPrivateFlags &= ~ALPHA_SET;
7725                invalidateViewProperty(true, false);
7726                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7727                    mDisplayList.setAlpha(alpha);
7728                }
7729            }
7730        }
7731    }
7732
7733    /**
7734     * Faster version of setAlpha() which performs the same steps except there are
7735     * no calls to invalidate(). The caller of this function should perform proper invalidation
7736     * on the parent and this object. The return value indicates whether the subclass handles
7737     * alpha (the return value for onSetAlpha()).
7738     *
7739     * @param alpha The new value for the alpha property
7740     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7741     *         the new value for the alpha property is different from the old value
7742     */
7743    boolean setAlphaNoInvalidation(float alpha) {
7744        ensureTransformationInfo();
7745        if (mTransformationInfo.mAlpha != alpha) {
7746            mTransformationInfo.mAlpha = alpha;
7747            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7748            if (subclassHandlesAlpha) {
7749                mPrivateFlags |= ALPHA_SET;
7750                return true;
7751            } else {
7752                mPrivateFlags &= ~ALPHA_SET;
7753                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7754                    mDisplayList.setAlpha(alpha);
7755                }
7756            }
7757        }
7758        return false;
7759    }
7760
7761    /**
7762     * Top position of this view relative to its parent.
7763     *
7764     * @return The top of this view, in pixels.
7765     */
7766    @ViewDebug.CapturedViewProperty
7767    public final int getTop() {
7768        return mTop;
7769    }
7770
7771    /**
7772     * Sets the top position of this view relative to its parent. This method is meant to be called
7773     * by the layout system and should not generally be called otherwise, because the property
7774     * may be changed at any time by the layout.
7775     *
7776     * @param top The top of this view, in pixels.
7777     */
7778    public final void setTop(int top) {
7779        if (top != mTop) {
7780            updateMatrix();
7781            final boolean matrixIsIdentity = mTransformationInfo == null
7782                    || mTransformationInfo.mMatrixIsIdentity;
7783            if (matrixIsIdentity) {
7784                if (mAttachInfo != null) {
7785                    int minTop;
7786                    int yLoc;
7787                    if (top < mTop) {
7788                        minTop = top;
7789                        yLoc = top - mTop;
7790                    } else {
7791                        minTop = mTop;
7792                        yLoc = 0;
7793                    }
7794                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7795                }
7796            } else {
7797                // Double-invalidation is necessary to capture view's old and new areas
7798                invalidate(true);
7799            }
7800
7801            int width = mRight - mLeft;
7802            int oldHeight = mBottom - mTop;
7803
7804            mTop = top;
7805            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7806                mDisplayList.setTop(mTop);
7807            }
7808
7809            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7810
7811            if (!matrixIsIdentity) {
7812                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7813                    // A change in dimension means an auto-centered pivot point changes, too
7814                    mTransformationInfo.mMatrixDirty = true;
7815                }
7816                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7817                invalidate(true);
7818            }
7819            mBackgroundSizeChanged = true;
7820            invalidateParentIfNeeded();
7821        }
7822    }
7823
7824    /**
7825     * Bottom position of this view relative to its parent.
7826     *
7827     * @return The bottom of this view, in pixels.
7828     */
7829    @ViewDebug.CapturedViewProperty
7830    public final int getBottom() {
7831        return mBottom;
7832    }
7833
7834    /**
7835     * True if this view has changed since the last time being drawn.
7836     *
7837     * @return The dirty state of this view.
7838     */
7839    public boolean isDirty() {
7840        return (mPrivateFlags & DIRTY_MASK) != 0;
7841    }
7842
7843    /**
7844     * Sets the bottom position of this view relative to its parent. This method is meant to be
7845     * called by the layout system and should not generally be called otherwise, because the
7846     * property may be changed at any time by the layout.
7847     *
7848     * @param bottom The bottom of this view, in pixels.
7849     */
7850    public final void setBottom(int bottom) {
7851        if (bottom != mBottom) {
7852            updateMatrix();
7853            final boolean matrixIsIdentity = mTransformationInfo == null
7854                    || mTransformationInfo.mMatrixIsIdentity;
7855            if (matrixIsIdentity) {
7856                if (mAttachInfo != null) {
7857                    int maxBottom;
7858                    if (bottom < mBottom) {
7859                        maxBottom = mBottom;
7860                    } else {
7861                        maxBottom = bottom;
7862                    }
7863                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7864                }
7865            } else {
7866                // Double-invalidation is necessary to capture view's old and new areas
7867                invalidate(true);
7868            }
7869
7870            int width = mRight - mLeft;
7871            int oldHeight = mBottom - mTop;
7872
7873            mBottom = bottom;
7874            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7875                mDisplayList.setBottom(mBottom);
7876            }
7877
7878            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7879
7880            if (!matrixIsIdentity) {
7881                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7882                    // A change in dimension means an auto-centered pivot point changes, too
7883                    mTransformationInfo.mMatrixDirty = true;
7884                }
7885                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7886                invalidate(true);
7887            }
7888            mBackgroundSizeChanged = true;
7889            invalidateParentIfNeeded();
7890        }
7891    }
7892
7893    /**
7894     * Left position of this view relative to its parent.
7895     *
7896     * @return The left edge of this view, in pixels.
7897     */
7898    @ViewDebug.CapturedViewProperty
7899    public final int getLeft() {
7900        return mLeft;
7901    }
7902
7903    /**
7904     * Sets the left position of this view relative to its parent. This method is meant to be called
7905     * by the layout system and should not generally be called otherwise, because the property
7906     * may be changed at any time by the layout.
7907     *
7908     * @param left The bottom of this view, in pixels.
7909     */
7910    public final void setLeft(int left) {
7911        if (left != mLeft) {
7912            updateMatrix();
7913            final boolean matrixIsIdentity = mTransformationInfo == null
7914                    || mTransformationInfo.mMatrixIsIdentity;
7915            if (matrixIsIdentity) {
7916                if (mAttachInfo != null) {
7917                    int minLeft;
7918                    int xLoc;
7919                    if (left < mLeft) {
7920                        minLeft = left;
7921                        xLoc = left - mLeft;
7922                    } else {
7923                        minLeft = mLeft;
7924                        xLoc = 0;
7925                    }
7926                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7927                }
7928            } else {
7929                // Double-invalidation is necessary to capture view's old and new areas
7930                invalidate(true);
7931            }
7932
7933            int oldWidth = mRight - mLeft;
7934            int height = mBottom - mTop;
7935
7936            mLeft = left;
7937            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7938                mDisplayList.setLeft(left);
7939            }
7940
7941            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7942
7943            if (!matrixIsIdentity) {
7944                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7945                    // A change in dimension means an auto-centered pivot point changes, too
7946                    mTransformationInfo.mMatrixDirty = true;
7947                }
7948                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7949                invalidate(true);
7950            }
7951            mBackgroundSizeChanged = true;
7952            invalidateParentIfNeeded();
7953            if (USE_DISPLAY_LIST_PROPERTIES) {
7954
7955            }
7956        }
7957    }
7958
7959    /**
7960     * Right position of this view relative to its parent.
7961     *
7962     * @return The right edge of this view, in pixels.
7963     */
7964    @ViewDebug.CapturedViewProperty
7965    public final int getRight() {
7966        return mRight;
7967    }
7968
7969    /**
7970     * Sets the right position of this view relative to its parent. This method is meant to be called
7971     * by the layout system and should not generally be called otherwise, because the property
7972     * may be changed at any time by the layout.
7973     *
7974     * @param right The bottom of this view, in pixels.
7975     */
7976    public final void setRight(int right) {
7977        if (right != mRight) {
7978            updateMatrix();
7979            final boolean matrixIsIdentity = mTransformationInfo == null
7980                    || mTransformationInfo.mMatrixIsIdentity;
7981            if (matrixIsIdentity) {
7982                if (mAttachInfo != null) {
7983                    int maxRight;
7984                    if (right < mRight) {
7985                        maxRight = mRight;
7986                    } else {
7987                        maxRight = right;
7988                    }
7989                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7990                }
7991            } else {
7992                // Double-invalidation is necessary to capture view's old and new areas
7993                invalidate(true);
7994            }
7995
7996            int oldWidth = mRight - mLeft;
7997            int height = mBottom - mTop;
7998
7999            mRight = right;
8000            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8001                mDisplayList.setRight(mRight);
8002            }
8003
8004            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8005
8006            if (!matrixIsIdentity) {
8007                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8008                    // A change in dimension means an auto-centered pivot point changes, too
8009                    mTransformationInfo.mMatrixDirty = true;
8010                }
8011                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8012                invalidate(true);
8013            }
8014            mBackgroundSizeChanged = true;
8015            invalidateParentIfNeeded();
8016        }
8017    }
8018
8019    /**
8020     * The visual x position of this view, in pixels. This is equivalent to the
8021     * {@link #setTranslationX(float) translationX} property plus the current
8022     * {@link #getLeft() left} property.
8023     *
8024     * @return The visual x position of this view, in pixels.
8025     */
8026    @ViewDebug.ExportedProperty(category = "drawing")
8027    public float getX() {
8028        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8029    }
8030
8031    /**
8032     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8033     * {@link #setTranslationX(float) translationX} property to be the difference between
8034     * the x value passed in and the current {@link #getLeft() left} property.
8035     *
8036     * @param x The visual x position of this view, in pixels.
8037     */
8038    public void setX(float x) {
8039        setTranslationX(x - mLeft);
8040    }
8041
8042    /**
8043     * The visual y position of this view, in pixels. This is equivalent to the
8044     * {@link #setTranslationY(float) translationY} property plus the current
8045     * {@link #getTop() top} property.
8046     *
8047     * @return The visual y position of this view, in pixels.
8048     */
8049    @ViewDebug.ExportedProperty(category = "drawing")
8050    public float getY() {
8051        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8052    }
8053
8054    /**
8055     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8056     * {@link #setTranslationY(float) translationY} property to be the difference between
8057     * the y value passed in and the current {@link #getTop() top} property.
8058     *
8059     * @param y The visual y position of this view, in pixels.
8060     */
8061    public void setY(float y) {
8062        setTranslationY(y - mTop);
8063    }
8064
8065
8066    /**
8067     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8068     * This position is post-layout, in addition to wherever the object's
8069     * layout placed it.
8070     *
8071     * @return The horizontal position of this view relative to its left position, in pixels.
8072     */
8073    @ViewDebug.ExportedProperty(category = "drawing")
8074    public float getTranslationX() {
8075        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8076    }
8077
8078    /**
8079     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8080     * This effectively positions the object post-layout, in addition to wherever the object's
8081     * layout placed it.
8082     *
8083     * @param translationX The horizontal position of this view relative to its left position,
8084     * in pixels.
8085     *
8086     * @attr ref android.R.styleable#View_translationX
8087     */
8088    public void setTranslationX(float translationX) {
8089        ensureTransformationInfo();
8090        final TransformationInfo info = mTransformationInfo;
8091        if (info.mTranslationX != translationX) {
8092            // Double-invalidation is necessary to capture view's old and new areas
8093            invalidateViewProperty(true, false);
8094            info.mTranslationX = translationX;
8095            info.mMatrixDirty = true;
8096            invalidateViewProperty(false, true);
8097            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8098                mDisplayList.setTranslationX(translationX);
8099            }
8100        }
8101    }
8102
8103    /**
8104     * The horizontal location of this view relative to its {@link #getTop() top} position.
8105     * This position is post-layout, in addition to wherever the object's
8106     * layout placed it.
8107     *
8108     * @return The vertical position of this view relative to its top position,
8109     * in pixels.
8110     */
8111    @ViewDebug.ExportedProperty(category = "drawing")
8112    public float getTranslationY() {
8113        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
8114    }
8115
8116    /**
8117     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8118     * This effectively positions the object post-layout, in addition to wherever the object's
8119     * layout placed it.
8120     *
8121     * @param translationY The vertical position of this view relative to its top position,
8122     * in pixels.
8123     *
8124     * @attr ref android.R.styleable#View_translationY
8125     */
8126    public void setTranslationY(float translationY) {
8127        ensureTransformationInfo();
8128        final TransformationInfo info = mTransformationInfo;
8129        if (info.mTranslationY != translationY) {
8130            invalidateViewProperty(true, false);
8131            info.mTranslationY = translationY;
8132            info.mMatrixDirty = true;
8133            invalidateViewProperty(false, true);
8134            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8135                mDisplayList.setTranslationY(translationY);
8136            }
8137        }
8138    }
8139
8140    /**
8141     * Hit rectangle in parent's coordinates
8142     *
8143     * @param outRect The hit rectangle of the view.
8144     */
8145    public void getHitRect(Rect outRect) {
8146        updateMatrix();
8147        final TransformationInfo info = mTransformationInfo;
8148        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8149            outRect.set(mLeft, mTop, mRight, mBottom);
8150        } else {
8151            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8152            tmpRect.set(-info.mPivotX, -info.mPivotY,
8153                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8154            info.mMatrix.mapRect(tmpRect);
8155            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8156                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8157        }
8158    }
8159
8160    /**
8161     * Determines whether the given point, in local coordinates is inside the view.
8162     */
8163    /*package*/ final boolean pointInView(float localX, float localY) {
8164        return localX >= 0 && localX < (mRight - mLeft)
8165                && localY >= 0 && localY < (mBottom - mTop);
8166    }
8167
8168    /**
8169     * Utility method to determine whether the given point, in local coordinates,
8170     * is inside the view, where the area of the view is expanded by the slop factor.
8171     * This method is called while processing touch-move events to determine if the event
8172     * is still within the view.
8173     */
8174    private boolean pointInView(float localX, float localY, float slop) {
8175        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8176                localY < ((mBottom - mTop) + slop);
8177    }
8178
8179    /**
8180     * When a view has focus and the user navigates away from it, the next view is searched for
8181     * starting from the rectangle filled in by this method.
8182     *
8183     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8184     * of the view.  However, if your view maintains some idea of internal selection,
8185     * such as a cursor, or a selected row or column, you should override this method and
8186     * fill in a more specific rectangle.
8187     *
8188     * @param r The rectangle to fill in, in this view's coordinates.
8189     */
8190    public void getFocusedRect(Rect r) {
8191        getDrawingRect(r);
8192    }
8193
8194    /**
8195     * If some part of this view is not clipped by any of its parents, then
8196     * return that area in r in global (root) coordinates. To convert r to local
8197     * coordinates (without taking possible View rotations into account), offset
8198     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8199     * If the view is completely clipped or translated out, return false.
8200     *
8201     * @param r If true is returned, r holds the global coordinates of the
8202     *        visible portion of this view.
8203     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8204     *        between this view and its root. globalOffet may be null.
8205     * @return true if r is non-empty (i.e. part of the view is visible at the
8206     *         root level.
8207     */
8208    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8209        int width = mRight - mLeft;
8210        int height = mBottom - mTop;
8211        if (width > 0 && height > 0) {
8212            r.set(0, 0, width, height);
8213            if (globalOffset != null) {
8214                globalOffset.set(-mScrollX, -mScrollY);
8215            }
8216            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8217        }
8218        return false;
8219    }
8220
8221    public final boolean getGlobalVisibleRect(Rect r) {
8222        return getGlobalVisibleRect(r, null);
8223    }
8224
8225    public final boolean getLocalVisibleRect(Rect r) {
8226        Point offset = new Point();
8227        if (getGlobalVisibleRect(r, offset)) {
8228            r.offset(-offset.x, -offset.y); // make r local
8229            return true;
8230        }
8231        return false;
8232    }
8233
8234    /**
8235     * Offset this view's vertical location by the specified number of pixels.
8236     *
8237     * @param offset the number of pixels to offset the view by
8238     */
8239    public void offsetTopAndBottom(int offset) {
8240        if (offset != 0) {
8241            updateMatrix();
8242            final boolean matrixIsIdentity = mTransformationInfo == null
8243                    || mTransformationInfo.mMatrixIsIdentity;
8244            if (matrixIsIdentity) {
8245                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8246                    invalidateViewProperty(false, false);
8247                } else {
8248                    final ViewParent p = mParent;
8249                    if (p != null && mAttachInfo != null) {
8250                        final Rect r = mAttachInfo.mTmpInvalRect;
8251                        int minTop;
8252                        int maxBottom;
8253                        int yLoc;
8254                        if (offset < 0) {
8255                            minTop = mTop + offset;
8256                            maxBottom = mBottom;
8257                            yLoc = offset;
8258                        } else {
8259                            minTop = mTop;
8260                            maxBottom = mBottom + offset;
8261                            yLoc = 0;
8262                        }
8263                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8264                        p.invalidateChild(this, r);
8265                    }
8266                }
8267            } else {
8268                invalidateViewProperty(false, false);
8269            }
8270
8271            mTop += offset;
8272            mBottom += offset;
8273            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8274                mDisplayList.offsetTopBottom(offset);
8275                invalidateViewProperty(false, false);
8276            } else {
8277                if (!matrixIsIdentity) {
8278                    invalidateViewProperty(false, true);
8279                }
8280                invalidateParentIfNeeded();
8281            }
8282        }
8283    }
8284
8285    /**
8286     * Offset this view's horizontal location by the specified amount of pixels.
8287     *
8288     * @param offset the numer of pixels to offset the view by
8289     */
8290    public void offsetLeftAndRight(int offset) {
8291        if (offset != 0) {
8292            updateMatrix();
8293            final boolean matrixIsIdentity = mTransformationInfo == null
8294                    || mTransformationInfo.mMatrixIsIdentity;
8295            if (matrixIsIdentity) {
8296                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8297                    invalidateViewProperty(false, false);
8298                } else {
8299                    final ViewParent p = mParent;
8300                    if (p != null && mAttachInfo != null) {
8301                        final Rect r = mAttachInfo.mTmpInvalRect;
8302                        int minLeft;
8303                        int maxRight;
8304                        if (offset < 0) {
8305                            minLeft = mLeft + offset;
8306                            maxRight = mRight;
8307                        } else {
8308                            minLeft = mLeft;
8309                            maxRight = mRight + offset;
8310                        }
8311                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8312                        p.invalidateChild(this, r);
8313                    }
8314                }
8315            } else {
8316                invalidateViewProperty(false, false);
8317            }
8318
8319            mLeft += offset;
8320            mRight += offset;
8321            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8322                mDisplayList.offsetLeftRight(offset);
8323                invalidateViewProperty(false, false);
8324            } else {
8325                if (!matrixIsIdentity) {
8326                    invalidateViewProperty(false, true);
8327                }
8328                invalidateParentIfNeeded();
8329            }
8330        }
8331    }
8332
8333    /**
8334     * Get the LayoutParams associated with this view. All views should have
8335     * layout parameters. These supply parameters to the <i>parent</i> of this
8336     * view specifying how it should be arranged. There are many subclasses of
8337     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8338     * of ViewGroup that are responsible for arranging their children.
8339     *
8340     * This method may return null if this View is not attached to a parent
8341     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8342     * was not invoked successfully. When a View is attached to a parent
8343     * ViewGroup, this method must not return null.
8344     *
8345     * @return The LayoutParams associated with this view, or null if no
8346     *         parameters have been set yet
8347     */
8348    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8349    public ViewGroup.LayoutParams getLayoutParams() {
8350        return mLayoutParams;
8351    }
8352
8353    /**
8354     * Set the layout parameters associated with this view. These supply
8355     * parameters to the <i>parent</i> of this view specifying how it should be
8356     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8357     * correspond to the different subclasses of ViewGroup that are responsible
8358     * for arranging their children.
8359     *
8360     * @param params The layout parameters for this view, cannot be null
8361     */
8362    public void setLayoutParams(ViewGroup.LayoutParams params) {
8363        if (params == null) {
8364            throw new NullPointerException("Layout parameters cannot be null");
8365        }
8366        mLayoutParams = params;
8367        if (mParent instanceof ViewGroup) {
8368            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8369        }
8370        requestLayout();
8371    }
8372
8373    /**
8374     * Set the scrolled position of your view. This will cause a call to
8375     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8376     * invalidated.
8377     * @param x the x position to scroll to
8378     * @param y the y position to scroll to
8379     */
8380    public void scrollTo(int x, int y) {
8381        if (mScrollX != x || mScrollY != y) {
8382            int oldX = mScrollX;
8383            int oldY = mScrollY;
8384            mScrollX = x;
8385            mScrollY = y;
8386            invalidateParentCaches();
8387            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8388            if (!awakenScrollBars()) {
8389                invalidate(true);
8390            }
8391        }
8392    }
8393
8394    /**
8395     * Move the scrolled position of your view. This will cause a call to
8396     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8397     * invalidated.
8398     * @param x the amount of pixels to scroll by horizontally
8399     * @param y the amount of pixels to scroll by vertically
8400     */
8401    public void scrollBy(int x, int y) {
8402        scrollTo(mScrollX + x, mScrollY + y);
8403    }
8404
8405    /**
8406     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8407     * animation to fade the scrollbars out after a default delay. If a subclass
8408     * provides animated scrolling, the start delay should equal the duration
8409     * of the scrolling animation.</p>
8410     *
8411     * <p>The animation starts only if at least one of the scrollbars is
8412     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8413     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8414     * this method returns true, and false otherwise. If the animation is
8415     * started, this method calls {@link #invalidate()}; in that case the
8416     * caller should not call {@link #invalidate()}.</p>
8417     *
8418     * <p>This method should be invoked every time a subclass directly updates
8419     * the scroll parameters.</p>
8420     *
8421     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8422     * and {@link #scrollTo(int, int)}.</p>
8423     *
8424     * @return true if the animation is played, false otherwise
8425     *
8426     * @see #awakenScrollBars(int)
8427     * @see #scrollBy(int, int)
8428     * @see #scrollTo(int, int)
8429     * @see #isHorizontalScrollBarEnabled()
8430     * @see #isVerticalScrollBarEnabled()
8431     * @see #setHorizontalScrollBarEnabled(boolean)
8432     * @see #setVerticalScrollBarEnabled(boolean)
8433     */
8434    protected boolean awakenScrollBars() {
8435        return mScrollCache != null &&
8436                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8437    }
8438
8439    /**
8440     * Trigger the scrollbars to draw.
8441     * This method differs from awakenScrollBars() only in its default duration.
8442     * initialAwakenScrollBars() will show the scroll bars for longer than
8443     * usual to give the user more of a chance to notice them.
8444     *
8445     * @return true if the animation is played, false otherwise.
8446     */
8447    private boolean initialAwakenScrollBars() {
8448        return mScrollCache != null &&
8449                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8450    }
8451
8452    /**
8453     * <p>
8454     * Trigger the scrollbars to draw. When invoked this method starts an
8455     * animation to fade the scrollbars out after a fixed delay. If a subclass
8456     * provides animated scrolling, the start delay should equal the duration of
8457     * the scrolling animation.
8458     * </p>
8459     *
8460     * <p>
8461     * The animation starts only if at least one of the scrollbars is enabled,
8462     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8463     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8464     * this method returns true, and false otherwise. If the animation is
8465     * started, this method calls {@link #invalidate()}; in that case the caller
8466     * should not call {@link #invalidate()}.
8467     * </p>
8468     *
8469     * <p>
8470     * This method should be invoked everytime a subclass directly updates the
8471     * scroll parameters.
8472     * </p>
8473     *
8474     * @param startDelay the delay, in milliseconds, after which the animation
8475     *        should start; when the delay is 0, the animation starts
8476     *        immediately
8477     * @return true if the animation is played, false otherwise
8478     *
8479     * @see #scrollBy(int, int)
8480     * @see #scrollTo(int, int)
8481     * @see #isHorizontalScrollBarEnabled()
8482     * @see #isVerticalScrollBarEnabled()
8483     * @see #setHorizontalScrollBarEnabled(boolean)
8484     * @see #setVerticalScrollBarEnabled(boolean)
8485     */
8486    protected boolean awakenScrollBars(int startDelay) {
8487        return awakenScrollBars(startDelay, true);
8488    }
8489
8490    /**
8491     * <p>
8492     * Trigger the scrollbars to draw. When invoked this method starts an
8493     * animation to fade the scrollbars out after a fixed delay. If a subclass
8494     * provides animated scrolling, the start delay should equal the duration of
8495     * the scrolling animation.
8496     * </p>
8497     *
8498     * <p>
8499     * The animation starts only if at least one of the scrollbars is enabled,
8500     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8501     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8502     * this method returns true, and false otherwise. If the animation is
8503     * started, this method calls {@link #invalidate()} if the invalidate parameter
8504     * is set to true; in that case the caller
8505     * should not call {@link #invalidate()}.
8506     * </p>
8507     *
8508     * <p>
8509     * This method should be invoked everytime a subclass directly updates the
8510     * scroll parameters.
8511     * </p>
8512     *
8513     * @param startDelay the delay, in milliseconds, after which the animation
8514     *        should start; when the delay is 0, the animation starts
8515     *        immediately
8516     *
8517     * @param invalidate Wheter this method should call invalidate
8518     *
8519     * @return true if the animation is played, false otherwise
8520     *
8521     * @see #scrollBy(int, int)
8522     * @see #scrollTo(int, int)
8523     * @see #isHorizontalScrollBarEnabled()
8524     * @see #isVerticalScrollBarEnabled()
8525     * @see #setHorizontalScrollBarEnabled(boolean)
8526     * @see #setVerticalScrollBarEnabled(boolean)
8527     */
8528    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8529        final ScrollabilityCache scrollCache = mScrollCache;
8530
8531        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8532            return false;
8533        }
8534
8535        if (scrollCache.scrollBar == null) {
8536            scrollCache.scrollBar = new ScrollBarDrawable();
8537        }
8538
8539        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8540
8541            if (invalidate) {
8542                // Invalidate to show the scrollbars
8543                invalidate(true);
8544            }
8545
8546            if (scrollCache.state == ScrollabilityCache.OFF) {
8547                // FIXME: this is copied from WindowManagerService.
8548                // We should get this value from the system when it
8549                // is possible to do so.
8550                final int KEY_REPEAT_FIRST_DELAY = 750;
8551                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8552            }
8553
8554            // Tell mScrollCache when we should start fading. This may
8555            // extend the fade start time if one was already scheduled
8556            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8557            scrollCache.fadeStartTime = fadeStartTime;
8558            scrollCache.state = ScrollabilityCache.ON;
8559
8560            // Schedule our fader to run, unscheduling any old ones first
8561            if (mAttachInfo != null) {
8562                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8563                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8564            }
8565
8566            return true;
8567        }
8568
8569        return false;
8570    }
8571
8572    /**
8573     * Do not invalidate views which are not visible and which are not running an animation. They
8574     * will not get drawn and they should not set dirty flags as if they will be drawn
8575     */
8576    private boolean skipInvalidate() {
8577        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8578                (!(mParent instanceof ViewGroup) ||
8579                        !((ViewGroup) mParent).isViewTransitioning(this));
8580    }
8581    /**
8582     * Mark the area defined by dirty as needing to be drawn. If the view is
8583     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8584     * in the future. This must be called from a UI thread. To call from a non-UI
8585     * thread, call {@link #postInvalidate()}.
8586     *
8587     * WARNING: This method is destructive to dirty.
8588     * @param dirty the rectangle representing the bounds of the dirty region
8589     */
8590    public void invalidate(Rect dirty) {
8591        if (ViewDebug.TRACE_HIERARCHY) {
8592            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8593        }
8594
8595        if (skipInvalidate()) {
8596            return;
8597        }
8598        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8599                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8600                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8601            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8602            mPrivateFlags |= INVALIDATED;
8603            mPrivateFlags |= DIRTY;
8604            final ViewParent p = mParent;
8605            final AttachInfo ai = mAttachInfo;
8606            //noinspection PointlessBooleanExpression,ConstantConditions
8607            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8608                if (p != null && ai != null && ai.mHardwareAccelerated) {
8609                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8610                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8611                    p.invalidateChild(this, null);
8612                    return;
8613                }
8614            }
8615            if (p != null && ai != null) {
8616                final int scrollX = mScrollX;
8617                final int scrollY = mScrollY;
8618                final Rect r = ai.mTmpInvalRect;
8619                r.set(dirty.left - scrollX, dirty.top - scrollY,
8620                        dirty.right - scrollX, dirty.bottom - scrollY);
8621                mParent.invalidateChild(this, r);
8622            }
8623        }
8624    }
8625
8626    /**
8627     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8628     * The coordinates of the dirty rect are relative to the view.
8629     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8630     * will be called at some point in the future. This must be called from
8631     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8632     * @param l the left position of the dirty region
8633     * @param t the top position of the dirty region
8634     * @param r the right position of the dirty region
8635     * @param b the bottom position of the dirty region
8636     */
8637    public void invalidate(int l, int t, int r, int b) {
8638        if (ViewDebug.TRACE_HIERARCHY) {
8639            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8640        }
8641
8642        if (skipInvalidate()) {
8643            return;
8644        }
8645        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8646                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8647                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8648            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8649            mPrivateFlags |= INVALIDATED;
8650            mPrivateFlags |= DIRTY;
8651            final ViewParent p = mParent;
8652            final AttachInfo ai = mAttachInfo;
8653            //noinspection PointlessBooleanExpression,ConstantConditions
8654            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8655                if (p != null && ai != null && ai.mHardwareAccelerated) {
8656                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8657                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8658                    p.invalidateChild(this, null);
8659                    return;
8660                }
8661            }
8662            if (p != null && ai != null && l < r && t < b) {
8663                final int scrollX = mScrollX;
8664                final int scrollY = mScrollY;
8665                final Rect tmpr = ai.mTmpInvalRect;
8666                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8667                p.invalidateChild(this, tmpr);
8668            }
8669        }
8670    }
8671
8672    /**
8673     * Invalidate the whole view. If the view is visible,
8674     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8675     * the future. This must be called from a UI thread. To call from a non-UI thread,
8676     * call {@link #postInvalidate()}.
8677     */
8678    public void invalidate() {
8679        invalidate(true);
8680    }
8681
8682    /**
8683     * This is where the invalidate() work actually happens. A full invalidate()
8684     * causes the drawing cache to be invalidated, but this function can be called with
8685     * invalidateCache set to false to skip that invalidation step for cases that do not
8686     * need it (for example, a component that remains at the same dimensions with the same
8687     * content).
8688     *
8689     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8690     * well. This is usually true for a full invalidate, but may be set to false if the
8691     * View's contents or dimensions have not changed.
8692     */
8693    void invalidate(boolean invalidateCache) {
8694        if (ViewDebug.TRACE_HIERARCHY) {
8695            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8696        }
8697
8698        if (skipInvalidate()) {
8699            return;
8700        }
8701        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8702                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8703                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8704            mLastIsOpaque = isOpaque();
8705            mPrivateFlags &= ~DRAWN;
8706            mPrivateFlags |= DIRTY;
8707            if (invalidateCache) {
8708                mPrivateFlags |= INVALIDATED;
8709                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8710            }
8711            final AttachInfo ai = mAttachInfo;
8712            final ViewParent p = mParent;
8713            //noinspection PointlessBooleanExpression,ConstantConditions
8714            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8715                if (p != null && ai != null && ai.mHardwareAccelerated) {
8716                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8717                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8718                    p.invalidateChild(this, null);
8719                    return;
8720                }
8721            }
8722
8723            if (p != null && ai != null) {
8724                final Rect r = ai.mTmpInvalRect;
8725                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8726                // Don't call invalidate -- we don't want to internally scroll
8727                // our own bounds
8728                p.invalidateChild(this, r);
8729            }
8730        }
8731    }
8732
8733    /**
8734     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
8735     * set any flags or handle all of the cases handled by the default invalidation methods.
8736     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
8737     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
8738     * walk up the hierarchy, transforming the dirty rect as necessary.
8739     *
8740     * The method also handles normal invalidation logic if display list properties are not
8741     * being used in this view. The invalidateParent and forceRedraw flags are used by that
8742     * backup approach, to handle these cases used in the various property-setting methods.
8743     *
8744     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
8745     * are not being used in this view
8746     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
8747     * list properties are not being used in this view
8748     */
8749    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
8750        if (!USE_DISPLAY_LIST_PROPERTIES || mDisplayList == null ||
8751                (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
8752            if (invalidateParent) {
8753                invalidateParentCaches();
8754            }
8755            if (forceRedraw) {
8756                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8757            }
8758            invalidate(false);
8759        } else {
8760            final AttachInfo ai = mAttachInfo;
8761            final ViewParent p = mParent;
8762            if (p != null && ai != null) {
8763                final Rect r = ai.mTmpInvalRect;
8764                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8765                if (mParent instanceof ViewGroup) {
8766                    ((ViewGroup) mParent).invalidateChildFast(this, r);
8767                } else {
8768                    mParent.invalidateChild(this, r);
8769                }
8770            }
8771        }
8772    }
8773
8774    /**
8775     * Utility method to transform a given Rect by the current matrix of this view.
8776     */
8777    void transformRect(final Rect rect) {
8778        if (!getMatrix().isIdentity()) {
8779            RectF boundingRect = mAttachInfo.mTmpTransformRect;
8780            boundingRect.set(rect);
8781            getMatrix().mapRect(boundingRect);
8782            rect.set((int) (boundingRect.left - 0.5f),
8783                    (int) (boundingRect.top - 0.5f),
8784                    (int) (boundingRect.right + 0.5f),
8785                    (int) (boundingRect.bottom + 0.5f));
8786        }
8787    }
8788
8789    /**
8790     * Used to indicate that the parent of this view should clear its caches. This functionality
8791     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8792     * which is necessary when various parent-managed properties of the view change, such as
8793     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8794     * clears the parent caches and does not causes an invalidate event.
8795     *
8796     * @hide
8797     */
8798    protected void invalidateParentCaches() {
8799        if (mParent instanceof View) {
8800            ((View) mParent).mPrivateFlags |= INVALIDATED;
8801        }
8802    }
8803
8804    /**
8805     * Used to indicate that the parent of this view should be invalidated. This functionality
8806     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8807     * which is necessary when various parent-managed properties of the view change, such as
8808     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8809     * an invalidation event to the parent.
8810     *
8811     * @hide
8812     */
8813    protected void invalidateParentIfNeeded() {
8814        if (isHardwareAccelerated() && mParent instanceof View) {
8815            ((View) mParent).invalidate(true);
8816        }
8817    }
8818
8819    /**
8820     * Indicates whether this View is opaque. An opaque View guarantees that it will
8821     * draw all the pixels overlapping its bounds using a fully opaque color.
8822     *
8823     * Subclasses of View should override this method whenever possible to indicate
8824     * whether an instance is opaque. Opaque Views are treated in a special way by
8825     * the View hierarchy, possibly allowing it to perform optimizations during
8826     * invalidate/draw passes.
8827     *
8828     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8829     */
8830    @ViewDebug.ExportedProperty(category = "drawing")
8831    public boolean isOpaque() {
8832        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8833                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8834                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8835    }
8836
8837    /**
8838     * @hide
8839     */
8840    protected void computeOpaqueFlags() {
8841        // Opaque if:
8842        //   - Has a background
8843        //   - Background is opaque
8844        //   - Doesn't have scrollbars or scrollbars are inside overlay
8845
8846        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8847            mPrivateFlags |= OPAQUE_BACKGROUND;
8848        } else {
8849            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8850        }
8851
8852        final int flags = mViewFlags;
8853        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8854                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8855            mPrivateFlags |= OPAQUE_SCROLLBARS;
8856        } else {
8857            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8858        }
8859    }
8860
8861    /**
8862     * @hide
8863     */
8864    protected boolean hasOpaqueScrollbars() {
8865        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8866    }
8867
8868    /**
8869     * @return A handler associated with the thread running the View. This
8870     * handler can be used to pump events in the UI events queue.
8871     */
8872    public Handler getHandler() {
8873        if (mAttachInfo != null) {
8874            return mAttachInfo.mHandler;
8875        }
8876        return null;
8877    }
8878
8879    /**
8880     * Gets the view root associated with the View.
8881     * @return The view root, or null if none.
8882     * @hide
8883     */
8884    public ViewRootImpl getViewRootImpl() {
8885        if (mAttachInfo != null) {
8886            return mAttachInfo.mViewRootImpl;
8887        }
8888        return null;
8889    }
8890
8891    /**
8892     * <p>Causes the Runnable to be added to the message queue.
8893     * The runnable will be run on the user interface thread.</p>
8894     *
8895     * <p>This method can be invoked from outside of the UI thread
8896     * only when this View is attached to a window.</p>
8897     *
8898     * @param action The Runnable that will be executed.
8899     *
8900     * @return Returns true if the Runnable was successfully placed in to the
8901     *         message queue.  Returns false on failure, usually because the
8902     *         looper processing the message queue is exiting.
8903     */
8904    public boolean post(Runnable action) {
8905        final AttachInfo attachInfo = mAttachInfo;
8906        if (attachInfo != null) {
8907            return attachInfo.mHandler.post(action);
8908        }
8909        // Assume that post will succeed later
8910        ViewRootImpl.getRunQueue().post(action);
8911        return true;
8912    }
8913
8914    /**
8915     * <p>Causes the Runnable to be added to the message queue, to be run
8916     * after the specified amount of time elapses.
8917     * The runnable will be run on the user interface thread.</p>
8918     *
8919     * <p>This method can be invoked from outside of the UI thread
8920     * only when this View is attached to a window.</p>
8921     *
8922     * @param action The Runnable that will be executed.
8923     * @param delayMillis The delay (in milliseconds) until the Runnable
8924     *        will be executed.
8925     *
8926     * @return true if the Runnable was successfully placed in to the
8927     *         message queue.  Returns false on failure, usually because the
8928     *         looper processing the message queue is exiting.  Note that a
8929     *         result of true does not mean the Runnable will be processed --
8930     *         if the looper is quit before the delivery time of the message
8931     *         occurs then the message will be dropped.
8932     */
8933    public boolean postDelayed(Runnable action, long delayMillis) {
8934        final AttachInfo attachInfo = mAttachInfo;
8935        if (attachInfo != null) {
8936            return attachInfo.mHandler.postDelayed(action, delayMillis);
8937        }
8938        // Assume that post will succeed later
8939        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8940        return true;
8941    }
8942
8943    /**
8944     * <p>Causes the Runnable to execute on the next animation time step.
8945     * The runnable will be run on the user interface thread.</p>
8946     *
8947     * <p>This method can be invoked from outside of the UI thread
8948     * only when this View is attached to a window.</p>
8949     *
8950     * @param action The Runnable that will be executed.
8951     *
8952     * @hide
8953     */
8954    public void postOnAnimation(Runnable action) {
8955        final AttachInfo attachInfo = mAttachInfo;
8956        if (attachInfo != null) {
8957            attachInfo.mViewRootImpl.mChoreographer.postAnimationCallback(action, null);
8958        } else {
8959            // Assume that post will succeed later
8960            ViewRootImpl.getRunQueue().post(action);
8961        }
8962    }
8963
8964    /**
8965     * <p>Causes the Runnable to execute on the next animation time step,
8966     * after the specified amount of time elapses.
8967     * The runnable will be run on the user interface thread.</p>
8968     *
8969     * <p>This method can be invoked from outside of the UI thread
8970     * only when this View is attached to a window.</p>
8971     *
8972     * @param action The Runnable that will be executed.
8973     * @param delayMillis The delay (in milliseconds) until the Runnable
8974     *        will be executed.
8975     *
8976     * @hide
8977     */
8978    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
8979        final AttachInfo attachInfo = mAttachInfo;
8980        if (attachInfo != null) {
8981            attachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed(
8982                    action, null, delayMillis);
8983        } else {
8984            // Assume that post will succeed later
8985            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8986        }
8987    }
8988
8989    /**
8990     * <p>Removes the specified Runnable from the message queue.</p>
8991     *
8992     * <p>This method can be invoked from outside of the UI thread
8993     * only when this View is attached to a window.</p>
8994     *
8995     * @param action The Runnable to remove from the message handling queue
8996     *
8997     * @return true if this view could ask the Handler to remove the Runnable,
8998     *         false otherwise. When the returned value is true, the Runnable
8999     *         may or may not have been actually removed from the message queue
9000     *         (for instance, if the Runnable was not in the queue already.)
9001     */
9002    public boolean removeCallbacks(Runnable action) {
9003        if (action != null) {
9004            final AttachInfo attachInfo = mAttachInfo;
9005            if (attachInfo != null) {
9006                attachInfo.mHandler.removeCallbacks(action);
9007                attachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(action, null);
9008            } else {
9009                // Assume that post will succeed later
9010                ViewRootImpl.getRunQueue().removeCallbacks(action);
9011            }
9012        }
9013        return true;
9014    }
9015
9016    /**
9017     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9018     * Use this to invalidate the View from a non-UI thread.</p>
9019     *
9020     * <p>This method can be invoked from outside of the UI thread
9021     * only when this View is attached to a window.</p>
9022     *
9023     * @see #invalidate()
9024     */
9025    public void postInvalidate() {
9026        postInvalidateDelayed(0);
9027    }
9028
9029    /**
9030     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9031     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9032     *
9033     * <p>This method can be invoked from outside of the UI thread
9034     * only when this View is attached to a window.</p>
9035     *
9036     * @param left The left coordinate of the rectangle to invalidate.
9037     * @param top The top coordinate of the rectangle to invalidate.
9038     * @param right The right coordinate of the rectangle to invalidate.
9039     * @param bottom The bottom coordinate of the rectangle to invalidate.
9040     *
9041     * @see #invalidate(int, int, int, int)
9042     * @see #invalidate(Rect)
9043     */
9044    public void postInvalidate(int left, int top, int right, int bottom) {
9045        postInvalidateDelayed(0, left, top, right, bottom);
9046    }
9047
9048    /**
9049     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9050     * loop. Waits for the specified amount of time.</p>
9051     *
9052     * <p>This method can be invoked from outside of the UI thread
9053     * only when this View is attached to a window.</p>
9054     *
9055     * @param delayMilliseconds the duration in milliseconds to delay the
9056     *         invalidation by
9057     */
9058    public void postInvalidateDelayed(long delayMilliseconds) {
9059        // We try only with the AttachInfo because there's no point in invalidating
9060        // if we are not attached to our window
9061        final AttachInfo attachInfo = mAttachInfo;
9062        if (attachInfo != null) {
9063            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9064        }
9065    }
9066
9067    /**
9068     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9069     * through the event loop. Waits for the specified amount of time.</p>
9070     *
9071     * <p>This method can be invoked from outside of the UI thread
9072     * only when this View is attached to a window.</p>
9073     *
9074     * @param delayMilliseconds the duration in milliseconds to delay the
9075     *         invalidation by
9076     * @param left The left coordinate of the rectangle to invalidate.
9077     * @param top The top coordinate of the rectangle to invalidate.
9078     * @param right The right coordinate of the rectangle to invalidate.
9079     * @param bottom The bottom coordinate of the rectangle to invalidate.
9080     */
9081    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
9082            int right, int bottom) {
9083
9084        // We try only with the AttachInfo because there's no point in invalidating
9085        // if we are not attached to our window
9086        final AttachInfo attachInfo = mAttachInfo;
9087        if (attachInfo != null) {
9088            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9089            info.target = this;
9090            info.left = left;
9091            info.top = top;
9092            info.right = right;
9093            info.bottom = bottom;
9094
9095            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
9096        }
9097    }
9098
9099    /**
9100     * <p>Cause an invalidate to happen on the next animation time step, typically the
9101     * next display frame.</p>
9102     *
9103     * <p>This method can be invoked from outside of the UI thread
9104     * only when this View is attached to a window.</p>
9105     *
9106     * @hide
9107     */
9108    public void postInvalidateOnAnimation() {
9109        // We try only with the AttachInfo because there's no point in invalidating
9110        // if we are not attached to our window
9111        final AttachInfo attachInfo = mAttachInfo;
9112        if (attachInfo != null) {
9113            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
9114        }
9115    }
9116
9117    /**
9118     * <p>Cause an invalidate of the specified area to happen on the next animation
9119     * time step, typically the next display frame.</p>
9120     *
9121     * <p>This method can be invoked from outside of the UI thread
9122     * only when this View is attached to a window.</p>
9123     *
9124     * @param left The left coordinate of the rectangle to invalidate.
9125     * @param top The top coordinate of the rectangle to invalidate.
9126     * @param right The right coordinate of the rectangle to invalidate.
9127     * @param bottom The bottom coordinate of the rectangle to invalidate.
9128     *
9129     * @hide
9130     */
9131    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
9132        // We try only with the AttachInfo because there's no point in invalidating
9133        // if we are not attached to our window
9134        final AttachInfo attachInfo = mAttachInfo;
9135        if (attachInfo != null) {
9136            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9137            info.target = this;
9138            info.left = left;
9139            info.top = top;
9140            info.right = right;
9141            info.bottom = bottom;
9142
9143            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
9144        }
9145    }
9146
9147    /**
9148     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
9149     * This event is sent at most once every
9150     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
9151     */
9152    private void postSendViewScrolledAccessibilityEventCallback() {
9153        if (mSendViewScrolledAccessibilityEvent == null) {
9154            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
9155        }
9156        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
9157            mSendViewScrolledAccessibilityEvent.mIsPending = true;
9158            postDelayed(mSendViewScrolledAccessibilityEvent,
9159                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
9160        }
9161    }
9162
9163    /**
9164     * Called by a parent to request that a child update its values for mScrollX
9165     * and mScrollY if necessary. This will typically be done if the child is
9166     * animating a scroll using a {@link android.widget.Scroller Scroller}
9167     * object.
9168     */
9169    public void computeScroll() {
9170    }
9171
9172    /**
9173     * <p>Indicate whether the horizontal edges are faded when the view is
9174     * scrolled horizontally.</p>
9175     *
9176     * @return true if the horizontal edges should are faded on scroll, false
9177     *         otherwise
9178     *
9179     * @see #setHorizontalFadingEdgeEnabled(boolean)
9180     * @attr ref android.R.styleable#View_requiresFadingEdge
9181     */
9182    public boolean isHorizontalFadingEdgeEnabled() {
9183        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
9184    }
9185
9186    /**
9187     * <p>Define whether the horizontal edges should be faded when this view
9188     * is scrolled horizontally.</p>
9189     *
9190     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
9191     *                                    be faded when the view is scrolled
9192     *                                    horizontally
9193     *
9194     * @see #isHorizontalFadingEdgeEnabled()
9195     * @attr ref android.R.styleable#View_requiresFadingEdge
9196     */
9197    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
9198        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
9199            if (horizontalFadingEdgeEnabled) {
9200                initScrollCache();
9201            }
9202
9203            mViewFlags ^= FADING_EDGE_HORIZONTAL;
9204        }
9205    }
9206
9207    /**
9208     * <p>Indicate whether the vertical edges are faded when the view is
9209     * scrolled horizontally.</p>
9210     *
9211     * @return true if the vertical edges should are faded on scroll, false
9212     *         otherwise
9213     *
9214     * @see #setVerticalFadingEdgeEnabled(boolean)
9215     * @attr ref android.R.styleable#View_requiresFadingEdge
9216     */
9217    public boolean isVerticalFadingEdgeEnabled() {
9218        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
9219    }
9220
9221    /**
9222     * <p>Define whether the vertical edges should be faded when this view
9223     * is scrolled vertically.</p>
9224     *
9225     * @param verticalFadingEdgeEnabled true if the vertical edges should
9226     *                                  be faded when the view is scrolled
9227     *                                  vertically
9228     *
9229     * @see #isVerticalFadingEdgeEnabled()
9230     * @attr ref android.R.styleable#View_requiresFadingEdge
9231     */
9232    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
9233        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
9234            if (verticalFadingEdgeEnabled) {
9235                initScrollCache();
9236            }
9237
9238            mViewFlags ^= FADING_EDGE_VERTICAL;
9239        }
9240    }
9241
9242    /**
9243     * Returns the strength, or intensity, of the top faded edge. The strength is
9244     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9245     * returns 0.0 or 1.0 but no value in between.
9246     *
9247     * Subclasses should override this method to provide a smoother fade transition
9248     * when scrolling occurs.
9249     *
9250     * @return the intensity of the top fade as a float between 0.0f and 1.0f
9251     */
9252    protected float getTopFadingEdgeStrength() {
9253        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
9254    }
9255
9256    /**
9257     * Returns the strength, or intensity, of the bottom faded edge. The strength is
9258     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9259     * returns 0.0 or 1.0 but no value in between.
9260     *
9261     * Subclasses should override this method to provide a smoother fade transition
9262     * when scrolling occurs.
9263     *
9264     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
9265     */
9266    protected float getBottomFadingEdgeStrength() {
9267        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
9268                computeVerticalScrollRange() ? 1.0f : 0.0f;
9269    }
9270
9271    /**
9272     * Returns the strength, or intensity, of the left faded edge. The strength is
9273     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9274     * returns 0.0 or 1.0 but no value in between.
9275     *
9276     * Subclasses should override this method to provide a smoother fade transition
9277     * when scrolling occurs.
9278     *
9279     * @return the intensity of the left fade as a float between 0.0f and 1.0f
9280     */
9281    protected float getLeftFadingEdgeStrength() {
9282        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
9283    }
9284
9285    /**
9286     * Returns the strength, or intensity, of the right faded edge. The strength is
9287     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9288     * returns 0.0 or 1.0 but no value in between.
9289     *
9290     * Subclasses should override this method to provide a smoother fade transition
9291     * when scrolling occurs.
9292     *
9293     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9294     */
9295    protected float getRightFadingEdgeStrength() {
9296        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9297                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9298    }
9299
9300    /**
9301     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9302     * scrollbar is not drawn by default.</p>
9303     *
9304     * @return true if the horizontal scrollbar should be painted, false
9305     *         otherwise
9306     *
9307     * @see #setHorizontalScrollBarEnabled(boolean)
9308     */
9309    public boolean isHorizontalScrollBarEnabled() {
9310        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9311    }
9312
9313    /**
9314     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9315     * scrollbar is not drawn by default.</p>
9316     *
9317     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9318     *                                   be painted
9319     *
9320     * @see #isHorizontalScrollBarEnabled()
9321     */
9322    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9323        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9324            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9325            computeOpaqueFlags();
9326            resolvePadding();
9327        }
9328    }
9329
9330    /**
9331     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9332     * scrollbar is not drawn by default.</p>
9333     *
9334     * @return true if the vertical scrollbar should be painted, false
9335     *         otherwise
9336     *
9337     * @see #setVerticalScrollBarEnabled(boolean)
9338     */
9339    public boolean isVerticalScrollBarEnabled() {
9340        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9341    }
9342
9343    /**
9344     * <p>Define whether the vertical scrollbar should be drawn or not. The
9345     * scrollbar is not drawn by default.</p>
9346     *
9347     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9348     *                                 be painted
9349     *
9350     * @see #isVerticalScrollBarEnabled()
9351     */
9352    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9353        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9354            mViewFlags ^= SCROLLBARS_VERTICAL;
9355            computeOpaqueFlags();
9356            resolvePadding();
9357        }
9358    }
9359
9360    /**
9361     * @hide
9362     */
9363    protected void recomputePadding() {
9364        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9365    }
9366
9367    /**
9368     * Define whether scrollbars will fade when the view is not scrolling.
9369     *
9370     * @param fadeScrollbars wheter to enable fading
9371     *
9372     */
9373    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9374        initScrollCache();
9375        final ScrollabilityCache scrollabilityCache = mScrollCache;
9376        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9377        if (fadeScrollbars) {
9378            scrollabilityCache.state = ScrollabilityCache.OFF;
9379        } else {
9380            scrollabilityCache.state = ScrollabilityCache.ON;
9381        }
9382    }
9383
9384    /**
9385     *
9386     * Returns true if scrollbars will fade when this view is not scrolling
9387     *
9388     * @return true if scrollbar fading is enabled
9389     */
9390    public boolean isScrollbarFadingEnabled() {
9391        return mScrollCache != null && mScrollCache.fadeScrollBars;
9392    }
9393
9394    /**
9395     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9396     * inset. When inset, they add to the padding of the view. And the scrollbars
9397     * can be drawn inside the padding area or on the edge of the view. For example,
9398     * if a view has a background drawable and you want to draw the scrollbars
9399     * inside the padding specified by the drawable, you can use
9400     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9401     * appear at the edge of the view, ignoring the padding, then you can use
9402     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9403     * @param style the style of the scrollbars. Should be one of
9404     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9405     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9406     * @see #SCROLLBARS_INSIDE_OVERLAY
9407     * @see #SCROLLBARS_INSIDE_INSET
9408     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9409     * @see #SCROLLBARS_OUTSIDE_INSET
9410     */
9411    public void setScrollBarStyle(int style) {
9412        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9413            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9414            computeOpaqueFlags();
9415            resolvePadding();
9416        }
9417    }
9418
9419    /**
9420     * <p>Returns the current scrollbar style.</p>
9421     * @return the current scrollbar style
9422     * @see #SCROLLBARS_INSIDE_OVERLAY
9423     * @see #SCROLLBARS_INSIDE_INSET
9424     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9425     * @see #SCROLLBARS_OUTSIDE_INSET
9426     */
9427    @ViewDebug.ExportedProperty(mapping = {
9428            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9429            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9430            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9431            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9432    })
9433    public int getScrollBarStyle() {
9434        return mViewFlags & SCROLLBARS_STYLE_MASK;
9435    }
9436
9437    /**
9438     * <p>Compute the horizontal range that the horizontal scrollbar
9439     * represents.</p>
9440     *
9441     * <p>The range is expressed in arbitrary units that must be the same as the
9442     * units used by {@link #computeHorizontalScrollExtent()} and
9443     * {@link #computeHorizontalScrollOffset()}.</p>
9444     *
9445     * <p>The default range is the drawing width of this view.</p>
9446     *
9447     * @return the total horizontal range represented by the horizontal
9448     *         scrollbar
9449     *
9450     * @see #computeHorizontalScrollExtent()
9451     * @see #computeHorizontalScrollOffset()
9452     * @see android.widget.ScrollBarDrawable
9453     */
9454    protected int computeHorizontalScrollRange() {
9455        return getWidth();
9456    }
9457
9458    /**
9459     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9460     * within the horizontal range. This value is used to compute the position
9461     * of the thumb within the scrollbar's track.</p>
9462     *
9463     * <p>The range is expressed in arbitrary units that must be the same as the
9464     * units used by {@link #computeHorizontalScrollRange()} and
9465     * {@link #computeHorizontalScrollExtent()}.</p>
9466     *
9467     * <p>The default offset is the scroll offset of this view.</p>
9468     *
9469     * @return the horizontal offset of the scrollbar's thumb
9470     *
9471     * @see #computeHorizontalScrollRange()
9472     * @see #computeHorizontalScrollExtent()
9473     * @see android.widget.ScrollBarDrawable
9474     */
9475    protected int computeHorizontalScrollOffset() {
9476        return mScrollX;
9477    }
9478
9479    /**
9480     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9481     * within the horizontal range. This value is used to compute the length
9482     * of the thumb within the scrollbar's track.</p>
9483     *
9484     * <p>The range is expressed in arbitrary units that must be the same as the
9485     * units used by {@link #computeHorizontalScrollRange()} and
9486     * {@link #computeHorizontalScrollOffset()}.</p>
9487     *
9488     * <p>The default extent is the drawing width of this view.</p>
9489     *
9490     * @return the horizontal extent of the scrollbar's thumb
9491     *
9492     * @see #computeHorizontalScrollRange()
9493     * @see #computeHorizontalScrollOffset()
9494     * @see android.widget.ScrollBarDrawable
9495     */
9496    protected int computeHorizontalScrollExtent() {
9497        return getWidth();
9498    }
9499
9500    /**
9501     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9502     *
9503     * <p>The range is expressed in arbitrary units that must be the same as the
9504     * units used by {@link #computeVerticalScrollExtent()} and
9505     * {@link #computeVerticalScrollOffset()}.</p>
9506     *
9507     * @return the total vertical range represented by the vertical scrollbar
9508     *
9509     * <p>The default range is the drawing height of this view.</p>
9510     *
9511     * @see #computeVerticalScrollExtent()
9512     * @see #computeVerticalScrollOffset()
9513     * @see android.widget.ScrollBarDrawable
9514     */
9515    protected int computeVerticalScrollRange() {
9516        return getHeight();
9517    }
9518
9519    /**
9520     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9521     * within the horizontal range. This value is used to compute the position
9522     * of the thumb within the scrollbar's track.</p>
9523     *
9524     * <p>The range is expressed in arbitrary units that must be the same as the
9525     * units used by {@link #computeVerticalScrollRange()} and
9526     * {@link #computeVerticalScrollExtent()}.</p>
9527     *
9528     * <p>The default offset is the scroll offset of this view.</p>
9529     *
9530     * @return the vertical offset of the scrollbar's thumb
9531     *
9532     * @see #computeVerticalScrollRange()
9533     * @see #computeVerticalScrollExtent()
9534     * @see android.widget.ScrollBarDrawable
9535     */
9536    protected int computeVerticalScrollOffset() {
9537        return mScrollY;
9538    }
9539
9540    /**
9541     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9542     * within the vertical range. This value is used to compute the length
9543     * of the thumb within the scrollbar's track.</p>
9544     *
9545     * <p>The range is expressed in arbitrary units that must be the same as the
9546     * units used by {@link #computeVerticalScrollRange()} and
9547     * {@link #computeVerticalScrollOffset()}.</p>
9548     *
9549     * <p>The default extent is the drawing height of this view.</p>
9550     *
9551     * @return the vertical extent of the scrollbar's thumb
9552     *
9553     * @see #computeVerticalScrollRange()
9554     * @see #computeVerticalScrollOffset()
9555     * @see android.widget.ScrollBarDrawable
9556     */
9557    protected int computeVerticalScrollExtent() {
9558        return getHeight();
9559    }
9560
9561    /**
9562     * Check if this view can be scrolled horizontally in a certain direction.
9563     *
9564     * @param direction Negative to check scrolling left, positive to check scrolling right.
9565     * @return true if this view can be scrolled in the specified direction, false otherwise.
9566     */
9567    public boolean canScrollHorizontally(int direction) {
9568        final int offset = computeHorizontalScrollOffset();
9569        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9570        if (range == 0) return false;
9571        if (direction < 0) {
9572            return offset > 0;
9573        } else {
9574            return offset < range - 1;
9575        }
9576    }
9577
9578    /**
9579     * Check if this view can be scrolled vertically in a certain direction.
9580     *
9581     * @param direction Negative to check scrolling up, positive to check scrolling down.
9582     * @return true if this view can be scrolled in the specified direction, false otherwise.
9583     */
9584    public boolean canScrollVertically(int direction) {
9585        final int offset = computeVerticalScrollOffset();
9586        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9587        if (range == 0) return false;
9588        if (direction < 0) {
9589            return offset > 0;
9590        } else {
9591            return offset < range - 1;
9592        }
9593    }
9594
9595    /**
9596     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9597     * scrollbars are painted only if they have been awakened first.</p>
9598     *
9599     * @param canvas the canvas on which to draw the scrollbars
9600     *
9601     * @see #awakenScrollBars(int)
9602     */
9603    protected final void onDrawScrollBars(Canvas canvas) {
9604        // scrollbars are drawn only when the animation is running
9605        final ScrollabilityCache cache = mScrollCache;
9606        if (cache != null) {
9607
9608            int state = cache.state;
9609
9610            if (state == ScrollabilityCache.OFF) {
9611                return;
9612            }
9613
9614            boolean invalidate = false;
9615
9616            if (state == ScrollabilityCache.FADING) {
9617                // We're fading -- get our fade interpolation
9618                if (cache.interpolatorValues == null) {
9619                    cache.interpolatorValues = new float[1];
9620                }
9621
9622                float[] values = cache.interpolatorValues;
9623
9624                // Stops the animation if we're done
9625                if (cache.scrollBarInterpolator.timeToValues(values) ==
9626                        Interpolator.Result.FREEZE_END) {
9627                    cache.state = ScrollabilityCache.OFF;
9628                } else {
9629                    cache.scrollBar.setAlpha(Math.round(values[0]));
9630                }
9631
9632                // This will make the scroll bars inval themselves after
9633                // drawing. We only want this when we're fading so that
9634                // we prevent excessive redraws
9635                invalidate = true;
9636            } else {
9637                // We're just on -- but we may have been fading before so
9638                // reset alpha
9639                cache.scrollBar.setAlpha(255);
9640            }
9641
9642
9643            final int viewFlags = mViewFlags;
9644
9645            final boolean drawHorizontalScrollBar =
9646                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9647            final boolean drawVerticalScrollBar =
9648                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9649                && !isVerticalScrollBarHidden();
9650
9651            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9652                final int width = mRight - mLeft;
9653                final int height = mBottom - mTop;
9654
9655                final ScrollBarDrawable scrollBar = cache.scrollBar;
9656
9657                final int scrollX = mScrollX;
9658                final int scrollY = mScrollY;
9659                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9660
9661                int left, top, right, bottom;
9662
9663                if (drawHorizontalScrollBar) {
9664                    int size = scrollBar.getSize(false);
9665                    if (size <= 0) {
9666                        size = cache.scrollBarSize;
9667                    }
9668
9669                    scrollBar.setParameters(computeHorizontalScrollRange(),
9670                                            computeHorizontalScrollOffset(),
9671                                            computeHorizontalScrollExtent(), false);
9672                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9673                            getVerticalScrollbarWidth() : 0;
9674                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9675                    left = scrollX + (mPaddingLeft & inside);
9676                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9677                    bottom = top + size;
9678                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9679                    if (invalidate) {
9680                        invalidate(left, top, right, bottom);
9681                    }
9682                }
9683
9684                if (drawVerticalScrollBar) {
9685                    int size = scrollBar.getSize(true);
9686                    if (size <= 0) {
9687                        size = cache.scrollBarSize;
9688                    }
9689
9690                    scrollBar.setParameters(computeVerticalScrollRange(),
9691                                            computeVerticalScrollOffset(),
9692                                            computeVerticalScrollExtent(), true);
9693                    switch (mVerticalScrollbarPosition) {
9694                        default:
9695                        case SCROLLBAR_POSITION_DEFAULT:
9696                        case SCROLLBAR_POSITION_RIGHT:
9697                            left = scrollX + width - size - (mUserPaddingRight & inside);
9698                            break;
9699                        case SCROLLBAR_POSITION_LEFT:
9700                            left = scrollX + (mUserPaddingLeft & inside);
9701                            break;
9702                    }
9703                    top = scrollY + (mPaddingTop & inside);
9704                    right = left + size;
9705                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9706                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9707                    if (invalidate) {
9708                        invalidate(left, top, right, bottom);
9709                    }
9710                }
9711            }
9712        }
9713    }
9714
9715    /**
9716     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9717     * FastScroller is visible.
9718     * @return whether to temporarily hide the vertical scrollbar
9719     * @hide
9720     */
9721    protected boolean isVerticalScrollBarHidden() {
9722        return false;
9723    }
9724
9725    /**
9726     * <p>Draw the horizontal scrollbar if
9727     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9728     *
9729     * @param canvas the canvas on which to draw the scrollbar
9730     * @param scrollBar the scrollbar's drawable
9731     *
9732     * @see #isHorizontalScrollBarEnabled()
9733     * @see #computeHorizontalScrollRange()
9734     * @see #computeHorizontalScrollExtent()
9735     * @see #computeHorizontalScrollOffset()
9736     * @see android.widget.ScrollBarDrawable
9737     * @hide
9738     */
9739    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9740            int l, int t, int r, int b) {
9741        scrollBar.setBounds(l, t, r, b);
9742        scrollBar.draw(canvas);
9743    }
9744
9745    /**
9746     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9747     * returns true.</p>
9748     *
9749     * @param canvas the canvas on which to draw the scrollbar
9750     * @param scrollBar the scrollbar's drawable
9751     *
9752     * @see #isVerticalScrollBarEnabled()
9753     * @see #computeVerticalScrollRange()
9754     * @see #computeVerticalScrollExtent()
9755     * @see #computeVerticalScrollOffset()
9756     * @see android.widget.ScrollBarDrawable
9757     * @hide
9758     */
9759    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9760            int l, int t, int r, int b) {
9761        scrollBar.setBounds(l, t, r, b);
9762        scrollBar.draw(canvas);
9763    }
9764
9765    /**
9766     * Implement this to do your drawing.
9767     *
9768     * @param canvas the canvas on which the background will be drawn
9769     */
9770    protected void onDraw(Canvas canvas) {
9771    }
9772
9773    /*
9774     * Caller is responsible for calling requestLayout if necessary.
9775     * (This allows addViewInLayout to not request a new layout.)
9776     */
9777    void assignParent(ViewParent parent) {
9778        if (mParent == null) {
9779            mParent = parent;
9780        } else if (parent == null) {
9781            mParent = null;
9782        } else {
9783            throw new RuntimeException("view " + this + " being added, but"
9784                    + " it already has a parent");
9785        }
9786    }
9787
9788    /**
9789     * This is called when the view is attached to a window.  At this point it
9790     * has a Surface and will start drawing.  Note that this function is
9791     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9792     * however it may be called any time before the first onDraw -- including
9793     * before or after {@link #onMeasure(int, int)}.
9794     *
9795     * @see #onDetachedFromWindow()
9796     */
9797    protected void onAttachedToWindow() {
9798        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9799            mParent.requestTransparentRegion(this);
9800        }
9801        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9802            initialAwakenScrollBars();
9803            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9804        }
9805        jumpDrawablesToCurrentState();
9806        // Order is important here: LayoutDirection MUST be resolved before Padding
9807        // and TextDirection
9808        resolveLayoutDirectionIfNeeded();
9809        resolvePadding();
9810        resolveTextDirection();
9811        if (isFocused()) {
9812            InputMethodManager imm = InputMethodManager.peekInstance();
9813            imm.focusIn(this);
9814        }
9815    }
9816
9817    /**
9818     * @see #onScreenStateChanged(int)
9819     */
9820    void dispatchScreenStateChanged(int screenState) {
9821        onScreenStateChanged(screenState);
9822    }
9823
9824    /**
9825     * This method is called whenever the state of the screen this view is
9826     * attached to changes. A state change will usually occurs when the screen
9827     * turns on or off (whether it happens automatically or the user does it
9828     * manually.)
9829     *
9830     * @param screenState The new state of the screen. Can be either
9831     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
9832     */
9833    public void onScreenStateChanged(int screenState) {
9834    }
9835
9836    /**
9837     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9838     * that the parent directionality can and will be resolved before its children.
9839     */
9840    private void resolveLayoutDirectionIfNeeded() {
9841        // Do not resolve if it is not needed
9842        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9843
9844        // Clear any previous layout direction resolution
9845        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
9846
9847        // Set resolved depending on layout direction
9848        switch (getLayoutDirection()) {
9849            case LAYOUT_DIRECTION_INHERIT:
9850                // We cannot do the resolution if there is no parent
9851                if (mParent == null) return;
9852
9853                // If this is root view, no need to look at parent's layout dir.
9854                if (mParent instanceof ViewGroup) {
9855                    ViewGroup viewGroup = ((ViewGroup) mParent);
9856
9857                    // Check if the parent view group can resolve
9858                    if (! viewGroup.canResolveLayoutDirection()) {
9859                        return;
9860                    }
9861                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9862                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9863                    }
9864                }
9865                break;
9866            case LAYOUT_DIRECTION_RTL:
9867                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9868                break;
9869            case LAYOUT_DIRECTION_LOCALE:
9870                if(isLayoutDirectionRtl(Locale.getDefault())) {
9871                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9872                }
9873                break;
9874            default:
9875                // Nothing to do, LTR by default
9876        }
9877
9878        // Set to resolved
9879        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9880        onResolvedLayoutDirectionChanged();
9881        // Resolve padding
9882        resolvePadding();
9883    }
9884
9885    /**
9886     * Called when layout direction has been resolved.
9887     *
9888     * The default implementation does nothing.
9889     */
9890    public void onResolvedLayoutDirectionChanged() {
9891    }
9892
9893    /**
9894     * Resolve padding depending on layout direction.
9895     */
9896    public void resolvePadding() {
9897        // If the user specified the absolute padding (either with android:padding or
9898        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9899        // use the default padding or the padding from the background drawable
9900        // (stored at this point in mPadding*)
9901        int resolvedLayoutDirection = getResolvedLayoutDirection();
9902        switch (resolvedLayoutDirection) {
9903            case LAYOUT_DIRECTION_RTL:
9904                // Start user padding override Right user padding. Otherwise, if Right user
9905                // padding is not defined, use the default Right padding. If Right user padding
9906                // is defined, just use it.
9907                if (mUserPaddingStart >= 0) {
9908                    mUserPaddingRight = mUserPaddingStart;
9909                } else if (mUserPaddingRight < 0) {
9910                    mUserPaddingRight = mPaddingRight;
9911                }
9912                if (mUserPaddingEnd >= 0) {
9913                    mUserPaddingLeft = mUserPaddingEnd;
9914                } else if (mUserPaddingLeft < 0) {
9915                    mUserPaddingLeft = mPaddingLeft;
9916                }
9917                break;
9918            case LAYOUT_DIRECTION_LTR:
9919            default:
9920                // Start user padding override Left user padding. Otherwise, if Left user
9921                // padding is not defined, use the default left padding. If Left user padding
9922                // is defined, just use it.
9923                if (mUserPaddingStart >= 0) {
9924                    mUserPaddingLeft = mUserPaddingStart;
9925                } else if (mUserPaddingLeft < 0) {
9926                    mUserPaddingLeft = mPaddingLeft;
9927                }
9928                if (mUserPaddingEnd >= 0) {
9929                    mUserPaddingRight = mUserPaddingEnd;
9930                } else if (mUserPaddingRight < 0) {
9931                    mUserPaddingRight = mPaddingRight;
9932                }
9933        }
9934
9935        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9936
9937        if(isPaddingRelative()) {
9938            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
9939        } else {
9940            recomputePadding();
9941        }
9942        onPaddingChanged(resolvedLayoutDirection);
9943    }
9944
9945    /**
9946     * Resolve padding depending on the layout direction. Subclasses that care about
9947     * padding resolution should override this method. The default implementation does
9948     * nothing.
9949     *
9950     * @param layoutDirection the direction of the layout
9951     *
9952     * @see {@link #LAYOUT_DIRECTION_LTR}
9953     * @see {@link #LAYOUT_DIRECTION_RTL}
9954     */
9955    public void onPaddingChanged(int layoutDirection) {
9956    }
9957
9958    /**
9959     * Check if layout direction resolution can be done.
9960     *
9961     * @return true if layout direction resolution can be done otherwise return false.
9962     */
9963    public boolean canResolveLayoutDirection() {
9964        switch (getLayoutDirection()) {
9965            case LAYOUT_DIRECTION_INHERIT:
9966                return (mParent != null);
9967            default:
9968                return true;
9969        }
9970    }
9971
9972    /**
9973     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
9974     * when reset is done.
9975     */
9976    public void resetResolvedLayoutDirection() {
9977        // Reset the current resolved bits
9978        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
9979        onResolvedLayoutDirectionReset();
9980        // Reset also the text direction
9981        resetResolvedTextDirection();
9982    }
9983
9984    /**
9985     * Called during reset of resolved layout direction.
9986     *
9987     * Subclasses need to override this method to clear cached information that depends on the
9988     * resolved layout direction, or to inform child views that inherit their layout direction.
9989     *
9990     * The default implementation does nothing.
9991     */
9992    public void onResolvedLayoutDirectionReset() {
9993    }
9994
9995    /**
9996     * Check if a Locale uses an RTL script.
9997     *
9998     * @param locale Locale to check
9999     * @return true if the Locale uses an RTL script.
10000     */
10001    protected static boolean isLayoutDirectionRtl(Locale locale) {
10002        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
10003    }
10004
10005    /**
10006     * This is called when the view is detached from a window.  At this point it
10007     * no longer has a surface for drawing.
10008     *
10009     * @see #onAttachedToWindow()
10010     */
10011    protected void onDetachedFromWindow() {
10012        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
10013
10014        removeUnsetPressCallback();
10015        removeLongPressCallback();
10016        removePerformClickCallback();
10017        removeSendViewScrolledAccessibilityEventCallback();
10018
10019        destroyDrawingCache();
10020
10021        destroyLayer(false);
10022
10023        if (mAttachInfo != null) {
10024            if (mDisplayList != null) {
10025                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
10026            }
10027            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
10028        } else {
10029            if (mDisplayList != null) {
10030                // Should never happen
10031                mDisplayList.invalidate();
10032            }
10033        }
10034
10035        mCurrentAnimation = null;
10036
10037        resetResolvedLayoutDirection();
10038    }
10039
10040    /**
10041     * @return The number of times this view has been attached to a window
10042     */
10043    protected int getWindowAttachCount() {
10044        return mWindowAttachCount;
10045    }
10046
10047    /**
10048     * Retrieve a unique token identifying the window this view is attached to.
10049     * @return Return the window's token for use in
10050     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
10051     */
10052    public IBinder getWindowToken() {
10053        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
10054    }
10055
10056    /**
10057     * Retrieve a unique token identifying the top-level "real" window of
10058     * the window that this view is attached to.  That is, this is like
10059     * {@link #getWindowToken}, except if the window this view in is a panel
10060     * window (attached to another containing window), then the token of
10061     * the containing window is returned instead.
10062     *
10063     * @return Returns the associated window token, either
10064     * {@link #getWindowToken()} or the containing window's token.
10065     */
10066    public IBinder getApplicationWindowToken() {
10067        AttachInfo ai = mAttachInfo;
10068        if (ai != null) {
10069            IBinder appWindowToken = ai.mPanelParentWindowToken;
10070            if (appWindowToken == null) {
10071                appWindowToken = ai.mWindowToken;
10072            }
10073            return appWindowToken;
10074        }
10075        return null;
10076    }
10077
10078    /**
10079     * Retrieve private session object this view hierarchy is using to
10080     * communicate with the window manager.
10081     * @return the session object to communicate with the window manager
10082     */
10083    /*package*/ IWindowSession getWindowSession() {
10084        return mAttachInfo != null ? mAttachInfo.mSession : null;
10085    }
10086
10087    /**
10088     * @param info the {@link android.view.View.AttachInfo} to associated with
10089     *        this view
10090     */
10091    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
10092        //System.out.println("Attached! " + this);
10093        mAttachInfo = info;
10094        mWindowAttachCount++;
10095        // We will need to evaluate the drawable state at least once.
10096        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
10097        if (mFloatingTreeObserver != null) {
10098            info.mTreeObserver.merge(mFloatingTreeObserver);
10099            mFloatingTreeObserver = null;
10100        }
10101        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
10102            mAttachInfo.mScrollContainers.add(this);
10103            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
10104        }
10105        performCollectViewAttributes(visibility);
10106        onAttachedToWindow();
10107
10108        ListenerInfo li = mListenerInfo;
10109        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10110                li != null ? li.mOnAttachStateChangeListeners : null;
10111        if (listeners != null && listeners.size() > 0) {
10112            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10113            // perform the dispatching. The iterator is a safe guard against listeners that
10114            // could mutate the list by calling the various add/remove methods. This prevents
10115            // the array from being modified while we iterate it.
10116            for (OnAttachStateChangeListener listener : listeners) {
10117                listener.onViewAttachedToWindow(this);
10118            }
10119        }
10120
10121        int vis = info.mWindowVisibility;
10122        if (vis != GONE) {
10123            onWindowVisibilityChanged(vis);
10124        }
10125        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
10126            // If nobody has evaluated the drawable state yet, then do it now.
10127            refreshDrawableState();
10128        }
10129    }
10130
10131    void dispatchDetachedFromWindow() {
10132        AttachInfo info = mAttachInfo;
10133        if (info != null) {
10134            int vis = info.mWindowVisibility;
10135            if (vis != GONE) {
10136                onWindowVisibilityChanged(GONE);
10137            }
10138        }
10139
10140        onDetachedFromWindow();
10141
10142        ListenerInfo li = mListenerInfo;
10143        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10144                li != null ? li.mOnAttachStateChangeListeners : null;
10145        if (listeners != null && listeners.size() > 0) {
10146            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10147            // perform the dispatching. The iterator is a safe guard against listeners that
10148            // could mutate the list by calling the various add/remove methods. This prevents
10149            // the array from being modified while we iterate it.
10150            for (OnAttachStateChangeListener listener : listeners) {
10151                listener.onViewDetachedFromWindow(this);
10152            }
10153        }
10154
10155        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
10156            mAttachInfo.mScrollContainers.remove(this);
10157            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
10158        }
10159
10160        mAttachInfo = null;
10161    }
10162
10163    /**
10164     * Store this view hierarchy's frozen state into the given container.
10165     *
10166     * @param container The SparseArray in which to save the view's state.
10167     *
10168     * @see #restoreHierarchyState(android.util.SparseArray)
10169     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10170     * @see #onSaveInstanceState()
10171     */
10172    public void saveHierarchyState(SparseArray<Parcelable> container) {
10173        dispatchSaveInstanceState(container);
10174    }
10175
10176    /**
10177     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
10178     * this view and its children. May be overridden to modify how freezing happens to a
10179     * view's children; for example, some views may want to not store state for their children.
10180     *
10181     * @param container The SparseArray in which to save the view's state.
10182     *
10183     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10184     * @see #saveHierarchyState(android.util.SparseArray)
10185     * @see #onSaveInstanceState()
10186     */
10187    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
10188        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
10189            mPrivateFlags &= ~SAVE_STATE_CALLED;
10190            Parcelable state = onSaveInstanceState();
10191            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10192                throw new IllegalStateException(
10193                        "Derived class did not call super.onSaveInstanceState()");
10194            }
10195            if (state != null) {
10196                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
10197                // + ": " + state);
10198                container.put(mID, state);
10199            }
10200        }
10201    }
10202
10203    /**
10204     * Hook allowing a view to generate a representation of its internal state
10205     * that can later be used to create a new instance with that same state.
10206     * This state should only contain information that is not persistent or can
10207     * not be reconstructed later. For example, you will never store your
10208     * current position on screen because that will be computed again when a
10209     * new instance of the view is placed in its view hierarchy.
10210     * <p>
10211     * Some examples of things you may store here: the current cursor position
10212     * in a text view (but usually not the text itself since that is stored in a
10213     * content provider or other persistent storage), the currently selected
10214     * item in a list view.
10215     *
10216     * @return Returns a Parcelable object containing the view's current dynamic
10217     *         state, or null if there is nothing interesting to save. The
10218     *         default implementation returns null.
10219     * @see #onRestoreInstanceState(android.os.Parcelable)
10220     * @see #saveHierarchyState(android.util.SparseArray)
10221     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10222     * @see #setSaveEnabled(boolean)
10223     */
10224    protected Parcelable onSaveInstanceState() {
10225        mPrivateFlags |= SAVE_STATE_CALLED;
10226        return BaseSavedState.EMPTY_STATE;
10227    }
10228
10229    /**
10230     * Restore this view hierarchy's frozen state from the given container.
10231     *
10232     * @param container The SparseArray which holds previously frozen states.
10233     *
10234     * @see #saveHierarchyState(android.util.SparseArray)
10235     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10236     * @see #onRestoreInstanceState(android.os.Parcelable)
10237     */
10238    public void restoreHierarchyState(SparseArray<Parcelable> container) {
10239        dispatchRestoreInstanceState(container);
10240    }
10241
10242    /**
10243     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
10244     * state for this view and its children. May be overridden to modify how restoring
10245     * happens to a view's children; for example, some views may want to not store state
10246     * for their children.
10247     *
10248     * @param container The SparseArray which holds previously saved state.
10249     *
10250     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10251     * @see #restoreHierarchyState(android.util.SparseArray)
10252     * @see #onRestoreInstanceState(android.os.Parcelable)
10253     */
10254    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
10255        if (mID != NO_ID) {
10256            Parcelable state = container.get(mID);
10257            if (state != null) {
10258                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
10259                // + ": " + state);
10260                mPrivateFlags &= ~SAVE_STATE_CALLED;
10261                onRestoreInstanceState(state);
10262                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10263                    throw new IllegalStateException(
10264                            "Derived class did not call super.onRestoreInstanceState()");
10265                }
10266            }
10267        }
10268    }
10269
10270    /**
10271     * Hook allowing a view to re-apply a representation of its internal state that had previously
10272     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
10273     * null state.
10274     *
10275     * @param state The frozen state that had previously been returned by
10276     *        {@link #onSaveInstanceState}.
10277     *
10278     * @see #onSaveInstanceState()
10279     * @see #restoreHierarchyState(android.util.SparseArray)
10280     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10281     */
10282    protected void onRestoreInstanceState(Parcelable state) {
10283        mPrivateFlags |= SAVE_STATE_CALLED;
10284        if (state != BaseSavedState.EMPTY_STATE && state != null) {
10285            throw new IllegalArgumentException("Wrong state class, expecting View State but "
10286                    + "received " + state.getClass().toString() + " instead. This usually happens "
10287                    + "when two views of different type have the same id in the same hierarchy. "
10288                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
10289                    + "other views do not use the same id.");
10290        }
10291    }
10292
10293    /**
10294     * <p>Return the time at which the drawing of the view hierarchy started.</p>
10295     *
10296     * @return the drawing start time in milliseconds
10297     */
10298    public long getDrawingTime() {
10299        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
10300    }
10301
10302    /**
10303     * <p>Enables or disables the duplication of the parent's state into this view. When
10304     * duplication is enabled, this view gets its drawable state from its parent rather
10305     * than from its own internal properties.</p>
10306     *
10307     * <p>Note: in the current implementation, setting this property to true after the
10308     * view was added to a ViewGroup might have no effect at all. This property should
10309     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
10310     *
10311     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
10312     * property is enabled, an exception will be thrown.</p>
10313     *
10314     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
10315     * parent, these states should not be affected by this method.</p>
10316     *
10317     * @param enabled True to enable duplication of the parent's drawable state, false
10318     *                to disable it.
10319     *
10320     * @see #getDrawableState()
10321     * @see #isDuplicateParentStateEnabled()
10322     */
10323    public void setDuplicateParentStateEnabled(boolean enabled) {
10324        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
10325    }
10326
10327    /**
10328     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
10329     *
10330     * @return True if this view's drawable state is duplicated from the parent,
10331     *         false otherwise
10332     *
10333     * @see #getDrawableState()
10334     * @see #setDuplicateParentStateEnabled(boolean)
10335     */
10336    public boolean isDuplicateParentStateEnabled() {
10337        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10338    }
10339
10340    /**
10341     * <p>Specifies the type of layer backing this view. The layer can be
10342     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10343     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10344     *
10345     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10346     * instance that controls how the layer is composed on screen. The following
10347     * properties of the paint are taken into account when composing the layer:</p>
10348     * <ul>
10349     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10350     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10351     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10352     * </ul>
10353     *
10354     * <p>If this view has an alpha value set to < 1.0 by calling
10355     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10356     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10357     * equivalent to setting a hardware layer on this view and providing a paint with
10358     * the desired alpha value.<p>
10359     *
10360     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10361     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10362     * for more information on when and how to use layers.</p>
10363     *
10364     * @param layerType The ype of layer to use with this view, must be one of
10365     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10366     *        {@link #LAYER_TYPE_HARDWARE}
10367     * @param paint The paint used to compose the layer. This argument is optional
10368     *        and can be null. It is ignored when the layer type is
10369     *        {@link #LAYER_TYPE_NONE}
10370     *
10371     * @see #getLayerType()
10372     * @see #LAYER_TYPE_NONE
10373     * @see #LAYER_TYPE_SOFTWARE
10374     * @see #LAYER_TYPE_HARDWARE
10375     * @see #setAlpha(float)
10376     *
10377     * @attr ref android.R.styleable#View_layerType
10378     */
10379    public void setLayerType(int layerType, Paint paint) {
10380        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10381            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10382                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10383        }
10384
10385        if (layerType == mLayerType) {
10386            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10387                mLayerPaint = paint == null ? new Paint() : paint;
10388                invalidateParentCaches();
10389                invalidate(true);
10390            }
10391            return;
10392        }
10393
10394        // Destroy any previous software drawing cache if needed
10395        switch (mLayerType) {
10396            case LAYER_TYPE_HARDWARE:
10397                destroyLayer(false);
10398                // fall through - non-accelerated views may use software layer mechanism instead
10399            case LAYER_TYPE_SOFTWARE:
10400                destroyDrawingCache();
10401                break;
10402            default:
10403                break;
10404        }
10405
10406        mLayerType = layerType;
10407        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10408        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10409        mLocalDirtyRect = layerDisabled ? null : new Rect();
10410
10411        invalidateParentCaches();
10412        invalidate(true);
10413    }
10414
10415    /**
10416     * Indicates whether this view has a static layer. A view with layer type
10417     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10418     * dynamic.
10419     */
10420    boolean hasStaticLayer() {
10421        return true;
10422    }
10423
10424    /**
10425     * Indicates what type of layer is currently associated with this view. By default
10426     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10427     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10428     * for more information on the different types of layers.
10429     *
10430     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10431     *         {@link #LAYER_TYPE_HARDWARE}
10432     *
10433     * @see #setLayerType(int, android.graphics.Paint)
10434     * @see #buildLayer()
10435     * @see #LAYER_TYPE_NONE
10436     * @see #LAYER_TYPE_SOFTWARE
10437     * @see #LAYER_TYPE_HARDWARE
10438     */
10439    public int getLayerType() {
10440        return mLayerType;
10441    }
10442
10443    /**
10444     * Forces this view's layer to be created and this view to be rendered
10445     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10446     * invoking this method will have no effect.
10447     *
10448     * This method can for instance be used to render a view into its layer before
10449     * starting an animation. If this view is complex, rendering into the layer
10450     * before starting the animation will avoid skipping frames.
10451     *
10452     * @throws IllegalStateException If this view is not attached to a window
10453     *
10454     * @see #setLayerType(int, android.graphics.Paint)
10455     */
10456    public void buildLayer() {
10457        if (mLayerType == LAYER_TYPE_NONE) return;
10458
10459        if (mAttachInfo == null) {
10460            throw new IllegalStateException("This view must be attached to a window first");
10461        }
10462
10463        switch (mLayerType) {
10464            case LAYER_TYPE_HARDWARE:
10465                if (mAttachInfo.mHardwareRenderer != null &&
10466                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10467                        mAttachInfo.mHardwareRenderer.validate()) {
10468                    getHardwareLayer();
10469                }
10470                break;
10471            case LAYER_TYPE_SOFTWARE:
10472                buildDrawingCache(true);
10473                break;
10474        }
10475    }
10476
10477    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10478    void flushLayer() {
10479        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10480            mHardwareLayer.flush();
10481        }
10482    }
10483
10484    /**
10485     * <p>Returns a hardware layer that can be used to draw this view again
10486     * without executing its draw method.</p>
10487     *
10488     * @return A HardwareLayer ready to render, or null if an error occurred.
10489     */
10490    HardwareLayer getHardwareLayer() {
10491        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10492                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10493            return null;
10494        }
10495
10496        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10497
10498        final int width = mRight - mLeft;
10499        final int height = mBottom - mTop;
10500
10501        if (width == 0 || height == 0) {
10502            return null;
10503        }
10504
10505        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10506            if (mHardwareLayer == null) {
10507                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10508                        width, height, isOpaque());
10509                mLocalDirtyRect.set(0, 0, width, height);
10510            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10511                mHardwareLayer.resize(width, height);
10512                mLocalDirtyRect.set(0, 0, width, height);
10513            }
10514
10515            // The layer is not valid if the underlying GPU resources cannot be allocated
10516            if (!mHardwareLayer.isValid()) {
10517                return null;
10518            }
10519
10520            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
10521            mLocalDirtyRect.setEmpty();
10522        }
10523
10524        return mHardwareLayer;
10525    }
10526
10527    /**
10528     * Destroys this View's hardware layer if possible.
10529     *
10530     * @return True if the layer was destroyed, false otherwise.
10531     *
10532     * @see #setLayerType(int, android.graphics.Paint)
10533     * @see #LAYER_TYPE_HARDWARE
10534     */
10535    boolean destroyLayer(boolean valid) {
10536        if (mHardwareLayer != null) {
10537            AttachInfo info = mAttachInfo;
10538            if (info != null && info.mHardwareRenderer != null &&
10539                    info.mHardwareRenderer.isEnabled() &&
10540                    (valid || info.mHardwareRenderer.validate())) {
10541                mHardwareLayer.destroy();
10542                mHardwareLayer = null;
10543
10544                invalidate(true);
10545                invalidateParentCaches();
10546            }
10547            return true;
10548        }
10549        return false;
10550    }
10551
10552    /**
10553     * Destroys all hardware rendering resources. This method is invoked
10554     * when the system needs to reclaim resources. Upon execution of this
10555     * method, you should free any OpenGL resources created by the view.
10556     *
10557     * Note: you <strong>must</strong> call
10558     * <code>super.destroyHardwareResources()</code> when overriding
10559     * this method.
10560     *
10561     * @hide
10562     */
10563    protected void destroyHardwareResources() {
10564        destroyLayer(true);
10565    }
10566
10567    /**
10568     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10569     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10570     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10571     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10572     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10573     * null.</p>
10574     *
10575     * <p>Enabling the drawing cache is similar to
10576     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10577     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10578     * drawing cache has no effect on rendering because the system uses a different mechanism
10579     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10580     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10581     * for information on how to enable software and hardware layers.</p>
10582     *
10583     * <p>This API can be used to manually generate
10584     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10585     * {@link #getDrawingCache()}.</p>
10586     *
10587     * @param enabled true to enable the drawing cache, false otherwise
10588     *
10589     * @see #isDrawingCacheEnabled()
10590     * @see #getDrawingCache()
10591     * @see #buildDrawingCache()
10592     * @see #setLayerType(int, android.graphics.Paint)
10593     */
10594    public void setDrawingCacheEnabled(boolean enabled) {
10595        mCachingFailed = false;
10596        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10597    }
10598
10599    /**
10600     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10601     *
10602     * @return true if the drawing cache is enabled
10603     *
10604     * @see #setDrawingCacheEnabled(boolean)
10605     * @see #getDrawingCache()
10606     */
10607    @ViewDebug.ExportedProperty(category = "drawing")
10608    public boolean isDrawingCacheEnabled() {
10609        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10610    }
10611
10612    /**
10613     * Debugging utility which recursively outputs the dirty state of a view and its
10614     * descendants.
10615     *
10616     * @hide
10617     */
10618    @SuppressWarnings({"UnusedDeclaration"})
10619    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10620        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10621                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10622                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10623                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10624        if (clear) {
10625            mPrivateFlags &= clearMask;
10626        }
10627        if (this instanceof ViewGroup) {
10628            ViewGroup parent = (ViewGroup) this;
10629            final int count = parent.getChildCount();
10630            for (int i = 0; i < count; i++) {
10631                final View child = parent.getChildAt(i);
10632                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10633            }
10634        }
10635    }
10636
10637    /**
10638     * This method is used by ViewGroup to cause its children to restore or recreate their
10639     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10640     * to recreate its own display list, which would happen if it went through the normal
10641     * draw/dispatchDraw mechanisms.
10642     *
10643     * @hide
10644     */
10645    protected void dispatchGetDisplayList() {}
10646
10647    /**
10648     * A view that is not attached or hardware accelerated cannot create a display list.
10649     * This method checks these conditions and returns the appropriate result.
10650     *
10651     * @return true if view has the ability to create a display list, false otherwise.
10652     *
10653     * @hide
10654     */
10655    public boolean canHaveDisplayList() {
10656        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10657    }
10658
10659    /**
10660     * @return The HardwareRenderer associated with that view or null if hardware rendering
10661     * is not supported or this this has not been attached to a window.
10662     *
10663     * @hide
10664     */
10665    public HardwareRenderer getHardwareRenderer() {
10666        if (mAttachInfo != null) {
10667            return mAttachInfo.mHardwareRenderer;
10668        }
10669        return null;
10670    }
10671
10672    /**
10673     * Returns a DisplayList. If the incoming displayList is null, one will be created.
10674     * Otherwise, the same display list will be returned (after having been rendered into
10675     * along the way, depending on the invalidation state of the view).
10676     *
10677     * @param displayList The previous version of this displayList, could be null.
10678     * @param isLayer Whether the requester of the display list is a layer. If so,
10679     * the view will avoid creating a layer inside the resulting display list.
10680     * @return A new or reused DisplayList object.
10681     */
10682    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
10683        if (!canHaveDisplayList()) {
10684            return null;
10685        }
10686
10687        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10688                displayList == null || !displayList.isValid() ||
10689                (!isLayer && mRecreateDisplayList))) {
10690            // Don't need to recreate the display list, just need to tell our
10691            // children to restore/recreate theirs
10692            if (displayList != null && displayList.isValid() &&
10693                    !isLayer && !mRecreateDisplayList) {
10694                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10695                mPrivateFlags &= ~DIRTY_MASK;
10696                dispatchGetDisplayList();
10697
10698                return displayList;
10699            }
10700
10701            if (!isLayer) {
10702                // If we got here, we're recreating it. Mark it as such to ensure that
10703                // we copy in child display lists into ours in drawChild()
10704                mRecreateDisplayList = true;
10705            }
10706            if (displayList == null) {
10707                final String name = getClass().getSimpleName();
10708                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10709                // If we're creating a new display list, make sure our parent gets invalidated
10710                // since they will need to recreate their display list to account for this
10711                // new child display list.
10712                invalidateParentCaches();
10713            }
10714
10715            boolean caching = false;
10716            final HardwareCanvas canvas = displayList.start();
10717            int restoreCount = 0;
10718            int width = mRight - mLeft;
10719            int height = mBottom - mTop;
10720
10721            try {
10722                canvas.setViewport(width, height);
10723                // The dirty rect should always be null for a display list
10724                canvas.onPreDraw(null);
10725                int layerType = (
10726                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
10727                        getLayerType() : LAYER_TYPE_NONE;
10728                if (!isLayer && layerType == LAYER_TYPE_HARDWARE && USE_DISPLAY_LIST_PROPERTIES) {
10729                    final HardwareLayer layer = getHardwareLayer();
10730                    if (layer != null && layer.isValid()) {
10731                        canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
10732                    } else {
10733                        canvas.saveLayer(0, 0,
10734                                mRight - mLeft, mBottom - mTop, mLayerPaint,
10735                                Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
10736                    }
10737                    caching = true;
10738                } else {
10739
10740                    computeScroll();
10741
10742                    if (!USE_DISPLAY_LIST_PROPERTIES) {
10743                        restoreCount = canvas.save();
10744                    }
10745                    canvas.translate(-mScrollX, -mScrollY);
10746                    if (!isLayer) {
10747                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10748                        mPrivateFlags &= ~DIRTY_MASK;
10749                    }
10750
10751                    // Fast path for layouts with no backgrounds
10752                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10753                        dispatchDraw(canvas);
10754                    } else {
10755                        draw(canvas);
10756                    }
10757                }
10758            } finally {
10759                if (USE_DISPLAY_LIST_PROPERTIES) {
10760                    canvas.restoreToCount(restoreCount);
10761                }
10762                canvas.onPostDraw();
10763
10764                displayList.end();
10765                if (USE_DISPLAY_LIST_PROPERTIES) {
10766                    displayList.setCaching(caching);
10767                }
10768                if (isLayer && USE_DISPLAY_LIST_PROPERTIES) {
10769                    displayList.setLeftTopRightBottom(0, 0, width, height);
10770                } else {
10771                    setDisplayListProperties(displayList);
10772                }
10773            }
10774        } else if (!isLayer) {
10775            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10776            mPrivateFlags &= ~DIRTY_MASK;
10777        }
10778
10779        return displayList;
10780    }
10781
10782    /**
10783     * Get the DisplayList for the HardwareLayer
10784     *
10785     * @param layer The HardwareLayer whose DisplayList we want
10786     * @return A DisplayList fopr the specified HardwareLayer
10787     */
10788    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
10789        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
10790        layer.setDisplayList(displayList);
10791        return displayList;
10792    }
10793
10794
10795    /**
10796     * <p>Returns a display list that can be used to draw this view again
10797     * without executing its draw method.</p>
10798     *
10799     * @return A DisplayList ready to replay, or null if caching is not enabled.
10800     *
10801     * @hide
10802     */
10803    public DisplayList getDisplayList() {
10804        mDisplayList = getDisplayList(mDisplayList, false);
10805        return mDisplayList;
10806    }
10807
10808    /**
10809     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10810     *
10811     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10812     *
10813     * @see #getDrawingCache(boolean)
10814     */
10815    public Bitmap getDrawingCache() {
10816        return getDrawingCache(false);
10817    }
10818
10819    /**
10820     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10821     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10822     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10823     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10824     * request the drawing cache by calling this method and draw it on screen if the
10825     * returned bitmap is not null.</p>
10826     *
10827     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10828     * this method will create a bitmap of the same size as this view. Because this bitmap
10829     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10830     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10831     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10832     * size than the view. This implies that your application must be able to handle this
10833     * size.</p>
10834     *
10835     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10836     *        the current density of the screen when the application is in compatibility
10837     *        mode.
10838     *
10839     * @return A bitmap representing this view or null if cache is disabled.
10840     *
10841     * @see #setDrawingCacheEnabled(boolean)
10842     * @see #isDrawingCacheEnabled()
10843     * @see #buildDrawingCache(boolean)
10844     * @see #destroyDrawingCache()
10845     */
10846    public Bitmap getDrawingCache(boolean autoScale) {
10847        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10848            return null;
10849        }
10850        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10851            buildDrawingCache(autoScale);
10852        }
10853        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10854    }
10855
10856    /**
10857     * <p>Frees the resources used by the drawing cache. If you call
10858     * {@link #buildDrawingCache()} manually without calling
10859     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10860     * should cleanup the cache with this method afterwards.</p>
10861     *
10862     * @see #setDrawingCacheEnabled(boolean)
10863     * @see #buildDrawingCache()
10864     * @see #getDrawingCache()
10865     */
10866    public void destroyDrawingCache() {
10867        if (mDrawingCache != null) {
10868            mDrawingCache.recycle();
10869            mDrawingCache = null;
10870        }
10871        if (mUnscaledDrawingCache != null) {
10872            mUnscaledDrawingCache.recycle();
10873            mUnscaledDrawingCache = null;
10874        }
10875    }
10876
10877    /**
10878     * Setting a solid background color for the drawing cache's bitmaps will improve
10879     * performance and memory usage. Note, though that this should only be used if this
10880     * view will always be drawn on top of a solid color.
10881     *
10882     * @param color The background color to use for the drawing cache's bitmap
10883     *
10884     * @see #setDrawingCacheEnabled(boolean)
10885     * @see #buildDrawingCache()
10886     * @see #getDrawingCache()
10887     */
10888    public void setDrawingCacheBackgroundColor(int color) {
10889        if (color != mDrawingCacheBackgroundColor) {
10890            mDrawingCacheBackgroundColor = color;
10891            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10892        }
10893    }
10894
10895    /**
10896     * @see #setDrawingCacheBackgroundColor(int)
10897     *
10898     * @return The background color to used for the drawing cache's bitmap
10899     */
10900    public int getDrawingCacheBackgroundColor() {
10901        return mDrawingCacheBackgroundColor;
10902    }
10903
10904    /**
10905     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10906     *
10907     * @see #buildDrawingCache(boolean)
10908     */
10909    public void buildDrawingCache() {
10910        buildDrawingCache(false);
10911    }
10912
10913    /**
10914     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10915     *
10916     * <p>If you call {@link #buildDrawingCache()} manually without calling
10917     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10918     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10919     *
10920     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10921     * this method will create a bitmap of the same size as this view. Because this bitmap
10922     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10923     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10924     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10925     * size than the view. This implies that your application must be able to handle this
10926     * size.</p>
10927     *
10928     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10929     * you do not need the drawing cache bitmap, calling this method will increase memory
10930     * usage and cause the view to be rendered in software once, thus negatively impacting
10931     * performance.</p>
10932     *
10933     * @see #getDrawingCache()
10934     * @see #destroyDrawingCache()
10935     */
10936    public void buildDrawingCache(boolean autoScale) {
10937        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10938                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10939            mCachingFailed = false;
10940
10941            if (ViewDebug.TRACE_HIERARCHY) {
10942                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10943            }
10944
10945            int width = mRight - mLeft;
10946            int height = mBottom - mTop;
10947
10948            final AttachInfo attachInfo = mAttachInfo;
10949            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10950
10951            if (autoScale && scalingRequired) {
10952                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10953                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10954            }
10955
10956            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10957            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10958            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10959
10960            if (width <= 0 || height <= 0 ||
10961                     // Projected bitmap size in bytes
10962                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10963                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10964                destroyDrawingCache();
10965                mCachingFailed = true;
10966                return;
10967            }
10968
10969            boolean clear = true;
10970            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10971
10972            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10973                Bitmap.Config quality;
10974                if (!opaque) {
10975                    // Never pick ARGB_4444 because it looks awful
10976                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10977                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10978                        case DRAWING_CACHE_QUALITY_AUTO:
10979                            quality = Bitmap.Config.ARGB_8888;
10980                            break;
10981                        case DRAWING_CACHE_QUALITY_LOW:
10982                            quality = Bitmap.Config.ARGB_8888;
10983                            break;
10984                        case DRAWING_CACHE_QUALITY_HIGH:
10985                            quality = Bitmap.Config.ARGB_8888;
10986                            break;
10987                        default:
10988                            quality = Bitmap.Config.ARGB_8888;
10989                            break;
10990                    }
10991                } else {
10992                    // Optimization for translucent windows
10993                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10994                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10995                }
10996
10997                // Try to cleanup memory
10998                if (bitmap != null) bitmap.recycle();
10999
11000                try {
11001                    bitmap = Bitmap.createBitmap(width, height, quality);
11002                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
11003                    if (autoScale) {
11004                        mDrawingCache = bitmap;
11005                    } else {
11006                        mUnscaledDrawingCache = bitmap;
11007                    }
11008                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
11009                } catch (OutOfMemoryError e) {
11010                    // If there is not enough memory to create the bitmap cache, just
11011                    // ignore the issue as bitmap caches are not required to draw the
11012                    // view hierarchy
11013                    if (autoScale) {
11014                        mDrawingCache = null;
11015                    } else {
11016                        mUnscaledDrawingCache = null;
11017                    }
11018                    mCachingFailed = true;
11019                    return;
11020                }
11021
11022                clear = drawingCacheBackgroundColor != 0;
11023            }
11024
11025            Canvas canvas;
11026            if (attachInfo != null) {
11027                canvas = attachInfo.mCanvas;
11028                if (canvas == null) {
11029                    canvas = new Canvas();
11030                }
11031                canvas.setBitmap(bitmap);
11032                // Temporarily clobber the cached Canvas in case one of our children
11033                // is also using a drawing cache. Without this, the children would
11034                // steal the canvas by attaching their own bitmap to it and bad, bad
11035                // thing would happen (invisible views, corrupted drawings, etc.)
11036                attachInfo.mCanvas = null;
11037            } else {
11038                // This case should hopefully never or seldom happen
11039                canvas = new Canvas(bitmap);
11040            }
11041
11042            if (clear) {
11043                bitmap.eraseColor(drawingCacheBackgroundColor);
11044            }
11045
11046            computeScroll();
11047            final int restoreCount = canvas.save();
11048
11049            if (autoScale && scalingRequired) {
11050                final float scale = attachInfo.mApplicationScale;
11051                canvas.scale(scale, scale);
11052            }
11053
11054            canvas.translate(-mScrollX, -mScrollY);
11055
11056            mPrivateFlags |= DRAWN;
11057            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
11058                    mLayerType != LAYER_TYPE_NONE) {
11059                mPrivateFlags |= DRAWING_CACHE_VALID;
11060            }
11061
11062            // Fast path for layouts with no backgrounds
11063            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11064                if (ViewDebug.TRACE_HIERARCHY) {
11065                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11066                }
11067                mPrivateFlags &= ~DIRTY_MASK;
11068                dispatchDraw(canvas);
11069            } else {
11070                draw(canvas);
11071            }
11072
11073            canvas.restoreToCount(restoreCount);
11074            canvas.setBitmap(null);
11075
11076            if (attachInfo != null) {
11077                // Restore the cached Canvas for our siblings
11078                attachInfo.mCanvas = canvas;
11079            }
11080        }
11081    }
11082
11083    /**
11084     * Create a snapshot of the view into a bitmap.  We should probably make
11085     * some form of this public, but should think about the API.
11086     */
11087    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
11088        int width = mRight - mLeft;
11089        int height = mBottom - mTop;
11090
11091        final AttachInfo attachInfo = mAttachInfo;
11092        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
11093        width = (int) ((width * scale) + 0.5f);
11094        height = (int) ((height * scale) + 0.5f);
11095
11096        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
11097        if (bitmap == null) {
11098            throw new OutOfMemoryError();
11099        }
11100
11101        Resources resources = getResources();
11102        if (resources != null) {
11103            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
11104        }
11105
11106        Canvas canvas;
11107        if (attachInfo != null) {
11108            canvas = attachInfo.mCanvas;
11109            if (canvas == null) {
11110                canvas = new Canvas();
11111            }
11112            canvas.setBitmap(bitmap);
11113            // Temporarily clobber the cached Canvas in case one of our children
11114            // is also using a drawing cache. Without this, the children would
11115            // steal the canvas by attaching their own bitmap to it and bad, bad
11116            // things would happen (invisible views, corrupted drawings, etc.)
11117            attachInfo.mCanvas = null;
11118        } else {
11119            // This case should hopefully never or seldom happen
11120            canvas = new Canvas(bitmap);
11121        }
11122
11123        if ((backgroundColor & 0xff000000) != 0) {
11124            bitmap.eraseColor(backgroundColor);
11125        }
11126
11127        computeScroll();
11128        final int restoreCount = canvas.save();
11129        canvas.scale(scale, scale);
11130        canvas.translate(-mScrollX, -mScrollY);
11131
11132        // Temporarily remove the dirty mask
11133        int flags = mPrivateFlags;
11134        mPrivateFlags &= ~DIRTY_MASK;
11135
11136        // Fast path for layouts with no backgrounds
11137        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11138            dispatchDraw(canvas);
11139        } else {
11140            draw(canvas);
11141        }
11142
11143        mPrivateFlags = flags;
11144
11145        canvas.restoreToCount(restoreCount);
11146        canvas.setBitmap(null);
11147
11148        if (attachInfo != null) {
11149            // Restore the cached Canvas for our siblings
11150            attachInfo.mCanvas = canvas;
11151        }
11152
11153        return bitmap;
11154    }
11155
11156    /**
11157     * Indicates whether this View is currently in edit mode. A View is usually
11158     * in edit mode when displayed within a developer tool. For instance, if
11159     * this View is being drawn by a visual user interface builder, this method
11160     * should return true.
11161     *
11162     * Subclasses should check the return value of this method to provide
11163     * different behaviors if their normal behavior might interfere with the
11164     * host environment. For instance: the class spawns a thread in its
11165     * constructor, the drawing code relies on device-specific features, etc.
11166     *
11167     * This method is usually checked in the drawing code of custom widgets.
11168     *
11169     * @return True if this View is in edit mode, false otherwise.
11170     */
11171    public boolean isInEditMode() {
11172        return false;
11173    }
11174
11175    /**
11176     * If the View draws content inside its padding and enables fading edges,
11177     * it needs to support padding offsets. Padding offsets are added to the
11178     * fading edges to extend the length of the fade so that it covers pixels
11179     * drawn inside the padding.
11180     *
11181     * Subclasses of this class should override this method if they need
11182     * to draw content inside the padding.
11183     *
11184     * @return True if padding offset must be applied, false otherwise.
11185     *
11186     * @see #getLeftPaddingOffset()
11187     * @see #getRightPaddingOffset()
11188     * @see #getTopPaddingOffset()
11189     * @see #getBottomPaddingOffset()
11190     *
11191     * @since CURRENT
11192     */
11193    protected boolean isPaddingOffsetRequired() {
11194        return false;
11195    }
11196
11197    /**
11198     * Amount by which to extend the left fading region. Called only when
11199     * {@link #isPaddingOffsetRequired()} returns true.
11200     *
11201     * @return The left padding offset in pixels.
11202     *
11203     * @see #isPaddingOffsetRequired()
11204     *
11205     * @since CURRENT
11206     */
11207    protected int getLeftPaddingOffset() {
11208        return 0;
11209    }
11210
11211    /**
11212     * Amount by which to extend the right fading region. Called only when
11213     * {@link #isPaddingOffsetRequired()} returns true.
11214     *
11215     * @return The right padding offset in pixels.
11216     *
11217     * @see #isPaddingOffsetRequired()
11218     *
11219     * @since CURRENT
11220     */
11221    protected int getRightPaddingOffset() {
11222        return 0;
11223    }
11224
11225    /**
11226     * Amount by which to extend the top fading region. Called only when
11227     * {@link #isPaddingOffsetRequired()} returns true.
11228     *
11229     * @return The top padding offset in pixels.
11230     *
11231     * @see #isPaddingOffsetRequired()
11232     *
11233     * @since CURRENT
11234     */
11235    protected int getTopPaddingOffset() {
11236        return 0;
11237    }
11238
11239    /**
11240     * Amount by which to extend the bottom fading region. Called only when
11241     * {@link #isPaddingOffsetRequired()} returns true.
11242     *
11243     * @return The bottom padding offset in pixels.
11244     *
11245     * @see #isPaddingOffsetRequired()
11246     *
11247     * @since CURRENT
11248     */
11249    protected int getBottomPaddingOffset() {
11250        return 0;
11251    }
11252
11253    /**
11254     * @hide
11255     * @param offsetRequired
11256     */
11257    protected int getFadeTop(boolean offsetRequired) {
11258        int top = mPaddingTop;
11259        if (offsetRequired) top += getTopPaddingOffset();
11260        return top;
11261    }
11262
11263    /**
11264     * @hide
11265     * @param offsetRequired
11266     */
11267    protected int getFadeHeight(boolean offsetRequired) {
11268        int padding = mPaddingTop;
11269        if (offsetRequired) padding += getTopPaddingOffset();
11270        return mBottom - mTop - mPaddingBottom - padding;
11271    }
11272
11273    /**
11274     * <p>Indicates whether this view is attached to a hardware accelerated
11275     * window or not.</p>
11276     *
11277     * <p>Even if this method returns true, it does not mean that every call
11278     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
11279     * accelerated {@link android.graphics.Canvas}. For instance, if this view
11280     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
11281     * window is hardware accelerated,
11282     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
11283     * return false, and this method will return true.</p>
11284     *
11285     * @return True if the view is attached to a window and the window is
11286     *         hardware accelerated; false in any other case.
11287     */
11288    public boolean isHardwareAccelerated() {
11289        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
11290    }
11291
11292    /**
11293     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
11294     * case of an active Animation being run on the view.
11295     */
11296    private boolean drawAnimation(ViewGroup parent, long drawingTime,
11297            Animation a, boolean scalingRequired) {
11298        Transformation invalidationTransform;
11299        final int flags = parent.mGroupFlags;
11300        final boolean initialized = a.isInitialized();
11301        if (!initialized) {
11302            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
11303            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
11304            onAnimationStart();
11305        }
11306
11307        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
11308        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
11309            if (parent.mInvalidationTransformation == null) {
11310                parent.mInvalidationTransformation = new Transformation();
11311            }
11312            invalidationTransform = parent.mInvalidationTransformation;
11313            a.getTransformation(drawingTime, invalidationTransform, 1f);
11314        } else {
11315            invalidationTransform = parent.mChildTransformation;
11316        }
11317        if (more) {
11318            if (!a.willChangeBounds()) {
11319                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
11320                        parent.FLAG_OPTIMIZE_INVALIDATE) {
11321                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
11322                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
11323                    // The child need to draw an animation, potentially offscreen, so
11324                    // make sure we do not cancel invalidate requests
11325                    parent.mPrivateFlags |= DRAW_ANIMATION;
11326                    parent.invalidate(mLeft, mTop, mRight, mBottom);
11327                }
11328            } else {
11329                if (parent.mInvalidateRegion == null) {
11330                    parent.mInvalidateRegion = new RectF();
11331                }
11332                final RectF region = parent.mInvalidateRegion;
11333                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
11334                        invalidationTransform);
11335
11336                // The child need to draw an animation, potentially offscreen, so
11337                // make sure we do not cancel invalidate requests
11338                parent.mPrivateFlags |= DRAW_ANIMATION;
11339
11340                final int left = mLeft + (int) region.left;
11341                final int top = mTop + (int) region.top;
11342                parent.invalidate(left, top, left + (int) (region.width() + .5f),
11343                        top + (int) (region.height() + .5f));
11344            }
11345        }
11346        return more;
11347    }
11348
11349    void setDisplayListProperties() {
11350        setDisplayListProperties(mDisplayList);
11351    }
11352
11353    /**
11354     * This method is called by getDisplayList() when a display list is created or re-rendered.
11355     * It sets or resets the current value of all properties on that display list (resetting is
11356     * necessary when a display list is being re-created, because we need to make sure that
11357     * previously-set transform values
11358     */
11359    void setDisplayListProperties(DisplayList displayList) {
11360        if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) {
11361            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
11362            if (mParent instanceof ViewGroup) {
11363                displayList.setClipChildren(
11364                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
11365            }
11366            if (mAttachInfo != null && mAttachInfo.mScalingRequired &&
11367                    mAttachInfo.mApplicationScale != 1.0f) {
11368                displayList.setApplicationScale(1f / mAttachInfo.mApplicationScale);
11369            }
11370            if (mTransformationInfo != null) {
11371                displayList.setTransformationInfo(mTransformationInfo.mAlpha,
11372                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
11373                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
11374                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
11375                        mTransformationInfo.mScaleY);
11376                displayList.setCameraDistance(getCameraDistance());
11377                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
11378                    displayList.setPivotX(getPivotX());
11379                    displayList.setPivotY(getPivotY());
11380                }
11381            }
11382        }
11383    }
11384
11385    /**
11386     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
11387     * This draw() method is an implementation detail and is not intended to be overridden or
11388     * to be called from anywhere else other than ViewGroup.drawChild().
11389     */
11390    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
11391        boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null &&
11392                mAttachInfo.mHardwareAccelerated;
11393        boolean more = false;
11394        final boolean childHasIdentityMatrix = hasIdentityMatrix();
11395        final int flags = parent.mGroupFlags;
11396
11397        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
11398            parent.mChildTransformation.clear();
11399            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11400        }
11401
11402        Transformation transformToApply = null;
11403        boolean concatMatrix = false;
11404
11405        boolean scalingRequired = false;
11406        boolean caching;
11407        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11408
11409        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11410        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
11411                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
11412            caching = true;
11413            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11414        } else {
11415            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11416        }
11417
11418        final Animation a = getAnimation();
11419        if (a != null) {
11420            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11421            concatMatrix = a.willChangeTransformationMatrix();
11422            transformToApply = parent.mChildTransformation;
11423        } else if ((flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
11424            final boolean hasTransform =
11425                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11426            if (hasTransform) {
11427                final int transformType = parent.mChildTransformation.getTransformationType();
11428                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11429                        parent.mChildTransformation : null;
11430                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11431            }
11432        }
11433
11434        concatMatrix |= !childHasIdentityMatrix;
11435
11436        // Sets the flag as early as possible to allow draw() implementations
11437        // to call invalidate() successfully when doing animations
11438        mPrivateFlags |= DRAWN;
11439
11440        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11441                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11442            return more;
11443        }
11444
11445        if (hardwareAccelerated) {
11446            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11447            // retain the flag's value temporarily in the mRecreateDisplayList flag
11448            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11449            mPrivateFlags &= ~INVALIDATED;
11450        }
11451
11452        computeScroll();
11453
11454        final int sx = mScrollX;
11455        final int sy = mScrollY;
11456
11457        DisplayList displayList = null;
11458        Bitmap cache = null;
11459        boolean hasDisplayList = false;
11460        if (caching) {
11461            if (!hardwareAccelerated) {
11462                if (layerType != LAYER_TYPE_NONE) {
11463                    layerType = LAYER_TYPE_SOFTWARE;
11464                    buildDrawingCache(true);
11465                }
11466                cache = getDrawingCache(true);
11467            } else {
11468                switch (layerType) {
11469                    case LAYER_TYPE_SOFTWARE:
11470                        buildDrawingCache(true);
11471                        cache = getDrawingCache(true);
11472                        break;
11473                    case LAYER_TYPE_HARDWARE:
11474                        if (useDisplayListProperties) {
11475                            hasDisplayList = canHaveDisplayList();
11476                        }
11477                        break;
11478                    case LAYER_TYPE_NONE:
11479                        // Delay getting the display list until animation-driven alpha values are
11480                        // set up and possibly passed on to the view
11481                        hasDisplayList = canHaveDisplayList();
11482                        break;
11483                }
11484            }
11485        }
11486        useDisplayListProperties &= hasDisplayList;
11487
11488        final boolean hasNoCache = cache == null || hasDisplayList;
11489        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11490                layerType != LAYER_TYPE_HARDWARE;
11491
11492        int restoreTo = -1;
11493        if (!useDisplayListProperties || transformToApply != null) {
11494            restoreTo = canvas.save();
11495        }
11496        if (offsetForScroll) {
11497            canvas.translate(mLeft - sx, mTop - sy);
11498        } else {
11499            if (!useDisplayListProperties) {
11500                canvas.translate(mLeft, mTop);
11501            }
11502            if (scalingRequired) {
11503                if (useDisplayListProperties) {
11504                    restoreTo = canvas.save();
11505                }
11506                // mAttachInfo cannot be null, otherwise scalingRequired == false
11507                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11508                canvas.scale(scale, scale);
11509            }
11510        }
11511
11512        float alpha = useDisplayListProperties ? 1 : getAlpha();
11513        if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) {
11514            if (transformToApply != null || !childHasIdentityMatrix) {
11515                int transX = 0;
11516                int transY = 0;
11517
11518                if (offsetForScroll) {
11519                    transX = -sx;
11520                    transY = -sy;
11521                }
11522
11523                if (transformToApply != null) {
11524                    if (concatMatrix) {
11525                        // Undo the scroll translation, apply the transformation matrix,
11526                        // then redo the scroll translate to get the correct result.
11527                        canvas.translate(-transX, -transY);
11528                        canvas.concat(transformToApply.getMatrix());
11529                        canvas.translate(transX, transY);
11530                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11531                    }
11532
11533                    float transformAlpha = transformToApply.getAlpha();
11534                    if (transformAlpha < 1.0f) {
11535                        alpha *= transformToApply.getAlpha();
11536                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11537                    }
11538                }
11539
11540                if (!childHasIdentityMatrix && !useDisplayListProperties) {
11541                    canvas.translate(-transX, -transY);
11542                    canvas.concat(getMatrix());
11543                    canvas.translate(transX, transY);
11544                }
11545            }
11546
11547            if (alpha < 1.0f) {
11548                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11549                if (hasNoCache) {
11550                    final int multipliedAlpha = (int) (255 * alpha);
11551                    if (!onSetAlpha(multipliedAlpha)) {
11552                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11553                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
11554                                layerType != LAYER_TYPE_NONE) {
11555                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11556                        }
11557                        if (layerType == LAYER_TYPE_NONE) {
11558                            final int scrollX = hasDisplayList ? 0 : sx;
11559                            final int scrollY = hasDisplayList ? 0 : sy;
11560                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11561                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11562                        }
11563                    } else {
11564                        // Alpha is handled by the child directly, clobber the layer's alpha
11565                        mPrivateFlags |= ALPHA_SET;
11566                    }
11567                }
11568            }
11569        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11570            onSetAlpha(255);
11571            mPrivateFlags &= ~ALPHA_SET;
11572        }
11573
11574        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
11575                !useDisplayListProperties) {
11576            if (offsetForScroll) {
11577                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11578            } else {
11579                if (!scalingRequired || cache == null) {
11580                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11581                } else {
11582                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11583                }
11584            }
11585        }
11586
11587        if (hasDisplayList) {
11588            displayList = getDisplayList();
11589            if (!displayList.isValid()) {
11590                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11591                // to getDisplayList(), the display list will be marked invalid and we should not
11592                // try to use it again.
11593                displayList = null;
11594                hasDisplayList = false;
11595            }
11596        }
11597
11598        if (hasNoCache) {
11599            boolean layerRendered = false;
11600            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
11601                final HardwareLayer layer = getHardwareLayer();
11602                if (layer != null && layer.isValid()) {
11603                    mLayerPaint.setAlpha((int) (alpha * 255));
11604                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11605                    layerRendered = true;
11606                } else {
11607                    final int scrollX = hasDisplayList ? 0 : sx;
11608                    final int scrollY = hasDisplayList ? 0 : sy;
11609                    canvas.saveLayer(scrollX, scrollY,
11610                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11611                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11612                }
11613            }
11614
11615            if (!layerRendered) {
11616                if (!hasDisplayList) {
11617                    // Fast path for layouts with no backgrounds
11618                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11619                        if (ViewDebug.TRACE_HIERARCHY) {
11620                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11621                        }
11622                        mPrivateFlags &= ~DIRTY_MASK;
11623                        dispatchDraw(canvas);
11624                    } else {
11625                        draw(canvas);
11626                    }
11627                } else {
11628                    mPrivateFlags &= ~DIRTY_MASK;
11629                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11630                            mRight - mLeft, mBottom - mTop, null, flags);
11631                }
11632            }
11633        } else if (cache != null) {
11634            mPrivateFlags &= ~DIRTY_MASK;
11635            Paint cachePaint;
11636
11637            if (layerType == LAYER_TYPE_NONE) {
11638                cachePaint = parent.mCachePaint;
11639                if (cachePaint == null) {
11640                    cachePaint = new Paint();
11641                    cachePaint.setDither(false);
11642                    parent.mCachePaint = cachePaint;
11643                }
11644                if (alpha < 1.0f) {
11645                    cachePaint.setAlpha((int) (alpha * 255));
11646                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
11647                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
11648                    cachePaint.setAlpha(255);
11649                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
11650                }
11651            } else {
11652                cachePaint = mLayerPaint;
11653                cachePaint.setAlpha((int) (alpha * 255));
11654            }
11655            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11656        }
11657
11658        if (restoreTo >= 0) {
11659            canvas.restoreToCount(restoreTo);
11660        }
11661
11662        if (a != null && !more) {
11663            if (!hardwareAccelerated && !a.getFillAfter()) {
11664                onSetAlpha(255);
11665            }
11666            parent.finishAnimatingView(this, a);
11667        }
11668
11669        if (more && hardwareAccelerated) {
11670            // invalidation is the trigger to recreate display lists, so if we're using
11671            // display lists to render, force an invalidate to allow the animation to
11672            // continue drawing another frame
11673            parent.invalidate(true);
11674            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11675                // alpha animations should cause the child to recreate its display list
11676                invalidate(true);
11677            }
11678        }
11679
11680        mRecreateDisplayList = false;
11681
11682        return more;
11683    }
11684
11685    /**
11686     * Manually render this view (and all of its children) to the given Canvas.
11687     * The view must have already done a full layout before this function is
11688     * called.  When implementing a view, implement
11689     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11690     * If you do need to override this method, call the superclass version.
11691     *
11692     * @param canvas The Canvas to which the View is rendered.
11693     */
11694    public void draw(Canvas canvas) {
11695        if (ViewDebug.TRACE_HIERARCHY) {
11696            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11697        }
11698
11699        final int privateFlags = mPrivateFlags;
11700        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11701                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11702        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11703
11704        /*
11705         * Draw traversal performs several drawing steps which must be executed
11706         * in the appropriate order:
11707         *
11708         *      1. Draw the background
11709         *      2. If necessary, save the canvas' layers to prepare for fading
11710         *      3. Draw view's content
11711         *      4. Draw children
11712         *      5. If necessary, draw the fading edges and restore layers
11713         *      6. Draw decorations (scrollbars for instance)
11714         */
11715
11716        // Step 1, draw the background, if needed
11717        int saveCount;
11718
11719        if (!dirtyOpaque) {
11720            final Drawable background = mBGDrawable;
11721            if (background != null) {
11722                final int scrollX = mScrollX;
11723                final int scrollY = mScrollY;
11724
11725                if (mBackgroundSizeChanged) {
11726                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11727                    mBackgroundSizeChanged = false;
11728                }
11729
11730                if ((scrollX | scrollY) == 0) {
11731                    background.draw(canvas);
11732                } else {
11733                    canvas.translate(scrollX, scrollY);
11734                    background.draw(canvas);
11735                    canvas.translate(-scrollX, -scrollY);
11736                }
11737            }
11738        }
11739
11740        // skip step 2 & 5 if possible (common case)
11741        final int viewFlags = mViewFlags;
11742        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11743        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11744        if (!verticalEdges && !horizontalEdges) {
11745            // Step 3, draw the content
11746            if (!dirtyOpaque) onDraw(canvas);
11747
11748            // Step 4, draw the children
11749            dispatchDraw(canvas);
11750
11751            // Step 6, draw decorations (scrollbars)
11752            onDrawScrollBars(canvas);
11753
11754            // we're done...
11755            return;
11756        }
11757
11758        /*
11759         * Here we do the full fledged routine...
11760         * (this is an uncommon case where speed matters less,
11761         * this is why we repeat some of the tests that have been
11762         * done above)
11763         */
11764
11765        boolean drawTop = false;
11766        boolean drawBottom = false;
11767        boolean drawLeft = false;
11768        boolean drawRight = false;
11769
11770        float topFadeStrength = 0.0f;
11771        float bottomFadeStrength = 0.0f;
11772        float leftFadeStrength = 0.0f;
11773        float rightFadeStrength = 0.0f;
11774
11775        // Step 2, save the canvas' layers
11776        int paddingLeft = mPaddingLeft;
11777
11778        final boolean offsetRequired = isPaddingOffsetRequired();
11779        if (offsetRequired) {
11780            paddingLeft += getLeftPaddingOffset();
11781        }
11782
11783        int left = mScrollX + paddingLeft;
11784        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11785        int top = mScrollY + getFadeTop(offsetRequired);
11786        int bottom = top + getFadeHeight(offsetRequired);
11787
11788        if (offsetRequired) {
11789            right += getRightPaddingOffset();
11790            bottom += getBottomPaddingOffset();
11791        }
11792
11793        final ScrollabilityCache scrollabilityCache = mScrollCache;
11794        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11795        int length = (int) fadeHeight;
11796
11797        // clip the fade length if top and bottom fades overlap
11798        // overlapping fades produce odd-looking artifacts
11799        if (verticalEdges && (top + length > bottom - length)) {
11800            length = (bottom - top) / 2;
11801        }
11802
11803        // also clip horizontal fades if necessary
11804        if (horizontalEdges && (left + length > right - length)) {
11805            length = (right - left) / 2;
11806        }
11807
11808        if (verticalEdges) {
11809            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11810            drawTop = topFadeStrength * fadeHeight > 1.0f;
11811            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11812            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11813        }
11814
11815        if (horizontalEdges) {
11816            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11817            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11818            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11819            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11820        }
11821
11822        saveCount = canvas.getSaveCount();
11823
11824        int solidColor = getSolidColor();
11825        if (solidColor == 0) {
11826            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11827
11828            if (drawTop) {
11829                canvas.saveLayer(left, top, right, top + length, null, flags);
11830            }
11831
11832            if (drawBottom) {
11833                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11834            }
11835
11836            if (drawLeft) {
11837                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11838            }
11839
11840            if (drawRight) {
11841                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11842            }
11843        } else {
11844            scrollabilityCache.setFadeColor(solidColor);
11845        }
11846
11847        // Step 3, draw the content
11848        if (!dirtyOpaque) onDraw(canvas);
11849
11850        // Step 4, draw the children
11851        dispatchDraw(canvas);
11852
11853        // Step 5, draw the fade effect and restore layers
11854        final Paint p = scrollabilityCache.paint;
11855        final Matrix matrix = scrollabilityCache.matrix;
11856        final Shader fade = scrollabilityCache.shader;
11857
11858        if (drawTop) {
11859            matrix.setScale(1, fadeHeight * topFadeStrength);
11860            matrix.postTranslate(left, top);
11861            fade.setLocalMatrix(matrix);
11862            canvas.drawRect(left, top, right, top + length, p);
11863        }
11864
11865        if (drawBottom) {
11866            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11867            matrix.postRotate(180);
11868            matrix.postTranslate(left, bottom);
11869            fade.setLocalMatrix(matrix);
11870            canvas.drawRect(left, bottom - length, right, bottom, p);
11871        }
11872
11873        if (drawLeft) {
11874            matrix.setScale(1, fadeHeight * leftFadeStrength);
11875            matrix.postRotate(-90);
11876            matrix.postTranslate(left, top);
11877            fade.setLocalMatrix(matrix);
11878            canvas.drawRect(left, top, left + length, bottom, p);
11879        }
11880
11881        if (drawRight) {
11882            matrix.setScale(1, fadeHeight * rightFadeStrength);
11883            matrix.postRotate(90);
11884            matrix.postTranslate(right, top);
11885            fade.setLocalMatrix(matrix);
11886            canvas.drawRect(right - length, top, right, bottom, p);
11887        }
11888
11889        canvas.restoreToCount(saveCount);
11890
11891        // Step 6, draw decorations (scrollbars)
11892        onDrawScrollBars(canvas);
11893    }
11894
11895    /**
11896     * Override this if your view is known to always be drawn on top of a solid color background,
11897     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11898     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11899     * should be set to 0xFF.
11900     *
11901     * @see #setVerticalFadingEdgeEnabled(boolean)
11902     * @see #setHorizontalFadingEdgeEnabled(boolean)
11903     *
11904     * @return The known solid color background for this view, or 0 if the color may vary
11905     */
11906    @ViewDebug.ExportedProperty(category = "drawing")
11907    public int getSolidColor() {
11908        return 0;
11909    }
11910
11911    /**
11912     * Build a human readable string representation of the specified view flags.
11913     *
11914     * @param flags the view flags to convert to a string
11915     * @return a String representing the supplied flags
11916     */
11917    private static String printFlags(int flags) {
11918        String output = "";
11919        int numFlags = 0;
11920        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11921            output += "TAKES_FOCUS";
11922            numFlags++;
11923        }
11924
11925        switch (flags & VISIBILITY_MASK) {
11926        case INVISIBLE:
11927            if (numFlags > 0) {
11928                output += " ";
11929            }
11930            output += "INVISIBLE";
11931            // USELESS HERE numFlags++;
11932            break;
11933        case GONE:
11934            if (numFlags > 0) {
11935                output += " ";
11936            }
11937            output += "GONE";
11938            // USELESS HERE numFlags++;
11939            break;
11940        default:
11941            break;
11942        }
11943        return output;
11944    }
11945
11946    /**
11947     * Build a human readable string representation of the specified private
11948     * view flags.
11949     *
11950     * @param privateFlags the private view flags to convert to a string
11951     * @return a String representing the supplied flags
11952     */
11953    private static String printPrivateFlags(int privateFlags) {
11954        String output = "";
11955        int numFlags = 0;
11956
11957        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11958            output += "WANTS_FOCUS";
11959            numFlags++;
11960        }
11961
11962        if ((privateFlags & FOCUSED) == FOCUSED) {
11963            if (numFlags > 0) {
11964                output += " ";
11965            }
11966            output += "FOCUSED";
11967            numFlags++;
11968        }
11969
11970        if ((privateFlags & SELECTED) == SELECTED) {
11971            if (numFlags > 0) {
11972                output += " ";
11973            }
11974            output += "SELECTED";
11975            numFlags++;
11976        }
11977
11978        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11979            if (numFlags > 0) {
11980                output += " ";
11981            }
11982            output += "IS_ROOT_NAMESPACE";
11983            numFlags++;
11984        }
11985
11986        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11987            if (numFlags > 0) {
11988                output += " ";
11989            }
11990            output += "HAS_BOUNDS";
11991            numFlags++;
11992        }
11993
11994        if ((privateFlags & DRAWN) == DRAWN) {
11995            if (numFlags > 0) {
11996                output += " ";
11997            }
11998            output += "DRAWN";
11999            // USELESS HERE numFlags++;
12000        }
12001        return output;
12002    }
12003
12004    /**
12005     * <p>Indicates whether or not this view's layout will be requested during
12006     * the next hierarchy layout pass.</p>
12007     *
12008     * @return true if the layout will be forced during next layout pass
12009     */
12010    public boolean isLayoutRequested() {
12011        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
12012    }
12013
12014    /**
12015     * Assign a size and position to a view and all of its
12016     * descendants
12017     *
12018     * <p>This is the second phase of the layout mechanism.
12019     * (The first is measuring). In this phase, each parent calls
12020     * layout on all of its children to position them.
12021     * This is typically done using the child measurements
12022     * that were stored in the measure pass().</p>
12023     *
12024     * <p>Derived classes should not override this method.
12025     * Derived classes with children should override
12026     * onLayout. In that method, they should
12027     * call layout on each of their children.</p>
12028     *
12029     * @param l Left position, relative to parent
12030     * @param t Top position, relative to parent
12031     * @param r Right position, relative to parent
12032     * @param b Bottom position, relative to parent
12033     */
12034    @SuppressWarnings({"unchecked"})
12035    public void layout(int l, int t, int r, int b) {
12036        int oldL = mLeft;
12037        int oldT = mTop;
12038        int oldB = mBottom;
12039        int oldR = mRight;
12040        boolean changed = setFrame(l, t, r, b);
12041        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
12042            if (ViewDebug.TRACE_HIERARCHY) {
12043                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
12044            }
12045
12046            onLayout(changed, l, t, r, b);
12047            mPrivateFlags &= ~LAYOUT_REQUIRED;
12048
12049            ListenerInfo li = mListenerInfo;
12050            if (li != null && li.mOnLayoutChangeListeners != null) {
12051                ArrayList<OnLayoutChangeListener> listenersCopy =
12052                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
12053                int numListeners = listenersCopy.size();
12054                for (int i = 0; i < numListeners; ++i) {
12055                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
12056                }
12057            }
12058        }
12059        mPrivateFlags &= ~FORCE_LAYOUT;
12060    }
12061
12062    /**
12063     * Called from layout when this view should
12064     * assign a size and position to each of its children.
12065     *
12066     * Derived classes with children should override
12067     * this method and call layout on each of
12068     * their children.
12069     * @param changed This is a new size or position for this view
12070     * @param left Left position, relative to parent
12071     * @param top Top position, relative to parent
12072     * @param right Right position, relative to parent
12073     * @param bottom Bottom position, relative to parent
12074     */
12075    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
12076    }
12077
12078    /**
12079     * Assign a size and position to this view.
12080     *
12081     * This is called from layout.
12082     *
12083     * @param left Left position, relative to parent
12084     * @param top Top position, relative to parent
12085     * @param right Right position, relative to parent
12086     * @param bottom Bottom position, relative to parent
12087     * @return true if the new size and position are different than the
12088     *         previous ones
12089     * {@hide}
12090     */
12091    protected boolean setFrame(int left, int top, int right, int bottom) {
12092        boolean changed = false;
12093
12094        if (DBG) {
12095            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
12096                    + right + "," + bottom + ")");
12097        }
12098
12099        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
12100            changed = true;
12101
12102            // Remember our drawn bit
12103            int drawn = mPrivateFlags & DRAWN;
12104
12105            int oldWidth = mRight - mLeft;
12106            int oldHeight = mBottom - mTop;
12107            int newWidth = right - left;
12108            int newHeight = bottom - top;
12109            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
12110
12111            // Invalidate our old position
12112            invalidate(sizeChanged);
12113
12114            mLeft = left;
12115            mTop = top;
12116            mRight = right;
12117            mBottom = bottom;
12118            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
12119                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12120            }
12121
12122            mPrivateFlags |= HAS_BOUNDS;
12123
12124
12125            if (sizeChanged) {
12126                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
12127                    // A change in dimension means an auto-centered pivot point changes, too
12128                    if (mTransformationInfo != null) {
12129                        mTransformationInfo.mMatrixDirty = true;
12130                    }
12131                }
12132                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
12133            }
12134
12135            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
12136                // If we are visible, force the DRAWN bit to on so that
12137                // this invalidate will go through (at least to our parent).
12138                // This is because someone may have invalidated this view
12139                // before this call to setFrame came in, thereby clearing
12140                // the DRAWN bit.
12141                mPrivateFlags |= DRAWN;
12142                invalidate(sizeChanged);
12143                // parent display list may need to be recreated based on a change in the bounds
12144                // of any child
12145                invalidateParentCaches();
12146            }
12147
12148            // Reset drawn bit to original value (invalidate turns it off)
12149            mPrivateFlags |= drawn;
12150
12151            mBackgroundSizeChanged = true;
12152        }
12153        return changed;
12154    }
12155
12156    /**
12157     * Finalize inflating a view from XML.  This is called as the last phase
12158     * of inflation, after all child views have been added.
12159     *
12160     * <p>Even if the subclass overrides onFinishInflate, they should always be
12161     * sure to call the super method, so that we get called.
12162     */
12163    protected void onFinishInflate() {
12164    }
12165
12166    /**
12167     * Returns the resources associated with this view.
12168     *
12169     * @return Resources object.
12170     */
12171    public Resources getResources() {
12172        return mResources;
12173    }
12174
12175    /**
12176     * Invalidates the specified Drawable.
12177     *
12178     * @param drawable the drawable to invalidate
12179     */
12180    public void invalidateDrawable(Drawable drawable) {
12181        if (verifyDrawable(drawable)) {
12182            final Rect dirty = drawable.getBounds();
12183            final int scrollX = mScrollX;
12184            final int scrollY = mScrollY;
12185
12186            invalidate(dirty.left + scrollX, dirty.top + scrollY,
12187                    dirty.right + scrollX, dirty.bottom + scrollY);
12188        }
12189    }
12190
12191    /**
12192     * Schedules an action on a drawable to occur at a specified time.
12193     *
12194     * @param who the recipient of the action
12195     * @param what the action to run on the drawable
12196     * @param when the time at which the action must occur. Uses the
12197     *        {@link SystemClock#uptimeMillis} timebase.
12198     */
12199    public void scheduleDrawable(Drawable who, Runnable what, long when) {
12200        if (verifyDrawable(who) && what != null) {
12201            final long delay = when - SystemClock.uptimeMillis();
12202            if (mAttachInfo != null) {
12203                mAttachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed(
12204                        what, who, Choreographer.subtractFrameDelay(delay));
12205            } else {
12206                ViewRootImpl.getRunQueue().postDelayed(what, delay);
12207            }
12208        }
12209    }
12210
12211    /**
12212     * Cancels a scheduled action on a drawable.
12213     *
12214     * @param who the recipient of the action
12215     * @param what the action to cancel
12216     */
12217    public void unscheduleDrawable(Drawable who, Runnable what) {
12218        if (verifyDrawable(who) && what != null) {
12219            if (mAttachInfo != null) {
12220                mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(what, who);
12221            } else {
12222                ViewRootImpl.getRunQueue().removeCallbacks(what);
12223            }
12224        }
12225    }
12226
12227    /**
12228     * Unschedule any events associated with the given Drawable.  This can be
12229     * used when selecting a new Drawable into a view, so that the previous
12230     * one is completely unscheduled.
12231     *
12232     * @param who The Drawable to unschedule.
12233     *
12234     * @see #drawableStateChanged
12235     */
12236    public void unscheduleDrawable(Drawable who) {
12237        if (mAttachInfo != null && who != null) {
12238            mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(null, who);
12239        }
12240    }
12241
12242    /**
12243    * Return the layout direction of a given Drawable.
12244    *
12245    * @param who the Drawable to query
12246    */
12247    public int getResolvedLayoutDirection(Drawable who) {
12248        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
12249    }
12250
12251    /**
12252     * If your view subclass is displaying its own Drawable objects, it should
12253     * override this function and return true for any Drawable it is
12254     * displaying.  This allows animations for those drawables to be
12255     * scheduled.
12256     *
12257     * <p>Be sure to call through to the super class when overriding this
12258     * function.
12259     *
12260     * @param who The Drawable to verify.  Return true if it is one you are
12261     *            displaying, else return the result of calling through to the
12262     *            super class.
12263     *
12264     * @return boolean If true than the Drawable is being displayed in the
12265     *         view; else false and it is not allowed to animate.
12266     *
12267     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
12268     * @see #drawableStateChanged()
12269     */
12270    protected boolean verifyDrawable(Drawable who) {
12271        return who == mBGDrawable;
12272    }
12273
12274    /**
12275     * This function is called whenever the state of the view changes in such
12276     * a way that it impacts the state of drawables being shown.
12277     *
12278     * <p>Be sure to call through to the superclass when overriding this
12279     * function.
12280     *
12281     * @see Drawable#setState(int[])
12282     */
12283    protected void drawableStateChanged() {
12284        Drawable d = mBGDrawable;
12285        if (d != null && d.isStateful()) {
12286            d.setState(getDrawableState());
12287        }
12288    }
12289
12290    /**
12291     * Call this to force a view to update its drawable state. This will cause
12292     * drawableStateChanged to be called on this view. Views that are interested
12293     * in the new state should call getDrawableState.
12294     *
12295     * @see #drawableStateChanged
12296     * @see #getDrawableState
12297     */
12298    public void refreshDrawableState() {
12299        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
12300        drawableStateChanged();
12301
12302        ViewParent parent = mParent;
12303        if (parent != null) {
12304            parent.childDrawableStateChanged(this);
12305        }
12306    }
12307
12308    /**
12309     * Return an array of resource IDs of the drawable states representing the
12310     * current state of the view.
12311     *
12312     * @return The current drawable state
12313     *
12314     * @see Drawable#setState(int[])
12315     * @see #drawableStateChanged()
12316     * @see #onCreateDrawableState(int)
12317     */
12318    public final int[] getDrawableState() {
12319        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
12320            return mDrawableState;
12321        } else {
12322            mDrawableState = onCreateDrawableState(0);
12323            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
12324            return mDrawableState;
12325        }
12326    }
12327
12328    /**
12329     * Generate the new {@link android.graphics.drawable.Drawable} state for
12330     * this view. This is called by the view
12331     * system when the cached Drawable state is determined to be invalid.  To
12332     * retrieve the current state, you should use {@link #getDrawableState}.
12333     *
12334     * @param extraSpace if non-zero, this is the number of extra entries you
12335     * would like in the returned array in which you can place your own
12336     * states.
12337     *
12338     * @return Returns an array holding the current {@link Drawable} state of
12339     * the view.
12340     *
12341     * @see #mergeDrawableStates(int[], int[])
12342     */
12343    protected int[] onCreateDrawableState(int extraSpace) {
12344        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
12345                mParent instanceof View) {
12346            return ((View) mParent).onCreateDrawableState(extraSpace);
12347        }
12348
12349        int[] drawableState;
12350
12351        int privateFlags = mPrivateFlags;
12352
12353        int viewStateIndex = 0;
12354        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
12355        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
12356        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
12357        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
12358        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
12359        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
12360        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
12361                HardwareRenderer.isAvailable()) {
12362            // This is set if HW acceleration is requested, even if the current
12363            // process doesn't allow it.  This is just to allow app preview
12364            // windows to better match their app.
12365            viewStateIndex |= VIEW_STATE_ACCELERATED;
12366        }
12367        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
12368
12369        final int privateFlags2 = mPrivateFlags2;
12370        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
12371        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
12372
12373        drawableState = VIEW_STATE_SETS[viewStateIndex];
12374
12375        //noinspection ConstantIfStatement
12376        if (false) {
12377            Log.i("View", "drawableStateIndex=" + viewStateIndex);
12378            Log.i("View", toString()
12379                    + " pressed=" + ((privateFlags & PRESSED) != 0)
12380                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
12381                    + " fo=" + hasFocus()
12382                    + " sl=" + ((privateFlags & SELECTED) != 0)
12383                    + " wf=" + hasWindowFocus()
12384                    + ": " + Arrays.toString(drawableState));
12385        }
12386
12387        if (extraSpace == 0) {
12388            return drawableState;
12389        }
12390
12391        final int[] fullState;
12392        if (drawableState != null) {
12393            fullState = new int[drawableState.length + extraSpace];
12394            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
12395        } else {
12396            fullState = new int[extraSpace];
12397        }
12398
12399        return fullState;
12400    }
12401
12402    /**
12403     * Merge your own state values in <var>additionalState</var> into the base
12404     * state values <var>baseState</var> that were returned by
12405     * {@link #onCreateDrawableState(int)}.
12406     *
12407     * @param baseState The base state values returned by
12408     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
12409     * own additional state values.
12410     *
12411     * @param additionalState The additional state values you would like
12412     * added to <var>baseState</var>; this array is not modified.
12413     *
12414     * @return As a convenience, the <var>baseState</var> array you originally
12415     * passed into the function is returned.
12416     *
12417     * @see #onCreateDrawableState(int)
12418     */
12419    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
12420        final int N = baseState.length;
12421        int i = N - 1;
12422        while (i >= 0 && baseState[i] == 0) {
12423            i--;
12424        }
12425        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12426        return baseState;
12427    }
12428
12429    /**
12430     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12431     * on all Drawable objects associated with this view.
12432     */
12433    public void jumpDrawablesToCurrentState() {
12434        if (mBGDrawable != null) {
12435            mBGDrawable.jumpToCurrentState();
12436        }
12437    }
12438
12439    /**
12440     * Sets the background color for this view.
12441     * @param color the color of the background
12442     */
12443    @RemotableViewMethod
12444    public void setBackgroundColor(int color) {
12445        if (mBGDrawable instanceof ColorDrawable) {
12446            ((ColorDrawable) mBGDrawable).setColor(color);
12447        } else {
12448            setBackgroundDrawable(new ColorDrawable(color));
12449        }
12450    }
12451
12452    /**
12453     * Set the background to a given resource. The resource should refer to
12454     * a Drawable object or 0 to remove the background.
12455     * @param resid The identifier of the resource.
12456     * @attr ref android.R.styleable#View_background
12457     */
12458    @RemotableViewMethod
12459    public void setBackgroundResource(int resid) {
12460        if (resid != 0 && resid == mBackgroundResource) {
12461            return;
12462        }
12463
12464        Drawable d= null;
12465        if (resid != 0) {
12466            d = mResources.getDrawable(resid);
12467        }
12468        setBackgroundDrawable(d);
12469
12470        mBackgroundResource = resid;
12471    }
12472
12473    /**
12474     * Set the background to a given Drawable, or remove the background. If the
12475     * background has padding, this View's padding is set to the background's
12476     * padding. However, when a background is removed, this View's padding isn't
12477     * touched. If setting the padding is desired, please use
12478     * {@link #setPadding(int, int, int, int)}.
12479     *
12480     * @param d The Drawable to use as the background, or null to remove the
12481     *        background
12482     */
12483    public void setBackgroundDrawable(Drawable d) {
12484        if (d == mBGDrawable) {
12485            return;
12486        }
12487
12488        boolean requestLayout = false;
12489
12490        mBackgroundResource = 0;
12491
12492        /*
12493         * Regardless of whether we're setting a new background or not, we want
12494         * to clear the previous drawable.
12495         */
12496        if (mBGDrawable != null) {
12497            mBGDrawable.setCallback(null);
12498            unscheduleDrawable(mBGDrawable);
12499        }
12500
12501        if (d != null) {
12502            Rect padding = sThreadLocal.get();
12503            if (padding == null) {
12504                padding = new Rect();
12505                sThreadLocal.set(padding);
12506            }
12507            if (d.getPadding(padding)) {
12508                switch (d.getResolvedLayoutDirectionSelf()) {
12509                    case LAYOUT_DIRECTION_RTL:
12510                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12511                        break;
12512                    case LAYOUT_DIRECTION_LTR:
12513                    default:
12514                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12515                }
12516            }
12517
12518            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12519            // if it has a different minimum size, we should layout again
12520            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12521                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12522                requestLayout = true;
12523            }
12524
12525            d.setCallback(this);
12526            if (d.isStateful()) {
12527                d.setState(getDrawableState());
12528            }
12529            d.setVisible(getVisibility() == VISIBLE, false);
12530            mBGDrawable = d;
12531
12532            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12533                mPrivateFlags &= ~SKIP_DRAW;
12534                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12535                requestLayout = true;
12536            }
12537        } else {
12538            /* Remove the background */
12539            mBGDrawable = null;
12540
12541            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12542                /*
12543                 * This view ONLY drew the background before and we're removing
12544                 * the background, so now it won't draw anything
12545                 * (hence we SKIP_DRAW)
12546                 */
12547                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12548                mPrivateFlags |= SKIP_DRAW;
12549            }
12550
12551            /*
12552             * When the background is set, we try to apply its padding to this
12553             * View. When the background is removed, we don't touch this View's
12554             * padding. This is noted in the Javadocs. Hence, we don't need to
12555             * requestLayout(), the invalidate() below is sufficient.
12556             */
12557
12558            // The old background's minimum size could have affected this
12559            // View's layout, so let's requestLayout
12560            requestLayout = true;
12561        }
12562
12563        computeOpaqueFlags();
12564
12565        if (requestLayout) {
12566            requestLayout();
12567        }
12568
12569        mBackgroundSizeChanged = true;
12570        invalidate(true);
12571    }
12572
12573    /**
12574     * Gets the background drawable
12575     * @return The drawable used as the background for this view, if any.
12576     */
12577    public Drawable getBackground() {
12578        return mBGDrawable;
12579    }
12580
12581    /**
12582     * Sets the padding. The view may add on the space required to display
12583     * the scrollbars, depending on the style and visibility of the scrollbars.
12584     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12585     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12586     * from the values set in this call.
12587     *
12588     * @attr ref android.R.styleable#View_padding
12589     * @attr ref android.R.styleable#View_paddingBottom
12590     * @attr ref android.R.styleable#View_paddingLeft
12591     * @attr ref android.R.styleable#View_paddingRight
12592     * @attr ref android.R.styleable#View_paddingTop
12593     * @param left the left padding in pixels
12594     * @param top the top padding in pixels
12595     * @param right the right padding in pixels
12596     * @param bottom the bottom padding in pixels
12597     */
12598    public void setPadding(int left, int top, int right, int bottom) {
12599        mUserPaddingStart = -1;
12600        mUserPaddingEnd = -1;
12601        mUserPaddingRelative = false;
12602
12603        internalSetPadding(left, top, right, bottom);
12604    }
12605
12606    private void internalSetPadding(int left, int top, int right, int bottom) {
12607        mUserPaddingLeft = left;
12608        mUserPaddingRight = right;
12609        mUserPaddingBottom = bottom;
12610
12611        final int viewFlags = mViewFlags;
12612        boolean changed = false;
12613
12614        // Common case is there are no scroll bars.
12615        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12616            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12617                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12618                        ? 0 : getVerticalScrollbarWidth();
12619                switch (mVerticalScrollbarPosition) {
12620                    case SCROLLBAR_POSITION_DEFAULT:
12621                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12622                            left += offset;
12623                        } else {
12624                            right += offset;
12625                        }
12626                        break;
12627                    case SCROLLBAR_POSITION_RIGHT:
12628                        right += offset;
12629                        break;
12630                    case SCROLLBAR_POSITION_LEFT:
12631                        left += offset;
12632                        break;
12633                }
12634            }
12635            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12636                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12637                        ? 0 : getHorizontalScrollbarHeight();
12638            }
12639        }
12640
12641        if (mPaddingLeft != left) {
12642            changed = true;
12643            mPaddingLeft = left;
12644        }
12645        if (mPaddingTop != top) {
12646            changed = true;
12647            mPaddingTop = top;
12648        }
12649        if (mPaddingRight != right) {
12650            changed = true;
12651            mPaddingRight = right;
12652        }
12653        if (mPaddingBottom != bottom) {
12654            changed = true;
12655            mPaddingBottom = bottom;
12656        }
12657
12658        if (changed) {
12659            requestLayout();
12660        }
12661    }
12662
12663    /**
12664     * Sets the relative padding. The view may add on the space required to display
12665     * the scrollbars, depending on the style and visibility of the scrollbars.
12666     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12667     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12668     * from the values set in this call.
12669     *
12670     * @attr ref android.R.styleable#View_padding
12671     * @attr ref android.R.styleable#View_paddingBottom
12672     * @attr ref android.R.styleable#View_paddingStart
12673     * @attr ref android.R.styleable#View_paddingEnd
12674     * @attr ref android.R.styleable#View_paddingTop
12675     * @param start the start padding in pixels
12676     * @param top the top padding in pixels
12677     * @param end the end padding in pixels
12678     * @param bottom the bottom padding in pixels
12679     */
12680    public void setPaddingRelative(int start, int top, int end, int bottom) {
12681        mUserPaddingStart = start;
12682        mUserPaddingEnd = end;
12683        mUserPaddingRelative = true;
12684
12685        switch(getResolvedLayoutDirection()) {
12686            case LAYOUT_DIRECTION_RTL:
12687                internalSetPadding(end, top, start, bottom);
12688                break;
12689            case LAYOUT_DIRECTION_LTR:
12690            default:
12691                internalSetPadding(start, top, end, bottom);
12692        }
12693    }
12694
12695    /**
12696     * Returns the top padding of this view.
12697     *
12698     * @return the top padding in pixels
12699     */
12700    public int getPaddingTop() {
12701        return mPaddingTop;
12702    }
12703
12704    /**
12705     * Returns the bottom padding of this view. If there are inset and enabled
12706     * scrollbars, this value may include the space required to display the
12707     * scrollbars as well.
12708     *
12709     * @return the bottom padding in pixels
12710     */
12711    public int getPaddingBottom() {
12712        return mPaddingBottom;
12713    }
12714
12715    /**
12716     * Returns the left padding of this view. If there are inset and enabled
12717     * scrollbars, this value may include the space required to display the
12718     * scrollbars as well.
12719     *
12720     * @return the left padding in pixels
12721     */
12722    public int getPaddingLeft() {
12723        return mPaddingLeft;
12724    }
12725
12726    /**
12727     * Returns the start padding of this view depending on its resolved layout direction.
12728     * If there are inset and enabled scrollbars, this value may include the space
12729     * required to display the scrollbars as well.
12730     *
12731     * @return the start padding in pixels
12732     */
12733    public int getPaddingStart() {
12734        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12735                mPaddingRight : mPaddingLeft;
12736    }
12737
12738    /**
12739     * Returns the right padding of this view. If there are inset and enabled
12740     * scrollbars, this value may include the space required to display the
12741     * scrollbars as well.
12742     *
12743     * @return the right padding in pixels
12744     */
12745    public int getPaddingRight() {
12746        return mPaddingRight;
12747    }
12748
12749    /**
12750     * Returns the end padding of this view depending on its resolved layout direction.
12751     * If there are inset and enabled scrollbars, this value may include the space
12752     * required to display the scrollbars as well.
12753     *
12754     * @return the end padding in pixels
12755     */
12756    public int getPaddingEnd() {
12757        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12758                mPaddingLeft : mPaddingRight;
12759    }
12760
12761    /**
12762     * Return if the padding as been set thru relative values
12763     * {@link #setPaddingRelative(int, int, int, int)} or thru
12764     * @attr ref android.R.styleable#View_paddingStart or
12765     * @attr ref android.R.styleable#View_paddingEnd
12766     *
12767     * @return true if the padding is relative or false if it is not.
12768     */
12769    public boolean isPaddingRelative() {
12770        return mUserPaddingRelative;
12771    }
12772
12773    /**
12774     * Changes the selection state of this view. A view can be selected or not.
12775     * Note that selection is not the same as focus. Views are typically
12776     * selected in the context of an AdapterView like ListView or GridView;
12777     * the selected view is the view that is highlighted.
12778     *
12779     * @param selected true if the view must be selected, false otherwise
12780     */
12781    public void setSelected(boolean selected) {
12782        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12783            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12784            if (!selected) resetPressedState();
12785            invalidate(true);
12786            refreshDrawableState();
12787            dispatchSetSelected(selected);
12788        }
12789    }
12790
12791    /**
12792     * Dispatch setSelected to all of this View's children.
12793     *
12794     * @see #setSelected(boolean)
12795     *
12796     * @param selected The new selected state
12797     */
12798    protected void dispatchSetSelected(boolean selected) {
12799    }
12800
12801    /**
12802     * Indicates the selection state of this view.
12803     *
12804     * @return true if the view is selected, false otherwise
12805     */
12806    @ViewDebug.ExportedProperty
12807    public boolean isSelected() {
12808        return (mPrivateFlags & SELECTED) != 0;
12809    }
12810
12811    /**
12812     * Changes the activated state of this view. A view can be activated or not.
12813     * Note that activation is not the same as selection.  Selection is
12814     * a transient property, representing the view (hierarchy) the user is
12815     * currently interacting with.  Activation is a longer-term state that the
12816     * user can move views in and out of.  For example, in a list view with
12817     * single or multiple selection enabled, the views in the current selection
12818     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12819     * here.)  The activated state is propagated down to children of the view it
12820     * is set on.
12821     *
12822     * @param activated true if the view must be activated, false otherwise
12823     */
12824    public void setActivated(boolean activated) {
12825        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12826            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12827            invalidate(true);
12828            refreshDrawableState();
12829            dispatchSetActivated(activated);
12830        }
12831    }
12832
12833    /**
12834     * Dispatch setActivated to all of this View's children.
12835     *
12836     * @see #setActivated(boolean)
12837     *
12838     * @param activated The new activated state
12839     */
12840    protected void dispatchSetActivated(boolean activated) {
12841    }
12842
12843    /**
12844     * Indicates the activation state of this view.
12845     *
12846     * @return true if the view is activated, false otherwise
12847     */
12848    @ViewDebug.ExportedProperty
12849    public boolean isActivated() {
12850        return (mPrivateFlags & ACTIVATED) != 0;
12851    }
12852
12853    /**
12854     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12855     * observer can be used to get notifications when global events, like
12856     * layout, happen.
12857     *
12858     * The returned ViewTreeObserver observer is not guaranteed to remain
12859     * valid for the lifetime of this View. If the caller of this method keeps
12860     * a long-lived reference to ViewTreeObserver, it should always check for
12861     * the return value of {@link ViewTreeObserver#isAlive()}.
12862     *
12863     * @return The ViewTreeObserver for this view's hierarchy.
12864     */
12865    public ViewTreeObserver getViewTreeObserver() {
12866        if (mAttachInfo != null) {
12867            return mAttachInfo.mTreeObserver;
12868        }
12869        if (mFloatingTreeObserver == null) {
12870            mFloatingTreeObserver = new ViewTreeObserver();
12871        }
12872        return mFloatingTreeObserver;
12873    }
12874
12875    /**
12876     * <p>Finds the topmost view in the current view hierarchy.</p>
12877     *
12878     * @return the topmost view containing this view
12879     */
12880    public View getRootView() {
12881        if (mAttachInfo != null) {
12882            final View v = mAttachInfo.mRootView;
12883            if (v != null) {
12884                return v;
12885            }
12886        }
12887
12888        View parent = this;
12889
12890        while (parent.mParent != null && parent.mParent instanceof View) {
12891            parent = (View) parent.mParent;
12892        }
12893
12894        return parent;
12895    }
12896
12897    /**
12898     * <p>Computes the coordinates of this view on the screen. The argument
12899     * must be an array of two integers. After the method returns, the array
12900     * contains the x and y location in that order.</p>
12901     *
12902     * @param location an array of two integers in which to hold the coordinates
12903     */
12904    public void getLocationOnScreen(int[] location) {
12905        getLocationInWindow(location);
12906
12907        final AttachInfo info = mAttachInfo;
12908        if (info != null) {
12909            location[0] += info.mWindowLeft;
12910            location[1] += info.mWindowTop;
12911        }
12912    }
12913
12914    /**
12915     * <p>Computes the coordinates of this view in its window. The argument
12916     * must be an array of two integers. After the method returns, the array
12917     * contains the x and y location in that order.</p>
12918     *
12919     * @param location an array of two integers in which to hold the coordinates
12920     */
12921    public void getLocationInWindow(int[] location) {
12922        if (location == null || location.length < 2) {
12923            throw new IllegalArgumentException("location must be an array of two integers");
12924        }
12925
12926        if (mAttachInfo == null) {
12927            // When the view is not attached to a window, this method does not make sense
12928            location[0] = location[1] = 0;
12929            return;
12930        }
12931
12932        float[] position = mAttachInfo.mTmpTransformLocation;
12933        position[0] = position[1] = 0.0f;
12934
12935        if (!hasIdentityMatrix()) {
12936            getMatrix().mapPoints(position);
12937        }
12938
12939        position[0] += mLeft;
12940        position[1] += mTop;
12941
12942        ViewParent viewParent = mParent;
12943        while (viewParent instanceof View) {
12944            final View view = (View) viewParent;
12945
12946            position[0] -= view.mScrollX;
12947            position[1] -= view.mScrollY;
12948
12949            if (!view.hasIdentityMatrix()) {
12950                view.getMatrix().mapPoints(position);
12951            }
12952
12953            position[0] += view.mLeft;
12954            position[1] += view.mTop;
12955
12956            viewParent = view.mParent;
12957        }
12958
12959        if (viewParent instanceof ViewRootImpl) {
12960            // *cough*
12961            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12962            position[1] -= vr.mCurScrollY;
12963        }
12964
12965        location[0] = (int) (position[0] + 0.5f);
12966        location[1] = (int) (position[1] + 0.5f);
12967    }
12968
12969    /**
12970     * {@hide}
12971     * @param id the id of the view to be found
12972     * @return the view of the specified id, null if cannot be found
12973     */
12974    protected View findViewTraversal(int id) {
12975        if (id == mID) {
12976            return this;
12977        }
12978        return null;
12979    }
12980
12981    /**
12982     * {@hide}
12983     * @param tag the tag of the view to be found
12984     * @return the view of specified tag, null if cannot be found
12985     */
12986    protected View findViewWithTagTraversal(Object tag) {
12987        if (tag != null && tag.equals(mTag)) {
12988            return this;
12989        }
12990        return null;
12991    }
12992
12993    /**
12994     * {@hide}
12995     * @param predicate The predicate to evaluate.
12996     * @param childToSkip If not null, ignores this child during the recursive traversal.
12997     * @return The first view that matches the predicate or null.
12998     */
12999    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
13000        if (predicate.apply(this)) {
13001            return this;
13002        }
13003        return null;
13004    }
13005
13006    /**
13007     * Look for a child view with the given id.  If this view has the given
13008     * id, return this view.
13009     *
13010     * @param id The id to search for.
13011     * @return The view that has the given id in the hierarchy or null
13012     */
13013    public final View findViewById(int id) {
13014        if (id < 0) {
13015            return null;
13016        }
13017        return findViewTraversal(id);
13018    }
13019
13020    /**
13021     * Finds a view by its unuque and stable accessibility id.
13022     *
13023     * @param accessibilityId The searched accessibility id.
13024     * @return The found view.
13025     */
13026    final View findViewByAccessibilityId(int accessibilityId) {
13027        if (accessibilityId < 0) {
13028            return null;
13029        }
13030        return findViewByAccessibilityIdTraversal(accessibilityId);
13031    }
13032
13033    /**
13034     * Performs the traversal to find a view by its unuque and stable accessibility id.
13035     *
13036     * <strong>Note:</strong>This method does not stop at the root namespace
13037     * boundary since the user can touch the screen at an arbitrary location
13038     * potentially crossing the root namespace bounday which will send an
13039     * accessibility event to accessibility services and they should be able
13040     * to obtain the event source. Also accessibility ids are guaranteed to be
13041     * unique in the window.
13042     *
13043     * @param accessibilityId The accessibility id.
13044     * @return The found view.
13045     */
13046    View findViewByAccessibilityIdTraversal(int accessibilityId) {
13047        if (getAccessibilityViewId() == accessibilityId) {
13048            return this;
13049        }
13050        return null;
13051    }
13052
13053    /**
13054     * Look for a child view with the given tag.  If this view has the given
13055     * tag, return this view.
13056     *
13057     * @param tag The tag to search for, using "tag.equals(getTag())".
13058     * @return The View that has the given tag in the hierarchy or null
13059     */
13060    public final View findViewWithTag(Object tag) {
13061        if (tag == null) {
13062            return null;
13063        }
13064        return findViewWithTagTraversal(tag);
13065    }
13066
13067    /**
13068     * {@hide}
13069     * Look for a child view that matches the specified predicate.
13070     * If this view matches the predicate, return this view.
13071     *
13072     * @param predicate The predicate to evaluate.
13073     * @return The first view that matches the predicate or null.
13074     */
13075    public final View findViewByPredicate(Predicate<View> predicate) {
13076        return findViewByPredicateTraversal(predicate, null);
13077    }
13078
13079    /**
13080     * {@hide}
13081     * Look for a child view that matches the specified predicate,
13082     * starting with the specified view and its descendents and then
13083     * recusively searching the ancestors and siblings of that view
13084     * until this view is reached.
13085     *
13086     * This method is useful in cases where the predicate does not match
13087     * a single unique view (perhaps multiple views use the same id)
13088     * and we are trying to find the view that is "closest" in scope to the
13089     * starting view.
13090     *
13091     * @param start The view to start from.
13092     * @param predicate The predicate to evaluate.
13093     * @return The first view that matches the predicate or null.
13094     */
13095    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
13096        View childToSkip = null;
13097        for (;;) {
13098            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
13099            if (view != null || start == this) {
13100                return view;
13101            }
13102
13103            ViewParent parent = start.getParent();
13104            if (parent == null || !(parent instanceof View)) {
13105                return null;
13106            }
13107
13108            childToSkip = start;
13109            start = (View) parent;
13110        }
13111    }
13112
13113    /**
13114     * Sets the identifier for this view. The identifier does not have to be
13115     * unique in this view's hierarchy. The identifier should be a positive
13116     * number.
13117     *
13118     * @see #NO_ID
13119     * @see #getId()
13120     * @see #findViewById(int)
13121     *
13122     * @param id a number used to identify the view
13123     *
13124     * @attr ref android.R.styleable#View_id
13125     */
13126    public void setId(int id) {
13127        mID = id;
13128    }
13129
13130    /**
13131     * {@hide}
13132     *
13133     * @param isRoot true if the view belongs to the root namespace, false
13134     *        otherwise
13135     */
13136    public void setIsRootNamespace(boolean isRoot) {
13137        if (isRoot) {
13138            mPrivateFlags |= IS_ROOT_NAMESPACE;
13139        } else {
13140            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
13141        }
13142    }
13143
13144    /**
13145     * {@hide}
13146     *
13147     * @return true if the view belongs to the root namespace, false otherwise
13148     */
13149    public boolean isRootNamespace() {
13150        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
13151    }
13152
13153    /**
13154     * Returns this view's identifier.
13155     *
13156     * @return a positive integer used to identify the view or {@link #NO_ID}
13157     *         if the view has no ID
13158     *
13159     * @see #setId(int)
13160     * @see #findViewById(int)
13161     * @attr ref android.R.styleable#View_id
13162     */
13163    @ViewDebug.CapturedViewProperty
13164    public int getId() {
13165        return mID;
13166    }
13167
13168    /**
13169     * Returns this view's tag.
13170     *
13171     * @return the Object stored in this view as a tag
13172     *
13173     * @see #setTag(Object)
13174     * @see #getTag(int)
13175     */
13176    @ViewDebug.ExportedProperty
13177    public Object getTag() {
13178        return mTag;
13179    }
13180
13181    /**
13182     * Sets the tag associated with this view. A tag can be used to mark
13183     * a view in its hierarchy and does not have to be unique within the
13184     * hierarchy. Tags can also be used to store data within a view without
13185     * resorting to another data structure.
13186     *
13187     * @param tag an Object to tag the view with
13188     *
13189     * @see #getTag()
13190     * @see #setTag(int, Object)
13191     */
13192    public void setTag(final Object tag) {
13193        mTag = tag;
13194    }
13195
13196    /**
13197     * Returns the tag associated with this view and the specified key.
13198     *
13199     * @param key The key identifying the tag
13200     *
13201     * @return the Object stored in this view as a tag
13202     *
13203     * @see #setTag(int, Object)
13204     * @see #getTag()
13205     */
13206    public Object getTag(int key) {
13207        if (mKeyedTags != null) return mKeyedTags.get(key);
13208        return null;
13209    }
13210
13211    /**
13212     * Sets a tag associated with this view and a key. A tag can be used
13213     * to mark a view in its hierarchy and does not have to be unique within
13214     * the hierarchy. Tags can also be used to store data within a view
13215     * without resorting to another data structure.
13216     *
13217     * The specified key should be an id declared in the resources of the
13218     * application to ensure it is unique (see the <a
13219     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
13220     * Keys identified as belonging to
13221     * the Android framework or not associated with any package will cause
13222     * an {@link IllegalArgumentException} to be thrown.
13223     *
13224     * @param key The key identifying the tag
13225     * @param tag An Object to tag the view with
13226     *
13227     * @throws IllegalArgumentException If they specified key is not valid
13228     *
13229     * @see #setTag(Object)
13230     * @see #getTag(int)
13231     */
13232    public void setTag(int key, final Object tag) {
13233        // If the package id is 0x00 or 0x01, it's either an undefined package
13234        // or a framework id
13235        if ((key >>> 24) < 2) {
13236            throw new IllegalArgumentException("The key must be an application-specific "
13237                    + "resource id.");
13238        }
13239
13240        setKeyedTag(key, tag);
13241    }
13242
13243    /**
13244     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
13245     * framework id.
13246     *
13247     * @hide
13248     */
13249    public void setTagInternal(int key, Object tag) {
13250        if ((key >>> 24) != 0x1) {
13251            throw new IllegalArgumentException("The key must be a framework-specific "
13252                    + "resource id.");
13253        }
13254
13255        setKeyedTag(key, tag);
13256    }
13257
13258    private void setKeyedTag(int key, Object tag) {
13259        if (mKeyedTags == null) {
13260            mKeyedTags = new SparseArray<Object>();
13261        }
13262
13263        mKeyedTags.put(key, tag);
13264    }
13265
13266    /**
13267     * @param consistency The type of consistency. See ViewDebug for more information.
13268     *
13269     * @hide
13270     */
13271    protected boolean dispatchConsistencyCheck(int consistency) {
13272        return onConsistencyCheck(consistency);
13273    }
13274
13275    /**
13276     * Method that subclasses should implement to check their consistency. The type of
13277     * consistency check is indicated by the bit field passed as a parameter.
13278     *
13279     * @param consistency The type of consistency. See ViewDebug for more information.
13280     *
13281     * @throws IllegalStateException if the view is in an inconsistent state.
13282     *
13283     * @hide
13284     */
13285    protected boolean onConsistencyCheck(int consistency) {
13286        boolean result = true;
13287
13288        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
13289        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
13290
13291        if (checkLayout) {
13292            if (getParent() == null) {
13293                result = false;
13294                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13295                        "View " + this + " does not have a parent.");
13296            }
13297
13298            if (mAttachInfo == null) {
13299                result = false;
13300                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13301                        "View " + this + " is not attached to a window.");
13302            }
13303        }
13304
13305        if (checkDrawing) {
13306            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
13307            // from their draw() method
13308
13309            if ((mPrivateFlags & DRAWN) != DRAWN &&
13310                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
13311                result = false;
13312                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13313                        "View " + this + " was invalidated but its drawing cache is valid.");
13314            }
13315        }
13316
13317        return result;
13318    }
13319
13320    /**
13321     * Prints information about this view in the log output, with the tag
13322     * {@link #VIEW_LOG_TAG}.
13323     *
13324     * @hide
13325     */
13326    public void debug() {
13327        debug(0);
13328    }
13329
13330    /**
13331     * Prints information about this view in the log output, with the tag
13332     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
13333     * indentation defined by the <code>depth</code>.
13334     *
13335     * @param depth the indentation level
13336     *
13337     * @hide
13338     */
13339    protected void debug(int depth) {
13340        String output = debugIndent(depth - 1);
13341
13342        output += "+ " + this;
13343        int id = getId();
13344        if (id != -1) {
13345            output += " (id=" + id + ")";
13346        }
13347        Object tag = getTag();
13348        if (tag != null) {
13349            output += " (tag=" + tag + ")";
13350        }
13351        Log.d(VIEW_LOG_TAG, output);
13352
13353        if ((mPrivateFlags & FOCUSED) != 0) {
13354            output = debugIndent(depth) + " FOCUSED";
13355            Log.d(VIEW_LOG_TAG, output);
13356        }
13357
13358        output = debugIndent(depth);
13359        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
13360                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
13361                + "} ";
13362        Log.d(VIEW_LOG_TAG, output);
13363
13364        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
13365                || mPaddingBottom != 0) {
13366            output = debugIndent(depth);
13367            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
13368                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
13369            Log.d(VIEW_LOG_TAG, output);
13370        }
13371
13372        output = debugIndent(depth);
13373        output += "mMeasureWidth=" + mMeasuredWidth +
13374                " mMeasureHeight=" + mMeasuredHeight;
13375        Log.d(VIEW_LOG_TAG, output);
13376
13377        output = debugIndent(depth);
13378        if (mLayoutParams == null) {
13379            output += "BAD! no layout params";
13380        } else {
13381            output = mLayoutParams.debug(output);
13382        }
13383        Log.d(VIEW_LOG_TAG, output);
13384
13385        output = debugIndent(depth);
13386        output += "flags={";
13387        output += View.printFlags(mViewFlags);
13388        output += "}";
13389        Log.d(VIEW_LOG_TAG, output);
13390
13391        output = debugIndent(depth);
13392        output += "privateFlags={";
13393        output += View.printPrivateFlags(mPrivateFlags);
13394        output += "}";
13395        Log.d(VIEW_LOG_TAG, output);
13396    }
13397
13398    /**
13399     * Creates a string of whitespaces used for indentation.
13400     *
13401     * @param depth the indentation level
13402     * @return a String containing (depth * 2 + 3) * 2 white spaces
13403     *
13404     * @hide
13405     */
13406    protected static String debugIndent(int depth) {
13407        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
13408        for (int i = 0; i < (depth * 2) + 3; i++) {
13409            spaces.append(' ').append(' ');
13410        }
13411        return spaces.toString();
13412    }
13413
13414    /**
13415     * <p>Return the offset of the widget's text baseline from the widget's top
13416     * boundary. If this widget does not support baseline alignment, this
13417     * method returns -1. </p>
13418     *
13419     * @return the offset of the baseline within the widget's bounds or -1
13420     *         if baseline alignment is not supported
13421     */
13422    @ViewDebug.ExportedProperty(category = "layout")
13423    public int getBaseline() {
13424        return -1;
13425    }
13426
13427    /**
13428     * Call this when something has changed which has invalidated the
13429     * layout of this view. This will schedule a layout pass of the view
13430     * tree.
13431     */
13432    public void requestLayout() {
13433        if (ViewDebug.TRACE_HIERARCHY) {
13434            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13435        }
13436
13437        mPrivateFlags |= FORCE_LAYOUT;
13438        mPrivateFlags |= INVALIDATED;
13439
13440        if (mParent != null) {
13441            if (mLayoutParams != null) {
13442                mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
13443            }
13444            if (!mParent.isLayoutRequested()) {
13445                mParent.requestLayout();
13446            }
13447        }
13448    }
13449
13450    /**
13451     * Forces this view to be laid out during the next layout pass.
13452     * This method does not call requestLayout() or forceLayout()
13453     * on the parent.
13454     */
13455    public void forceLayout() {
13456        mPrivateFlags |= FORCE_LAYOUT;
13457        mPrivateFlags |= INVALIDATED;
13458    }
13459
13460    /**
13461     * <p>
13462     * This is called to find out how big a view should be. The parent
13463     * supplies constraint information in the width and height parameters.
13464     * </p>
13465     *
13466     * <p>
13467     * The actual measurement work of a view is performed in
13468     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13469     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13470     * </p>
13471     *
13472     *
13473     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13474     *        parent
13475     * @param heightMeasureSpec Vertical space requirements as imposed by the
13476     *        parent
13477     *
13478     * @see #onMeasure(int, int)
13479     */
13480    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13481        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13482                widthMeasureSpec != mOldWidthMeasureSpec ||
13483                heightMeasureSpec != mOldHeightMeasureSpec) {
13484
13485            // first clears the measured dimension flag
13486            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13487
13488            if (ViewDebug.TRACE_HIERARCHY) {
13489                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13490            }
13491
13492            // measure ourselves, this should set the measured dimension flag back
13493            onMeasure(widthMeasureSpec, heightMeasureSpec);
13494
13495            // flag not set, setMeasuredDimension() was not invoked, we raise
13496            // an exception to warn the developer
13497            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13498                throw new IllegalStateException("onMeasure() did not set the"
13499                        + " measured dimension by calling"
13500                        + " setMeasuredDimension()");
13501            }
13502
13503            mPrivateFlags |= LAYOUT_REQUIRED;
13504        }
13505
13506        mOldWidthMeasureSpec = widthMeasureSpec;
13507        mOldHeightMeasureSpec = heightMeasureSpec;
13508    }
13509
13510    /**
13511     * <p>
13512     * Measure the view and its content to determine the measured width and the
13513     * measured height. This method is invoked by {@link #measure(int, int)} and
13514     * should be overriden by subclasses to provide accurate and efficient
13515     * measurement of their contents.
13516     * </p>
13517     *
13518     * <p>
13519     * <strong>CONTRACT:</strong> When overriding this method, you
13520     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13521     * measured width and height of this view. Failure to do so will trigger an
13522     * <code>IllegalStateException</code>, thrown by
13523     * {@link #measure(int, int)}. Calling the superclass'
13524     * {@link #onMeasure(int, int)} is a valid use.
13525     * </p>
13526     *
13527     * <p>
13528     * The base class implementation of measure defaults to the background size,
13529     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13530     * override {@link #onMeasure(int, int)} to provide better measurements of
13531     * their content.
13532     * </p>
13533     *
13534     * <p>
13535     * If this method is overridden, it is the subclass's responsibility to make
13536     * sure the measured height and width are at least the view's minimum height
13537     * and width ({@link #getSuggestedMinimumHeight()} and
13538     * {@link #getSuggestedMinimumWidth()}).
13539     * </p>
13540     *
13541     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13542     *                         The requirements are encoded with
13543     *                         {@link android.view.View.MeasureSpec}.
13544     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13545     *                         The requirements are encoded with
13546     *                         {@link android.view.View.MeasureSpec}.
13547     *
13548     * @see #getMeasuredWidth()
13549     * @see #getMeasuredHeight()
13550     * @see #setMeasuredDimension(int, int)
13551     * @see #getSuggestedMinimumHeight()
13552     * @see #getSuggestedMinimumWidth()
13553     * @see android.view.View.MeasureSpec#getMode(int)
13554     * @see android.view.View.MeasureSpec#getSize(int)
13555     */
13556    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13557        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13558                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13559    }
13560
13561    /**
13562     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13563     * measured width and measured height. Failing to do so will trigger an
13564     * exception at measurement time.</p>
13565     *
13566     * @param measuredWidth The measured width of this view.  May be a complex
13567     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13568     * {@link #MEASURED_STATE_TOO_SMALL}.
13569     * @param measuredHeight The measured height of this view.  May be a complex
13570     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13571     * {@link #MEASURED_STATE_TOO_SMALL}.
13572     */
13573    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13574        mMeasuredWidth = measuredWidth;
13575        mMeasuredHeight = measuredHeight;
13576
13577        mPrivateFlags |= MEASURED_DIMENSION_SET;
13578    }
13579
13580    /**
13581     * Merge two states as returned by {@link #getMeasuredState()}.
13582     * @param curState The current state as returned from a view or the result
13583     * of combining multiple views.
13584     * @param newState The new view state to combine.
13585     * @return Returns a new integer reflecting the combination of the two
13586     * states.
13587     */
13588    public static int combineMeasuredStates(int curState, int newState) {
13589        return curState | newState;
13590    }
13591
13592    /**
13593     * Version of {@link #resolveSizeAndState(int, int, int)}
13594     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13595     */
13596    public static int resolveSize(int size, int measureSpec) {
13597        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13598    }
13599
13600    /**
13601     * Utility to reconcile a desired size and state, with constraints imposed
13602     * by a MeasureSpec.  Will take the desired size, unless a different size
13603     * is imposed by the constraints.  The returned value is a compound integer,
13604     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13605     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13606     * size is smaller than the size the view wants to be.
13607     *
13608     * @param size How big the view wants to be
13609     * @param measureSpec Constraints imposed by the parent
13610     * @return Size information bit mask as defined by
13611     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13612     */
13613    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13614        int result = size;
13615        int specMode = MeasureSpec.getMode(measureSpec);
13616        int specSize =  MeasureSpec.getSize(measureSpec);
13617        switch (specMode) {
13618        case MeasureSpec.UNSPECIFIED:
13619            result = size;
13620            break;
13621        case MeasureSpec.AT_MOST:
13622            if (specSize < size) {
13623                result = specSize | MEASURED_STATE_TOO_SMALL;
13624            } else {
13625                result = size;
13626            }
13627            break;
13628        case MeasureSpec.EXACTLY:
13629            result = specSize;
13630            break;
13631        }
13632        return result | (childMeasuredState&MEASURED_STATE_MASK);
13633    }
13634
13635    /**
13636     * Utility to return a default size. Uses the supplied size if the
13637     * MeasureSpec imposed no constraints. Will get larger if allowed
13638     * by the MeasureSpec.
13639     *
13640     * @param size Default size for this view
13641     * @param measureSpec Constraints imposed by the parent
13642     * @return The size this view should be.
13643     */
13644    public static int getDefaultSize(int size, int measureSpec) {
13645        int result = size;
13646        int specMode = MeasureSpec.getMode(measureSpec);
13647        int specSize = MeasureSpec.getSize(measureSpec);
13648
13649        switch (specMode) {
13650        case MeasureSpec.UNSPECIFIED:
13651            result = size;
13652            break;
13653        case MeasureSpec.AT_MOST:
13654        case MeasureSpec.EXACTLY:
13655            result = specSize;
13656            break;
13657        }
13658        return result;
13659    }
13660
13661    /**
13662     * Returns the suggested minimum height that the view should use. This
13663     * returns the maximum of the view's minimum height
13664     * and the background's minimum height
13665     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13666     * <p>
13667     * When being used in {@link #onMeasure(int, int)}, the caller should still
13668     * ensure the returned height is within the requirements of the parent.
13669     *
13670     * @return The suggested minimum height of the view.
13671     */
13672    protected int getSuggestedMinimumHeight() {
13673        int suggestedMinHeight = mMinHeight;
13674
13675        if (mBGDrawable != null) {
13676            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13677            if (suggestedMinHeight < bgMinHeight) {
13678                suggestedMinHeight = bgMinHeight;
13679            }
13680        }
13681
13682        return suggestedMinHeight;
13683    }
13684
13685    /**
13686     * Returns the suggested minimum width that the view should use. This
13687     * returns the maximum of the view's minimum width)
13688     * and the background's minimum width
13689     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13690     * <p>
13691     * When being used in {@link #onMeasure(int, int)}, the caller should still
13692     * ensure the returned width is within the requirements of the parent.
13693     *
13694     * @return The suggested minimum width of the view.
13695     */
13696    protected int getSuggestedMinimumWidth() {
13697        int suggestedMinWidth = mMinWidth;
13698
13699        if (mBGDrawable != null) {
13700            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13701            if (suggestedMinWidth < bgMinWidth) {
13702                suggestedMinWidth = bgMinWidth;
13703            }
13704        }
13705
13706        return suggestedMinWidth;
13707    }
13708
13709    /**
13710     * Sets the minimum height of the view. It is not guaranteed the view will
13711     * be able to achieve this minimum height (for example, if its parent layout
13712     * constrains it with less available height).
13713     *
13714     * @param minHeight The minimum height the view will try to be.
13715     */
13716    public void setMinimumHeight(int minHeight) {
13717        mMinHeight = minHeight;
13718    }
13719
13720    /**
13721     * Sets the minimum width of the view. It is not guaranteed the view will
13722     * be able to achieve this minimum width (for example, if its parent layout
13723     * constrains it with less available width).
13724     *
13725     * @param minWidth The minimum width the view will try to be.
13726     */
13727    public void setMinimumWidth(int minWidth) {
13728        mMinWidth = minWidth;
13729    }
13730
13731    /**
13732     * Get the animation currently associated with this view.
13733     *
13734     * @return The animation that is currently playing or
13735     *         scheduled to play for this view.
13736     */
13737    public Animation getAnimation() {
13738        return mCurrentAnimation;
13739    }
13740
13741    /**
13742     * Start the specified animation now.
13743     *
13744     * @param animation the animation to start now
13745     */
13746    public void startAnimation(Animation animation) {
13747        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13748        setAnimation(animation);
13749        invalidateParentCaches();
13750        invalidate(true);
13751    }
13752
13753    /**
13754     * Cancels any animations for this view.
13755     */
13756    public void clearAnimation() {
13757        if (mCurrentAnimation != null) {
13758            mCurrentAnimation.detach();
13759        }
13760        mCurrentAnimation = null;
13761        invalidateParentIfNeeded();
13762    }
13763
13764    /**
13765     * Sets the next animation to play for this view.
13766     * If you want the animation to play immediately, use
13767     * startAnimation. This method provides allows fine-grained
13768     * control over the start time and invalidation, but you
13769     * must make sure that 1) the animation has a start time set, and
13770     * 2) the view will be invalidated when the animation is supposed to
13771     * start.
13772     *
13773     * @param animation The next animation, or null.
13774     */
13775    public void setAnimation(Animation animation) {
13776        mCurrentAnimation = animation;
13777        if (animation != null) {
13778            animation.reset();
13779        }
13780    }
13781
13782    /**
13783     * Invoked by a parent ViewGroup to notify the start of the animation
13784     * currently associated with this view. If you override this method,
13785     * always call super.onAnimationStart();
13786     *
13787     * @see #setAnimation(android.view.animation.Animation)
13788     * @see #getAnimation()
13789     */
13790    protected void onAnimationStart() {
13791        mPrivateFlags |= ANIMATION_STARTED;
13792    }
13793
13794    /**
13795     * Invoked by a parent ViewGroup to notify the end of the animation
13796     * currently associated with this view. If you override this method,
13797     * always call super.onAnimationEnd();
13798     *
13799     * @see #setAnimation(android.view.animation.Animation)
13800     * @see #getAnimation()
13801     */
13802    protected void onAnimationEnd() {
13803        mPrivateFlags &= ~ANIMATION_STARTED;
13804    }
13805
13806    /**
13807     * Invoked if there is a Transform that involves alpha. Subclass that can
13808     * draw themselves with the specified alpha should return true, and then
13809     * respect that alpha when their onDraw() is called. If this returns false
13810     * then the view may be redirected to draw into an offscreen buffer to
13811     * fulfill the request, which will look fine, but may be slower than if the
13812     * subclass handles it internally. The default implementation returns false.
13813     *
13814     * @param alpha The alpha (0..255) to apply to the view's drawing
13815     * @return true if the view can draw with the specified alpha.
13816     */
13817    protected boolean onSetAlpha(int alpha) {
13818        return false;
13819    }
13820
13821    /**
13822     * This is used by the RootView to perform an optimization when
13823     * the view hierarchy contains one or several SurfaceView.
13824     * SurfaceView is always considered transparent, but its children are not,
13825     * therefore all View objects remove themselves from the global transparent
13826     * region (passed as a parameter to this function).
13827     *
13828     * @param region The transparent region for this ViewAncestor (window).
13829     *
13830     * @return Returns true if the effective visibility of the view at this
13831     * point is opaque, regardless of the transparent region; returns false
13832     * if it is possible for underlying windows to be seen behind the view.
13833     *
13834     * {@hide}
13835     */
13836    public boolean gatherTransparentRegion(Region region) {
13837        final AttachInfo attachInfo = mAttachInfo;
13838        if (region != null && attachInfo != null) {
13839            final int pflags = mPrivateFlags;
13840            if ((pflags & SKIP_DRAW) == 0) {
13841                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13842                // remove it from the transparent region.
13843                final int[] location = attachInfo.mTransparentLocation;
13844                getLocationInWindow(location);
13845                region.op(location[0], location[1], location[0] + mRight - mLeft,
13846                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13847            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13848                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13849                // exists, so we remove the background drawable's non-transparent
13850                // parts from this transparent region.
13851                applyDrawableToTransparentRegion(mBGDrawable, region);
13852            }
13853        }
13854        return true;
13855    }
13856
13857    /**
13858     * Play a sound effect for this view.
13859     *
13860     * <p>The framework will play sound effects for some built in actions, such as
13861     * clicking, but you may wish to play these effects in your widget,
13862     * for instance, for internal navigation.
13863     *
13864     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13865     * {@link #isSoundEffectsEnabled()} is true.
13866     *
13867     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13868     */
13869    public void playSoundEffect(int soundConstant) {
13870        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13871            return;
13872        }
13873        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13874    }
13875
13876    /**
13877     * BZZZTT!!1!
13878     *
13879     * <p>Provide haptic feedback to the user for this view.
13880     *
13881     * <p>The framework will provide haptic feedback for some built in actions,
13882     * such as long presses, but you may wish to provide feedback for your
13883     * own widget.
13884     *
13885     * <p>The feedback will only be performed if
13886     * {@link #isHapticFeedbackEnabled()} is true.
13887     *
13888     * @param feedbackConstant One of the constants defined in
13889     * {@link HapticFeedbackConstants}
13890     */
13891    public boolean performHapticFeedback(int feedbackConstant) {
13892        return performHapticFeedback(feedbackConstant, 0);
13893    }
13894
13895    /**
13896     * BZZZTT!!1!
13897     *
13898     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13899     *
13900     * @param feedbackConstant One of the constants defined in
13901     * {@link HapticFeedbackConstants}
13902     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13903     */
13904    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13905        if (mAttachInfo == null) {
13906            return false;
13907        }
13908        //noinspection SimplifiableIfStatement
13909        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13910                && !isHapticFeedbackEnabled()) {
13911            return false;
13912        }
13913        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13914                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13915    }
13916
13917    /**
13918     * Request that the visibility of the status bar be changed.
13919     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13920     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13921     */
13922    public void setSystemUiVisibility(int visibility) {
13923        if (visibility != mSystemUiVisibility) {
13924            mSystemUiVisibility = visibility;
13925            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13926                mParent.recomputeViewAttributes(this);
13927            }
13928        }
13929    }
13930
13931    /**
13932     * Returns the status bar visibility that this view has requested.
13933     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13934     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13935     */
13936    public int getSystemUiVisibility() {
13937        return mSystemUiVisibility;
13938    }
13939
13940    /**
13941     * Set a listener to receive callbacks when the visibility of the system bar changes.
13942     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13943     */
13944    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13945        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13946        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13947            mParent.recomputeViewAttributes(this);
13948        }
13949    }
13950
13951    /**
13952     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13953     * the view hierarchy.
13954     */
13955    public void dispatchSystemUiVisibilityChanged(int visibility) {
13956        ListenerInfo li = mListenerInfo;
13957        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13958            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13959                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13960        }
13961    }
13962
13963    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13964        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13965        if (val != mSystemUiVisibility) {
13966            setSystemUiVisibility(val);
13967        }
13968    }
13969
13970    /**
13971     * Creates an image that the system displays during the drag and drop
13972     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13973     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13974     * appearance as the given View. The default also positions the center of the drag shadow
13975     * directly under the touch point. If no View is provided (the constructor with no parameters
13976     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13977     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13978     * default is an invisible drag shadow.
13979     * <p>
13980     * You are not required to use the View you provide to the constructor as the basis of the
13981     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13982     * anything you want as the drag shadow.
13983     * </p>
13984     * <p>
13985     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13986     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13987     *  size and position of the drag shadow. It uses this data to construct a
13988     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13989     *  so that your application can draw the shadow image in the Canvas.
13990     * </p>
13991     *
13992     * <div class="special reference">
13993     * <h3>Developer Guides</h3>
13994     * <p>For a guide to implementing drag and drop features, read the
13995     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13996     * </div>
13997     */
13998    public static class DragShadowBuilder {
13999        private final WeakReference<View> mView;
14000
14001        /**
14002         * Constructs a shadow image builder based on a View. By default, the resulting drag
14003         * shadow will have the same appearance and dimensions as the View, with the touch point
14004         * over the center of the View.
14005         * @param view A View. Any View in scope can be used.
14006         */
14007        public DragShadowBuilder(View view) {
14008            mView = new WeakReference<View>(view);
14009        }
14010
14011        /**
14012         * Construct a shadow builder object with no associated View.  This
14013         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
14014         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
14015         * to supply the drag shadow's dimensions and appearance without
14016         * reference to any View object. If they are not overridden, then the result is an
14017         * invisible drag shadow.
14018         */
14019        public DragShadowBuilder() {
14020            mView = new WeakReference<View>(null);
14021        }
14022
14023        /**
14024         * Returns the View object that had been passed to the
14025         * {@link #View.DragShadowBuilder(View)}
14026         * constructor.  If that View parameter was {@code null} or if the
14027         * {@link #View.DragShadowBuilder()}
14028         * constructor was used to instantiate the builder object, this method will return
14029         * null.
14030         *
14031         * @return The View object associate with this builder object.
14032         */
14033        @SuppressWarnings({"JavadocReference"})
14034        final public View getView() {
14035            return mView.get();
14036        }
14037
14038        /**
14039         * Provides the metrics for the shadow image. These include the dimensions of
14040         * the shadow image, and the point within that shadow that should
14041         * be centered under the touch location while dragging.
14042         * <p>
14043         * The default implementation sets the dimensions of the shadow to be the
14044         * same as the dimensions of the View itself and centers the shadow under
14045         * the touch point.
14046         * </p>
14047         *
14048         * @param shadowSize A {@link android.graphics.Point} containing the width and height
14049         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
14050         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
14051         * image.
14052         *
14053         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
14054         * shadow image that should be underneath the touch point during the drag and drop
14055         * operation. Your application must set {@link android.graphics.Point#x} to the
14056         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
14057         */
14058        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
14059            final View view = mView.get();
14060            if (view != null) {
14061                shadowSize.set(view.getWidth(), view.getHeight());
14062                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
14063            } else {
14064                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
14065            }
14066        }
14067
14068        /**
14069         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
14070         * based on the dimensions it received from the
14071         * {@link #onProvideShadowMetrics(Point, Point)} callback.
14072         *
14073         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
14074         */
14075        public void onDrawShadow(Canvas canvas) {
14076            final View view = mView.get();
14077            if (view != null) {
14078                view.draw(canvas);
14079            } else {
14080                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
14081            }
14082        }
14083    }
14084
14085    /**
14086     * Starts a drag and drop operation. When your application calls this method, it passes a
14087     * {@link android.view.View.DragShadowBuilder} object to the system. The
14088     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
14089     * to get metrics for the drag shadow, and then calls the object's
14090     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
14091     * <p>
14092     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
14093     *  drag events to all the View objects in your application that are currently visible. It does
14094     *  this either by calling the View object's drag listener (an implementation of
14095     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
14096     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
14097     *  Both are passed a {@link android.view.DragEvent} object that has a
14098     *  {@link android.view.DragEvent#getAction()} value of
14099     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
14100     * </p>
14101     * <p>
14102     * Your application can invoke startDrag() on any attached View object. The View object does not
14103     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
14104     * be related to the View the user selected for dragging.
14105     * </p>
14106     * @param data A {@link android.content.ClipData} object pointing to the data to be
14107     * transferred by the drag and drop operation.
14108     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
14109     * drag shadow.
14110     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
14111     * drop operation. This Object is put into every DragEvent object sent by the system during the
14112     * current drag.
14113     * <p>
14114     * myLocalState is a lightweight mechanism for the sending information from the dragged View
14115     * to the target Views. For example, it can contain flags that differentiate between a
14116     * a copy operation and a move operation.
14117     * </p>
14118     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
14119     * so the parameter should be set to 0.
14120     * @return {@code true} if the method completes successfully, or
14121     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
14122     * do a drag, and so no drag operation is in progress.
14123     */
14124    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
14125            Object myLocalState, int flags) {
14126        if (ViewDebug.DEBUG_DRAG) {
14127            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
14128        }
14129        boolean okay = false;
14130
14131        Point shadowSize = new Point();
14132        Point shadowTouchPoint = new Point();
14133        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
14134
14135        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
14136                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
14137            throw new IllegalStateException("Drag shadow dimensions must not be negative");
14138        }
14139
14140        if (ViewDebug.DEBUG_DRAG) {
14141            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
14142                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
14143        }
14144        Surface surface = new Surface();
14145        try {
14146            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
14147                    flags, shadowSize.x, shadowSize.y, surface);
14148            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
14149                    + " surface=" + surface);
14150            if (token != null) {
14151                Canvas canvas = surface.lockCanvas(null);
14152                try {
14153                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
14154                    shadowBuilder.onDrawShadow(canvas);
14155                } finally {
14156                    surface.unlockCanvasAndPost(canvas);
14157                }
14158
14159                final ViewRootImpl root = getViewRootImpl();
14160
14161                // Cache the local state object for delivery with DragEvents
14162                root.setLocalDragState(myLocalState);
14163
14164                // repurpose 'shadowSize' for the last touch point
14165                root.getLastTouchPoint(shadowSize);
14166
14167                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
14168                        shadowSize.x, shadowSize.y,
14169                        shadowTouchPoint.x, shadowTouchPoint.y, data);
14170                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
14171
14172                // Off and running!  Release our local surface instance; the drag
14173                // shadow surface is now managed by the system process.
14174                surface.release();
14175            }
14176        } catch (Exception e) {
14177            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
14178            surface.destroy();
14179        }
14180
14181        return okay;
14182    }
14183
14184    /**
14185     * Handles drag events sent by the system following a call to
14186     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
14187     *<p>
14188     * When the system calls this method, it passes a
14189     * {@link android.view.DragEvent} object. A call to
14190     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
14191     * in DragEvent. The method uses these to determine what is happening in the drag and drop
14192     * operation.
14193     * @param event The {@link android.view.DragEvent} sent by the system.
14194     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
14195     * in DragEvent, indicating the type of drag event represented by this object.
14196     * @return {@code true} if the method was successful, otherwise {@code false}.
14197     * <p>
14198     *  The method should return {@code true} in response to an action type of
14199     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
14200     *  operation.
14201     * </p>
14202     * <p>
14203     *  The method should also return {@code true} in response to an action type of
14204     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
14205     *  {@code false} if it didn't.
14206     * </p>
14207     */
14208    public boolean onDragEvent(DragEvent event) {
14209        return false;
14210    }
14211
14212    /**
14213     * Detects if this View is enabled and has a drag event listener.
14214     * If both are true, then it calls the drag event listener with the
14215     * {@link android.view.DragEvent} it received. If the drag event listener returns
14216     * {@code true}, then dispatchDragEvent() returns {@code true}.
14217     * <p>
14218     * For all other cases, the method calls the
14219     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
14220     * method and returns its result.
14221     * </p>
14222     * <p>
14223     * This ensures that a drag event is always consumed, even if the View does not have a drag
14224     * event listener. However, if the View has a listener and the listener returns true, then
14225     * onDragEvent() is not called.
14226     * </p>
14227     */
14228    public boolean dispatchDragEvent(DragEvent event) {
14229        //noinspection SimplifiableIfStatement
14230        ListenerInfo li = mListenerInfo;
14231        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
14232                && li.mOnDragListener.onDrag(this, event)) {
14233            return true;
14234        }
14235        return onDragEvent(event);
14236    }
14237
14238    boolean canAcceptDrag() {
14239        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
14240    }
14241
14242    /**
14243     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
14244     * it is ever exposed at all.
14245     * @hide
14246     */
14247    public void onCloseSystemDialogs(String reason) {
14248    }
14249
14250    /**
14251     * Given a Drawable whose bounds have been set to draw into this view,
14252     * update a Region being computed for
14253     * {@link #gatherTransparentRegion(android.graphics.Region)} so
14254     * that any non-transparent parts of the Drawable are removed from the
14255     * given transparent region.
14256     *
14257     * @param dr The Drawable whose transparency is to be applied to the region.
14258     * @param region A Region holding the current transparency information,
14259     * where any parts of the region that are set are considered to be
14260     * transparent.  On return, this region will be modified to have the
14261     * transparency information reduced by the corresponding parts of the
14262     * Drawable that are not transparent.
14263     * {@hide}
14264     */
14265    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
14266        if (DBG) {
14267            Log.i("View", "Getting transparent region for: " + this);
14268        }
14269        final Region r = dr.getTransparentRegion();
14270        final Rect db = dr.getBounds();
14271        final AttachInfo attachInfo = mAttachInfo;
14272        if (r != null && attachInfo != null) {
14273            final int w = getRight()-getLeft();
14274            final int h = getBottom()-getTop();
14275            if (db.left > 0) {
14276                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
14277                r.op(0, 0, db.left, h, Region.Op.UNION);
14278            }
14279            if (db.right < w) {
14280                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
14281                r.op(db.right, 0, w, h, Region.Op.UNION);
14282            }
14283            if (db.top > 0) {
14284                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
14285                r.op(0, 0, w, db.top, Region.Op.UNION);
14286            }
14287            if (db.bottom < h) {
14288                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
14289                r.op(0, db.bottom, w, h, Region.Op.UNION);
14290            }
14291            final int[] location = attachInfo.mTransparentLocation;
14292            getLocationInWindow(location);
14293            r.translate(location[0], location[1]);
14294            region.op(r, Region.Op.INTERSECT);
14295        } else {
14296            region.op(db, Region.Op.DIFFERENCE);
14297        }
14298    }
14299
14300    private void checkForLongClick(int delayOffset) {
14301        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
14302            mHasPerformedLongPress = false;
14303
14304            if (mPendingCheckForLongPress == null) {
14305                mPendingCheckForLongPress = new CheckForLongPress();
14306            }
14307            mPendingCheckForLongPress.rememberWindowAttachCount();
14308            postDelayed(mPendingCheckForLongPress,
14309                    ViewConfiguration.getLongPressTimeout() - delayOffset);
14310        }
14311    }
14312
14313    /**
14314     * Inflate a view from an XML resource.  This convenience method wraps the {@link
14315     * LayoutInflater} class, which provides a full range of options for view inflation.
14316     *
14317     * @param context The Context object for your activity or application.
14318     * @param resource The resource ID to inflate
14319     * @param root A view group that will be the parent.  Used to properly inflate the
14320     * layout_* parameters.
14321     * @see LayoutInflater
14322     */
14323    public static View inflate(Context context, int resource, ViewGroup root) {
14324        LayoutInflater factory = LayoutInflater.from(context);
14325        return factory.inflate(resource, root);
14326    }
14327
14328    /**
14329     * Scroll the view with standard behavior for scrolling beyond the normal
14330     * content boundaries. Views that call this method should override
14331     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
14332     * results of an over-scroll operation.
14333     *
14334     * Views can use this method to handle any touch or fling-based scrolling.
14335     *
14336     * @param deltaX Change in X in pixels
14337     * @param deltaY Change in Y in pixels
14338     * @param scrollX Current X scroll value in pixels before applying deltaX
14339     * @param scrollY Current Y scroll value in pixels before applying deltaY
14340     * @param scrollRangeX Maximum content scroll range along the X axis
14341     * @param scrollRangeY Maximum content scroll range along the Y axis
14342     * @param maxOverScrollX Number of pixels to overscroll by in either direction
14343     *          along the X axis.
14344     * @param maxOverScrollY Number of pixels to overscroll by in either direction
14345     *          along the Y axis.
14346     * @param isTouchEvent true if this scroll operation is the result of a touch event.
14347     * @return true if scrolling was clamped to an over-scroll boundary along either
14348     *          axis, false otherwise.
14349     */
14350    @SuppressWarnings({"UnusedParameters"})
14351    protected boolean overScrollBy(int deltaX, int deltaY,
14352            int scrollX, int scrollY,
14353            int scrollRangeX, int scrollRangeY,
14354            int maxOverScrollX, int maxOverScrollY,
14355            boolean isTouchEvent) {
14356        final int overScrollMode = mOverScrollMode;
14357        final boolean canScrollHorizontal =
14358                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
14359        final boolean canScrollVertical =
14360                computeVerticalScrollRange() > computeVerticalScrollExtent();
14361        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
14362                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
14363        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
14364                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
14365
14366        int newScrollX = scrollX + deltaX;
14367        if (!overScrollHorizontal) {
14368            maxOverScrollX = 0;
14369        }
14370
14371        int newScrollY = scrollY + deltaY;
14372        if (!overScrollVertical) {
14373            maxOverScrollY = 0;
14374        }
14375
14376        // Clamp values if at the limits and record
14377        final int left = -maxOverScrollX;
14378        final int right = maxOverScrollX + scrollRangeX;
14379        final int top = -maxOverScrollY;
14380        final int bottom = maxOverScrollY + scrollRangeY;
14381
14382        boolean clampedX = false;
14383        if (newScrollX > right) {
14384            newScrollX = right;
14385            clampedX = true;
14386        } else if (newScrollX < left) {
14387            newScrollX = left;
14388            clampedX = true;
14389        }
14390
14391        boolean clampedY = false;
14392        if (newScrollY > bottom) {
14393            newScrollY = bottom;
14394            clampedY = true;
14395        } else if (newScrollY < top) {
14396            newScrollY = top;
14397            clampedY = true;
14398        }
14399
14400        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
14401
14402        return clampedX || clampedY;
14403    }
14404
14405    /**
14406     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
14407     * respond to the results of an over-scroll operation.
14408     *
14409     * @param scrollX New X scroll value in pixels
14410     * @param scrollY New Y scroll value in pixels
14411     * @param clampedX True if scrollX was clamped to an over-scroll boundary
14412     * @param clampedY True if scrollY was clamped to an over-scroll boundary
14413     */
14414    protected void onOverScrolled(int scrollX, int scrollY,
14415            boolean clampedX, boolean clampedY) {
14416        // Intentionally empty.
14417    }
14418
14419    /**
14420     * Returns the over-scroll mode for this view. The result will be
14421     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14422     * (allow over-scrolling only if the view content is larger than the container),
14423     * or {@link #OVER_SCROLL_NEVER}.
14424     *
14425     * @return This view's over-scroll mode.
14426     */
14427    public int getOverScrollMode() {
14428        return mOverScrollMode;
14429    }
14430
14431    /**
14432     * Set the over-scroll mode for this view. Valid over-scroll modes are
14433     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14434     * (allow over-scrolling only if the view content is larger than the container),
14435     * or {@link #OVER_SCROLL_NEVER}.
14436     *
14437     * Setting the over-scroll mode of a view will have an effect only if the
14438     * view is capable of scrolling.
14439     *
14440     * @param overScrollMode The new over-scroll mode for this view.
14441     */
14442    public void setOverScrollMode(int overScrollMode) {
14443        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14444                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14445                overScrollMode != OVER_SCROLL_NEVER) {
14446            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14447        }
14448        mOverScrollMode = overScrollMode;
14449    }
14450
14451    /**
14452     * Gets a scale factor that determines the distance the view should scroll
14453     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14454     * @return The vertical scroll scale factor.
14455     * @hide
14456     */
14457    protected float getVerticalScrollFactor() {
14458        if (mVerticalScrollFactor == 0) {
14459            TypedValue outValue = new TypedValue();
14460            if (!mContext.getTheme().resolveAttribute(
14461                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14462                throw new IllegalStateException(
14463                        "Expected theme to define listPreferredItemHeight.");
14464            }
14465            mVerticalScrollFactor = outValue.getDimension(
14466                    mContext.getResources().getDisplayMetrics());
14467        }
14468        return mVerticalScrollFactor;
14469    }
14470
14471    /**
14472     * Gets a scale factor that determines the distance the view should scroll
14473     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14474     * @return The horizontal scroll scale factor.
14475     * @hide
14476     */
14477    protected float getHorizontalScrollFactor() {
14478        // TODO: Should use something else.
14479        return getVerticalScrollFactor();
14480    }
14481
14482    /**
14483     * Return the value specifying the text direction or policy that was set with
14484     * {@link #setTextDirection(int)}.
14485     *
14486     * @return the defined text direction. It can be one of:
14487     *
14488     * {@link #TEXT_DIRECTION_INHERIT},
14489     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14490     * {@link #TEXT_DIRECTION_ANY_RTL},
14491     * {@link #TEXT_DIRECTION_LTR},
14492     * {@link #TEXT_DIRECTION_RTL},
14493     * {@link #TEXT_DIRECTION_LOCALE},
14494     */
14495    public int getTextDirection() {
14496        return mTextDirection;
14497    }
14498
14499    /**
14500     * Set the text direction.
14501     *
14502     * @param textDirection the direction to set. Should be one of:
14503     *
14504     * {@link #TEXT_DIRECTION_INHERIT},
14505     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14506     * {@link #TEXT_DIRECTION_ANY_RTL},
14507     * {@link #TEXT_DIRECTION_LTR},
14508     * {@link #TEXT_DIRECTION_RTL},
14509     * {@link #TEXT_DIRECTION_LOCALE},
14510     */
14511    public void setTextDirection(int textDirection) {
14512        if (textDirection != mTextDirection) {
14513            mTextDirection = textDirection;
14514            resetResolvedTextDirection();
14515            requestLayout();
14516        }
14517    }
14518
14519    /**
14520     * Return the resolved text direction.
14521     *
14522     * @return the resolved text direction. Return one of:
14523     *
14524     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14525     * {@link #TEXT_DIRECTION_ANY_RTL},
14526     * {@link #TEXT_DIRECTION_LTR},
14527     * {@link #TEXT_DIRECTION_RTL},
14528     * {@link #TEXT_DIRECTION_LOCALE},
14529     */
14530    public int getResolvedTextDirection() {
14531        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
14532            resolveTextDirection();
14533        }
14534        return mResolvedTextDirection;
14535    }
14536
14537    /**
14538     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
14539     * resolution is done.
14540     */
14541    public void resolveTextDirection() {
14542        if (mResolvedTextDirection != TEXT_DIRECTION_INHERIT) {
14543            // Resolution has already been done.
14544            return;
14545        }
14546        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
14547            mResolvedTextDirection = mTextDirection;
14548        } else if (mParent != null && mParent instanceof ViewGroup) {
14549            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
14550        } else {
14551            mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
14552        }
14553        onResolvedTextDirectionChanged();
14554    }
14555
14556    /**
14557     * Called when text direction has been resolved. Subclasses that care about text direction
14558     * resolution should override this method.
14559     *
14560     * The default implementation does nothing.
14561     */
14562    public void onResolvedTextDirectionChanged() {
14563    }
14564
14565    /**
14566     * Reset resolved text direction. Text direction can be resolved with a call to
14567     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
14568     * reset is done.
14569     */
14570    public void resetResolvedTextDirection() {
14571        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
14572        onResolvedTextDirectionReset();
14573    }
14574
14575    /**
14576     * Called when text direction is reset. Subclasses that care about text direction reset should
14577     * override this method and do a reset of the text direction of their children. The default
14578     * implementation does nothing.
14579     */
14580    public void onResolvedTextDirectionReset() {
14581    }
14582
14583    //
14584    // Properties
14585    //
14586    /**
14587     * A Property wrapper around the <code>alpha</code> functionality handled by the
14588     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14589     */
14590    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14591        @Override
14592        public void setValue(View object, float value) {
14593            object.setAlpha(value);
14594        }
14595
14596        @Override
14597        public Float get(View object) {
14598            return object.getAlpha();
14599        }
14600    };
14601
14602    /**
14603     * A Property wrapper around the <code>translationX</code> functionality handled by the
14604     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14605     */
14606    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14607        @Override
14608        public void setValue(View object, float value) {
14609            object.setTranslationX(value);
14610        }
14611
14612                @Override
14613        public Float get(View object) {
14614            return object.getTranslationX();
14615        }
14616    };
14617
14618    /**
14619     * A Property wrapper around the <code>translationY</code> functionality handled by the
14620     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14621     */
14622    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14623        @Override
14624        public void setValue(View object, float value) {
14625            object.setTranslationY(value);
14626        }
14627
14628        @Override
14629        public Float get(View object) {
14630            return object.getTranslationY();
14631        }
14632    };
14633
14634    /**
14635     * A Property wrapper around the <code>x</code> functionality handled by the
14636     * {@link View#setX(float)} and {@link View#getX()} methods.
14637     */
14638    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14639        @Override
14640        public void setValue(View object, float value) {
14641            object.setX(value);
14642        }
14643
14644        @Override
14645        public Float get(View object) {
14646            return object.getX();
14647        }
14648    };
14649
14650    /**
14651     * A Property wrapper around the <code>y</code> functionality handled by the
14652     * {@link View#setY(float)} and {@link View#getY()} methods.
14653     */
14654    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
14655        @Override
14656        public void setValue(View object, float value) {
14657            object.setY(value);
14658        }
14659
14660        @Override
14661        public Float get(View object) {
14662            return object.getY();
14663        }
14664    };
14665
14666    /**
14667     * A Property wrapper around the <code>rotation</code> functionality handled by the
14668     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
14669     */
14670    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
14671        @Override
14672        public void setValue(View object, float value) {
14673            object.setRotation(value);
14674        }
14675
14676        @Override
14677        public Float get(View object) {
14678            return object.getRotation();
14679        }
14680    };
14681
14682    /**
14683     * A Property wrapper around the <code>rotationX</code> functionality handled by the
14684     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
14685     */
14686    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
14687        @Override
14688        public void setValue(View object, float value) {
14689            object.setRotationX(value);
14690        }
14691
14692        @Override
14693        public Float get(View object) {
14694            return object.getRotationX();
14695        }
14696    };
14697
14698    /**
14699     * A Property wrapper around the <code>rotationY</code> functionality handled by the
14700     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
14701     */
14702    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
14703        @Override
14704        public void setValue(View object, float value) {
14705            object.setRotationY(value);
14706        }
14707
14708        @Override
14709        public Float get(View object) {
14710            return object.getRotationY();
14711        }
14712    };
14713
14714    /**
14715     * A Property wrapper around the <code>scaleX</code> functionality handled by the
14716     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
14717     */
14718    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
14719        @Override
14720        public void setValue(View object, float value) {
14721            object.setScaleX(value);
14722        }
14723
14724        @Override
14725        public Float get(View object) {
14726            return object.getScaleX();
14727        }
14728    };
14729
14730    /**
14731     * A Property wrapper around the <code>scaleY</code> functionality handled by the
14732     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
14733     */
14734    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
14735        @Override
14736        public void setValue(View object, float value) {
14737            object.setScaleY(value);
14738        }
14739
14740        @Override
14741        public Float get(View object) {
14742            return object.getScaleY();
14743        }
14744    };
14745
14746    /**
14747     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
14748     * Each MeasureSpec represents a requirement for either the width or the height.
14749     * A MeasureSpec is comprised of a size and a mode. There are three possible
14750     * modes:
14751     * <dl>
14752     * <dt>UNSPECIFIED</dt>
14753     * <dd>
14754     * The parent has not imposed any constraint on the child. It can be whatever size
14755     * it wants.
14756     * </dd>
14757     *
14758     * <dt>EXACTLY</dt>
14759     * <dd>
14760     * The parent has determined an exact size for the child. The child is going to be
14761     * given those bounds regardless of how big it wants to be.
14762     * </dd>
14763     *
14764     * <dt>AT_MOST</dt>
14765     * <dd>
14766     * The child can be as large as it wants up to the specified size.
14767     * </dd>
14768     * </dl>
14769     *
14770     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14771     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14772     */
14773    public static class MeasureSpec {
14774        private static final int MODE_SHIFT = 30;
14775        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14776
14777        /**
14778         * Measure specification mode: The parent has not imposed any constraint
14779         * on the child. It can be whatever size it wants.
14780         */
14781        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14782
14783        /**
14784         * Measure specification mode: The parent has determined an exact size
14785         * for the child. The child is going to be given those bounds regardless
14786         * of how big it wants to be.
14787         */
14788        public static final int EXACTLY     = 1 << MODE_SHIFT;
14789
14790        /**
14791         * Measure specification mode: The child can be as large as it wants up
14792         * to the specified size.
14793         */
14794        public static final int AT_MOST     = 2 << MODE_SHIFT;
14795
14796        /**
14797         * Creates a measure specification based on the supplied size and mode.
14798         *
14799         * The mode must always be one of the following:
14800         * <ul>
14801         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14802         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14803         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14804         * </ul>
14805         *
14806         * @param size the size of the measure specification
14807         * @param mode the mode of the measure specification
14808         * @return the measure specification based on size and mode
14809         */
14810        public static int makeMeasureSpec(int size, int mode) {
14811            return size + mode;
14812        }
14813
14814        /**
14815         * Extracts the mode from the supplied measure specification.
14816         *
14817         * @param measureSpec the measure specification to extract the mode from
14818         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14819         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14820         *         {@link android.view.View.MeasureSpec#EXACTLY}
14821         */
14822        public static int getMode(int measureSpec) {
14823            return (measureSpec & MODE_MASK);
14824        }
14825
14826        /**
14827         * Extracts the size from the supplied measure specification.
14828         *
14829         * @param measureSpec the measure specification to extract the size from
14830         * @return the size in pixels defined in the supplied measure specification
14831         */
14832        public static int getSize(int measureSpec) {
14833            return (measureSpec & ~MODE_MASK);
14834        }
14835
14836        /**
14837         * Returns a String representation of the specified measure
14838         * specification.
14839         *
14840         * @param measureSpec the measure specification to convert to a String
14841         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14842         */
14843        public static String toString(int measureSpec) {
14844            int mode = getMode(measureSpec);
14845            int size = getSize(measureSpec);
14846
14847            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14848
14849            if (mode == UNSPECIFIED)
14850                sb.append("UNSPECIFIED ");
14851            else if (mode == EXACTLY)
14852                sb.append("EXACTLY ");
14853            else if (mode == AT_MOST)
14854                sb.append("AT_MOST ");
14855            else
14856                sb.append(mode).append(" ");
14857
14858            sb.append(size);
14859            return sb.toString();
14860        }
14861    }
14862
14863    class CheckForLongPress implements Runnable {
14864
14865        private int mOriginalWindowAttachCount;
14866
14867        public void run() {
14868            if (isPressed() && (mParent != null)
14869                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14870                if (performLongClick()) {
14871                    mHasPerformedLongPress = true;
14872                }
14873            }
14874        }
14875
14876        public void rememberWindowAttachCount() {
14877            mOriginalWindowAttachCount = mWindowAttachCount;
14878        }
14879    }
14880
14881    private final class CheckForTap implements Runnable {
14882        public void run() {
14883            mPrivateFlags &= ~PREPRESSED;
14884            setPressed(true);
14885            checkForLongClick(ViewConfiguration.getTapTimeout());
14886        }
14887    }
14888
14889    private final class PerformClick implements Runnable {
14890        public void run() {
14891            performClick();
14892        }
14893    }
14894
14895    /** @hide */
14896    public void hackTurnOffWindowResizeAnim(boolean off) {
14897        mAttachInfo.mTurnOffWindowResizeAnim = off;
14898    }
14899
14900    /**
14901     * This method returns a ViewPropertyAnimator object, which can be used to animate
14902     * specific properties on this View.
14903     *
14904     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14905     */
14906    public ViewPropertyAnimator animate() {
14907        if (mAnimator == null) {
14908            mAnimator = new ViewPropertyAnimator(this);
14909        }
14910        return mAnimator;
14911    }
14912
14913    /**
14914     * Interface definition for a callback to be invoked when a key event is
14915     * dispatched to this view. The callback will be invoked before the key
14916     * event is given to the view.
14917     */
14918    public interface OnKeyListener {
14919        /**
14920         * Called when a key is dispatched to a view. This allows listeners to
14921         * get a chance to respond before the target view.
14922         *
14923         * @param v The view the key has been dispatched to.
14924         * @param keyCode The code for the physical key that was pressed
14925         * @param event The KeyEvent object containing full information about
14926         *        the event.
14927         * @return True if the listener has consumed the event, false otherwise.
14928         */
14929        boolean onKey(View v, int keyCode, KeyEvent event);
14930    }
14931
14932    /**
14933     * Interface definition for a callback to be invoked when a touch event is
14934     * dispatched to this view. The callback will be invoked before the touch
14935     * event is given to the view.
14936     */
14937    public interface OnTouchListener {
14938        /**
14939         * Called when a touch event is dispatched to a view. This allows listeners to
14940         * get a chance to respond before the target view.
14941         *
14942         * @param v The view the touch event has been dispatched to.
14943         * @param event The MotionEvent object containing full information about
14944         *        the event.
14945         * @return True if the listener has consumed the event, false otherwise.
14946         */
14947        boolean onTouch(View v, MotionEvent event);
14948    }
14949
14950    /**
14951     * Interface definition for a callback to be invoked when a hover event is
14952     * dispatched to this view. The callback will be invoked before the hover
14953     * event is given to the view.
14954     */
14955    public interface OnHoverListener {
14956        /**
14957         * Called when a hover event is dispatched to a view. This allows listeners to
14958         * get a chance to respond before the target view.
14959         *
14960         * @param v The view the hover event has been dispatched to.
14961         * @param event The MotionEvent object containing full information about
14962         *        the event.
14963         * @return True if the listener has consumed the event, false otherwise.
14964         */
14965        boolean onHover(View v, MotionEvent event);
14966    }
14967
14968    /**
14969     * Interface definition for a callback to be invoked when a generic motion event is
14970     * dispatched to this view. The callback will be invoked before the generic motion
14971     * event is given to the view.
14972     */
14973    public interface OnGenericMotionListener {
14974        /**
14975         * Called when a generic motion event is dispatched to a view. This allows listeners to
14976         * get a chance to respond before the target view.
14977         *
14978         * @param v The view the generic motion event has been dispatched to.
14979         * @param event The MotionEvent object containing full information about
14980         *        the event.
14981         * @return True if the listener has consumed the event, false otherwise.
14982         */
14983        boolean onGenericMotion(View v, MotionEvent event);
14984    }
14985
14986    /**
14987     * Interface definition for a callback to be invoked when a view has been clicked and held.
14988     */
14989    public interface OnLongClickListener {
14990        /**
14991         * Called when a view has been clicked and held.
14992         *
14993         * @param v The view that was clicked and held.
14994         *
14995         * @return true if the callback consumed the long click, false otherwise.
14996         */
14997        boolean onLongClick(View v);
14998    }
14999
15000    /**
15001     * Interface definition for a callback to be invoked when a drag is being dispatched
15002     * to this view.  The callback will be invoked before the hosting view's own
15003     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
15004     * onDrag(event) behavior, it should return 'false' from this callback.
15005     *
15006     * <div class="special reference">
15007     * <h3>Developer Guides</h3>
15008     * <p>For a guide to implementing drag and drop features, read the
15009     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15010     * </div>
15011     */
15012    public interface OnDragListener {
15013        /**
15014         * Called when a drag event is dispatched to a view. This allows listeners
15015         * to get a chance to override base View behavior.
15016         *
15017         * @param v The View that received the drag event.
15018         * @param event The {@link android.view.DragEvent} object for the drag event.
15019         * @return {@code true} if the drag event was handled successfully, or {@code false}
15020         * if the drag event was not handled. Note that {@code false} will trigger the View
15021         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
15022         */
15023        boolean onDrag(View v, DragEvent event);
15024    }
15025
15026    /**
15027     * Interface definition for a callback to be invoked when the focus state of
15028     * a view changed.
15029     */
15030    public interface OnFocusChangeListener {
15031        /**
15032         * Called when the focus state of a view has changed.
15033         *
15034         * @param v The view whose state has changed.
15035         * @param hasFocus The new focus state of v.
15036         */
15037        void onFocusChange(View v, boolean hasFocus);
15038    }
15039
15040    /**
15041     * Interface definition for a callback to be invoked when a view is clicked.
15042     */
15043    public interface OnClickListener {
15044        /**
15045         * Called when a view has been clicked.
15046         *
15047         * @param v The view that was clicked.
15048         */
15049        void onClick(View v);
15050    }
15051
15052    /**
15053     * Interface definition for a callback to be invoked when the context menu
15054     * for this view is being built.
15055     */
15056    public interface OnCreateContextMenuListener {
15057        /**
15058         * Called when the context menu for this view is being built. It is not
15059         * safe to hold onto the menu after this method returns.
15060         *
15061         * @param menu The context menu that is being built
15062         * @param v The view for which the context menu is being built
15063         * @param menuInfo Extra information about the item for which the
15064         *            context menu should be shown. This information will vary
15065         *            depending on the class of v.
15066         */
15067        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
15068    }
15069
15070    /**
15071     * Interface definition for a callback to be invoked when the status bar changes
15072     * visibility.  This reports <strong>global</strong> changes to the system UI
15073     * state, not just what the application is requesting.
15074     *
15075     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
15076     */
15077    public interface OnSystemUiVisibilityChangeListener {
15078        /**
15079         * Called when the status bar changes visibility because of a call to
15080         * {@link View#setSystemUiVisibility(int)}.
15081         *
15082         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
15083         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
15084         * <strong>global</strong> state of the UI visibility flags, not what your
15085         * app is currently applying.
15086         */
15087        public void onSystemUiVisibilityChange(int visibility);
15088    }
15089
15090    /**
15091     * Interface definition for a callback to be invoked when this view is attached
15092     * or detached from its window.
15093     */
15094    public interface OnAttachStateChangeListener {
15095        /**
15096         * Called when the view is attached to a window.
15097         * @param v The view that was attached
15098         */
15099        public void onViewAttachedToWindow(View v);
15100        /**
15101         * Called when the view is detached from a window.
15102         * @param v The view that was detached
15103         */
15104        public void onViewDetachedFromWindow(View v);
15105    }
15106
15107    private final class UnsetPressedState implements Runnable {
15108        public void run() {
15109            setPressed(false);
15110        }
15111    }
15112
15113    /**
15114     * Base class for derived classes that want to save and restore their own
15115     * state in {@link android.view.View#onSaveInstanceState()}.
15116     */
15117    public static class BaseSavedState extends AbsSavedState {
15118        /**
15119         * Constructor used when reading from a parcel. Reads the state of the superclass.
15120         *
15121         * @param source
15122         */
15123        public BaseSavedState(Parcel source) {
15124            super(source);
15125        }
15126
15127        /**
15128         * Constructor called by derived classes when creating their SavedState objects
15129         *
15130         * @param superState The state of the superclass of this view
15131         */
15132        public BaseSavedState(Parcelable superState) {
15133            super(superState);
15134        }
15135
15136        public static final Parcelable.Creator<BaseSavedState> CREATOR =
15137                new Parcelable.Creator<BaseSavedState>() {
15138            public BaseSavedState createFromParcel(Parcel in) {
15139                return new BaseSavedState(in);
15140            }
15141
15142            public BaseSavedState[] newArray(int size) {
15143                return new BaseSavedState[size];
15144            }
15145        };
15146    }
15147
15148    /**
15149     * A set of information given to a view when it is attached to its parent
15150     * window.
15151     */
15152    static class AttachInfo {
15153        interface Callbacks {
15154            void playSoundEffect(int effectId);
15155            boolean performHapticFeedback(int effectId, boolean always);
15156        }
15157
15158        /**
15159         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
15160         * to a Handler. This class contains the target (View) to invalidate and
15161         * the coordinates of the dirty rectangle.
15162         *
15163         * For performance purposes, this class also implements a pool of up to
15164         * POOL_LIMIT objects that get reused. This reduces memory allocations
15165         * whenever possible.
15166         */
15167        static class InvalidateInfo implements Poolable<InvalidateInfo> {
15168            private static final int POOL_LIMIT = 10;
15169            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
15170                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
15171                        public InvalidateInfo newInstance() {
15172                            return new InvalidateInfo();
15173                        }
15174
15175                        public void onAcquired(InvalidateInfo element) {
15176                        }
15177
15178                        public void onReleased(InvalidateInfo element) {
15179                            element.target = null;
15180                        }
15181                    }, POOL_LIMIT)
15182            );
15183
15184            private InvalidateInfo mNext;
15185            private boolean mIsPooled;
15186
15187            View target;
15188
15189            int left;
15190            int top;
15191            int right;
15192            int bottom;
15193
15194            public void setNextPoolable(InvalidateInfo element) {
15195                mNext = element;
15196            }
15197
15198            public InvalidateInfo getNextPoolable() {
15199                return mNext;
15200            }
15201
15202            static InvalidateInfo acquire() {
15203                return sPool.acquire();
15204            }
15205
15206            void release() {
15207                sPool.release(this);
15208            }
15209
15210            public boolean isPooled() {
15211                return mIsPooled;
15212            }
15213
15214            public void setPooled(boolean isPooled) {
15215                mIsPooled = isPooled;
15216            }
15217        }
15218
15219        final IWindowSession mSession;
15220
15221        final IWindow mWindow;
15222
15223        final IBinder mWindowToken;
15224
15225        final Callbacks mRootCallbacks;
15226
15227        HardwareCanvas mHardwareCanvas;
15228
15229        /**
15230         * The top view of the hierarchy.
15231         */
15232        View mRootView;
15233
15234        IBinder mPanelParentWindowToken;
15235        Surface mSurface;
15236
15237        boolean mHardwareAccelerated;
15238        boolean mHardwareAccelerationRequested;
15239        HardwareRenderer mHardwareRenderer;
15240
15241        boolean mScreenOn;
15242
15243        /**
15244         * Scale factor used by the compatibility mode
15245         */
15246        float mApplicationScale;
15247
15248        /**
15249         * Indicates whether the application is in compatibility mode
15250         */
15251        boolean mScalingRequired;
15252
15253        /**
15254         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
15255         */
15256        boolean mTurnOffWindowResizeAnim;
15257
15258        /**
15259         * Left position of this view's window
15260         */
15261        int mWindowLeft;
15262
15263        /**
15264         * Top position of this view's window
15265         */
15266        int mWindowTop;
15267
15268        /**
15269         * Indicates whether views need to use 32-bit drawing caches
15270         */
15271        boolean mUse32BitDrawingCache;
15272
15273        /**
15274         * For windows that are full-screen but using insets to layout inside
15275         * of the screen decorations, these are the current insets for the
15276         * content of the window.
15277         */
15278        final Rect mContentInsets = new Rect();
15279
15280        /**
15281         * For windows that are full-screen but using insets to layout inside
15282         * of the screen decorations, these are the current insets for the
15283         * actual visible parts of the window.
15284         */
15285        final Rect mVisibleInsets = new Rect();
15286
15287        /**
15288         * The internal insets given by this window.  This value is
15289         * supplied by the client (through
15290         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
15291         * be given to the window manager when changed to be used in laying
15292         * out windows behind it.
15293         */
15294        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
15295                = new ViewTreeObserver.InternalInsetsInfo();
15296
15297        /**
15298         * All views in the window's hierarchy that serve as scroll containers,
15299         * used to determine if the window can be resized or must be panned
15300         * to adjust for a soft input area.
15301         */
15302        final ArrayList<View> mScrollContainers = new ArrayList<View>();
15303
15304        final KeyEvent.DispatcherState mKeyDispatchState
15305                = new KeyEvent.DispatcherState();
15306
15307        /**
15308         * Indicates whether the view's window currently has the focus.
15309         */
15310        boolean mHasWindowFocus;
15311
15312        /**
15313         * The current visibility of the window.
15314         */
15315        int mWindowVisibility;
15316
15317        /**
15318         * Indicates the time at which drawing started to occur.
15319         */
15320        long mDrawingTime;
15321
15322        /**
15323         * Indicates whether or not ignoring the DIRTY_MASK flags.
15324         */
15325        boolean mIgnoreDirtyState;
15326
15327        /**
15328         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
15329         * to avoid clearing that flag prematurely.
15330         */
15331        boolean mSetIgnoreDirtyState = false;
15332
15333        /**
15334         * Indicates whether the view's window is currently in touch mode.
15335         */
15336        boolean mInTouchMode;
15337
15338        /**
15339         * Indicates that ViewAncestor should trigger a global layout change
15340         * the next time it performs a traversal
15341         */
15342        boolean mRecomputeGlobalAttributes;
15343
15344        /**
15345         * Always report new attributes at next traversal.
15346         */
15347        boolean mForceReportNewAttributes;
15348
15349        /**
15350         * Set during a traveral if any views want to keep the screen on.
15351         */
15352        boolean mKeepScreenOn;
15353
15354        /**
15355         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
15356         */
15357        int mSystemUiVisibility;
15358
15359        /**
15360         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
15361         * attached.
15362         */
15363        boolean mHasSystemUiListeners;
15364
15365        /**
15366         * Set if the visibility of any views has changed.
15367         */
15368        boolean mViewVisibilityChanged;
15369
15370        /**
15371         * Set to true if a view has been scrolled.
15372         */
15373        boolean mViewScrollChanged;
15374
15375        /**
15376         * Global to the view hierarchy used as a temporary for dealing with
15377         * x/y points in the transparent region computations.
15378         */
15379        final int[] mTransparentLocation = new int[2];
15380
15381        /**
15382         * Global to the view hierarchy used as a temporary for dealing with
15383         * x/y points in the ViewGroup.invalidateChild implementation.
15384         */
15385        final int[] mInvalidateChildLocation = new int[2];
15386
15387
15388        /**
15389         * Global to the view hierarchy used as a temporary for dealing with
15390         * x/y location when view is transformed.
15391         */
15392        final float[] mTmpTransformLocation = new float[2];
15393
15394        /**
15395         * The view tree observer used to dispatch global events like
15396         * layout, pre-draw, touch mode change, etc.
15397         */
15398        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
15399
15400        /**
15401         * A Canvas used by the view hierarchy to perform bitmap caching.
15402         */
15403        Canvas mCanvas;
15404
15405        /**
15406         * The view root impl.
15407         */
15408        final ViewRootImpl mViewRootImpl;
15409
15410        /**
15411         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
15412         * handler can be used to pump events in the UI events queue.
15413         */
15414        final Handler mHandler;
15415
15416        /**
15417         * Temporary for use in computing invalidate rectangles while
15418         * calling up the hierarchy.
15419         */
15420        final Rect mTmpInvalRect = new Rect();
15421
15422        /**
15423         * Temporary for use in computing hit areas with transformed views
15424         */
15425        final RectF mTmpTransformRect = new RectF();
15426
15427        /**
15428         * Temporary list for use in collecting focusable descendents of a view.
15429         */
15430        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
15431
15432        /**
15433         * The id of the window for accessibility purposes.
15434         */
15435        int mAccessibilityWindowId = View.NO_ID;
15436
15437        /**
15438         * Creates a new set of attachment information with the specified
15439         * events handler and thread.
15440         *
15441         * @param handler the events handler the view must use
15442         */
15443        AttachInfo(IWindowSession session, IWindow window,
15444                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
15445            mSession = session;
15446            mWindow = window;
15447            mWindowToken = window.asBinder();
15448            mViewRootImpl = viewRootImpl;
15449            mHandler = handler;
15450            mRootCallbacks = effectPlayer;
15451        }
15452    }
15453
15454    /**
15455     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15456     * is supported. This avoids keeping too many unused fields in most
15457     * instances of View.</p>
15458     */
15459    private static class ScrollabilityCache implements Runnable {
15460
15461        /**
15462         * Scrollbars are not visible
15463         */
15464        public static final int OFF = 0;
15465
15466        /**
15467         * Scrollbars are visible
15468         */
15469        public static final int ON = 1;
15470
15471        /**
15472         * Scrollbars are fading away
15473         */
15474        public static final int FADING = 2;
15475
15476        public boolean fadeScrollBars;
15477
15478        public int fadingEdgeLength;
15479        public int scrollBarDefaultDelayBeforeFade;
15480        public int scrollBarFadeDuration;
15481
15482        public int scrollBarSize;
15483        public ScrollBarDrawable scrollBar;
15484        public float[] interpolatorValues;
15485        public View host;
15486
15487        public final Paint paint;
15488        public final Matrix matrix;
15489        public Shader shader;
15490
15491        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15492
15493        private static final float[] OPAQUE = { 255 };
15494        private static final float[] TRANSPARENT = { 0.0f };
15495
15496        /**
15497         * When fading should start. This time moves into the future every time
15498         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15499         */
15500        public long fadeStartTime;
15501
15502
15503        /**
15504         * The current state of the scrollbars: ON, OFF, or FADING
15505         */
15506        public int state = OFF;
15507
15508        private int mLastColor;
15509
15510        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15511            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15512            scrollBarSize = configuration.getScaledScrollBarSize();
15513            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15514            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15515
15516            paint = new Paint();
15517            matrix = new Matrix();
15518            // use use a height of 1, and then wack the matrix each time we
15519            // actually use it.
15520            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15521
15522            paint.setShader(shader);
15523            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15524            this.host = host;
15525        }
15526
15527        public void setFadeColor(int color) {
15528            if (color != 0 && color != mLastColor) {
15529                mLastColor = color;
15530                color |= 0xFF000000;
15531
15532                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15533                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15534
15535                paint.setShader(shader);
15536                // Restore the default transfer mode (src_over)
15537                paint.setXfermode(null);
15538            }
15539        }
15540
15541        public void run() {
15542            long now = AnimationUtils.currentAnimationTimeMillis();
15543            if (now >= fadeStartTime) {
15544
15545                // the animation fades the scrollbars out by changing
15546                // the opacity (alpha) from fully opaque to fully
15547                // transparent
15548                int nextFrame = (int) now;
15549                int framesCount = 0;
15550
15551                Interpolator interpolator = scrollBarInterpolator;
15552
15553                // Start opaque
15554                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15555
15556                // End transparent
15557                nextFrame += scrollBarFadeDuration;
15558                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15559
15560                state = FADING;
15561
15562                // Kick off the fade animation
15563                host.invalidate(true);
15564            }
15565        }
15566    }
15567
15568    /**
15569     * Resuable callback for sending
15570     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15571     */
15572    private class SendViewScrolledAccessibilityEvent implements Runnable {
15573        public volatile boolean mIsPending;
15574
15575        public void run() {
15576            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15577            mIsPending = false;
15578        }
15579    }
15580
15581    /**
15582     * <p>
15583     * This class represents a delegate that can be registered in a {@link View}
15584     * to enhance accessibility support via composition rather via inheritance.
15585     * It is specifically targeted to widget developers that extend basic View
15586     * classes i.e. classes in package android.view, that would like their
15587     * applications to be backwards compatible.
15588     * </p>
15589     * <p>
15590     * A scenario in which a developer would like to use an accessibility delegate
15591     * is overriding a method introduced in a later API version then the minimal API
15592     * version supported by the application. For example, the method
15593     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15594     * in API version 4 when the accessibility APIs were first introduced. If a
15595     * developer would like his application to run on API version 4 devices (assuming
15596     * all other APIs used by the application are version 4 or lower) and take advantage
15597     * of this method, instead of overriding the method which would break the application's
15598     * backwards compatibility, he can override the corresponding method in this
15599     * delegate and register the delegate in the target View if the API version of
15600     * the system is high enough i.e. the API version is same or higher to the API
15601     * version that introduced
15602     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15603     * </p>
15604     * <p>
15605     * Here is an example implementation:
15606     * </p>
15607     * <code><pre><p>
15608     * if (Build.VERSION.SDK_INT >= 14) {
15609     *     // If the API version is equal of higher than the version in
15610     *     // which onInitializeAccessibilityNodeInfo was introduced we
15611     *     // register a delegate with a customized implementation.
15612     *     View view = findViewById(R.id.view_id);
15613     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15614     *         public void onInitializeAccessibilityNodeInfo(View host,
15615     *                 AccessibilityNodeInfo info) {
15616     *             // Let the default implementation populate the info.
15617     *             super.onInitializeAccessibilityNodeInfo(host, info);
15618     *             // Set some other information.
15619     *             info.setEnabled(host.isEnabled());
15620     *         }
15621     *     });
15622     * }
15623     * </code></pre></p>
15624     * <p>
15625     * This delegate contains methods that correspond to the accessibility methods
15626     * in View. If a delegate has been specified the implementation in View hands
15627     * off handling to the corresponding method in this delegate. The default
15628     * implementation the delegate methods behaves exactly as the corresponding
15629     * method in View for the case of no accessibility delegate been set. Hence,
15630     * to customize the behavior of a View method, clients can override only the
15631     * corresponding delegate method without altering the behavior of the rest
15632     * accessibility related methods of the host view.
15633     * </p>
15634     */
15635    public static class AccessibilityDelegate {
15636
15637        /**
15638         * Sends an accessibility event of the given type. If accessibility is not
15639         * enabled this method has no effect.
15640         * <p>
15641         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15642         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15643         * been set.
15644         * </p>
15645         *
15646         * @param host The View hosting the delegate.
15647         * @param eventType The type of the event to send.
15648         *
15649         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
15650         */
15651        public void sendAccessibilityEvent(View host, int eventType) {
15652            host.sendAccessibilityEventInternal(eventType);
15653        }
15654
15655        /**
15656         * Sends an accessibility event. This method behaves exactly as
15657         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
15658         * empty {@link AccessibilityEvent} and does not perform a check whether
15659         * accessibility is enabled.
15660         * <p>
15661         * The default implementation behaves as
15662         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15663         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
15664         * the case of no accessibility delegate been set.
15665         * </p>
15666         *
15667         * @param host The View hosting the delegate.
15668         * @param event The event to send.
15669         *
15670         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15671         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15672         */
15673        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
15674            host.sendAccessibilityEventUncheckedInternal(event);
15675        }
15676
15677        /**
15678         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
15679         * to its children for adding their text content to the event.
15680         * <p>
15681         * The default implementation behaves as
15682         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15683         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
15684         * the case of no accessibility delegate been set.
15685         * </p>
15686         *
15687         * @param host The View hosting the delegate.
15688         * @param event The event.
15689         * @return True if the event population was completed.
15690         *
15691         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15692         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15693         */
15694        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15695            return host.dispatchPopulateAccessibilityEventInternal(event);
15696        }
15697
15698        /**
15699         * Gives a chance to the host View to populate the accessibility event with its
15700         * text content.
15701         * <p>
15702         * The default implementation behaves as
15703         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
15704         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
15705         * the case of no accessibility delegate been set.
15706         * </p>
15707         *
15708         * @param host The View hosting the delegate.
15709         * @param event The accessibility event which to populate.
15710         *
15711         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
15712         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
15713         */
15714        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15715            host.onPopulateAccessibilityEventInternal(event);
15716        }
15717
15718        /**
15719         * Initializes an {@link AccessibilityEvent} with information about the
15720         * the host View which is the event source.
15721         * <p>
15722         * The default implementation behaves as
15723         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
15724         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
15725         * the case of no accessibility delegate been set.
15726         * </p>
15727         *
15728         * @param host The View hosting the delegate.
15729         * @param event The event to initialize.
15730         *
15731         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
15732         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
15733         */
15734        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
15735            host.onInitializeAccessibilityEventInternal(event);
15736        }
15737
15738        /**
15739         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
15740         * <p>
15741         * The default implementation behaves as
15742         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15743         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
15744         * the case of no accessibility delegate been set.
15745         * </p>
15746         *
15747         * @param host The View hosting the delegate.
15748         * @param info The instance to initialize.
15749         *
15750         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15751         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15752         */
15753        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
15754            host.onInitializeAccessibilityNodeInfoInternal(info);
15755        }
15756
15757        /**
15758         * Called when a child of the host View has requested sending an
15759         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
15760         * to augment the event.
15761         * <p>
15762         * The default implementation behaves as
15763         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15764         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15765         * the case of no accessibility delegate been set.
15766         * </p>
15767         *
15768         * @param host The View hosting the delegate.
15769         * @param child The child which requests sending the event.
15770         * @param event The event to be sent.
15771         * @return True if the event should be sent
15772         *
15773         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15774         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15775         */
15776        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15777                AccessibilityEvent event) {
15778            return host.onRequestSendAccessibilityEventInternal(child, event);
15779        }
15780
15781        /**
15782         * Gets the provider for managing a virtual view hierarchy rooted at this View
15783         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15784         * that explore the window content.
15785         * <p>
15786         * The default implementation behaves as
15787         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15788         * the case of no accessibility delegate been set.
15789         * </p>
15790         *
15791         * @return The provider.
15792         *
15793         * @see AccessibilityNodeProvider
15794         */
15795        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15796            return null;
15797        }
15798    }
15799}
15800