View.java revision 21aec19d3041fe040004dd32eef0cfd1bafd6fb6
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    /**
769     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
770     * that they are optional and should be skipped if the window has
771     * requested system UI flags that ignore those insets for layout.
772     */
773    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
774
775    /**
776     * <p>This view doesn't show fading edges.</p>
777     * {@hide}
778     */
779    static final int FADING_EDGE_NONE = 0x00000000;
780
781    /**
782     * <p>This view shows horizontal fading edges.</p>
783     * {@hide}
784     */
785    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
786
787    /**
788     * <p>This view shows vertical fading edges.</p>
789     * {@hide}
790     */
791    static final int FADING_EDGE_VERTICAL = 0x00002000;
792
793    /**
794     * <p>Mask for use with setFlags indicating bits used for indicating which
795     * fading edges are enabled.</p>
796     * {@hide}
797     */
798    static final int FADING_EDGE_MASK = 0x00003000;
799
800    /**
801     * <p>Indicates this view can be clicked. When clickable, a View reacts
802     * to clicks by notifying the OnClickListener.<p>
803     * {@hide}
804     */
805    static final int CLICKABLE = 0x00004000;
806
807    /**
808     * <p>Indicates this view is caching its drawing into a bitmap.</p>
809     * {@hide}
810     */
811    static final int DRAWING_CACHE_ENABLED = 0x00008000;
812
813    /**
814     * <p>Indicates that no icicle should be saved for this view.<p>
815     * {@hide}
816     */
817    static final int SAVE_DISABLED = 0x000010000;
818
819    /**
820     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
821     * property.</p>
822     * {@hide}
823     */
824    static final int SAVE_DISABLED_MASK = 0x000010000;
825
826    /**
827     * <p>Indicates that no drawing cache should ever be created for this view.<p>
828     * {@hide}
829     */
830    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
831
832    /**
833     * <p>Indicates this view can take / keep focus when int touch mode.</p>
834     * {@hide}
835     */
836    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
837
838    /**
839     * <p>Enables low quality mode for the drawing cache.</p>
840     */
841    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
842
843    /**
844     * <p>Enables high quality mode for the drawing cache.</p>
845     */
846    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
847
848    /**
849     * <p>Enables automatic quality mode for the drawing cache.</p>
850     */
851    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
852
853    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
854            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
855    };
856
857    /**
858     * <p>Mask for use with setFlags indicating bits used for the cache
859     * quality property.</p>
860     * {@hide}
861     */
862    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
863
864    /**
865     * <p>
866     * Indicates this view can be long clicked. When long clickable, a View
867     * reacts to long clicks by notifying the OnLongClickListener or showing a
868     * context menu.
869     * </p>
870     * {@hide}
871     */
872    static final int LONG_CLICKABLE = 0x00200000;
873
874    /**
875     * <p>Indicates that this view gets its drawable states from its direct parent
876     * and ignores its original internal states.</p>
877     *
878     * @hide
879     */
880    static final int DUPLICATE_PARENT_STATE = 0x00400000;
881
882    /**
883     * The scrollbar style to display the scrollbars inside the content area,
884     * without increasing the padding. The scrollbars will be overlaid with
885     * translucency on the view's content.
886     */
887    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
888
889    /**
890     * The scrollbar style to display the scrollbars inside the padded area,
891     * increasing the padding of the view. The scrollbars will not overlap the
892     * content area of the view.
893     */
894    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
895
896    /**
897     * The scrollbar style to display the scrollbars at the edge of the view,
898     * without increasing the padding. The scrollbars will be overlaid with
899     * translucency.
900     */
901    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
902
903    /**
904     * The scrollbar style to display the scrollbars at the edge of the view,
905     * increasing the padding of the view. The scrollbars will only overlap the
906     * background, if any.
907     */
908    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
909
910    /**
911     * Mask to check if the scrollbar style is overlay or inset.
912     * {@hide}
913     */
914    static final int SCROLLBARS_INSET_MASK = 0x01000000;
915
916    /**
917     * Mask to check if the scrollbar style is inside or outside.
918     * {@hide}
919     */
920    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
921
922    /**
923     * Mask for scrollbar style.
924     * {@hide}
925     */
926    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
927
928    /**
929     * View flag indicating that the screen should remain on while the
930     * window containing this view is visible to the user.  This effectively
931     * takes care of automatically setting the WindowManager's
932     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
933     */
934    public static final int KEEP_SCREEN_ON = 0x04000000;
935
936    /**
937     * View flag indicating whether this view should have sound effects enabled
938     * for events such as clicking and touching.
939     */
940    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
941
942    /**
943     * View flag indicating whether this view should have haptic feedback
944     * enabled for events such as long presses.
945     */
946    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
947
948    /**
949     * <p>Indicates that the view hierarchy should stop saving state when
950     * it reaches this view.  If state saving is initiated immediately at
951     * the view, it will be allowed.
952     * {@hide}
953     */
954    static final int PARENT_SAVE_DISABLED = 0x20000000;
955
956    /**
957     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
958     * {@hide}
959     */
960    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
961
962    /**
963     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
964     * should add all focusable Views regardless if they are focusable in touch mode.
965     */
966    public static final int FOCUSABLES_ALL = 0x00000000;
967
968    /**
969     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
970     * should add only Views focusable in touch mode.
971     */
972    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
973
974    /**
975     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
976     * item.
977     */
978    public static final int FOCUS_BACKWARD = 0x00000001;
979
980    /**
981     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
982     * item.
983     */
984    public static final int FOCUS_FORWARD = 0x00000002;
985
986    /**
987     * Use with {@link #focusSearch(int)}. Move focus to the left.
988     */
989    public static final int FOCUS_LEFT = 0x00000011;
990
991    /**
992     * Use with {@link #focusSearch(int)}. Move focus up.
993     */
994    public static final int FOCUS_UP = 0x00000021;
995
996    /**
997     * Use with {@link #focusSearch(int)}. Move focus to the right.
998     */
999    public static final int FOCUS_RIGHT = 0x00000042;
1000
1001    /**
1002     * Use with {@link #focusSearch(int)}. Move focus down.
1003     */
1004    public static final int FOCUS_DOWN = 0x00000082;
1005
1006    /**
1007     * Bits of {@link #getMeasuredWidthAndState()} and
1008     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1009     */
1010    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1011
1012    /**
1013     * Bits of {@link #getMeasuredWidthAndState()} and
1014     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1015     */
1016    public static final int MEASURED_STATE_MASK = 0xff000000;
1017
1018    /**
1019     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1020     * for functions that combine both width and height into a single int,
1021     * such as {@link #getMeasuredState()} and the childState argument of
1022     * {@link #resolveSizeAndState(int, int, int)}.
1023     */
1024    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1025
1026    /**
1027     * Bit of {@link #getMeasuredWidthAndState()} and
1028     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1029     * is smaller that the space the view would like to have.
1030     */
1031    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1032
1033    /**
1034     * Base View state sets
1035     */
1036    // Singles
1037    /**
1038     * Indicates the view has no states set. States are used with
1039     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1040     * view depending on its state.
1041     *
1042     * @see android.graphics.drawable.Drawable
1043     * @see #getDrawableState()
1044     */
1045    protected static final int[] EMPTY_STATE_SET;
1046    /**
1047     * Indicates the view is enabled. States are used with
1048     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1049     * view depending on its state.
1050     *
1051     * @see android.graphics.drawable.Drawable
1052     * @see #getDrawableState()
1053     */
1054    protected static final int[] ENABLED_STATE_SET;
1055    /**
1056     * Indicates the view is focused. States are used with
1057     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1058     * view depending on its state.
1059     *
1060     * @see android.graphics.drawable.Drawable
1061     * @see #getDrawableState()
1062     */
1063    protected static final int[] FOCUSED_STATE_SET;
1064    /**
1065     * Indicates the view is selected. States are used with
1066     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1067     * view depending on its state.
1068     *
1069     * @see android.graphics.drawable.Drawable
1070     * @see #getDrawableState()
1071     */
1072    protected static final int[] SELECTED_STATE_SET;
1073    /**
1074     * Indicates the view is pressed. States are used with
1075     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1076     * view depending on its state.
1077     *
1078     * @see android.graphics.drawable.Drawable
1079     * @see #getDrawableState()
1080     * @hide
1081     */
1082    protected static final int[] PRESSED_STATE_SET;
1083    /**
1084     * Indicates the view's window has focus. States are used with
1085     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1086     * view depending on its state.
1087     *
1088     * @see android.graphics.drawable.Drawable
1089     * @see #getDrawableState()
1090     */
1091    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1092    // Doubles
1093    /**
1094     * Indicates the view is enabled and has the focus.
1095     *
1096     * @see #ENABLED_STATE_SET
1097     * @see #FOCUSED_STATE_SET
1098     */
1099    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1100    /**
1101     * Indicates the view is enabled and selected.
1102     *
1103     * @see #ENABLED_STATE_SET
1104     * @see #SELECTED_STATE_SET
1105     */
1106    protected static final int[] ENABLED_SELECTED_STATE_SET;
1107    /**
1108     * Indicates the view is enabled and that its window has focus.
1109     *
1110     * @see #ENABLED_STATE_SET
1111     * @see #WINDOW_FOCUSED_STATE_SET
1112     */
1113    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1114    /**
1115     * Indicates the view is focused and selected.
1116     *
1117     * @see #FOCUSED_STATE_SET
1118     * @see #SELECTED_STATE_SET
1119     */
1120    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1121    /**
1122     * Indicates the view has the focus and that its window has the focus.
1123     *
1124     * @see #FOCUSED_STATE_SET
1125     * @see #WINDOW_FOCUSED_STATE_SET
1126     */
1127    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1128    /**
1129     * Indicates the view is selected and that its window has the focus.
1130     *
1131     * @see #SELECTED_STATE_SET
1132     * @see #WINDOW_FOCUSED_STATE_SET
1133     */
1134    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1135    // Triples
1136    /**
1137     * Indicates the view is enabled, focused and selected.
1138     *
1139     * @see #ENABLED_STATE_SET
1140     * @see #FOCUSED_STATE_SET
1141     * @see #SELECTED_STATE_SET
1142     */
1143    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1144    /**
1145     * Indicates the view is enabled, focused and its window has the focus.
1146     *
1147     * @see #ENABLED_STATE_SET
1148     * @see #FOCUSED_STATE_SET
1149     * @see #WINDOW_FOCUSED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1152    /**
1153     * Indicates the view is enabled, selected and its window has the focus.
1154     *
1155     * @see #ENABLED_STATE_SET
1156     * @see #SELECTED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused, selected and its window has the focus.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     * @see #WINDOW_FOCUSED_STATE_SET
1166     */
1167    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1168    /**
1169     * Indicates the view is enabled, focused, selected and its window
1170     * has the focus.
1171     *
1172     * @see #ENABLED_STATE_SET
1173     * @see #FOCUSED_STATE_SET
1174     * @see #SELECTED_STATE_SET
1175     * @see #WINDOW_FOCUSED_STATE_SET
1176     */
1177    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1178    /**
1179     * Indicates the view is pressed and its window has the focus.
1180     *
1181     * @see #PRESSED_STATE_SET
1182     * @see #WINDOW_FOCUSED_STATE_SET
1183     */
1184    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1185    /**
1186     * Indicates the view is pressed and selected.
1187     *
1188     * @see #PRESSED_STATE_SET
1189     * @see #SELECTED_STATE_SET
1190     */
1191    protected static final int[] PRESSED_SELECTED_STATE_SET;
1192    /**
1193     * Indicates the view is pressed, selected and its window has the focus.
1194     *
1195     * @see #PRESSED_STATE_SET
1196     * @see #SELECTED_STATE_SET
1197     * @see #WINDOW_FOCUSED_STATE_SET
1198     */
1199    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1200    /**
1201     * Indicates the view is pressed and focused.
1202     *
1203     * @see #PRESSED_STATE_SET
1204     * @see #FOCUSED_STATE_SET
1205     */
1206    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1207    /**
1208     * Indicates the view is pressed, focused and its window has the focus.
1209     *
1210     * @see #PRESSED_STATE_SET
1211     * @see #FOCUSED_STATE_SET
1212     * @see #WINDOW_FOCUSED_STATE_SET
1213     */
1214    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1215    /**
1216     * Indicates the view is pressed, focused and selected.
1217     *
1218     * @see #PRESSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     * @see #FOCUSED_STATE_SET
1221     */
1222    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed, focused, selected and its window has the focus.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #FOCUSED_STATE_SET
1228     * @see #SELECTED_STATE_SET
1229     * @see #WINDOW_FOCUSED_STATE_SET
1230     */
1231    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1232    /**
1233     * Indicates the view is pressed and enabled.
1234     *
1235     * @see #PRESSED_STATE_SET
1236     * @see #ENABLED_STATE_SET
1237     */
1238    protected static final int[] PRESSED_ENABLED_STATE_SET;
1239    /**
1240     * Indicates the view is pressed, enabled and its window has the focus.
1241     *
1242     * @see #PRESSED_STATE_SET
1243     * @see #ENABLED_STATE_SET
1244     * @see #WINDOW_FOCUSED_STATE_SET
1245     */
1246    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1247    /**
1248     * Indicates the view is pressed, enabled and selected.
1249     *
1250     * @see #PRESSED_STATE_SET
1251     * @see #ENABLED_STATE_SET
1252     * @see #SELECTED_STATE_SET
1253     */
1254    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1255    /**
1256     * Indicates the view is pressed, enabled, selected and its window has the
1257     * focus.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #ENABLED_STATE_SET
1261     * @see #SELECTED_STATE_SET
1262     * @see #WINDOW_FOCUSED_STATE_SET
1263     */
1264    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1265    /**
1266     * Indicates the view is pressed, enabled and focused.
1267     *
1268     * @see #PRESSED_STATE_SET
1269     * @see #ENABLED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed, enabled, focused and its window has the
1275     * focus.
1276     *
1277     * @see #PRESSED_STATE_SET
1278     * @see #ENABLED_STATE_SET
1279     * @see #FOCUSED_STATE_SET
1280     * @see #WINDOW_FOCUSED_STATE_SET
1281     */
1282    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1283    /**
1284     * Indicates the view is pressed, enabled, focused and selected.
1285     *
1286     * @see #PRESSED_STATE_SET
1287     * @see #ENABLED_STATE_SET
1288     * @see #SELECTED_STATE_SET
1289     * @see #FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, enabled, focused, selected and its window
1294     * has the focus.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     * @see #FOCUSED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1303
1304    /**
1305     * The order here is very important to {@link #getDrawableState()}
1306     */
1307    private static final int[][] VIEW_STATE_SETS;
1308
1309    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1310    static final int VIEW_STATE_SELECTED = 1 << 1;
1311    static final int VIEW_STATE_FOCUSED = 1 << 2;
1312    static final int VIEW_STATE_ENABLED = 1 << 3;
1313    static final int VIEW_STATE_PRESSED = 1 << 4;
1314    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1315    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1316    static final int VIEW_STATE_HOVERED = 1 << 7;
1317    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1318    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1319
1320    static final int[] VIEW_STATE_IDS = new int[] {
1321        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1322        R.attr.state_selected,          VIEW_STATE_SELECTED,
1323        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1324        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1325        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1326        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1327        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1328        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1329        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1330        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1331    };
1332
1333    static {
1334        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1335            throw new IllegalStateException(
1336                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1337        }
1338        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1339        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1340            int viewState = R.styleable.ViewDrawableStates[i];
1341            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1342                if (VIEW_STATE_IDS[j] == viewState) {
1343                    orderedIds[i * 2] = viewState;
1344                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1345                }
1346            }
1347        }
1348        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1349        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1350        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1351            int numBits = Integer.bitCount(i);
1352            int[] set = new int[numBits];
1353            int pos = 0;
1354            for (int j = 0; j < orderedIds.length; j += 2) {
1355                if ((i & orderedIds[j+1]) != 0) {
1356                    set[pos++] = orderedIds[j];
1357                }
1358            }
1359            VIEW_STATE_SETS[i] = set;
1360        }
1361
1362        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1363        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1364        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1365        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1367        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1368        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1370        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1371                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1372        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1373                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1374                | VIEW_STATE_FOCUSED];
1375        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1376        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1377                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1378        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1379                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1380        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1382                | VIEW_STATE_ENABLED];
1383        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1384                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1385        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1386                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1387                | VIEW_STATE_ENABLED];
1388        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1389                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1390                | VIEW_STATE_ENABLED];
1391        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1392                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1393                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1394
1395        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1396        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1397                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1398        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1399                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1400        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1402                | VIEW_STATE_PRESSED];
1403        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1404                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1405        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1406                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1407                | VIEW_STATE_PRESSED];
1408        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1410                | VIEW_STATE_PRESSED];
1411        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1413                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1414        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1416        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1418                | VIEW_STATE_PRESSED];
1419        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1421                | VIEW_STATE_PRESSED];
1422        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1424                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1425        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1427                | VIEW_STATE_PRESSED];
1428        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1430                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1431        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1434        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1436                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1437                | VIEW_STATE_PRESSED];
1438    }
1439
1440    /**
1441     * Accessibility event types that are dispatched for text population.
1442     */
1443    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1444            AccessibilityEvent.TYPE_VIEW_CLICKED
1445            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1446            | AccessibilityEvent.TYPE_VIEW_SELECTED
1447            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1448            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1449            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1450            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1451            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1452            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1453
1454    /**
1455     * Temporary Rect currently for use in setBackground().  This will probably
1456     * be extended in the future to hold our own class with more than just
1457     * a Rect. :)
1458     */
1459    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1460
1461    /**
1462     * Temporary flag, used to enable processing of View properties in the native DisplayList
1463     * object instead of during draw(). Soon to be enabled by default for hardware-accelerated
1464     * apps.
1465     * @hide
1466     */
1467    public static final boolean USE_DISPLAY_LIST_PROPERTIES = true;
1468
1469    /**
1470     * Map used to store views' tags.
1471     */
1472    private SparseArray<Object> mKeyedTags;
1473
1474    /**
1475     * The next available accessiiblity id.
1476     */
1477    private static int sNextAccessibilityViewId;
1478
1479    /**
1480     * The animation currently associated with this view.
1481     * @hide
1482     */
1483    protected Animation mCurrentAnimation = null;
1484
1485    /**
1486     * Width as measured during measure pass.
1487     * {@hide}
1488     */
1489    @ViewDebug.ExportedProperty(category = "measurement")
1490    int mMeasuredWidth;
1491
1492    /**
1493     * Height as measured during measure pass.
1494     * {@hide}
1495     */
1496    @ViewDebug.ExportedProperty(category = "measurement")
1497    int mMeasuredHeight;
1498
1499    /**
1500     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1501     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1502     * its display list. This flag, used only when hw accelerated, allows us to clear the
1503     * flag while retaining this information until it's needed (at getDisplayList() time and
1504     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1505     *
1506     * {@hide}
1507     */
1508    boolean mRecreateDisplayList = false;
1509
1510    /**
1511     * The view's identifier.
1512     * {@hide}
1513     *
1514     * @see #setId(int)
1515     * @see #getId()
1516     */
1517    @ViewDebug.ExportedProperty(resolveId = true)
1518    int mID = NO_ID;
1519
1520    /**
1521     * The stable ID of this view for accessibility purposes.
1522     */
1523    int mAccessibilityViewId = NO_ID;
1524
1525    /**
1526     * The view's tag.
1527     * {@hide}
1528     *
1529     * @see #setTag(Object)
1530     * @see #getTag()
1531     */
1532    protected Object mTag;
1533
1534    // for mPrivateFlags:
1535    /** {@hide} */
1536    static final int WANTS_FOCUS                    = 0x00000001;
1537    /** {@hide} */
1538    static final int FOCUSED                        = 0x00000002;
1539    /** {@hide} */
1540    static final int SELECTED                       = 0x00000004;
1541    /** {@hide} */
1542    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1543    /** {@hide} */
1544    static final int HAS_BOUNDS                     = 0x00000010;
1545    /** {@hide} */
1546    static final int DRAWN                          = 0x00000020;
1547    /**
1548     * When this flag is set, this view is running an animation on behalf of its
1549     * children and should therefore not cancel invalidate requests, even if they
1550     * lie outside of this view's bounds.
1551     *
1552     * {@hide}
1553     */
1554    static final int DRAW_ANIMATION                 = 0x00000040;
1555    /** {@hide} */
1556    static final int SKIP_DRAW                      = 0x00000080;
1557    /** {@hide} */
1558    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1559    /** {@hide} */
1560    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1561    /** {@hide} */
1562    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1563    /** {@hide} */
1564    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1565    /** {@hide} */
1566    static final int FORCE_LAYOUT                   = 0x00001000;
1567    /** {@hide} */
1568    static final int LAYOUT_REQUIRED                = 0x00002000;
1569
1570    private static final int PRESSED                = 0x00004000;
1571
1572    /** {@hide} */
1573    static final int DRAWING_CACHE_VALID            = 0x00008000;
1574    /**
1575     * Flag used to indicate that this view should be drawn once more (and only once
1576     * more) after its animation has completed.
1577     * {@hide}
1578     */
1579    static final int ANIMATION_STARTED              = 0x00010000;
1580
1581    private static final int SAVE_STATE_CALLED      = 0x00020000;
1582
1583    /**
1584     * Indicates that the View returned true when onSetAlpha() was called and that
1585     * the alpha must be restored.
1586     * {@hide}
1587     */
1588    static final int ALPHA_SET                      = 0x00040000;
1589
1590    /**
1591     * Set by {@link #setScrollContainer(boolean)}.
1592     */
1593    static final int SCROLL_CONTAINER               = 0x00080000;
1594
1595    /**
1596     * Set by {@link #setScrollContainer(boolean)}.
1597     */
1598    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1599
1600    /**
1601     * View flag indicating whether this view was invalidated (fully or partially.)
1602     *
1603     * @hide
1604     */
1605    static final int DIRTY                          = 0x00200000;
1606
1607    /**
1608     * View flag indicating whether this view was invalidated by an opaque
1609     * invalidate request.
1610     *
1611     * @hide
1612     */
1613    static final int DIRTY_OPAQUE                   = 0x00400000;
1614
1615    /**
1616     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1617     *
1618     * @hide
1619     */
1620    static final int DIRTY_MASK                     = 0x00600000;
1621
1622    /**
1623     * Indicates whether the background is opaque.
1624     *
1625     * @hide
1626     */
1627    static final int OPAQUE_BACKGROUND              = 0x00800000;
1628
1629    /**
1630     * Indicates whether the scrollbars are opaque.
1631     *
1632     * @hide
1633     */
1634    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1635
1636    /**
1637     * Indicates whether the view is opaque.
1638     *
1639     * @hide
1640     */
1641    static final int OPAQUE_MASK                    = 0x01800000;
1642
1643    /**
1644     * Indicates a prepressed state;
1645     * the short time between ACTION_DOWN and recognizing
1646     * a 'real' press. Prepressed is used to recognize quick taps
1647     * even when they are shorter than ViewConfiguration.getTapTimeout().
1648     *
1649     * @hide
1650     */
1651    private static final int PREPRESSED             = 0x02000000;
1652
1653    /**
1654     * Indicates whether the view is temporarily detached.
1655     *
1656     * @hide
1657     */
1658    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1659
1660    /**
1661     * Indicates that we should awaken scroll bars once attached
1662     *
1663     * @hide
1664     */
1665    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1666
1667    /**
1668     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1669     * @hide
1670     */
1671    private static final int HOVERED              = 0x10000000;
1672
1673    /**
1674     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1675     * for transform operations
1676     *
1677     * @hide
1678     */
1679    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1680
1681    /** {@hide} */
1682    static final int ACTIVATED                    = 0x40000000;
1683
1684    /**
1685     * Indicates that this view was specifically invalidated, not just dirtied because some
1686     * child view was invalidated. The flag is used to determine when we need to recreate
1687     * a view's display list (as opposed to just returning a reference to its existing
1688     * display list).
1689     *
1690     * @hide
1691     */
1692    static final int INVALIDATED                  = 0x80000000;
1693
1694    /* Masks for mPrivateFlags2 */
1695
1696    /**
1697     * Indicates that this view has reported that it can accept the current drag's content.
1698     * Cleared when the drag operation concludes.
1699     * @hide
1700     */
1701    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1702
1703    /**
1704     * Indicates that this view is currently directly under the drag location in a
1705     * drag-and-drop operation involving content that it can accept.  Cleared when
1706     * the drag exits the view, or when the drag operation concludes.
1707     * @hide
1708     */
1709    static final int DRAG_HOVERED                 = 0x00000002;
1710
1711    /**
1712     * Horizontal layout direction of this view is from Left to Right.
1713     * Use with {@link #setLayoutDirection}.
1714     */
1715    public static final int LAYOUT_DIRECTION_LTR = 0;
1716
1717    /**
1718     * Horizontal layout direction of this view is from Right to Left.
1719     * Use with {@link #setLayoutDirection}.
1720     */
1721    public static final int LAYOUT_DIRECTION_RTL = 1;
1722
1723    /**
1724     * Horizontal layout direction of this view is inherited from its parent.
1725     * Use with {@link #setLayoutDirection}.
1726     */
1727    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1728
1729    /**
1730     * Horizontal layout direction of this view is from deduced from the default language
1731     * script for the locale. Use with {@link #setLayoutDirection}.
1732     */
1733    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1734
1735    /**
1736     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1737     * @hide
1738     */
1739    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1740
1741    /**
1742     * Mask for use with private flags indicating bits used for horizontal layout direction.
1743     * @hide
1744     */
1745    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1746
1747    /**
1748     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1749     * right-to-left direction.
1750     * @hide
1751     */
1752    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1753
1754    /**
1755     * Indicates whether the view horizontal layout direction has been resolved.
1756     * @hide
1757     */
1758    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1759
1760    /**
1761     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1762     * @hide
1763     */
1764    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1765
1766    /*
1767     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1768     * flag value.
1769     * @hide
1770     */
1771    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1772            LAYOUT_DIRECTION_LTR,
1773            LAYOUT_DIRECTION_RTL,
1774            LAYOUT_DIRECTION_INHERIT,
1775            LAYOUT_DIRECTION_LOCALE
1776    };
1777
1778    /**
1779     * Default horizontal layout direction.
1780     * @hide
1781     */
1782    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1783
1784
1785    /**
1786     * Indicates that the view is tracking some sort of transient state
1787     * that the app should not need to be aware of, but that the framework
1788     * should take special care to preserve.
1789     *
1790     * @hide
1791     */
1792    static final int HAS_TRANSIENT_STATE = 0x00000100;
1793
1794
1795    /**
1796     * Text direction is inherited thru {@link ViewGroup}
1797     */
1798    public static final int TEXT_DIRECTION_INHERIT = 0;
1799
1800    /**
1801     * Text direction is using "first strong algorithm". The first strong directional character
1802     * determines the paragraph direction. If there is no strong directional character, the
1803     * paragraph direction is the view's resolved layout direction.
1804     */
1805    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1806
1807    /**
1808     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1809     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1810     * If there are neither, the paragraph direction is the view's resolved layout direction.
1811     */
1812    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1813
1814    /**
1815     * Text direction is forced to LTR.
1816     */
1817    public static final int TEXT_DIRECTION_LTR = 3;
1818
1819    /**
1820     * Text direction is forced to RTL.
1821     */
1822    public static final int TEXT_DIRECTION_RTL = 4;
1823
1824    /**
1825     * Text direction is coming from the system Locale.
1826     */
1827    public static final int TEXT_DIRECTION_LOCALE = 5;
1828
1829    /**
1830     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1831     * @hide
1832     */
1833    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1834
1835    /**
1836     * Default text direction is inherited
1837     */
1838    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1839
1840    /**
1841     * Mask for use with private flags indicating bits used for text direction.
1842     * @hide
1843     */
1844    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1845
1846    /**
1847     * Array of text direction flags for mapping attribute "textDirection" to correct
1848     * flag value.
1849     * @hide
1850     */
1851    private static final int[] TEXT_DIRECTION_FLAGS = {
1852            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1853            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1854            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1855            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1856            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1857            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1858    };
1859
1860    /**
1861     * Indicates whether the view text direction has been resolved.
1862     * @hide
1863     */
1864    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1865
1866    /**
1867     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1868     * @hide
1869     */
1870    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1871
1872    /**
1873     * Mask for use with private flags indicating bits used for resolved text direction.
1874     * @hide
1875     */
1876    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1877
1878    /**
1879     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1880     * @hide
1881     */
1882    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1883            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1884
1885
1886    /* End of masks for mPrivateFlags2 */
1887
1888    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1889
1890    /**
1891     * Always allow a user to over-scroll this view, provided it is a
1892     * view that can scroll.
1893     *
1894     * @see #getOverScrollMode()
1895     * @see #setOverScrollMode(int)
1896     */
1897    public static final int OVER_SCROLL_ALWAYS = 0;
1898
1899    /**
1900     * Allow a user to over-scroll this view only if the content is large
1901     * enough to meaningfully scroll, provided it is a view that can scroll.
1902     *
1903     * @see #getOverScrollMode()
1904     * @see #setOverScrollMode(int)
1905     */
1906    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1907
1908    /**
1909     * Never allow a user to over-scroll this view.
1910     *
1911     * @see #getOverScrollMode()
1912     * @see #setOverScrollMode(int)
1913     */
1914    public static final int OVER_SCROLL_NEVER = 2;
1915
1916    /**
1917     * Special constant for {@link #setSystemUiVisibility(int)}: View has
1918     * requested the system UI (status bar) to be visible (the default).
1919     *
1920     * @see #setSystemUiVisibility(int)
1921     */
1922    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1923
1924    /**
1925     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
1926     * system UI to enter an unobtrusive "low profile" mode.
1927     *
1928     * <p>This is for use in games, book readers, video players, or any other
1929     * "immersive" application where the usual system chrome is deemed too distracting.
1930     *
1931     * <p>In low profile mode, the status bar and/or navigation icons may dim.
1932     *
1933     * @see #setSystemUiVisibility(int)
1934     */
1935    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1936
1937    /**
1938     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
1939     * system navigation be temporarily hidden.
1940     *
1941     * <p>This is an even less obtrusive state than that called for by
1942     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1943     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1944     * those to disappear. This is useful (in conjunction with the
1945     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1946     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1947     * window flags) for displaying content using every last pixel on the display.
1948     *
1949     * <p>There is a limitation: because navigation controls are so important, the least user
1950     * interaction will cause them to reappear immediately.  When this happens, both
1951     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
1952     * so that both elements reappear at the same time.
1953     *
1954     * @see #setSystemUiVisibility(int)
1955     */
1956    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1957
1958    /**
1959     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
1960     * into the normal fullscreen mode so that its content can take over the screen
1961     * while still allowing the user to interact with the application.
1962     *
1963     * <p>This has the same visual effect as
1964     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
1965     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
1966     * meaning that non-critical screen decorations (such as the status bar) will be
1967     * hidden while the user is in the View's window, focusing the experience on
1968     * that content.  Unlike the window flag, if you are using ActionBar in
1969     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
1970     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
1971     * hide the action bar.
1972     *
1973     * <p>This approach to going fullscreen is best used over the window flag when
1974     * it is a transient state -- that is, the application does this at certain
1975     * points in its user interaction where it wants to allow the user to focus
1976     * on content, but not as a continuous state.  For situations where the application
1977     * would like to simply stay full screen the entire time (such as a game that
1978     * wants to take over the screen), the
1979     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
1980     * is usually a better approach.  The state set here will be removed by the system
1981     * in various situations (such as the user moving to another application) like
1982     * the other system UI states.
1983     *
1984     * <p>When using this flag, the application should provide some easy facility
1985     * for the user to go out of it.  A common example would be in an e-book
1986     * reader, where tapping on the screen brings back whatever screen and UI
1987     * decorations that had been hidden while the user was immersed in reading
1988     * the book.
1989     *
1990     * @see #setSystemUiVisibility(int)
1991     */
1992    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
1993
1994    /**
1995     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
1996     * flags, we would like a stable view of the content insets given to
1997     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
1998     * will always represent the worst case that the application can expect
1999     * as a continue state.  In practice this means with any of system bar,
2000     * nav bar, and status bar shown, but not the space that would be needed
2001     * for an input method.
2002     *
2003     * <p>If you are using ActionBar in
2004     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2005     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2006     * insets it adds to those given to the application.
2007     */
2008    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2009
2010    /**
2011     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2012     * to be layed out as if it has requested
2013     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2014     * allows it to avoid artifacts when switching in and out of that mode, at
2015     * the expense that some of its user interface may be covered by screen
2016     * decorations when they are shown.  You can perform layout of your inner
2017     * UI elements to account for the navagation system UI through the
2018     * {@link #fitSystemWindows(Rect)} method.
2019     */
2020    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2021
2022    /**
2023     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2024     * to be layed out as if it has requested
2025     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2026     * allows it to avoid artifacts when switching in and out of that mode, at
2027     * the expense that some of its user interface may be covered by screen
2028     * decorations when they are shown.  You can perform layout of your inner
2029     * UI elements to account for non-fullscreen system UI through the
2030     * {@link #fitSystemWindows(Rect)} method.
2031     */
2032    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2033
2034    /**
2035     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2036     */
2037    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2038
2039    /**
2040     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2041     */
2042    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2043
2044    /**
2045     * @hide
2046     *
2047     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2048     * out of the public fields to keep the undefined bits out of the developer's way.
2049     *
2050     * Flag to make the status bar not expandable.  Unless you also
2051     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2052     */
2053    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2054
2055    /**
2056     * @hide
2057     *
2058     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2059     * out of the public fields to keep the undefined bits out of the developer's way.
2060     *
2061     * Flag to hide notification icons and scrolling ticker text.
2062     */
2063    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2064
2065    /**
2066     * @hide
2067     *
2068     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2069     * out of the public fields to keep the undefined bits out of the developer's way.
2070     *
2071     * Flag to disable incoming notification alerts.  This will not block
2072     * icons, but it will block sound, vibrating and other visual or aural notifications.
2073     */
2074    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2075
2076    /**
2077     * @hide
2078     *
2079     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2080     * out of the public fields to keep the undefined bits out of the developer's way.
2081     *
2082     * Flag to hide only the scrolling ticker.  Note that
2083     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2084     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2085     */
2086    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2087
2088    /**
2089     * @hide
2090     *
2091     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2092     * out of the public fields to keep the undefined bits out of the developer's way.
2093     *
2094     * Flag to hide the center system info area.
2095     */
2096    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2097
2098    /**
2099     * @hide
2100     *
2101     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2102     * out of the public fields to keep the undefined bits out of the developer's way.
2103     *
2104     * Flag to hide only the home button.  Don't use this
2105     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2106     */
2107    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2108
2109    /**
2110     * @hide
2111     *
2112     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2113     * out of the public fields to keep the undefined bits out of the developer's way.
2114     *
2115     * Flag to hide only the back button. Don't use this
2116     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2117     */
2118    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2119
2120    /**
2121     * @hide
2122     *
2123     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2124     * out of the public fields to keep the undefined bits out of the developer's way.
2125     *
2126     * Flag to hide only the clock.  You might use this if your activity has
2127     * its own clock making the status bar's clock redundant.
2128     */
2129    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2130
2131    /**
2132     * @hide
2133     *
2134     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2135     * out of the public fields to keep the undefined bits out of the developer's way.
2136     *
2137     * Flag to hide only the recent apps button. Don't use this
2138     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2139     */
2140    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2141
2142    /**
2143     * @hide
2144     */
2145    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2146
2147    /**
2148     * These are the system UI flags that can be cleared by events outside
2149     * of an application.  Currently this is just the ability to tap on the
2150     * screen while hiding the navigation bar to have it return.
2151     * @hide
2152     */
2153    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2154            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2155            | SYSTEM_UI_FLAG_FULLSCREEN;
2156
2157    /**
2158     * Flags that can impact the layout in relation to system UI.
2159     */
2160    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2161            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2162            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2163
2164    /**
2165     * Find views that render the specified text.
2166     *
2167     * @see #findViewsWithText(ArrayList, CharSequence, int)
2168     */
2169    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2170
2171    /**
2172     * Find find views that contain the specified content description.
2173     *
2174     * @see #findViewsWithText(ArrayList, CharSequence, int)
2175     */
2176    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2177
2178    /**
2179     * Find views that contain {@link AccessibilityNodeProvider}. Such
2180     * a View is a root of virtual view hierarchy and may contain the searched
2181     * text. If this flag is set Views with providers are automatically
2182     * added and it is a responsibility of the client to call the APIs of
2183     * the provider to determine whether the virtual tree rooted at this View
2184     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2185     * represeting the virtual views with this text.
2186     *
2187     * @see #findViewsWithText(ArrayList, CharSequence, int)
2188     *
2189     * @hide
2190     */
2191    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2192
2193    /**
2194     * Indicates that the screen has changed state and is now off.
2195     *
2196     * @see #onScreenStateChanged(int)
2197     */
2198    public static final int SCREEN_STATE_OFF = 0x0;
2199
2200    /**
2201     * Indicates that the screen has changed state and is now on.
2202     *
2203     * @see #onScreenStateChanged(int)
2204     */
2205    public static final int SCREEN_STATE_ON = 0x1;
2206
2207    /**
2208     * Controls the over-scroll mode for this view.
2209     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2210     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2211     * and {@link #OVER_SCROLL_NEVER}.
2212     */
2213    private int mOverScrollMode;
2214
2215    /**
2216     * The parent this view is attached to.
2217     * {@hide}
2218     *
2219     * @see #getParent()
2220     */
2221    protected ViewParent mParent;
2222
2223    /**
2224     * {@hide}
2225     */
2226    AttachInfo mAttachInfo;
2227
2228    /**
2229     * {@hide}
2230     */
2231    @ViewDebug.ExportedProperty(flagMapping = {
2232        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2233                name = "FORCE_LAYOUT"),
2234        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2235                name = "LAYOUT_REQUIRED"),
2236        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2237            name = "DRAWING_CACHE_INVALID", outputIf = false),
2238        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2239        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2240        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2241        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2242    })
2243    int mPrivateFlags;
2244    int mPrivateFlags2;
2245
2246    /**
2247     * This view's request for the visibility of the status bar.
2248     * @hide
2249     */
2250    @ViewDebug.ExportedProperty(flagMapping = {
2251        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2252                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2253                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2254        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2255                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2256                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2257        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2258                                equals = SYSTEM_UI_FLAG_VISIBLE,
2259                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2260    })
2261    int mSystemUiVisibility;
2262
2263    /**
2264     * Count of how many windows this view has been attached to.
2265     */
2266    int mWindowAttachCount;
2267
2268    /**
2269     * The layout parameters associated with this view and used by the parent
2270     * {@link android.view.ViewGroup} to determine how this view should be
2271     * laid out.
2272     * {@hide}
2273     */
2274    protected ViewGroup.LayoutParams mLayoutParams;
2275
2276    /**
2277     * The view flags hold various views states.
2278     * {@hide}
2279     */
2280    @ViewDebug.ExportedProperty
2281    int mViewFlags;
2282
2283    static class TransformationInfo {
2284        /**
2285         * The transform matrix for the View. This transform is calculated internally
2286         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2287         * is used by default. Do *not* use this variable directly; instead call
2288         * getMatrix(), which will automatically recalculate the matrix if necessary
2289         * to get the correct matrix based on the latest rotation and scale properties.
2290         */
2291        private final Matrix mMatrix = new Matrix();
2292
2293        /**
2294         * The transform matrix for the View. This transform is calculated internally
2295         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2296         * is used by default. Do *not* use this variable directly; instead call
2297         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2298         * to get the correct matrix based on the latest rotation and scale properties.
2299         */
2300        private Matrix mInverseMatrix;
2301
2302        /**
2303         * An internal variable that tracks whether we need to recalculate the
2304         * transform matrix, based on whether the rotation or scaleX/Y properties
2305         * have changed since the matrix was last calculated.
2306         */
2307        boolean mMatrixDirty = false;
2308
2309        /**
2310         * An internal variable that tracks whether we need to recalculate the
2311         * transform matrix, based on whether the rotation or scaleX/Y properties
2312         * have changed since the matrix was last calculated.
2313         */
2314        private boolean mInverseMatrixDirty = true;
2315
2316        /**
2317         * A variable that tracks whether we need to recalculate the
2318         * transform matrix, based on whether the rotation or scaleX/Y properties
2319         * have changed since the matrix was last calculated. This variable
2320         * is only valid after a call to updateMatrix() or to a function that
2321         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2322         */
2323        private boolean mMatrixIsIdentity = true;
2324
2325        /**
2326         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2327         */
2328        private Camera mCamera = null;
2329
2330        /**
2331         * This matrix is used when computing the matrix for 3D rotations.
2332         */
2333        private Matrix matrix3D = null;
2334
2335        /**
2336         * These prev values are used to recalculate a centered pivot point when necessary. The
2337         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2338         * set), so thes values are only used then as well.
2339         */
2340        private int mPrevWidth = -1;
2341        private int mPrevHeight = -1;
2342
2343        /**
2344         * The degrees rotation around the vertical axis through the pivot point.
2345         */
2346        @ViewDebug.ExportedProperty
2347        float mRotationY = 0f;
2348
2349        /**
2350         * The degrees rotation around the horizontal axis through the pivot point.
2351         */
2352        @ViewDebug.ExportedProperty
2353        float mRotationX = 0f;
2354
2355        /**
2356         * The degrees rotation around the pivot point.
2357         */
2358        @ViewDebug.ExportedProperty
2359        float mRotation = 0f;
2360
2361        /**
2362         * The amount of translation of the object away from its left property (post-layout).
2363         */
2364        @ViewDebug.ExportedProperty
2365        float mTranslationX = 0f;
2366
2367        /**
2368         * The amount of translation of the object away from its top property (post-layout).
2369         */
2370        @ViewDebug.ExportedProperty
2371        float mTranslationY = 0f;
2372
2373        /**
2374         * The amount of scale in the x direction around the pivot point. A
2375         * value of 1 means no scaling is applied.
2376         */
2377        @ViewDebug.ExportedProperty
2378        float mScaleX = 1f;
2379
2380        /**
2381         * The amount of scale in the y direction around the pivot point. A
2382         * value of 1 means no scaling is applied.
2383         */
2384        @ViewDebug.ExportedProperty
2385        float mScaleY = 1f;
2386
2387        /**
2388         * The x location of the point around which the view is rotated and scaled.
2389         */
2390        @ViewDebug.ExportedProperty
2391        float mPivotX = 0f;
2392
2393        /**
2394         * The y location of the point around which the view is rotated and scaled.
2395         */
2396        @ViewDebug.ExportedProperty
2397        float mPivotY = 0f;
2398
2399        /**
2400         * The opacity of the View. This is a value from 0 to 1, where 0 means
2401         * completely transparent and 1 means completely opaque.
2402         */
2403        @ViewDebug.ExportedProperty
2404        float mAlpha = 1f;
2405    }
2406
2407    TransformationInfo mTransformationInfo;
2408
2409    private boolean mLastIsOpaque;
2410
2411    /**
2412     * Convenience value to check for float values that are close enough to zero to be considered
2413     * zero.
2414     */
2415    private static final float NONZERO_EPSILON = .001f;
2416
2417    /**
2418     * The distance in pixels from the left edge of this view's parent
2419     * to the left edge of this view.
2420     * {@hide}
2421     */
2422    @ViewDebug.ExportedProperty(category = "layout")
2423    protected int mLeft;
2424    /**
2425     * The distance in pixels from the left edge of this view's parent
2426     * to the right edge of this view.
2427     * {@hide}
2428     */
2429    @ViewDebug.ExportedProperty(category = "layout")
2430    protected int mRight;
2431    /**
2432     * The distance in pixels from the top edge of this view's parent
2433     * to the top edge of this view.
2434     * {@hide}
2435     */
2436    @ViewDebug.ExportedProperty(category = "layout")
2437    protected int mTop;
2438    /**
2439     * The distance in pixels from the top edge of this view's parent
2440     * to the bottom edge of this view.
2441     * {@hide}
2442     */
2443    @ViewDebug.ExportedProperty(category = "layout")
2444    protected int mBottom;
2445
2446    /**
2447     * The offset, in pixels, by which the content of this view is scrolled
2448     * horizontally.
2449     * {@hide}
2450     */
2451    @ViewDebug.ExportedProperty(category = "scrolling")
2452    protected int mScrollX;
2453    /**
2454     * The offset, in pixels, by which the content of this view is scrolled
2455     * vertically.
2456     * {@hide}
2457     */
2458    @ViewDebug.ExportedProperty(category = "scrolling")
2459    protected int mScrollY;
2460
2461    /**
2462     * The left padding in pixels, that is the distance in pixels between the
2463     * left edge of this view and the left edge of its content.
2464     * {@hide}
2465     */
2466    @ViewDebug.ExportedProperty(category = "padding")
2467    protected int mPaddingLeft;
2468    /**
2469     * The right padding in pixels, that is the distance in pixels between the
2470     * right edge of this view and the right edge of its content.
2471     * {@hide}
2472     */
2473    @ViewDebug.ExportedProperty(category = "padding")
2474    protected int mPaddingRight;
2475    /**
2476     * The top padding in pixels, that is the distance in pixels between the
2477     * top edge of this view and the top edge of its content.
2478     * {@hide}
2479     */
2480    @ViewDebug.ExportedProperty(category = "padding")
2481    protected int mPaddingTop;
2482    /**
2483     * The bottom padding in pixels, that is the distance in pixels between the
2484     * bottom edge of this view and the bottom edge of its content.
2485     * {@hide}
2486     */
2487    @ViewDebug.ExportedProperty(category = "padding")
2488    protected int mPaddingBottom;
2489
2490    /**
2491     * Briefly describes the view and is primarily used for accessibility support.
2492     */
2493    private CharSequence mContentDescription;
2494
2495    /**
2496     * Cache the paddingRight set by the user to append to the scrollbar's size.
2497     *
2498     * @hide
2499     */
2500    @ViewDebug.ExportedProperty(category = "padding")
2501    protected int mUserPaddingRight;
2502
2503    /**
2504     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2505     *
2506     * @hide
2507     */
2508    @ViewDebug.ExportedProperty(category = "padding")
2509    protected int mUserPaddingBottom;
2510
2511    /**
2512     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2513     *
2514     * @hide
2515     */
2516    @ViewDebug.ExportedProperty(category = "padding")
2517    protected int mUserPaddingLeft;
2518
2519    /**
2520     * Cache if the user padding is relative.
2521     *
2522     */
2523    @ViewDebug.ExportedProperty(category = "padding")
2524    boolean mUserPaddingRelative;
2525
2526    /**
2527     * Cache the paddingStart set by the user to append to the scrollbar's size.
2528     *
2529     */
2530    @ViewDebug.ExportedProperty(category = "padding")
2531    int mUserPaddingStart;
2532
2533    /**
2534     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2535     *
2536     */
2537    @ViewDebug.ExportedProperty(category = "padding")
2538    int mUserPaddingEnd;
2539
2540    /**
2541     * @hide
2542     */
2543    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2544    /**
2545     * @hide
2546     */
2547    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2548
2549    private Drawable mBGDrawable;
2550
2551    private int mBackgroundResource;
2552    private boolean mBackgroundSizeChanged;
2553
2554    static class ListenerInfo {
2555        /**
2556         * Listener used to dispatch focus change events.
2557         * This field should be made private, so it is hidden from the SDK.
2558         * {@hide}
2559         */
2560        protected OnFocusChangeListener mOnFocusChangeListener;
2561
2562        /**
2563         * Listeners for layout change events.
2564         */
2565        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2566
2567        /**
2568         * Listeners for attach events.
2569         */
2570        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2571
2572        /**
2573         * Listener used to dispatch click events.
2574         * This field should be made private, so it is hidden from the SDK.
2575         * {@hide}
2576         */
2577        public OnClickListener mOnClickListener;
2578
2579        /**
2580         * Listener used to dispatch long click events.
2581         * This field should be made private, so it is hidden from the SDK.
2582         * {@hide}
2583         */
2584        protected OnLongClickListener mOnLongClickListener;
2585
2586        /**
2587         * Listener used to build the context menu.
2588         * This field should be made private, so it is hidden from the SDK.
2589         * {@hide}
2590         */
2591        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2592
2593        private OnKeyListener mOnKeyListener;
2594
2595        private OnTouchListener mOnTouchListener;
2596
2597        private OnHoverListener mOnHoverListener;
2598
2599        private OnGenericMotionListener mOnGenericMotionListener;
2600
2601        private OnDragListener mOnDragListener;
2602
2603        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2604    }
2605
2606    ListenerInfo mListenerInfo;
2607
2608    /**
2609     * The application environment this view lives in.
2610     * This field should be made private, so it is hidden from the SDK.
2611     * {@hide}
2612     */
2613    protected Context mContext;
2614
2615    private final Resources mResources;
2616
2617    private ScrollabilityCache mScrollCache;
2618
2619    private int[] mDrawableState = null;
2620
2621    /**
2622     * Set to true when drawing cache is enabled and cannot be created.
2623     *
2624     * @hide
2625     */
2626    public boolean mCachingFailed;
2627
2628    private Bitmap mDrawingCache;
2629    private Bitmap mUnscaledDrawingCache;
2630    private HardwareLayer mHardwareLayer;
2631    DisplayList mDisplayList;
2632
2633    /**
2634     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2635     * the user may specify which view to go to next.
2636     */
2637    private int mNextFocusLeftId = View.NO_ID;
2638
2639    /**
2640     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2641     * the user may specify which view to go to next.
2642     */
2643    private int mNextFocusRightId = View.NO_ID;
2644
2645    /**
2646     * When this view has focus and the next focus is {@link #FOCUS_UP},
2647     * the user may specify which view to go to next.
2648     */
2649    private int mNextFocusUpId = View.NO_ID;
2650
2651    /**
2652     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2653     * the user may specify which view to go to next.
2654     */
2655    private int mNextFocusDownId = View.NO_ID;
2656
2657    /**
2658     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2659     * the user may specify which view to go to next.
2660     */
2661    int mNextFocusForwardId = View.NO_ID;
2662
2663    private CheckForLongPress mPendingCheckForLongPress;
2664    private CheckForTap mPendingCheckForTap = null;
2665    private PerformClick mPerformClick;
2666    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2667
2668    private UnsetPressedState mUnsetPressedState;
2669
2670    /**
2671     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2672     * up event while a long press is invoked as soon as the long press duration is reached, so
2673     * a long press could be performed before the tap is checked, in which case the tap's action
2674     * should not be invoked.
2675     */
2676    private boolean mHasPerformedLongPress;
2677
2678    /**
2679     * The minimum height of the view. We'll try our best to have the height
2680     * of this view to at least this amount.
2681     */
2682    @ViewDebug.ExportedProperty(category = "measurement")
2683    private int mMinHeight;
2684
2685    /**
2686     * The minimum width of the view. We'll try our best to have the width
2687     * of this view to at least this amount.
2688     */
2689    @ViewDebug.ExportedProperty(category = "measurement")
2690    private int mMinWidth;
2691
2692    /**
2693     * The delegate to handle touch events that are physically in this view
2694     * but should be handled by another view.
2695     */
2696    private TouchDelegate mTouchDelegate = null;
2697
2698    /**
2699     * Solid color to use as a background when creating the drawing cache. Enables
2700     * the cache to use 16 bit bitmaps instead of 32 bit.
2701     */
2702    private int mDrawingCacheBackgroundColor = 0;
2703
2704    /**
2705     * Special tree observer used when mAttachInfo is null.
2706     */
2707    private ViewTreeObserver mFloatingTreeObserver;
2708
2709    /**
2710     * Cache the touch slop from the context that created the view.
2711     */
2712    private int mTouchSlop;
2713
2714    /**
2715     * Object that handles automatic animation of view properties.
2716     */
2717    private ViewPropertyAnimator mAnimator = null;
2718
2719    /**
2720     * Flag indicating that a drag can cross window boundaries.  When
2721     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2722     * with this flag set, all visible applications will be able to participate
2723     * in the drag operation and receive the dragged content.
2724     *
2725     * @hide
2726     */
2727    public static final int DRAG_FLAG_GLOBAL = 1;
2728
2729    /**
2730     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2731     */
2732    private float mVerticalScrollFactor;
2733
2734    /**
2735     * Position of the vertical scroll bar.
2736     */
2737    private int mVerticalScrollbarPosition;
2738
2739    /**
2740     * Position the scroll bar at the default position as determined by the system.
2741     */
2742    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2743
2744    /**
2745     * Position the scroll bar along the left edge.
2746     */
2747    public static final int SCROLLBAR_POSITION_LEFT = 1;
2748
2749    /**
2750     * Position the scroll bar along the right edge.
2751     */
2752    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2753
2754    /**
2755     * Indicates that the view does not have a layer.
2756     *
2757     * @see #getLayerType()
2758     * @see #setLayerType(int, android.graphics.Paint)
2759     * @see #LAYER_TYPE_SOFTWARE
2760     * @see #LAYER_TYPE_HARDWARE
2761     */
2762    public static final int LAYER_TYPE_NONE = 0;
2763
2764    /**
2765     * <p>Indicates that the view has a software layer. A software layer is backed
2766     * by a bitmap and causes the view to be rendered using Android's software
2767     * rendering pipeline, even if hardware acceleration is enabled.</p>
2768     *
2769     * <p>Software layers have various usages:</p>
2770     * <p>When the application is not using hardware acceleration, a software layer
2771     * is useful to apply a specific color filter and/or blending mode and/or
2772     * translucency to a view and all its children.</p>
2773     * <p>When the application is using hardware acceleration, a software layer
2774     * is useful to render drawing primitives not supported by the hardware
2775     * accelerated pipeline. It can also be used to cache a complex view tree
2776     * into a texture and reduce the complexity of drawing operations. For instance,
2777     * when animating a complex view tree with a translation, a software layer can
2778     * be used to render the view tree only once.</p>
2779     * <p>Software layers should be avoided when the affected view tree updates
2780     * often. Every update will require to re-render the software layer, which can
2781     * potentially be slow (particularly when hardware acceleration is turned on
2782     * since the layer will have to be uploaded into a hardware texture after every
2783     * update.)</p>
2784     *
2785     * @see #getLayerType()
2786     * @see #setLayerType(int, android.graphics.Paint)
2787     * @see #LAYER_TYPE_NONE
2788     * @see #LAYER_TYPE_HARDWARE
2789     */
2790    public static final int LAYER_TYPE_SOFTWARE = 1;
2791
2792    /**
2793     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2794     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2795     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2796     * rendering pipeline, but only if hardware acceleration is turned on for the
2797     * view hierarchy. When hardware acceleration is turned off, hardware layers
2798     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2799     *
2800     * <p>A hardware layer is useful to apply a specific color filter and/or
2801     * blending mode and/or translucency to a view and all its children.</p>
2802     * <p>A hardware layer can be used to cache a complex view tree into a
2803     * texture and reduce the complexity of drawing operations. For instance,
2804     * when animating a complex view tree with a translation, a hardware layer can
2805     * be used to render the view tree only once.</p>
2806     * <p>A hardware layer can also be used to increase the rendering quality when
2807     * rotation transformations are applied on a view. It can also be used to
2808     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2809     *
2810     * @see #getLayerType()
2811     * @see #setLayerType(int, android.graphics.Paint)
2812     * @see #LAYER_TYPE_NONE
2813     * @see #LAYER_TYPE_SOFTWARE
2814     */
2815    public static final int LAYER_TYPE_HARDWARE = 2;
2816
2817    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2818            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2819            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2820            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2821    })
2822    int mLayerType = LAYER_TYPE_NONE;
2823    Paint mLayerPaint;
2824    Rect mLocalDirtyRect;
2825
2826    /**
2827     * Set to true when the view is sending hover accessibility events because it
2828     * is the innermost hovered view.
2829     */
2830    private boolean mSendingHoverAccessibilityEvents;
2831
2832    /**
2833     * Simple constructor to use when creating a view from code.
2834     *
2835     * @param context The Context the view is running in, through which it can
2836     *        access the current theme, resources, etc.
2837     */
2838    public View(Context context) {
2839        mContext = context;
2840        mResources = context != null ? context.getResources() : null;
2841        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
2842        // Set layout and text direction defaults
2843        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
2844                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT);
2845        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2846        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2847        mUserPaddingStart = -1;
2848        mUserPaddingEnd = -1;
2849        mUserPaddingRelative = false;
2850    }
2851
2852    /**
2853     * Delegate for injecting accessiblity functionality.
2854     */
2855    AccessibilityDelegate mAccessibilityDelegate;
2856
2857    /**
2858     * Consistency verifier for debugging purposes.
2859     * @hide
2860     */
2861    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2862            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2863                    new InputEventConsistencyVerifier(this, 0) : null;
2864
2865    /**
2866     * Constructor that is called when inflating a view from XML. This is called
2867     * when a view is being constructed from an XML file, supplying attributes
2868     * that were specified in the XML file. This version uses a default style of
2869     * 0, so the only attribute values applied are those in the Context's Theme
2870     * and the given AttributeSet.
2871     *
2872     * <p>
2873     * The method onFinishInflate() will be called after all children have been
2874     * added.
2875     *
2876     * @param context The Context the view is running in, through which it can
2877     *        access the current theme, resources, etc.
2878     * @param attrs The attributes of the XML tag that is inflating the view.
2879     * @see #View(Context, AttributeSet, int)
2880     */
2881    public View(Context context, AttributeSet attrs) {
2882        this(context, attrs, 0);
2883    }
2884
2885    /**
2886     * Perform inflation from XML and apply a class-specific base style. This
2887     * constructor of View allows subclasses to use their own base style when
2888     * they are inflating. For example, a Button class's constructor would call
2889     * this version of the super class constructor and supply
2890     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2891     * the theme's button style to modify all of the base view attributes (in
2892     * particular its background) as well as the Button class's attributes.
2893     *
2894     * @param context The Context the view is running in, through which it can
2895     *        access the current theme, resources, etc.
2896     * @param attrs The attributes of the XML tag that is inflating the view.
2897     * @param defStyle The default style to apply to this view. If 0, no style
2898     *        will be applied (beyond what is included in the theme). This may
2899     *        either be an attribute resource, whose value will be retrieved
2900     *        from the current theme, or an explicit style resource.
2901     * @see #View(Context, AttributeSet)
2902     */
2903    public View(Context context, AttributeSet attrs, int defStyle) {
2904        this(context);
2905
2906        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2907                defStyle, 0);
2908
2909        Drawable background = null;
2910
2911        int leftPadding = -1;
2912        int topPadding = -1;
2913        int rightPadding = -1;
2914        int bottomPadding = -1;
2915        int startPadding = -1;
2916        int endPadding = -1;
2917
2918        int padding = -1;
2919
2920        int viewFlagValues = 0;
2921        int viewFlagMasks = 0;
2922
2923        boolean setScrollContainer = false;
2924
2925        int x = 0;
2926        int y = 0;
2927
2928        float tx = 0;
2929        float ty = 0;
2930        float rotation = 0;
2931        float rotationX = 0;
2932        float rotationY = 0;
2933        float sx = 1f;
2934        float sy = 1f;
2935        boolean transformSet = false;
2936
2937        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2938
2939        int overScrollMode = mOverScrollMode;
2940        final int N = a.getIndexCount();
2941        for (int i = 0; i < N; i++) {
2942            int attr = a.getIndex(i);
2943            switch (attr) {
2944                case com.android.internal.R.styleable.View_background:
2945                    background = a.getDrawable(attr);
2946                    break;
2947                case com.android.internal.R.styleable.View_padding:
2948                    padding = a.getDimensionPixelSize(attr, -1);
2949                    break;
2950                 case com.android.internal.R.styleable.View_paddingLeft:
2951                    leftPadding = a.getDimensionPixelSize(attr, -1);
2952                    break;
2953                case com.android.internal.R.styleable.View_paddingTop:
2954                    topPadding = a.getDimensionPixelSize(attr, -1);
2955                    break;
2956                case com.android.internal.R.styleable.View_paddingRight:
2957                    rightPadding = a.getDimensionPixelSize(attr, -1);
2958                    break;
2959                case com.android.internal.R.styleable.View_paddingBottom:
2960                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2961                    break;
2962                case com.android.internal.R.styleable.View_paddingStart:
2963                    startPadding = a.getDimensionPixelSize(attr, -1);
2964                    break;
2965                case com.android.internal.R.styleable.View_paddingEnd:
2966                    endPadding = a.getDimensionPixelSize(attr, -1);
2967                    break;
2968                case com.android.internal.R.styleable.View_scrollX:
2969                    x = a.getDimensionPixelOffset(attr, 0);
2970                    break;
2971                case com.android.internal.R.styleable.View_scrollY:
2972                    y = a.getDimensionPixelOffset(attr, 0);
2973                    break;
2974                case com.android.internal.R.styleable.View_alpha:
2975                    setAlpha(a.getFloat(attr, 1f));
2976                    break;
2977                case com.android.internal.R.styleable.View_transformPivotX:
2978                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2979                    break;
2980                case com.android.internal.R.styleable.View_transformPivotY:
2981                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2982                    break;
2983                case com.android.internal.R.styleable.View_translationX:
2984                    tx = a.getDimensionPixelOffset(attr, 0);
2985                    transformSet = true;
2986                    break;
2987                case com.android.internal.R.styleable.View_translationY:
2988                    ty = a.getDimensionPixelOffset(attr, 0);
2989                    transformSet = true;
2990                    break;
2991                case com.android.internal.R.styleable.View_rotation:
2992                    rotation = a.getFloat(attr, 0);
2993                    transformSet = true;
2994                    break;
2995                case com.android.internal.R.styleable.View_rotationX:
2996                    rotationX = a.getFloat(attr, 0);
2997                    transformSet = true;
2998                    break;
2999                case com.android.internal.R.styleable.View_rotationY:
3000                    rotationY = a.getFloat(attr, 0);
3001                    transformSet = true;
3002                    break;
3003                case com.android.internal.R.styleable.View_scaleX:
3004                    sx = a.getFloat(attr, 1f);
3005                    transformSet = true;
3006                    break;
3007                case com.android.internal.R.styleable.View_scaleY:
3008                    sy = a.getFloat(attr, 1f);
3009                    transformSet = true;
3010                    break;
3011                case com.android.internal.R.styleable.View_id:
3012                    mID = a.getResourceId(attr, NO_ID);
3013                    break;
3014                case com.android.internal.R.styleable.View_tag:
3015                    mTag = a.getText(attr);
3016                    break;
3017                case com.android.internal.R.styleable.View_fitsSystemWindows:
3018                    if (a.getBoolean(attr, false)) {
3019                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3020                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3021                    }
3022                    break;
3023                case com.android.internal.R.styleable.View_focusable:
3024                    if (a.getBoolean(attr, false)) {
3025                        viewFlagValues |= FOCUSABLE;
3026                        viewFlagMasks |= FOCUSABLE_MASK;
3027                    }
3028                    break;
3029                case com.android.internal.R.styleable.View_focusableInTouchMode:
3030                    if (a.getBoolean(attr, false)) {
3031                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3032                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3033                    }
3034                    break;
3035                case com.android.internal.R.styleable.View_clickable:
3036                    if (a.getBoolean(attr, false)) {
3037                        viewFlagValues |= CLICKABLE;
3038                        viewFlagMasks |= CLICKABLE;
3039                    }
3040                    break;
3041                case com.android.internal.R.styleable.View_longClickable:
3042                    if (a.getBoolean(attr, false)) {
3043                        viewFlagValues |= LONG_CLICKABLE;
3044                        viewFlagMasks |= LONG_CLICKABLE;
3045                    }
3046                    break;
3047                case com.android.internal.R.styleable.View_saveEnabled:
3048                    if (!a.getBoolean(attr, true)) {
3049                        viewFlagValues |= SAVE_DISABLED;
3050                        viewFlagMasks |= SAVE_DISABLED_MASK;
3051                    }
3052                    break;
3053                case com.android.internal.R.styleable.View_duplicateParentState:
3054                    if (a.getBoolean(attr, false)) {
3055                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3056                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3057                    }
3058                    break;
3059                case com.android.internal.R.styleable.View_visibility:
3060                    final int visibility = a.getInt(attr, 0);
3061                    if (visibility != 0) {
3062                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3063                        viewFlagMasks |= VISIBILITY_MASK;
3064                    }
3065                    break;
3066                case com.android.internal.R.styleable.View_layoutDirection:
3067                    // Clear any layout direction flags (included resolved bits) already set
3068                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3069                    // Set the layout direction flags depending on the value of the attribute
3070                    final int layoutDirection = a.getInt(attr, -1);
3071                    final int value = (layoutDirection != -1) ?
3072                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3073                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3074                    break;
3075                case com.android.internal.R.styleable.View_drawingCacheQuality:
3076                    final int cacheQuality = a.getInt(attr, 0);
3077                    if (cacheQuality != 0) {
3078                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3079                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3080                    }
3081                    break;
3082                case com.android.internal.R.styleable.View_contentDescription:
3083                    mContentDescription = a.getString(attr);
3084                    break;
3085                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3086                    if (!a.getBoolean(attr, true)) {
3087                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3088                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3089                    }
3090                    break;
3091                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3092                    if (!a.getBoolean(attr, true)) {
3093                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3094                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3095                    }
3096                    break;
3097                case R.styleable.View_scrollbars:
3098                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3099                    if (scrollbars != SCROLLBARS_NONE) {
3100                        viewFlagValues |= scrollbars;
3101                        viewFlagMasks |= SCROLLBARS_MASK;
3102                        initializeScrollbars(a);
3103                    }
3104                    break;
3105                //noinspection deprecation
3106                case R.styleable.View_fadingEdge:
3107                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3108                        // Ignore the attribute starting with ICS
3109                        break;
3110                    }
3111                    // With builds < ICS, fall through and apply fading edges
3112                case R.styleable.View_requiresFadingEdge:
3113                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3114                    if (fadingEdge != FADING_EDGE_NONE) {
3115                        viewFlagValues |= fadingEdge;
3116                        viewFlagMasks |= FADING_EDGE_MASK;
3117                        initializeFadingEdge(a);
3118                    }
3119                    break;
3120                case R.styleable.View_scrollbarStyle:
3121                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3122                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3123                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3124                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3125                    }
3126                    break;
3127                case R.styleable.View_isScrollContainer:
3128                    setScrollContainer = true;
3129                    if (a.getBoolean(attr, false)) {
3130                        setScrollContainer(true);
3131                    }
3132                    break;
3133                case com.android.internal.R.styleable.View_keepScreenOn:
3134                    if (a.getBoolean(attr, false)) {
3135                        viewFlagValues |= KEEP_SCREEN_ON;
3136                        viewFlagMasks |= KEEP_SCREEN_ON;
3137                    }
3138                    break;
3139                case R.styleable.View_filterTouchesWhenObscured:
3140                    if (a.getBoolean(attr, false)) {
3141                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3142                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3143                    }
3144                    break;
3145                case R.styleable.View_nextFocusLeft:
3146                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3147                    break;
3148                case R.styleable.View_nextFocusRight:
3149                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3150                    break;
3151                case R.styleable.View_nextFocusUp:
3152                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3153                    break;
3154                case R.styleable.View_nextFocusDown:
3155                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3156                    break;
3157                case R.styleable.View_nextFocusForward:
3158                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3159                    break;
3160                case R.styleable.View_minWidth:
3161                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3162                    break;
3163                case R.styleable.View_minHeight:
3164                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3165                    break;
3166                case R.styleable.View_onClick:
3167                    if (context.isRestricted()) {
3168                        throw new IllegalStateException("The android:onClick attribute cannot "
3169                                + "be used within a restricted context");
3170                    }
3171
3172                    final String handlerName = a.getString(attr);
3173                    if (handlerName != null) {
3174                        setOnClickListener(new OnClickListener() {
3175                            private Method mHandler;
3176
3177                            public void onClick(View v) {
3178                                if (mHandler == null) {
3179                                    try {
3180                                        mHandler = getContext().getClass().getMethod(handlerName,
3181                                                View.class);
3182                                    } catch (NoSuchMethodException e) {
3183                                        int id = getId();
3184                                        String idText = id == NO_ID ? "" : " with id '"
3185                                                + getContext().getResources().getResourceEntryName(
3186                                                    id) + "'";
3187                                        throw new IllegalStateException("Could not find a method " +
3188                                                handlerName + "(View) in the activity "
3189                                                + getContext().getClass() + " for onClick handler"
3190                                                + " on view " + View.this.getClass() + idText, e);
3191                                    }
3192                                }
3193
3194                                try {
3195                                    mHandler.invoke(getContext(), View.this);
3196                                } catch (IllegalAccessException e) {
3197                                    throw new IllegalStateException("Could not execute non "
3198                                            + "public method of the activity", e);
3199                                } catch (InvocationTargetException e) {
3200                                    throw new IllegalStateException("Could not execute "
3201                                            + "method of the activity", e);
3202                                }
3203                            }
3204                        });
3205                    }
3206                    break;
3207                case R.styleable.View_overScrollMode:
3208                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3209                    break;
3210                case R.styleable.View_verticalScrollbarPosition:
3211                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3212                    break;
3213                case R.styleable.View_layerType:
3214                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3215                    break;
3216                case R.styleable.View_textDirection:
3217                    // Clear any text direction flag already set
3218                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3219                    // Set the text direction flags depending on the value of the attribute
3220                    final int textDirection = a.getInt(attr, -1);
3221                    if (textDirection != -1) {
3222                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3223                    }
3224                    break;
3225            }
3226        }
3227
3228        a.recycle();
3229
3230        setOverScrollMode(overScrollMode);
3231
3232        if (background != null) {
3233            setBackgroundDrawable(background);
3234        }
3235
3236        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3237        // layout direction). Those cached values will be used later during padding resolution.
3238        mUserPaddingStart = startPadding;
3239        mUserPaddingEnd = endPadding;
3240
3241        updateUserPaddingRelative();
3242
3243        if (padding >= 0) {
3244            leftPadding = padding;
3245            topPadding = padding;
3246            rightPadding = padding;
3247            bottomPadding = padding;
3248        }
3249
3250        // If the user specified the padding (either with android:padding or
3251        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3252        // use the default padding or the padding from the background drawable
3253        // (stored at this point in mPadding*)
3254        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3255                topPadding >= 0 ? topPadding : mPaddingTop,
3256                rightPadding >= 0 ? rightPadding : mPaddingRight,
3257                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3258
3259        if (viewFlagMasks != 0) {
3260            setFlags(viewFlagValues, viewFlagMasks);
3261        }
3262
3263        // Needs to be called after mViewFlags is set
3264        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3265            recomputePadding();
3266        }
3267
3268        if (x != 0 || y != 0) {
3269            scrollTo(x, y);
3270        }
3271
3272        if (transformSet) {
3273            setTranslationX(tx);
3274            setTranslationY(ty);
3275            setRotation(rotation);
3276            setRotationX(rotationX);
3277            setRotationY(rotationY);
3278            setScaleX(sx);
3279            setScaleY(sy);
3280        }
3281
3282        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3283            setScrollContainer(true);
3284        }
3285
3286        computeOpaqueFlags();
3287    }
3288
3289    private void updateUserPaddingRelative() {
3290        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3291    }
3292
3293    /**
3294     * Non-public constructor for use in testing
3295     */
3296    View() {
3297        mResources = null;
3298    }
3299
3300    /**
3301     * <p>
3302     * Initializes the fading edges from a given set of styled attributes. This
3303     * method should be called by subclasses that need fading edges and when an
3304     * instance of these subclasses is created programmatically rather than
3305     * being inflated from XML. This method is automatically called when the XML
3306     * is inflated.
3307     * </p>
3308     *
3309     * @param a the styled attributes set to initialize the fading edges from
3310     */
3311    protected void initializeFadingEdge(TypedArray a) {
3312        initScrollCache();
3313
3314        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3315                R.styleable.View_fadingEdgeLength,
3316                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3317    }
3318
3319    /**
3320     * Returns the size of the vertical faded edges used to indicate that more
3321     * content in this view is visible.
3322     *
3323     * @return The size in pixels of the vertical faded edge or 0 if vertical
3324     *         faded edges are not enabled for this view.
3325     * @attr ref android.R.styleable#View_fadingEdgeLength
3326     */
3327    public int getVerticalFadingEdgeLength() {
3328        if (isVerticalFadingEdgeEnabled()) {
3329            ScrollabilityCache cache = mScrollCache;
3330            if (cache != null) {
3331                return cache.fadingEdgeLength;
3332            }
3333        }
3334        return 0;
3335    }
3336
3337    /**
3338     * Set the size of the faded edge used to indicate that more content in this
3339     * view is available.  Will not change whether the fading edge is enabled; use
3340     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3341     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3342     * for the vertical or horizontal fading edges.
3343     *
3344     * @param length The size in pixels of the faded edge used to indicate that more
3345     *        content in this view is visible.
3346     */
3347    public void setFadingEdgeLength(int length) {
3348        initScrollCache();
3349        mScrollCache.fadingEdgeLength = length;
3350    }
3351
3352    /**
3353     * Returns the size of the horizontal faded edges used to indicate that more
3354     * content in this view is visible.
3355     *
3356     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3357     *         faded edges are not enabled for this view.
3358     * @attr ref android.R.styleable#View_fadingEdgeLength
3359     */
3360    public int getHorizontalFadingEdgeLength() {
3361        if (isHorizontalFadingEdgeEnabled()) {
3362            ScrollabilityCache cache = mScrollCache;
3363            if (cache != null) {
3364                return cache.fadingEdgeLength;
3365            }
3366        }
3367        return 0;
3368    }
3369
3370    /**
3371     * Returns the width of the vertical scrollbar.
3372     *
3373     * @return The width in pixels of the vertical scrollbar or 0 if there
3374     *         is no vertical scrollbar.
3375     */
3376    public int getVerticalScrollbarWidth() {
3377        ScrollabilityCache cache = mScrollCache;
3378        if (cache != null) {
3379            ScrollBarDrawable scrollBar = cache.scrollBar;
3380            if (scrollBar != null) {
3381                int size = scrollBar.getSize(true);
3382                if (size <= 0) {
3383                    size = cache.scrollBarSize;
3384                }
3385                return size;
3386            }
3387            return 0;
3388        }
3389        return 0;
3390    }
3391
3392    /**
3393     * Returns the height of the horizontal scrollbar.
3394     *
3395     * @return The height in pixels of the horizontal scrollbar or 0 if
3396     *         there is no horizontal scrollbar.
3397     */
3398    protected int getHorizontalScrollbarHeight() {
3399        ScrollabilityCache cache = mScrollCache;
3400        if (cache != null) {
3401            ScrollBarDrawable scrollBar = cache.scrollBar;
3402            if (scrollBar != null) {
3403                int size = scrollBar.getSize(false);
3404                if (size <= 0) {
3405                    size = cache.scrollBarSize;
3406                }
3407                return size;
3408            }
3409            return 0;
3410        }
3411        return 0;
3412    }
3413
3414    /**
3415     * <p>
3416     * Initializes the scrollbars from a given set of styled attributes. This
3417     * method should be called by subclasses that need scrollbars and when an
3418     * instance of these subclasses is created programmatically rather than
3419     * being inflated from XML. This method is automatically called when the XML
3420     * is inflated.
3421     * </p>
3422     *
3423     * @param a the styled attributes set to initialize the scrollbars from
3424     */
3425    protected void initializeScrollbars(TypedArray a) {
3426        initScrollCache();
3427
3428        final ScrollabilityCache scrollabilityCache = mScrollCache;
3429
3430        if (scrollabilityCache.scrollBar == null) {
3431            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3432        }
3433
3434        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3435
3436        if (!fadeScrollbars) {
3437            scrollabilityCache.state = ScrollabilityCache.ON;
3438        }
3439        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3440
3441
3442        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3443                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3444                        .getScrollBarFadeDuration());
3445        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3446                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3447                ViewConfiguration.getScrollDefaultDelay());
3448
3449
3450        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3451                com.android.internal.R.styleable.View_scrollbarSize,
3452                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3453
3454        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3455        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3456
3457        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3458        if (thumb != null) {
3459            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3460        }
3461
3462        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3463                false);
3464        if (alwaysDraw) {
3465            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3466        }
3467
3468        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3469        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3470
3471        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3472        if (thumb != null) {
3473            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3474        }
3475
3476        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3477                false);
3478        if (alwaysDraw) {
3479            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3480        }
3481
3482        // Re-apply user/background padding so that scrollbar(s) get added
3483        resolvePadding();
3484    }
3485
3486    /**
3487     * <p>
3488     * Initalizes the scrollability cache if necessary.
3489     * </p>
3490     */
3491    private void initScrollCache() {
3492        if (mScrollCache == null) {
3493            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3494        }
3495    }
3496
3497    /**
3498     * Set the position of the vertical scroll bar. Should be one of
3499     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3500     * {@link #SCROLLBAR_POSITION_RIGHT}.
3501     *
3502     * @param position Where the vertical scroll bar should be positioned.
3503     */
3504    public void setVerticalScrollbarPosition(int position) {
3505        if (mVerticalScrollbarPosition != position) {
3506            mVerticalScrollbarPosition = position;
3507            computeOpaqueFlags();
3508            resolvePadding();
3509        }
3510    }
3511
3512    /**
3513     * @return The position where the vertical scroll bar will show, if applicable.
3514     * @see #setVerticalScrollbarPosition(int)
3515     */
3516    public int getVerticalScrollbarPosition() {
3517        return mVerticalScrollbarPosition;
3518    }
3519
3520    ListenerInfo getListenerInfo() {
3521        if (mListenerInfo != null) {
3522            return mListenerInfo;
3523        }
3524        mListenerInfo = new ListenerInfo();
3525        return mListenerInfo;
3526    }
3527
3528    /**
3529     * Register a callback to be invoked when focus of this view changed.
3530     *
3531     * @param l The callback that will run.
3532     */
3533    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3534        getListenerInfo().mOnFocusChangeListener = l;
3535    }
3536
3537    /**
3538     * Add a listener that will be called when the bounds of the view change due to
3539     * layout processing.
3540     *
3541     * @param listener The listener that will be called when layout bounds change.
3542     */
3543    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3544        ListenerInfo li = getListenerInfo();
3545        if (li.mOnLayoutChangeListeners == null) {
3546            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3547        }
3548        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3549            li.mOnLayoutChangeListeners.add(listener);
3550        }
3551    }
3552
3553    /**
3554     * Remove a listener for layout changes.
3555     *
3556     * @param listener The listener for layout bounds change.
3557     */
3558    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3559        ListenerInfo li = mListenerInfo;
3560        if (li == null || li.mOnLayoutChangeListeners == null) {
3561            return;
3562        }
3563        li.mOnLayoutChangeListeners.remove(listener);
3564    }
3565
3566    /**
3567     * Add a listener for attach state changes.
3568     *
3569     * This listener will be called whenever this view is attached or detached
3570     * from a window. Remove the listener using
3571     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3572     *
3573     * @param listener Listener to attach
3574     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3575     */
3576    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3577        ListenerInfo li = getListenerInfo();
3578        if (li.mOnAttachStateChangeListeners == null) {
3579            li.mOnAttachStateChangeListeners
3580                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3581        }
3582        li.mOnAttachStateChangeListeners.add(listener);
3583    }
3584
3585    /**
3586     * Remove a listener for attach state changes. The listener will receive no further
3587     * notification of window attach/detach events.
3588     *
3589     * @param listener Listener to remove
3590     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3591     */
3592    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3593        ListenerInfo li = mListenerInfo;
3594        if (li == null || li.mOnAttachStateChangeListeners == null) {
3595            return;
3596        }
3597        li.mOnAttachStateChangeListeners.remove(listener);
3598    }
3599
3600    /**
3601     * Returns the focus-change callback registered for this view.
3602     *
3603     * @return The callback, or null if one is not registered.
3604     */
3605    public OnFocusChangeListener getOnFocusChangeListener() {
3606        ListenerInfo li = mListenerInfo;
3607        return li != null ? li.mOnFocusChangeListener : null;
3608    }
3609
3610    /**
3611     * Register a callback to be invoked when this view is clicked. If this view is not
3612     * clickable, it becomes clickable.
3613     *
3614     * @param l The callback that will run
3615     *
3616     * @see #setClickable(boolean)
3617     */
3618    public void setOnClickListener(OnClickListener l) {
3619        if (!isClickable()) {
3620            setClickable(true);
3621        }
3622        getListenerInfo().mOnClickListener = l;
3623    }
3624
3625    /**
3626     * Return whether this view has an attached OnClickListener.  Returns
3627     * true if there is a listener, false if there is none.
3628     */
3629    public boolean hasOnClickListeners() {
3630        ListenerInfo li = mListenerInfo;
3631        return (li != null && li.mOnClickListener != null);
3632    }
3633
3634    /**
3635     * Register a callback to be invoked when this view is clicked and held. If this view is not
3636     * long clickable, it becomes long clickable.
3637     *
3638     * @param l The callback that will run
3639     *
3640     * @see #setLongClickable(boolean)
3641     */
3642    public void setOnLongClickListener(OnLongClickListener l) {
3643        if (!isLongClickable()) {
3644            setLongClickable(true);
3645        }
3646        getListenerInfo().mOnLongClickListener = l;
3647    }
3648
3649    /**
3650     * Register a callback to be invoked when the context menu for this view is
3651     * being built. If this view is not long clickable, it becomes long clickable.
3652     *
3653     * @param l The callback that will run
3654     *
3655     */
3656    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3657        if (!isLongClickable()) {
3658            setLongClickable(true);
3659        }
3660        getListenerInfo().mOnCreateContextMenuListener = l;
3661    }
3662
3663    /**
3664     * Call this view's OnClickListener, if it is defined.  Performs all normal
3665     * actions associated with clicking: reporting accessibility event, playing
3666     * a sound, etc.
3667     *
3668     * @return True there was an assigned OnClickListener that was called, false
3669     *         otherwise is returned.
3670     */
3671    public boolean performClick() {
3672        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3673
3674        ListenerInfo li = mListenerInfo;
3675        if (li != null && li.mOnClickListener != null) {
3676            playSoundEffect(SoundEffectConstants.CLICK);
3677            li.mOnClickListener.onClick(this);
3678            return true;
3679        }
3680
3681        return false;
3682    }
3683
3684    /**
3685     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3686     * this only calls the listener, and does not do any associated clicking
3687     * actions like reporting an accessibility event.
3688     *
3689     * @return True there was an assigned OnClickListener that was called, false
3690     *         otherwise is returned.
3691     */
3692    public boolean callOnClick() {
3693        ListenerInfo li = mListenerInfo;
3694        if (li != null && li.mOnClickListener != null) {
3695            li.mOnClickListener.onClick(this);
3696            return true;
3697        }
3698        return false;
3699    }
3700
3701    /**
3702     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3703     * OnLongClickListener did not consume the event.
3704     *
3705     * @return True if one of the above receivers consumed the event, false otherwise.
3706     */
3707    public boolean performLongClick() {
3708        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3709
3710        boolean handled = false;
3711        ListenerInfo li = mListenerInfo;
3712        if (li != null && li.mOnLongClickListener != null) {
3713            handled = li.mOnLongClickListener.onLongClick(View.this);
3714        }
3715        if (!handled) {
3716            handled = showContextMenu();
3717        }
3718        if (handled) {
3719            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3720        }
3721        return handled;
3722    }
3723
3724    /**
3725     * Performs button-related actions during a touch down event.
3726     *
3727     * @param event The event.
3728     * @return True if the down was consumed.
3729     *
3730     * @hide
3731     */
3732    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3733        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3734            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3735                return true;
3736            }
3737        }
3738        return false;
3739    }
3740
3741    /**
3742     * Bring up the context menu for this view.
3743     *
3744     * @return Whether a context menu was displayed.
3745     */
3746    public boolean showContextMenu() {
3747        return getParent().showContextMenuForChild(this);
3748    }
3749
3750    /**
3751     * Bring up the context menu for this view, referring to the item under the specified point.
3752     *
3753     * @param x The referenced x coordinate.
3754     * @param y The referenced y coordinate.
3755     * @param metaState The keyboard modifiers that were pressed.
3756     * @return Whether a context menu was displayed.
3757     *
3758     * @hide
3759     */
3760    public boolean showContextMenu(float x, float y, int metaState) {
3761        return showContextMenu();
3762    }
3763
3764    /**
3765     * Start an action mode.
3766     *
3767     * @param callback Callback that will control the lifecycle of the action mode
3768     * @return The new action mode if it is started, null otherwise
3769     *
3770     * @see ActionMode
3771     */
3772    public ActionMode startActionMode(ActionMode.Callback callback) {
3773        ViewParent parent = getParent();
3774        if (parent == null) return null;
3775        return parent.startActionModeForChild(this, callback);
3776    }
3777
3778    /**
3779     * Register a callback to be invoked when a key is pressed in this view.
3780     * @param l the key listener to attach to this view
3781     */
3782    public void setOnKeyListener(OnKeyListener l) {
3783        getListenerInfo().mOnKeyListener = l;
3784    }
3785
3786    /**
3787     * Register a callback to be invoked when a touch event is sent to this view.
3788     * @param l the touch listener to attach to this view
3789     */
3790    public void setOnTouchListener(OnTouchListener l) {
3791        getListenerInfo().mOnTouchListener = l;
3792    }
3793
3794    /**
3795     * Register a callback to be invoked when a generic motion event is sent to this view.
3796     * @param l the generic motion listener to attach to this view
3797     */
3798    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3799        getListenerInfo().mOnGenericMotionListener = l;
3800    }
3801
3802    /**
3803     * Register a callback to be invoked when a hover event is sent to this view.
3804     * @param l the hover listener to attach to this view
3805     */
3806    public void setOnHoverListener(OnHoverListener l) {
3807        getListenerInfo().mOnHoverListener = l;
3808    }
3809
3810    /**
3811     * Register a drag event listener callback object for this View. The parameter is
3812     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3813     * View, the system calls the
3814     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3815     * @param l An implementation of {@link android.view.View.OnDragListener}.
3816     */
3817    public void setOnDragListener(OnDragListener l) {
3818        getListenerInfo().mOnDragListener = l;
3819    }
3820
3821    /**
3822     * Give this view focus. This will cause
3823     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3824     *
3825     * Note: this does not check whether this {@link View} should get focus, it just
3826     * gives it focus no matter what.  It should only be called internally by framework
3827     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3828     *
3829     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3830     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3831     *        focus moved when requestFocus() is called. It may not always
3832     *        apply, in which case use the default View.FOCUS_DOWN.
3833     * @param previouslyFocusedRect The rectangle of the view that had focus
3834     *        prior in this View's coordinate system.
3835     */
3836    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3837        if (DBG) {
3838            System.out.println(this + " requestFocus()");
3839        }
3840
3841        if ((mPrivateFlags & FOCUSED) == 0) {
3842            mPrivateFlags |= FOCUSED;
3843
3844            if (mParent != null) {
3845                mParent.requestChildFocus(this, this);
3846            }
3847
3848            onFocusChanged(true, direction, previouslyFocusedRect);
3849            refreshDrawableState();
3850        }
3851    }
3852
3853    /**
3854     * Request that a rectangle of this view be visible on the screen,
3855     * scrolling if necessary just enough.
3856     *
3857     * <p>A View should call this if it maintains some notion of which part
3858     * of its content is interesting.  For example, a text editing view
3859     * should call this when its cursor moves.
3860     *
3861     * @param rectangle The rectangle.
3862     * @return Whether any parent scrolled.
3863     */
3864    public boolean requestRectangleOnScreen(Rect rectangle) {
3865        return requestRectangleOnScreen(rectangle, false);
3866    }
3867
3868    /**
3869     * Request that a rectangle of this view be visible on the screen,
3870     * scrolling if necessary just enough.
3871     *
3872     * <p>A View should call this if it maintains some notion of which part
3873     * of its content is interesting.  For example, a text editing view
3874     * should call this when its cursor moves.
3875     *
3876     * <p>When <code>immediate</code> is set to true, scrolling will not be
3877     * animated.
3878     *
3879     * @param rectangle The rectangle.
3880     * @param immediate True to forbid animated scrolling, false otherwise
3881     * @return Whether any parent scrolled.
3882     */
3883    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3884        View child = this;
3885        ViewParent parent = mParent;
3886        boolean scrolled = false;
3887        while (parent != null) {
3888            scrolled |= parent.requestChildRectangleOnScreen(child,
3889                    rectangle, immediate);
3890
3891            // offset rect so next call has the rectangle in the
3892            // coordinate system of its direct child.
3893            rectangle.offset(child.getLeft(), child.getTop());
3894            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3895
3896            if (!(parent instanceof View)) {
3897                break;
3898            }
3899
3900            child = (View) parent;
3901            parent = child.getParent();
3902        }
3903        return scrolled;
3904    }
3905
3906    /**
3907     * Called when this view wants to give up focus. If focus is cleared
3908     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3909     * <p>
3910     * <strong>Note:</strong> When a View clears focus the framework is trying
3911     * to give focus to the first focusable View from the top. Hence, if this
3912     * View is the first from the top that can take focus, then its focus will
3913     * not be cleared nor will the focus change callback be invoked.
3914     * </p>
3915     */
3916    public void clearFocus() {
3917        if (DBG) {
3918            System.out.println(this + " clearFocus()");
3919        }
3920
3921        if ((mPrivateFlags & FOCUSED) != 0) {
3922            mPrivateFlags &= ~FOCUSED;
3923
3924            if (mParent != null) {
3925                mParent.clearChildFocus(this);
3926            }
3927
3928            onFocusChanged(false, 0, null);
3929            refreshDrawableState();
3930        }
3931    }
3932
3933    /**
3934     * Called to clear the focus of a view that is about to be removed.
3935     * Doesn't call clearChildFocus, which prevents this view from taking
3936     * focus again before it has been removed from the parent
3937     */
3938    void clearFocusForRemoval() {
3939        if ((mPrivateFlags & FOCUSED) != 0) {
3940            mPrivateFlags &= ~FOCUSED;
3941
3942            onFocusChanged(false, 0, null);
3943            refreshDrawableState();
3944
3945            // The view cleared focus and invoked the callbacks, so  now is the
3946            // time to give focus to the the first focusable from the top to
3947            // ensure that the gain focus is announced after clear focus.
3948            getRootView().requestFocus(FOCUS_FORWARD);
3949        }
3950    }
3951
3952    /**
3953     * Called internally by the view system when a new view is getting focus.
3954     * This is what clears the old focus.
3955     */
3956    void unFocus() {
3957        if (DBG) {
3958            System.out.println(this + " unFocus()");
3959        }
3960
3961        if ((mPrivateFlags & FOCUSED) != 0) {
3962            mPrivateFlags &= ~FOCUSED;
3963
3964            onFocusChanged(false, 0, null);
3965            refreshDrawableState();
3966        }
3967    }
3968
3969    /**
3970     * Returns true if this view has focus iteself, or is the ancestor of the
3971     * view that has focus.
3972     *
3973     * @return True if this view has or contains focus, false otherwise.
3974     */
3975    @ViewDebug.ExportedProperty(category = "focus")
3976    public boolean hasFocus() {
3977        return (mPrivateFlags & FOCUSED) != 0;
3978    }
3979
3980    /**
3981     * Returns true if this view is focusable or if it contains a reachable View
3982     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3983     * is a View whose parents do not block descendants focus.
3984     *
3985     * Only {@link #VISIBLE} views are considered focusable.
3986     *
3987     * @return True if the view is focusable or if the view contains a focusable
3988     *         View, false otherwise.
3989     *
3990     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3991     */
3992    public boolean hasFocusable() {
3993        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3994    }
3995
3996    /**
3997     * Called by the view system when the focus state of this view changes.
3998     * When the focus change event is caused by directional navigation, direction
3999     * and previouslyFocusedRect provide insight into where the focus is coming from.
4000     * When overriding, be sure to call up through to the super class so that
4001     * the standard focus handling will occur.
4002     *
4003     * @param gainFocus True if the View has focus; false otherwise.
4004     * @param direction The direction focus has moved when requestFocus()
4005     *                  is called to give this view focus. Values are
4006     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4007     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4008     *                  It may not always apply, in which case use the default.
4009     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4010     *        system, of the previously focused view.  If applicable, this will be
4011     *        passed in as finer grained information about where the focus is coming
4012     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4013     */
4014    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4015        if (gainFocus) {
4016            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4017        }
4018
4019        InputMethodManager imm = InputMethodManager.peekInstance();
4020        if (!gainFocus) {
4021            if (isPressed()) {
4022                setPressed(false);
4023            }
4024            if (imm != null && mAttachInfo != null
4025                    && mAttachInfo.mHasWindowFocus) {
4026                imm.focusOut(this);
4027            }
4028            onFocusLost();
4029        } else if (imm != null && mAttachInfo != null
4030                && mAttachInfo.mHasWindowFocus) {
4031            imm.focusIn(this);
4032        }
4033
4034        invalidate(true);
4035        ListenerInfo li = mListenerInfo;
4036        if (li != null && li.mOnFocusChangeListener != null) {
4037            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4038        }
4039
4040        if (mAttachInfo != null) {
4041            mAttachInfo.mKeyDispatchState.reset(this);
4042        }
4043    }
4044
4045    /**
4046     * Sends an accessibility event of the given type. If accessiiblity is
4047     * not enabled this method has no effect. The default implementation calls
4048     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4049     * to populate information about the event source (this View), then calls
4050     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4051     * populate the text content of the event source including its descendants,
4052     * and last calls
4053     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4054     * on its parent to resuest sending of the event to interested parties.
4055     * <p>
4056     * If an {@link AccessibilityDelegate} has been specified via calling
4057     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4058     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4059     * responsible for handling this call.
4060     * </p>
4061     *
4062     * @param eventType The type of the event to send, as defined by several types from
4063     * {@link android.view.accessibility.AccessibilityEvent}, such as
4064     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4065     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4066     *
4067     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4068     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4069     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4070     * @see AccessibilityDelegate
4071     */
4072    public void sendAccessibilityEvent(int eventType) {
4073        if (mAccessibilityDelegate != null) {
4074            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4075        } else {
4076            sendAccessibilityEventInternal(eventType);
4077        }
4078    }
4079
4080    /**
4081     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4082     * {@link AccessibilityEvent} to make an announcement which is related to some
4083     * sort of a context change for which none of the events representing UI transitions
4084     * is a good fit. For example, announcing a new page in a book. If accessibility
4085     * is not enabled this method does nothing.
4086     *
4087     * @param text The announcement text.
4088     */
4089    public void announceForAccessibility(CharSequence text) {
4090        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4091            AccessibilityEvent event = AccessibilityEvent.obtain(
4092                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4093            event.getText().add(text);
4094            sendAccessibilityEventUnchecked(event);
4095        }
4096    }
4097
4098    /**
4099     * @see #sendAccessibilityEvent(int)
4100     *
4101     * Note: Called from the default {@link AccessibilityDelegate}.
4102     */
4103    void sendAccessibilityEventInternal(int eventType) {
4104        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4105            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4106        }
4107    }
4108
4109    /**
4110     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4111     * takes as an argument an empty {@link AccessibilityEvent} and does not
4112     * perform a check whether accessibility is enabled.
4113     * <p>
4114     * If an {@link AccessibilityDelegate} has been specified via calling
4115     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4116     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4117     * is responsible for handling this call.
4118     * </p>
4119     *
4120     * @param event The event to send.
4121     *
4122     * @see #sendAccessibilityEvent(int)
4123     */
4124    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4125        if (mAccessibilityDelegate != null) {
4126           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4127        } else {
4128            sendAccessibilityEventUncheckedInternal(event);
4129        }
4130    }
4131
4132    /**
4133     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4134     *
4135     * Note: Called from the default {@link AccessibilityDelegate}.
4136     */
4137    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4138        if (!isShown()) {
4139            return;
4140        }
4141        onInitializeAccessibilityEvent(event);
4142        // Only a subset of accessibility events populates text content.
4143        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4144            dispatchPopulateAccessibilityEvent(event);
4145        }
4146        // In the beginning we called #isShown(), so we know that getParent() is not null.
4147        getParent().requestSendAccessibilityEvent(this, event);
4148    }
4149
4150    /**
4151     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4152     * to its children for adding their text content to the event. Note that the
4153     * event text is populated in a separate dispatch path since we add to the
4154     * event not only the text of the source but also the text of all its descendants.
4155     * A typical implementation will call
4156     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4157     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4158     * on each child. Override this method if custom population of the event text
4159     * content is required.
4160     * <p>
4161     * If an {@link AccessibilityDelegate} has been specified via calling
4162     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4163     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4164     * is responsible for handling this call.
4165     * </p>
4166     * <p>
4167     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4168     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4169     * </p>
4170     *
4171     * @param event The event.
4172     *
4173     * @return True if the event population was completed.
4174     */
4175    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4176        if (mAccessibilityDelegate != null) {
4177            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4178        } else {
4179            return dispatchPopulateAccessibilityEventInternal(event);
4180        }
4181    }
4182
4183    /**
4184     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4185     *
4186     * Note: Called from the default {@link AccessibilityDelegate}.
4187     */
4188    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4189        onPopulateAccessibilityEvent(event);
4190        return false;
4191    }
4192
4193    /**
4194     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4195     * giving a chance to this View to populate the accessibility event with its
4196     * text content. While this method is free to modify event
4197     * attributes other than text content, doing so should normally be performed in
4198     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4199     * <p>
4200     * Example: Adding formatted date string to an accessibility event in addition
4201     *          to the text added by the super implementation:
4202     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4203     *     super.onPopulateAccessibilityEvent(event);
4204     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4205     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4206     *         mCurrentDate.getTimeInMillis(), flags);
4207     *     event.getText().add(selectedDateUtterance);
4208     * }</pre>
4209     * <p>
4210     * If an {@link AccessibilityDelegate} has been specified via calling
4211     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4212     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4213     * is responsible for handling this call.
4214     * </p>
4215     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4216     * information to the event, in case the default implementation has basic information to add.
4217     * </p>
4218     *
4219     * @param event The accessibility event which to populate.
4220     *
4221     * @see #sendAccessibilityEvent(int)
4222     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4223     */
4224    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4225        if (mAccessibilityDelegate != null) {
4226            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4227        } else {
4228            onPopulateAccessibilityEventInternal(event);
4229        }
4230    }
4231
4232    /**
4233     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4234     *
4235     * Note: Called from the default {@link AccessibilityDelegate}.
4236     */
4237    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4238
4239    }
4240
4241    /**
4242     * Initializes an {@link AccessibilityEvent} with information about
4243     * this View which is the event source. In other words, the source of
4244     * an accessibility event is the view whose state change triggered firing
4245     * the event.
4246     * <p>
4247     * Example: Setting the password property of an event in addition
4248     *          to properties set by the super implementation:
4249     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4250     *     super.onInitializeAccessibilityEvent(event);
4251     *     event.setPassword(true);
4252     * }</pre>
4253     * <p>
4254     * If an {@link AccessibilityDelegate} has been specified via calling
4255     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4256     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4257     * is responsible for handling this call.
4258     * </p>
4259     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4260     * information to the event, in case the default implementation has basic information to add.
4261     * </p>
4262     * @param event The event to initialize.
4263     *
4264     * @see #sendAccessibilityEvent(int)
4265     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4266     */
4267    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4268        if (mAccessibilityDelegate != null) {
4269            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4270        } else {
4271            onInitializeAccessibilityEventInternal(event);
4272        }
4273    }
4274
4275    /**
4276     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4277     *
4278     * Note: Called from the default {@link AccessibilityDelegate}.
4279     */
4280    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4281        event.setSource(this);
4282        event.setClassName(View.class.getName());
4283        event.setPackageName(getContext().getPackageName());
4284        event.setEnabled(isEnabled());
4285        event.setContentDescription(mContentDescription);
4286
4287        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4288            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4289            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4290                    FOCUSABLES_ALL);
4291            event.setItemCount(focusablesTempList.size());
4292            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4293            focusablesTempList.clear();
4294        }
4295    }
4296
4297    /**
4298     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4299     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4300     * This method is responsible for obtaining an accessibility node info from a
4301     * pool of reusable instances and calling
4302     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4303     * initialize the former.
4304     * <p>
4305     * Note: The client is responsible for recycling the obtained instance by calling
4306     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4307     * </p>
4308     *
4309     * @return A populated {@link AccessibilityNodeInfo}.
4310     *
4311     * @see AccessibilityNodeInfo
4312     */
4313    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4314        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4315        if (provider != null) {
4316            return provider.createAccessibilityNodeInfo(View.NO_ID);
4317        } else {
4318            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4319            onInitializeAccessibilityNodeInfo(info);
4320            return info;
4321        }
4322    }
4323
4324    /**
4325     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4326     * The base implementation sets:
4327     * <ul>
4328     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4329     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4330     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4331     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4332     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4333     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4334     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4335     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4336     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4337     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4338     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4339     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4340     * </ul>
4341     * <p>
4342     * Subclasses should override this method, call the super implementation,
4343     * and set additional attributes.
4344     * </p>
4345     * <p>
4346     * If an {@link AccessibilityDelegate} has been specified via calling
4347     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4348     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4349     * is responsible for handling this call.
4350     * </p>
4351     *
4352     * @param info The instance to initialize.
4353     */
4354    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4355        if (mAccessibilityDelegate != null) {
4356            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4357        } else {
4358            onInitializeAccessibilityNodeInfoInternal(info);
4359        }
4360    }
4361
4362    /**
4363     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4364     *
4365     * Note: Called from the default {@link AccessibilityDelegate}.
4366     */
4367    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4368        Rect bounds = mAttachInfo.mTmpInvalRect;
4369        getDrawingRect(bounds);
4370        info.setBoundsInParent(bounds);
4371
4372        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4373        getLocationOnScreen(locationOnScreen);
4374        bounds.offsetTo(0, 0);
4375        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4376        info.setBoundsInScreen(bounds);
4377
4378        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4379            ViewParent parent = getParent();
4380            if (parent instanceof View) {
4381                View parentView = (View) parent;
4382                info.setParent(parentView);
4383            }
4384        }
4385
4386        info.setPackageName(mContext.getPackageName());
4387        info.setClassName(View.class.getName());
4388        info.setContentDescription(getContentDescription());
4389
4390        info.setEnabled(isEnabled());
4391        info.setClickable(isClickable());
4392        info.setFocusable(isFocusable());
4393        info.setFocused(isFocused());
4394        info.setSelected(isSelected());
4395        info.setLongClickable(isLongClickable());
4396
4397        // TODO: These make sense only if we are in an AdapterView but all
4398        // views can be selected. Maybe from accessiiblity perspective
4399        // we should report as selectable view in an AdapterView.
4400        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4401        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4402
4403        if (isFocusable()) {
4404            if (isFocused()) {
4405                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4406            } else {
4407                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4408            }
4409        }
4410    }
4411
4412    /**
4413     * Sets a delegate for implementing accessibility support via compositon as
4414     * opposed to inheritance. The delegate's primary use is for implementing
4415     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4416     *
4417     * @param delegate The delegate instance.
4418     *
4419     * @see AccessibilityDelegate
4420     */
4421    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4422        mAccessibilityDelegate = delegate;
4423    }
4424
4425    /**
4426     * Gets the provider for managing a virtual view hierarchy rooted at this View
4427     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4428     * that explore the window content.
4429     * <p>
4430     * If this method returns an instance, this instance is responsible for managing
4431     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4432     * View including the one representing the View itself. Similarly the returned
4433     * instance is responsible for performing accessibility actions on any virtual
4434     * view or the root view itself.
4435     * </p>
4436     * <p>
4437     * If an {@link AccessibilityDelegate} has been specified via calling
4438     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4439     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4440     * is responsible for handling this call.
4441     * </p>
4442     *
4443     * @return The provider.
4444     *
4445     * @see AccessibilityNodeProvider
4446     */
4447    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4448        if (mAccessibilityDelegate != null) {
4449            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4450        } else {
4451            return null;
4452        }
4453    }
4454
4455    /**
4456     * Gets the unique identifier of this view on the screen for accessibility purposes.
4457     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4458     *
4459     * @return The view accessibility id.
4460     *
4461     * @hide
4462     */
4463    public int getAccessibilityViewId() {
4464        if (mAccessibilityViewId == NO_ID) {
4465            mAccessibilityViewId = sNextAccessibilityViewId++;
4466        }
4467        return mAccessibilityViewId;
4468    }
4469
4470    /**
4471     * Gets the unique identifier of the window in which this View reseides.
4472     *
4473     * @return The window accessibility id.
4474     *
4475     * @hide
4476     */
4477    public int getAccessibilityWindowId() {
4478        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4479    }
4480
4481    /**
4482     * Gets the {@link View} description. It briefly describes the view and is
4483     * primarily used for accessibility support. Set this property to enable
4484     * better accessibility support for your application. This is especially
4485     * true for views that do not have textual representation (For example,
4486     * ImageButton).
4487     *
4488     * @return The content descriptiopn.
4489     *
4490     * @attr ref android.R.styleable#View_contentDescription
4491     */
4492    public CharSequence getContentDescription() {
4493        return mContentDescription;
4494    }
4495
4496    /**
4497     * Sets the {@link View} description. It briefly describes the view and is
4498     * primarily used for accessibility support. Set this property to enable
4499     * better accessibility support for your application. This is especially
4500     * true for views that do not have textual representation (For example,
4501     * ImageButton).
4502     *
4503     * @param contentDescription The content description.
4504     *
4505     * @attr ref android.R.styleable#View_contentDescription
4506     */
4507    @RemotableViewMethod
4508    public void setContentDescription(CharSequence contentDescription) {
4509        mContentDescription = contentDescription;
4510    }
4511
4512    /**
4513     * Invoked whenever this view loses focus, either by losing window focus or by losing
4514     * focus within its window. This method can be used to clear any state tied to the
4515     * focus. For instance, if a button is held pressed with the trackball and the window
4516     * loses focus, this method can be used to cancel the press.
4517     *
4518     * Subclasses of View overriding this method should always call super.onFocusLost().
4519     *
4520     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4521     * @see #onWindowFocusChanged(boolean)
4522     *
4523     * @hide pending API council approval
4524     */
4525    protected void onFocusLost() {
4526        resetPressedState();
4527    }
4528
4529    private void resetPressedState() {
4530        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4531            return;
4532        }
4533
4534        if (isPressed()) {
4535            setPressed(false);
4536
4537            if (!mHasPerformedLongPress) {
4538                removeLongPressCallback();
4539            }
4540        }
4541    }
4542
4543    /**
4544     * Returns true if this view has focus
4545     *
4546     * @return True if this view has focus, false otherwise.
4547     */
4548    @ViewDebug.ExportedProperty(category = "focus")
4549    public boolean isFocused() {
4550        return (mPrivateFlags & FOCUSED) != 0;
4551    }
4552
4553    /**
4554     * Find the view in the hierarchy rooted at this view that currently has
4555     * focus.
4556     *
4557     * @return The view that currently has focus, or null if no focused view can
4558     *         be found.
4559     */
4560    public View findFocus() {
4561        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4562    }
4563
4564    /**
4565     * Change whether this view is one of the set of scrollable containers in
4566     * its window.  This will be used to determine whether the window can
4567     * resize or must pan when a soft input area is open -- scrollable
4568     * containers allow the window to use resize mode since the container
4569     * will appropriately shrink.
4570     */
4571    public void setScrollContainer(boolean isScrollContainer) {
4572        if (isScrollContainer) {
4573            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4574                mAttachInfo.mScrollContainers.add(this);
4575                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4576            }
4577            mPrivateFlags |= SCROLL_CONTAINER;
4578        } else {
4579            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4580                mAttachInfo.mScrollContainers.remove(this);
4581            }
4582            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4583        }
4584    }
4585
4586    /**
4587     * Returns the quality of the drawing cache.
4588     *
4589     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4590     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4591     *
4592     * @see #setDrawingCacheQuality(int)
4593     * @see #setDrawingCacheEnabled(boolean)
4594     * @see #isDrawingCacheEnabled()
4595     *
4596     * @attr ref android.R.styleable#View_drawingCacheQuality
4597     */
4598    public int getDrawingCacheQuality() {
4599        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4600    }
4601
4602    /**
4603     * Set the drawing cache quality of this view. This value is used only when the
4604     * drawing cache is enabled
4605     *
4606     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4607     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4608     *
4609     * @see #getDrawingCacheQuality()
4610     * @see #setDrawingCacheEnabled(boolean)
4611     * @see #isDrawingCacheEnabled()
4612     *
4613     * @attr ref android.R.styleable#View_drawingCacheQuality
4614     */
4615    public void setDrawingCacheQuality(int quality) {
4616        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4617    }
4618
4619    /**
4620     * Returns whether the screen should remain on, corresponding to the current
4621     * value of {@link #KEEP_SCREEN_ON}.
4622     *
4623     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4624     *
4625     * @see #setKeepScreenOn(boolean)
4626     *
4627     * @attr ref android.R.styleable#View_keepScreenOn
4628     */
4629    public boolean getKeepScreenOn() {
4630        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4631    }
4632
4633    /**
4634     * Controls whether the screen should remain on, modifying the
4635     * value of {@link #KEEP_SCREEN_ON}.
4636     *
4637     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4638     *
4639     * @see #getKeepScreenOn()
4640     *
4641     * @attr ref android.R.styleable#View_keepScreenOn
4642     */
4643    public void setKeepScreenOn(boolean keepScreenOn) {
4644        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4645    }
4646
4647    /**
4648     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4649     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4650     *
4651     * @attr ref android.R.styleable#View_nextFocusLeft
4652     */
4653    public int getNextFocusLeftId() {
4654        return mNextFocusLeftId;
4655    }
4656
4657    /**
4658     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4659     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4660     * decide automatically.
4661     *
4662     * @attr ref android.R.styleable#View_nextFocusLeft
4663     */
4664    public void setNextFocusLeftId(int nextFocusLeftId) {
4665        mNextFocusLeftId = nextFocusLeftId;
4666    }
4667
4668    /**
4669     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4670     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4671     *
4672     * @attr ref android.R.styleable#View_nextFocusRight
4673     */
4674    public int getNextFocusRightId() {
4675        return mNextFocusRightId;
4676    }
4677
4678    /**
4679     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4680     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4681     * decide automatically.
4682     *
4683     * @attr ref android.R.styleable#View_nextFocusRight
4684     */
4685    public void setNextFocusRightId(int nextFocusRightId) {
4686        mNextFocusRightId = nextFocusRightId;
4687    }
4688
4689    /**
4690     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4691     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4692     *
4693     * @attr ref android.R.styleable#View_nextFocusUp
4694     */
4695    public int getNextFocusUpId() {
4696        return mNextFocusUpId;
4697    }
4698
4699    /**
4700     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4701     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4702     * decide automatically.
4703     *
4704     * @attr ref android.R.styleable#View_nextFocusUp
4705     */
4706    public void setNextFocusUpId(int nextFocusUpId) {
4707        mNextFocusUpId = nextFocusUpId;
4708    }
4709
4710    /**
4711     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4712     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4713     *
4714     * @attr ref android.R.styleable#View_nextFocusDown
4715     */
4716    public int getNextFocusDownId() {
4717        return mNextFocusDownId;
4718    }
4719
4720    /**
4721     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4722     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4723     * decide automatically.
4724     *
4725     * @attr ref android.R.styleable#View_nextFocusDown
4726     */
4727    public void setNextFocusDownId(int nextFocusDownId) {
4728        mNextFocusDownId = nextFocusDownId;
4729    }
4730
4731    /**
4732     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4733     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4734     *
4735     * @attr ref android.R.styleable#View_nextFocusForward
4736     */
4737    public int getNextFocusForwardId() {
4738        return mNextFocusForwardId;
4739    }
4740
4741    /**
4742     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4743     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4744     * decide automatically.
4745     *
4746     * @attr ref android.R.styleable#View_nextFocusForward
4747     */
4748    public void setNextFocusForwardId(int nextFocusForwardId) {
4749        mNextFocusForwardId = nextFocusForwardId;
4750    }
4751
4752    /**
4753     * Returns the visibility of this view and all of its ancestors
4754     *
4755     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4756     */
4757    public boolean isShown() {
4758        View current = this;
4759        //noinspection ConstantConditions
4760        do {
4761            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4762                return false;
4763            }
4764            ViewParent parent = current.mParent;
4765            if (parent == null) {
4766                return false; // We are not attached to the view root
4767            }
4768            if (!(parent instanceof View)) {
4769                return true;
4770            }
4771            current = (View) parent;
4772        } while (current != null);
4773
4774        return false;
4775    }
4776
4777    /**
4778     * Called by the view hierarchy when the content insets for a window have
4779     * changed, to allow it to adjust its content to fit within those windows.
4780     * The content insets tell you the space that the status bar, input method,
4781     * and other system windows infringe on the application's window.
4782     *
4783     * <p>You do not normally need to deal with this function, since the default
4784     * window decoration given to applications takes care of applying it to the
4785     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
4786     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
4787     * and your content can be placed under those system elements.  You can then
4788     * use this method within your view hierarchy if you have parts of your UI
4789     * which you would like to ensure are not being covered.
4790     *
4791     * <p>The default implementation of this method simply applies the content
4792     * inset's to the view's padding.  This can be enabled through
4793     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
4794     * the method and handle the insets however you would like.  Note that the
4795     * insets provided by the framework are always relative to the far edges
4796     * of the window, not accounting for the location of the called view within
4797     * that window.  (In fact when this method is called you do not yet know
4798     * where the layout will place the view, as it is done before layout happens.)
4799     *
4800     * <p>Note: unlike many View methods, there is no dispatch phase to this
4801     * call.  If you are overriding it in a ViewGroup and want to allow the
4802     * call to continue to your children, you must be sure to call the super
4803     * implementation.
4804     *
4805     * @param insets Current content insets of the window.  Prior to
4806     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
4807     * the insets or else you and Android will be unhappy.
4808     *
4809     * @return Return true if this view applied the insets and it should not
4810     * continue propagating further down the hierarchy, false otherwise.
4811     */
4812    protected boolean fitSystemWindows(Rect insets) {
4813        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4814            mUserPaddingStart = -1;
4815            mUserPaddingEnd = -1;
4816            mUserPaddingRelative = false;
4817            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
4818                    || mAttachInfo == null
4819                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
4820                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
4821                return true;
4822            } else {
4823                internalSetPadding(0, 0, 0, 0);
4824                return false;
4825            }
4826        }
4827        return false;
4828    }
4829
4830    /**
4831     * Set whether or not this view should account for system screen decorations
4832     * such as the status bar and inset its content. This allows this view to be
4833     * positioned in absolute screen coordinates and remain visible to the user.
4834     *
4835     * <p>This should only be used by top-level window decor views.
4836     *
4837     * @param fitSystemWindows true to inset content for system screen decorations, false for
4838     *                         default behavior.
4839     *
4840     * @attr ref android.R.styleable#View_fitsSystemWindows
4841     */
4842    public void setFitsSystemWindows(boolean fitSystemWindows) {
4843        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4844    }
4845
4846    /**
4847     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4848     * will account for system screen decorations such as the status bar and inset its
4849     * content. This allows the view to be positioned in absolute screen coordinates
4850     * and remain visible to the user.
4851     *
4852     * @return true if this view will adjust its content bounds for system screen decorations.
4853     *
4854     * @attr ref android.R.styleable#View_fitsSystemWindows
4855     */
4856    public boolean fitsSystemWindows() {
4857        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4858    }
4859
4860    /**
4861     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
4862     */
4863    public void requestFitSystemWindows() {
4864        if (mParent != null) {
4865            mParent.requestFitSystemWindows();
4866        }
4867    }
4868
4869    /**
4870     * For use by PhoneWindow to make its own system window fitting optional.
4871     * @hide
4872     */
4873    public void makeOptionalFitsSystemWindows() {
4874        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
4875    }
4876
4877    /**
4878     * Returns the visibility status for this view.
4879     *
4880     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4881     * @attr ref android.R.styleable#View_visibility
4882     */
4883    @ViewDebug.ExportedProperty(mapping = {
4884        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4885        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4886        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4887    })
4888    public int getVisibility() {
4889        return mViewFlags & VISIBILITY_MASK;
4890    }
4891
4892    /**
4893     * Set the enabled state of this view.
4894     *
4895     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4896     * @attr ref android.R.styleable#View_visibility
4897     */
4898    @RemotableViewMethod
4899    public void setVisibility(int visibility) {
4900        setFlags(visibility, VISIBILITY_MASK);
4901        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4902    }
4903
4904    /**
4905     * Returns the enabled status for this view. The interpretation of the
4906     * enabled state varies by subclass.
4907     *
4908     * @return True if this view is enabled, false otherwise.
4909     */
4910    @ViewDebug.ExportedProperty
4911    public boolean isEnabled() {
4912        return (mViewFlags & ENABLED_MASK) == ENABLED;
4913    }
4914
4915    /**
4916     * Set the enabled state of this view. The interpretation of the enabled
4917     * state varies by subclass.
4918     *
4919     * @param enabled True if this view is enabled, false otherwise.
4920     */
4921    @RemotableViewMethod
4922    public void setEnabled(boolean enabled) {
4923        if (enabled == isEnabled()) return;
4924
4925        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4926
4927        /*
4928         * The View most likely has to change its appearance, so refresh
4929         * the drawable state.
4930         */
4931        refreshDrawableState();
4932
4933        // Invalidate too, since the default behavior for views is to be
4934        // be drawn at 50% alpha rather than to change the drawable.
4935        invalidate(true);
4936    }
4937
4938    /**
4939     * Set whether this view can receive the focus.
4940     *
4941     * Setting this to false will also ensure that this view is not focusable
4942     * in touch mode.
4943     *
4944     * @param focusable If true, this view can receive the focus.
4945     *
4946     * @see #setFocusableInTouchMode(boolean)
4947     * @attr ref android.R.styleable#View_focusable
4948     */
4949    public void setFocusable(boolean focusable) {
4950        if (!focusable) {
4951            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4952        }
4953        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4954    }
4955
4956    /**
4957     * Set whether this view can receive focus while in touch mode.
4958     *
4959     * Setting this to true will also ensure that this view is focusable.
4960     *
4961     * @param focusableInTouchMode If true, this view can receive the focus while
4962     *   in touch mode.
4963     *
4964     * @see #setFocusable(boolean)
4965     * @attr ref android.R.styleable#View_focusableInTouchMode
4966     */
4967    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4968        // Focusable in touch mode should always be set before the focusable flag
4969        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4970        // which, in touch mode, will not successfully request focus on this view
4971        // because the focusable in touch mode flag is not set
4972        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4973        if (focusableInTouchMode) {
4974            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4975        }
4976    }
4977
4978    /**
4979     * Set whether this view should have sound effects enabled for events such as
4980     * clicking and touching.
4981     *
4982     * <p>You may wish to disable sound effects for a view if you already play sounds,
4983     * for instance, a dial key that plays dtmf tones.
4984     *
4985     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4986     * @see #isSoundEffectsEnabled()
4987     * @see #playSoundEffect(int)
4988     * @attr ref android.R.styleable#View_soundEffectsEnabled
4989     */
4990    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4991        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4992    }
4993
4994    /**
4995     * @return whether this view should have sound effects enabled for events such as
4996     *     clicking and touching.
4997     *
4998     * @see #setSoundEffectsEnabled(boolean)
4999     * @see #playSoundEffect(int)
5000     * @attr ref android.R.styleable#View_soundEffectsEnabled
5001     */
5002    @ViewDebug.ExportedProperty
5003    public boolean isSoundEffectsEnabled() {
5004        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5005    }
5006
5007    /**
5008     * Set whether this view should have haptic feedback for events such as
5009     * long presses.
5010     *
5011     * <p>You may wish to disable haptic feedback if your view already controls
5012     * its own haptic feedback.
5013     *
5014     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5015     * @see #isHapticFeedbackEnabled()
5016     * @see #performHapticFeedback(int)
5017     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5018     */
5019    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5020        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5021    }
5022
5023    /**
5024     * @return whether this view should have haptic feedback enabled for events
5025     * long presses.
5026     *
5027     * @see #setHapticFeedbackEnabled(boolean)
5028     * @see #performHapticFeedback(int)
5029     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5030     */
5031    @ViewDebug.ExportedProperty
5032    public boolean isHapticFeedbackEnabled() {
5033        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5034    }
5035
5036    /**
5037     * Returns the layout direction for this view.
5038     *
5039     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5040     *   {@link #LAYOUT_DIRECTION_RTL},
5041     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5042     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5043     * @attr ref android.R.styleable#View_layoutDirection
5044     */
5045    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5046        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5047        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5048        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5049        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5050    })
5051    public int getLayoutDirection() {
5052        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5053    }
5054
5055    /**
5056     * Set the layout direction for this view. This will propagate a reset of layout direction
5057     * resolution to the view's children and resolve layout direction for this view.
5058     *
5059     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5060     *   {@link #LAYOUT_DIRECTION_RTL},
5061     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5062     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5063     *
5064     * @attr ref android.R.styleable#View_layoutDirection
5065     */
5066    @RemotableViewMethod
5067    public void setLayoutDirection(int layoutDirection) {
5068        if (getLayoutDirection() != layoutDirection) {
5069            // Reset the current layout direction and the resolved one
5070            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5071            resetResolvedLayoutDirection();
5072            // Set the new layout direction (filtered) and ask for a layout pass
5073            mPrivateFlags2 |=
5074                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5075            requestLayout();
5076        }
5077    }
5078
5079    /**
5080     * Returns the resolved layout direction for this view.
5081     *
5082     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5083     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5084     */
5085    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5086        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5087        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5088    })
5089    public int getResolvedLayoutDirection() {
5090        // The layout diretion will be resolved only if needed
5091        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5092            resolveLayoutDirection();
5093        }
5094        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5095                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5096    }
5097
5098    /**
5099     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5100     * layout attribute and/or the inherited value from the parent
5101     *
5102     * @return true if the layout is right-to-left.
5103     */
5104    @ViewDebug.ExportedProperty(category = "layout")
5105    public boolean isLayoutRtl() {
5106        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5107    }
5108
5109    /**
5110     * Indicates whether the view is currently tracking transient state that the
5111     * app should not need to concern itself with saving and restoring, but that
5112     * the framework should take special note to preserve when possible.
5113     *
5114     * @return true if the view has transient state
5115     */
5116    @ViewDebug.ExportedProperty(category = "layout")
5117    public boolean hasTransientState() {
5118        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5119    }
5120
5121    /**
5122     * Set whether this view is currently tracking transient state that the
5123     * framework should attempt to preserve when possible.
5124     *
5125     * @param hasTransientState true if this view has transient state
5126     */
5127    public void setHasTransientState(boolean hasTransientState) {
5128        if (hasTransientState() == hasTransientState) return;
5129
5130        mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5131                (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5132        if (mParent != null) {
5133            try {
5134                mParent.childHasTransientStateChanged(this, hasTransientState);
5135            } catch (AbstractMethodError e) {
5136                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5137                        " does not fully implement ViewParent", e);
5138            }
5139        }
5140    }
5141
5142    /**
5143     * If this view doesn't do any drawing on its own, set this flag to
5144     * allow further optimizations. By default, this flag is not set on
5145     * View, but could be set on some View subclasses such as ViewGroup.
5146     *
5147     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5148     * you should clear this flag.
5149     *
5150     * @param willNotDraw whether or not this View draw on its own
5151     */
5152    public void setWillNotDraw(boolean willNotDraw) {
5153        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5154    }
5155
5156    /**
5157     * Returns whether or not this View draws on its own.
5158     *
5159     * @return true if this view has nothing to draw, false otherwise
5160     */
5161    @ViewDebug.ExportedProperty(category = "drawing")
5162    public boolean willNotDraw() {
5163        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5164    }
5165
5166    /**
5167     * When a View's drawing cache is enabled, drawing is redirected to an
5168     * offscreen bitmap. Some views, like an ImageView, must be able to
5169     * bypass this mechanism if they already draw a single bitmap, to avoid
5170     * unnecessary usage of the memory.
5171     *
5172     * @param willNotCacheDrawing true if this view does not cache its
5173     *        drawing, false otherwise
5174     */
5175    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5176        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5177    }
5178
5179    /**
5180     * Returns whether or not this View can cache its drawing or not.
5181     *
5182     * @return true if this view does not cache its drawing, false otherwise
5183     */
5184    @ViewDebug.ExportedProperty(category = "drawing")
5185    public boolean willNotCacheDrawing() {
5186        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5187    }
5188
5189    /**
5190     * Indicates whether this view reacts to click events or not.
5191     *
5192     * @return true if the view is clickable, false otherwise
5193     *
5194     * @see #setClickable(boolean)
5195     * @attr ref android.R.styleable#View_clickable
5196     */
5197    @ViewDebug.ExportedProperty
5198    public boolean isClickable() {
5199        return (mViewFlags & CLICKABLE) == CLICKABLE;
5200    }
5201
5202    /**
5203     * Enables or disables click events for this view. When a view
5204     * is clickable it will change its state to "pressed" on every click.
5205     * Subclasses should set the view clickable to visually react to
5206     * user's clicks.
5207     *
5208     * @param clickable true to make the view clickable, false otherwise
5209     *
5210     * @see #isClickable()
5211     * @attr ref android.R.styleable#View_clickable
5212     */
5213    public void setClickable(boolean clickable) {
5214        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5215    }
5216
5217    /**
5218     * Indicates whether this view reacts to long click events or not.
5219     *
5220     * @return true if the view is long clickable, false otherwise
5221     *
5222     * @see #setLongClickable(boolean)
5223     * @attr ref android.R.styleable#View_longClickable
5224     */
5225    public boolean isLongClickable() {
5226        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5227    }
5228
5229    /**
5230     * Enables or disables long click events for this view. When a view is long
5231     * clickable it reacts to the user holding down the button for a longer
5232     * duration than a tap. This event can either launch the listener or a
5233     * context menu.
5234     *
5235     * @param longClickable true to make the view long clickable, false otherwise
5236     * @see #isLongClickable()
5237     * @attr ref android.R.styleable#View_longClickable
5238     */
5239    public void setLongClickable(boolean longClickable) {
5240        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5241    }
5242
5243    /**
5244     * Sets the pressed state for this view.
5245     *
5246     * @see #isClickable()
5247     * @see #setClickable(boolean)
5248     *
5249     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5250     *        the View's internal state from a previously set "pressed" state.
5251     */
5252    public void setPressed(boolean pressed) {
5253        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5254
5255        if (pressed) {
5256            mPrivateFlags |= PRESSED;
5257        } else {
5258            mPrivateFlags &= ~PRESSED;
5259        }
5260
5261        if (needsRefresh) {
5262            refreshDrawableState();
5263        }
5264        dispatchSetPressed(pressed);
5265    }
5266
5267    /**
5268     * Dispatch setPressed to all of this View's children.
5269     *
5270     * @see #setPressed(boolean)
5271     *
5272     * @param pressed The new pressed state
5273     */
5274    protected void dispatchSetPressed(boolean pressed) {
5275    }
5276
5277    /**
5278     * Indicates whether the view is currently in pressed state. Unless
5279     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5280     * the pressed state.
5281     *
5282     * @see #setPressed(boolean)
5283     * @see #isClickable()
5284     * @see #setClickable(boolean)
5285     *
5286     * @return true if the view is currently pressed, false otherwise
5287     */
5288    public boolean isPressed() {
5289        return (mPrivateFlags & PRESSED) == PRESSED;
5290    }
5291
5292    /**
5293     * Indicates whether this view will save its state (that is,
5294     * whether its {@link #onSaveInstanceState} method will be called).
5295     *
5296     * @return Returns true if the view state saving is enabled, else false.
5297     *
5298     * @see #setSaveEnabled(boolean)
5299     * @attr ref android.R.styleable#View_saveEnabled
5300     */
5301    public boolean isSaveEnabled() {
5302        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5303    }
5304
5305    /**
5306     * Controls whether the saving of this view's state is
5307     * enabled (that is, whether its {@link #onSaveInstanceState} method
5308     * will be called).  Note that even if freezing is enabled, the
5309     * view still must have an id assigned to it (via {@link #setId(int)})
5310     * for its state to be saved.  This flag can only disable the
5311     * saving of this view; any child views may still have their state saved.
5312     *
5313     * @param enabled Set to false to <em>disable</em> state saving, or true
5314     * (the default) to allow it.
5315     *
5316     * @see #isSaveEnabled()
5317     * @see #setId(int)
5318     * @see #onSaveInstanceState()
5319     * @attr ref android.R.styleable#View_saveEnabled
5320     */
5321    public void setSaveEnabled(boolean enabled) {
5322        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5323    }
5324
5325    /**
5326     * Gets whether the framework should discard touches when the view's
5327     * window is obscured by another visible window.
5328     * Refer to the {@link View} security documentation for more details.
5329     *
5330     * @return True if touch filtering is enabled.
5331     *
5332     * @see #setFilterTouchesWhenObscured(boolean)
5333     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5334     */
5335    @ViewDebug.ExportedProperty
5336    public boolean getFilterTouchesWhenObscured() {
5337        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5338    }
5339
5340    /**
5341     * Sets whether the framework should discard touches when the view's
5342     * window is obscured by another visible window.
5343     * Refer to the {@link View} security documentation for more details.
5344     *
5345     * @param enabled True if touch filtering should be enabled.
5346     *
5347     * @see #getFilterTouchesWhenObscured
5348     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5349     */
5350    public void setFilterTouchesWhenObscured(boolean enabled) {
5351        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5352                FILTER_TOUCHES_WHEN_OBSCURED);
5353    }
5354
5355    /**
5356     * Indicates whether the entire hierarchy under this view will save its
5357     * state when a state saving traversal occurs from its parent.  The default
5358     * is true; if false, these views will not be saved unless
5359     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5360     *
5361     * @return Returns true if the view state saving from parent is enabled, else false.
5362     *
5363     * @see #setSaveFromParentEnabled(boolean)
5364     */
5365    public boolean isSaveFromParentEnabled() {
5366        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5367    }
5368
5369    /**
5370     * Controls whether the entire hierarchy under this view will save its
5371     * state when a state saving traversal occurs from its parent.  The default
5372     * is true; if false, these views will not be saved unless
5373     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5374     *
5375     * @param enabled Set to false to <em>disable</em> state saving, or true
5376     * (the default) to allow it.
5377     *
5378     * @see #isSaveFromParentEnabled()
5379     * @see #setId(int)
5380     * @see #onSaveInstanceState()
5381     */
5382    public void setSaveFromParentEnabled(boolean enabled) {
5383        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5384    }
5385
5386
5387    /**
5388     * Returns whether this View is able to take focus.
5389     *
5390     * @return True if this view can take focus, or false otherwise.
5391     * @attr ref android.R.styleable#View_focusable
5392     */
5393    @ViewDebug.ExportedProperty(category = "focus")
5394    public final boolean isFocusable() {
5395        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5396    }
5397
5398    /**
5399     * When a view is focusable, it may not want to take focus when in touch mode.
5400     * For example, a button would like focus when the user is navigating via a D-pad
5401     * so that the user can click on it, but once the user starts touching the screen,
5402     * the button shouldn't take focus
5403     * @return Whether the view is focusable in touch mode.
5404     * @attr ref android.R.styleable#View_focusableInTouchMode
5405     */
5406    @ViewDebug.ExportedProperty
5407    public final boolean isFocusableInTouchMode() {
5408        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5409    }
5410
5411    /**
5412     * Find the nearest view in the specified direction that can take focus.
5413     * This does not actually give focus to that view.
5414     *
5415     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5416     *
5417     * @return The nearest focusable in the specified direction, or null if none
5418     *         can be found.
5419     */
5420    public View focusSearch(int direction) {
5421        if (mParent != null) {
5422            return mParent.focusSearch(this, direction);
5423        } else {
5424            return null;
5425        }
5426    }
5427
5428    /**
5429     * This method is the last chance for the focused view and its ancestors to
5430     * respond to an arrow key. This is called when the focused view did not
5431     * consume the key internally, nor could the view system find a new view in
5432     * the requested direction to give focus to.
5433     *
5434     * @param focused The currently focused view.
5435     * @param direction The direction focus wants to move. One of FOCUS_UP,
5436     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5437     * @return True if the this view consumed this unhandled move.
5438     */
5439    public boolean dispatchUnhandledMove(View focused, int direction) {
5440        return false;
5441    }
5442
5443    /**
5444     * If a user manually specified the next view id for a particular direction,
5445     * use the root to look up the view.
5446     * @param root The root view of the hierarchy containing this view.
5447     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5448     * or FOCUS_BACKWARD.
5449     * @return The user specified next view, or null if there is none.
5450     */
5451    View findUserSetNextFocus(View root, int direction) {
5452        switch (direction) {
5453            case FOCUS_LEFT:
5454                if (mNextFocusLeftId == View.NO_ID) return null;
5455                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5456            case FOCUS_RIGHT:
5457                if (mNextFocusRightId == View.NO_ID) return null;
5458                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5459            case FOCUS_UP:
5460                if (mNextFocusUpId == View.NO_ID) return null;
5461                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5462            case FOCUS_DOWN:
5463                if (mNextFocusDownId == View.NO_ID) return null;
5464                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5465            case FOCUS_FORWARD:
5466                if (mNextFocusForwardId == View.NO_ID) return null;
5467                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5468            case FOCUS_BACKWARD: {
5469                if (mID == View.NO_ID) return null;
5470                final int id = mID;
5471                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5472                    @Override
5473                    public boolean apply(View t) {
5474                        return t.mNextFocusForwardId == id;
5475                    }
5476                });
5477            }
5478        }
5479        return null;
5480    }
5481
5482    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5483        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5484            @Override
5485            public boolean apply(View t) {
5486                return t.mID == childViewId;
5487            }
5488        });
5489
5490        if (result == null) {
5491            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5492                    + "by user for id " + childViewId);
5493        }
5494        return result;
5495    }
5496
5497    /**
5498     * Find and return all focusable views that are descendants of this view,
5499     * possibly including this view if it is focusable itself.
5500     *
5501     * @param direction The direction of the focus
5502     * @return A list of focusable views
5503     */
5504    public ArrayList<View> getFocusables(int direction) {
5505        ArrayList<View> result = new ArrayList<View>(24);
5506        addFocusables(result, direction);
5507        return result;
5508    }
5509
5510    /**
5511     * Add any focusable views that are descendants of this view (possibly
5512     * including this view if it is focusable itself) to views.  If we are in touch mode,
5513     * only add views that are also focusable in touch mode.
5514     *
5515     * @param views Focusable views found so far
5516     * @param direction The direction of the focus
5517     */
5518    public void addFocusables(ArrayList<View> views, int direction) {
5519        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5520    }
5521
5522    /**
5523     * Adds any focusable views that are descendants of this view (possibly
5524     * including this view if it is focusable itself) to views. This method
5525     * adds all focusable views regardless if we are in touch mode or
5526     * only views focusable in touch mode if we are in touch mode depending on
5527     * the focusable mode paramater.
5528     *
5529     * @param views Focusable views found so far or null if all we are interested is
5530     *        the number of focusables.
5531     * @param direction The direction of the focus.
5532     * @param focusableMode The type of focusables to be added.
5533     *
5534     * @see #FOCUSABLES_ALL
5535     * @see #FOCUSABLES_TOUCH_MODE
5536     */
5537    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5538        if (!isFocusable()) {
5539            return;
5540        }
5541
5542        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5543                isInTouchMode() && !isFocusableInTouchMode()) {
5544            return;
5545        }
5546
5547        if (views != null) {
5548            views.add(this);
5549        }
5550    }
5551
5552    /**
5553     * Finds the Views that contain given text. The containment is case insensitive.
5554     * The search is performed by either the text that the View renders or the content
5555     * description that describes the view for accessibility purposes and the view does
5556     * not render or both. Clients can specify how the search is to be performed via
5557     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5558     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5559     *
5560     * @param outViews The output list of matching Views.
5561     * @param searched The text to match against.
5562     *
5563     * @see #FIND_VIEWS_WITH_TEXT
5564     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5565     * @see #setContentDescription(CharSequence)
5566     */
5567    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5568        if (getAccessibilityNodeProvider() != null) {
5569            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5570                outViews.add(this);
5571            }
5572        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5573                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5574            String searchedLowerCase = searched.toString().toLowerCase();
5575            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5576            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5577                outViews.add(this);
5578            }
5579        }
5580    }
5581
5582    /**
5583     * Find and return all touchable views that are descendants of this view,
5584     * possibly including this view if it is touchable itself.
5585     *
5586     * @return A list of touchable views
5587     */
5588    public ArrayList<View> getTouchables() {
5589        ArrayList<View> result = new ArrayList<View>();
5590        addTouchables(result);
5591        return result;
5592    }
5593
5594    /**
5595     * Add any touchable views that are descendants of this view (possibly
5596     * including this view if it is touchable itself) to views.
5597     *
5598     * @param views Touchable views found so far
5599     */
5600    public void addTouchables(ArrayList<View> views) {
5601        final int viewFlags = mViewFlags;
5602
5603        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5604                && (viewFlags & ENABLED_MASK) == ENABLED) {
5605            views.add(this);
5606        }
5607    }
5608
5609    /**
5610     * Call this to try to give focus to a specific view or to one of its
5611     * descendants.
5612     *
5613     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5614     * false), or if it is focusable and it is not focusable in touch mode
5615     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5616     *
5617     * See also {@link #focusSearch(int)}, which is what you call to say that you
5618     * have focus, and you want your parent to look for the next one.
5619     *
5620     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5621     * {@link #FOCUS_DOWN} and <code>null</code>.
5622     *
5623     * @return Whether this view or one of its descendants actually took focus.
5624     */
5625    public final boolean requestFocus() {
5626        return requestFocus(View.FOCUS_DOWN);
5627    }
5628
5629
5630    /**
5631     * Call this to try to give focus to a specific view or to one of its
5632     * descendants and give it a hint about what direction focus is heading.
5633     *
5634     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5635     * false), or if it is focusable and it is not focusable in touch mode
5636     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5637     *
5638     * See also {@link #focusSearch(int)}, which is what you call to say that you
5639     * have focus, and you want your parent to look for the next one.
5640     *
5641     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5642     * <code>null</code> set for the previously focused rectangle.
5643     *
5644     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5645     * @return Whether this view or one of its descendants actually took focus.
5646     */
5647    public final boolean requestFocus(int direction) {
5648        return requestFocus(direction, null);
5649    }
5650
5651    /**
5652     * Call this to try to give focus to a specific view or to one of its descendants
5653     * and give it hints about the direction and a specific rectangle that the focus
5654     * is coming from.  The rectangle can help give larger views a finer grained hint
5655     * about where focus is coming from, and therefore, where to show selection, or
5656     * forward focus change internally.
5657     *
5658     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5659     * false), or if it is focusable and it is not focusable in touch mode
5660     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5661     *
5662     * A View will not take focus if it is not visible.
5663     *
5664     * A View will not take focus if one of its parents has
5665     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5666     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5667     *
5668     * See also {@link #focusSearch(int)}, which is what you call to say that you
5669     * have focus, and you want your parent to look for the next one.
5670     *
5671     * You may wish to override this method if your custom {@link View} has an internal
5672     * {@link View} that it wishes to forward the request to.
5673     *
5674     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5675     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5676     *        to give a finer grained hint about where focus is coming from.  May be null
5677     *        if there is no hint.
5678     * @return Whether this view or one of its descendants actually took focus.
5679     */
5680    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5681        // need to be focusable
5682        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5683                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5684            return false;
5685        }
5686
5687        // need to be focusable in touch mode if in touch mode
5688        if (isInTouchMode() &&
5689            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5690               return false;
5691        }
5692
5693        // need to not have any parents blocking us
5694        if (hasAncestorThatBlocksDescendantFocus()) {
5695            return false;
5696        }
5697
5698        handleFocusGainInternal(direction, previouslyFocusedRect);
5699        return true;
5700    }
5701
5702    /**
5703     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5704     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5705     * touch mode to request focus when they are touched.
5706     *
5707     * @return Whether this view or one of its descendants actually took focus.
5708     *
5709     * @see #isInTouchMode()
5710     *
5711     */
5712    public final boolean requestFocusFromTouch() {
5713        // Leave touch mode if we need to
5714        if (isInTouchMode()) {
5715            ViewRootImpl viewRoot = getViewRootImpl();
5716            if (viewRoot != null) {
5717                viewRoot.ensureTouchMode(false);
5718            }
5719        }
5720        return requestFocus(View.FOCUS_DOWN);
5721    }
5722
5723    /**
5724     * @return Whether any ancestor of this view blocks descendant focus.
5725     */
5726    private boolean hasAncestorThatBlocksDescendantFocus() {
5727        ViewParent ancestor = mParent;
5728        while (ancestor instanceof ViewGroup) {
5729            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5730            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5731                return true;
5732            } else {
5733                ancestor = vgAncestor.getParent();
5734            }
5735        }
5736        return false;
5737    }
5738
5739    /**
5740     * @hide
5741     */
5742    public void dispatchStartTemporaryDetach() {
5743        onStartTemporaryDetach();
5744    }
5745
5746    /**
5747     * This is called when a container is going to temporarily detach a child, with
5748     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5749     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5750     * {@link #onDetachedFromWindow()} when the container is done.
5751     */
5752    public void onStartTemporaryDetach() {
5753        removeUnsetPressCallback();
5754        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5755    }
5756
5757    /**
5758     * @hide
5759     */
5760    public void dispatchFinishTemporaryDetach() {
5761        onFinishTemporaryDetach();
5762    }
5763
5764    /**
5765     * Called after {@link #onStartTemporaryDetach} when the container is done
5766     * changing the view.
5767     */
5768    public void onFinishTemporaryDetach() {
5769    }
5770
5771    /**
5772     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5773     * for this view's window.  Returns null if the view is not currently attached
5774     * to the window.  Normally you will not need to use this directly, but
5775     * just use the standard high-level event callbacks like
5776     * {@link #onKeyDown(int, KeyEvent)}.
5777     */
5778    public KeyEvent.DispatcherState getKeyDispatcherState() {
5779        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5780    }
5781
5782    /**
5783     * Dispatch a key event before it is processed by any input method
5784     * associated with the view hierarchy.  This can be used to intercept
5785     * key events in special situations before the IME consumes them; a
5786     * typical example would be handling the BACK key to update the application's
5787     * UI instead of allowing the IME to see it and close itself.
5788     *
5789     * @param event The key event to be dispatched.
5790     * @return True if the event was handled, false otherwise.
5791     */
5792    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5793        return onKeyPreIme(event.getKeyCode(), event);
5794    }
5795
5796    /**
5797     * Dispatch a key event to the next view on the focus path. This path runs
5798     * from the top of the view tree down to the currently focused view. If this
5799     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5800     * the next node down the focus path. This method also fires any key
5801     * listeners.
5802     *
5803     * @param event The key event to be dispatched.
5804     * @return True if the event was handled, false otherwise.
5805     */
5806    public boolean dispatchKeyEvent(KeyEvent event) {
5807        if (mInputEventConsistencyVerifier != null) {
5808            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5809        }
5810
5811        // Give any attached key listener a first crack at the event.
5812        //noinspection SimplifiableIfStatement
5813        ListenerInfo li = mListenerInfo;
5814        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5815                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5816            return true;
5817        }
5818
5819        if (event.dispatch(this, mAttachInfo != null
5820                ? mAttachInfo.mKeyDispatchState : null, this)) {
5821            return true;
5822        }
5823
5824        if (mInputEventConsistencyVerifier != null) {
5825            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5826        }
5827        return false;
5828    }
5829
5830    /**
5831     * Dispatches a key shortcut event.
5832     *
5833     * @param event The key event to be dispatched.
5834     * @return True if the event was handled by the view, false otherwise.
5835     */
5836    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5837        return onKeyShortcut(event.getKeyCode(), event);
5838    }
5839
5840    /**
5841     * Pass the touch screen motion event down to the target view, or this
5842     * view if it is the target.
5843     *
5844     * @param event The motion event to be dispatched.
5845     * @return True if the event was handled by the view, false otherwise.
5846     */
5847    public boolean dispatchTouchEvent(MotionEvent event) {
5848        if (mInputEventConsistencyVerifier != null) {
5849            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5850        }
5851
5852        if (onFilterTouchEventForSecurity(event)) {
5853            //noinspection SimplifiableIfStatement
5854            ListenerInfo li = mListenerInfo;
5855            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5856                    && li.mOnTouchListener.onTouch(this, event)) {
5857                return true;
5858            }
5859
5860            if (onTouchEvent(event)) {
5861                return true;
5862            }
5863        }
5864
5865        if (mInputEventConsistencyVerifier != null) {
5866            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5867        }
5868        return false;
5869    }
5870
5871    /**
5872     * Filter the touch event to apply security policies.
5873     *
5874     * @param event The motion event to be filtered.
5875     * @return True if the event should be dispatched, false if the event should be dropped.
5876     *
5877     * @see #getFilterTouchesWhenObscured
5878     */
5879    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5880        //noinspection RedundantIfStatement
5881        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5882                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5883            // Window is obscured, drop this touch.
5884            return false;
5885        }
5886        return true;
5887    }
5888
5889    /**
5890     * Pass a trackball motion event down to the focused view.
5891     *
5892     * @param event The motion event to be dispatched.
5893     * @return True if the event was handled by the view, false otherwise.
5894     */
5895    public boolean dispatchTrackballEvent(MotionEvent event) {
5896        if (mInputEventConsistencyVerifier != null) {
5897            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5898        }
5899
5900        return onTrackballEvent(event);
5901    }
5902
5903    /**
5904     * Dispatch a generic motion event.
5905     * <p>
5906     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5907     * are delivered to the view under the pointer.  All other generic motion events are
5908     * delivered to the focused view.  Hover events are handled specially and are delivered
5909     * to {@link #onHoverEvent(MotionEvent)}.
5910     * </p>
5911     *
5912     * @param event The motion event to be dispatched.
5913     * @return True if the event was handled by the view, false otherwise.
5914     */
5915    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5916        if (mInputEventConsistencyVerifier != null) {
5917            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5918        }
5919
5920        final int source = event.getSource();
5921        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5922            final int action = event.getAction();
5923            if (action == MotionEvent.ACTION_HOVER_ENTER
5924                    || action == MotionEvent.ACTION_HOVER_MOVE
5925                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5926                if (dispatchHoverEvent(event)) {
5927                    return true;
5928                }
5929            } else if (dispatchGenericPointerEvent(event)) {
5930                return true;
5931            }
5932        } else if (dispatchGenericFocusedEvent(event)) {
5933            return true;
5934        }
5935
5936        if (dispatchGenericMotionEventInternal(event)) {
5937            return true;
5938        }
5939
5940        if (mInputEventConsistencyVerifier != null) {
5941            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5942        }
5943        return false;
5944    }
5945
5946    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5947        //noinspection SimplifiableIfStatement
5948        ListenerInfo li = mListenerInfo;
5949        if (li != null && li.mOnGenericMotionListener != null
5950                && (mViewFlags & ENABLED_MASK) == ENABLED
5951                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5952            return true;
5953        }
5954
5955        if (onGenericMotionEvent(event)) {
5956            return true;
5957        }
5958
5959        if (mInputEventConsistencyVerifier != null) {
5960            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5961        }
5962        return false;
5963    }
5964
5965    /**
5966     * Dispatch a hover event.
5967     * <p>
5968     * Do not call this method directly.
5969     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5970     * </p>
5971     *
5972     * @param event The motion event to be dispatched.
5973     * @return True if the event was handled by the view, false otherwise.
5974     */
5975    protected boolean dispatchHoverEvent(MotionEvent event) {
5976        //noinspection SimplifiableIfStatement
5977        ListenerInfo li = mListenerInfo;
5978        if (li != null && li.mOnHoverListener != null
5979                && (mViewFlags & ENABLED_MASK) == ENABLED
5980                && li.mOnHoverListener.onHover(this, event)) {
5981            return true;
5982        }
5983
5984        return onHoverEvent(event);
5985    }
5986
5987    /**
5988     * Returns true if the view has a child to which it has recently sent
5989     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5990     * it does not have a hovered child, then it must be the innermost hovered view.
5991     * @hide
5992     */
5993    protected boolean hasHoveredChild() {
5994        return false;
5995    }
5996
5997    /**
5998     * Dispatch a generic motion event to the view under the first pointer.
5999     * <p>
6000     * Do not call this method directly.
6001     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6002     * </p>
6003     *
6004     * @param event The motion event to be dispatched.
6005     * @return True if the event was handled by the view, false otherwise.
6006     */
6007    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6008        return false;
6009    }
6010
6011    /**
6012     * Dispatch a generic motion event to the currently focused view.
6013     * <p>
6014     * Do not call this method directly.
6015     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6016     * </p>
6017     *
6018     * @param event The motion event to be dispatched.
6019     * @return True if the event was handled by the view, false otherwise.
6020     */
6021    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6022        return false;
6023    }
6024
6025    /**
6026     * Dispatch a pointer event.
6027     * <p>
6028     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6029     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6030     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6031     * and should not be expected to handle other pointing device features.
6032     * </p>
6033     *
6034     * @param event The motion event to be dispatched.
6035     * @return True if the event was handled by the view, false otherwise.
6036     * @hide
6037     */
6038    public final boolean dispatchPointerEvent(MotionEvent event) {
6039        if (event.isTouchEvent()) {
6040            return dispatchTouchEvent(event);
6041        } else {
6042            return dispatchGenericMotionEvent(event);
6043        }
6044    }
6045
6046    /**
6047     * Called when the window containing this view gains or loses window focus.
6048     * ViewGroups should override to route to their children.
6049     *
6050     * @param hasFocus True if the window containing this view now has focus,
6051     *        false otherwise.
6052     */
6053    public void dispatchWindowFocusChanged(boolean hasFocus) {
6054        onWindowFocusChanged(hasFocus);
6055    }
6056
6057    /**
6058     * Called when the window containing this view gains or loses focus.  Note
6059     * that this is separate from view focus: to receive key events, both
6060     * your view and its window must have focus.  If a window is displayed
6061     * on top of yours that takes input focus, then your own window will lose
6062     * focus but the view focus will remain unchanged.
6063     *
6064     * @param hasWindowFocus True if the window containing this view now has
6065     *        focus, false otherwise.
6066     */
6067    public void onWindowFocusChanged(boolean hasWindowFocus) {
6068        InputMethodManager imm = InputMethodManager.peekInstance();
6069        if (!hasWindowFocus) {
6070            if (isPressed()) {
6071                setPressed(false);
6072            }
6073            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6074                imm.focusOut(this);
6075            }
6076            removeLongPressCallback();
6077            removeTapCallback();
6078            onFocusLost();
6079        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6080            imm.focusIn(this);
6081        }
6082        refreshDrawableState();
6083    }
6084
6085    /**
6086     * Returns true if this view is in a window that currently has window focus.
6087     * Note that this is not the same as the view itself having focus.
6088     *
6089     * @return True if this view is in a window that currently has window focus.
6090     */
6091    public boolean hasWindowFocus() {
6092        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6093    }
6094
6095    /**
6096     * Dispatch a view visibility change down the view hierarchy.
6097     * ViewGroups should override to route to their children.
6098     * @param changedView The view whose visibility changed. Could be 'this' or
6099     * an ancestor view.
6100     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6101     * {@link #INVISIBLE} or {@link #GONE}.
6102     */
6103    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6104        onVisibilityChanged(changedView, visibility);
6105    }
6106
6107    /**
6108     * Called when the visibility of the view or an ancestor of the view is changed.
6109     * @param changedView The view whose visibility changed. Could be 'this' or
6110     * an ancestor view.
6111     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6112     * {@link #INVISIBLE} or {@link #GONE}.
6113     */
6114    protected void onVisibilityChanged(View changedView, int visibility) {
6115        if (visibility == VISIBLE) {
6116            if (mAttachInfo != null) {
6117                initialAwakenScrollBars();
6118            } else {
6119                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6120            }
6121        }
6122    }
6123
6124    /**
6125     * Dispatch a hint about whether this view is displayed. For instance, when
6126     * a View moves out of the screen, it might receives a display hint indicating
6127     * the view is not displayed. Applications should not <em>rely</em> on this hint
6128     * as there is no guarantee that they will receive one.
6129     *
6130     * @param hint A hint about whether or not this view is displayed:
6131     * {@link #VISIBLE} or {@link #INVISIBLE}.
6132     */
6133    public void dispatchDisplayHint(int hint) {
6134        onDisplayHint(hint);
6135    }
6136
6137    /**
6138     * Gives this view a hint about whether is displayed or not. For instance, when
6139     * a View moves out of the screen, it might receives a display hint indicating
6140     * the view is not displayed. Applications should not <em>rely</em> on this hint
6141     * as there is no guarantee that they will receive one.
6142     *
6143     * @param hint A hint about whether or not this view is displayed:
6144     * {@link #VISIBLE} or {@link #INVISIBLE}.
6145     */
6146    protected void onDisplayHint(int hint) {
6147    }
6148
6149    /**
6150     * Dispatch a window visibility change down the view hierarchy.
6151     * ViewGroups should override to route to their children.
6152     *
6153     * @param visibility The new visibility of the window.
6154     *
6155     * @see #onWindowVisibilityChanged(int)
6156     */
6157    public void dispatchWindowVisibilityChanged(int visibility) {
6158        onWindowVisibilityChanged(visibility);
6159    }
6160
6161    /**
6162     * Called when the window containing has change its visibility
6163     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6164     * that this tells you whether or not your window is being made visible
6165     * to the window manager; this does <em>not</em> tell you whether or not
6166     * your window is obscured by other windows on the screen, even if it
6167     * is itself visible.
6168     *
6169     * @param visibility The new visibility of the window.
6170     */
6171    protected void onWindowVisibilityChanged(int visibility) {
6172        if (visibility == VISIBLE) {
6173            initialAwakenScrollBars();
6174        }
6175    }
6176
6177    /**
6178     * Returns the current visibility of the window this view is attached to
6179     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6180     *
6181     * @return Returns the current visibility of the view's window.
6182     */
6183    public int getWindowVisibility() {
6184        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6185    }
6186
6187    /**
6188     * Retrieve the overall visible display size in which the window this view is
6189     * attached to has been positioned in.  This takes into account screen
6190     * decorations above the window, for both cases where the window itself
6191     * is being position inside of them or the window is being placed under
6192     * then and covered insets are used for the window to position its content
6193     * inside.  In effect, this tells you the available area where content can
6194     * be placed and remain visible to users.
6195     *
6196     * <p>This function requires an IPC back to the window manager to retrieve
6197     * the requested information, so should not be used in performance critical
6198     * code like drawing.
6199     *
6200     * @param outRect Filled in with the visible display frame.  If the view
6201     * is not attached to a window, this is simply the raw display size.
6202     */
6203    public void getWindowVisibleDisplayFrame(Rect outRect) {
6204        if (mAttachInfo != null) {
6205            try {
6206                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6207            } catch (RemoteException e) {
6208                return;
6209            }
6210            // XXX This is really broken, and probably all needs to be done
6211            // in the window manager, and we need to know more about whether
6212            // we want the area behind or in front of the IME.
6213            final Rect insets = mAttachInfo.mVisibleInsets;
6214            outRect.left += insets.left;
6215            outRect.top += insets.top;
6216            outRect.right -= insets.right;
6217            outRect.bottom -= insets.bottom;
6218            return;
6219        }
6220        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6221        d.getRectSize(outRect);
6222    }
6223
6224    /**
6225     * Dispatch a notification about a resource configuration change down
6226     * the view hierarchy.
6227     * ViewGroups should override to route to their children.
6228     *
6229     * @param newConfig The new resource configuration.
6230     *
6231     * @see #onConfigurationChanged(android.content.res.Configuration)
6232     */
6233    public void dispatchConfigurationChanged(Configuration newConfig) {
6234        onConfigurationChanged(newConfig);
6235    }
6236
6237    /**
6238     * Called when the current configuration of the resources being used
6239     * by the application have changed.  You can use this to decide when
6240     * to reload resources that can changed based on orientation and other
6241     * configuration characterstics.  You only need to use this if you are
6242     * not relying on the normal {@link android.app.Activity} mechanism of
6243     * recreating the activity instance upon a configuration change.
6244     *
6245     * @param newConfig The new resource configuration.
6246     */
6247    protected void onConfigurationChanged(Configuration newConfig) {
6248    }
6249
6250    /**
6251     * Private function to aggregate all per-view attributes in to the view
6252     * root.
6253     */
6254    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6255        performCollectViewAttributes(attachInfo, visibility);
6256    }
6257
6258    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6259        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
6260            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6261                attachInfo.mKeepScreenOn = true;
6262            }
6263            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6264            ListenerInfo li = mListenerInfo;
6265            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6266                attachInfo.mHasSystemUiListeners = true;
6267            }
6268        }
6269    }
6270
6271    void needGlobalAttributesUpdate(boolean force) {
6272        final AttachInfo ai = mAttachInfo;
6273        if (ai != null) {
6274            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6275                    || ai.mHasSystemUiListeners) {
6276                ai.mRecomputeGlobalAttributes = true;
6277            }
6278        }
6279    }
6280
6281    /**
6282     * Returns whether the device is currently in touch mode.  Touch mode is entered
6283     * once the user begins interacting with the device by touch, and affects various
6284     * things like whether focus is always visible to the user.
6285     *
6286     * @return Whether the device is in touch mode.
6287     */
6288    @ViewDebug.ExportedProperty
6289    public boolean isInTouchMode() {
6290        if (mAttachInfo != null) {
6291            return mAttachInfo.mInTouchMode;
6292        } else {
6293            return ViewRootImpl.isInTouchMode();
6294        }
6295    }
6296
6297    /**
6298     * Returns the context the view is running in, through which it can
6299     * access the current theme, resources, etc.
6300     *
6301     * @return The view's Context.
6302     */
6303    @ViewDebug.CapturedViewProperty
6304    public final Context getContext() {
6305        return mContext;
6306    }
6307
6308    /**
6309     * Handle a key event before it is processed by any input method
6310     * associated with the view hierarchy.  This can be used to intercept
6311     * key events in special situations before the IME consumes them; a
6312     * typical example would be handling the BACK key to update the application's
6313     * UI instead of allowing the IME to see it and close itself.
6314     *
6315     * @param keyCode The value in event.getKeyCode().
6316     * @param event Description of the key event.
6317     * @return If you handled the event, return true. If you want to allow the
6318     *         event to be handled by the next receiver, return false.
6319     */
6320    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6321        return false;
6322    }
6323
6324    /**
6325     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6326     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6327     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6328     * is released, if the view is enabled and clickable.
6329     *
6330     * @param keyCode A key code that represents the button pressed, from
6331     *                {@link android.view.KeyEvent}.
6332     * @param event   The KeyEvent object that defines the button action.
6333     */
6334    public boolean onKeyDown(int keyCode, KeyEvent event) {
6335        boolean result = false;
6336
6337        switch (keyCode) {
6338            case KeyEvent.KEYCODE_DPAD_CENTER:
6339            case KeyEvent.KEYCODE_ENTER: {
6340                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6341                    return true;
6342                }
6343                // Long clickable items don't necessarily have to be clickable
6344                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6345                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6346                        (event.getRepeatCount() == 0)) {
6347                    setPressed(true);
6348                    checkForLongClick(0);
6349                    return true;
6350                }
6351                break;
6352            }
6353        }
6354        return result;
6355    }
6356
6357    /**
6358     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6359     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6360     * the event).
6361     */
6362    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6363        return false;
6364    }
6365
6366    /**
6367     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6368     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6369     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6370     * {@link KeyEvent#KEYCODE_ENTER} is released.
6371     *
6372     * @param keyCode A key code that represents the button pressed, from
6373     *                {@link android.view.KeyEvent}.
6374     * @param event   The KeyEvent object that defines the button action.
6375     */
6376    public boolean onKeyUp(int keyCode, KeyEvent event) {
6377        boolean result = false;
6378
6379        switch (keyCode) {
6380            case KeyEvent.KEYCODE_DPAD_CENTER:
6381            case KeyEvent.KEYCODE_ENTER: {
6382                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6383                    return true;
6384                }
6385                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6386                    setPressed(false);
6387
6388                    if (!mHasPerformedLongPress) {
6389                        // This is a tap, so remove the longpress check
6390                        removeLongPressCallback();
6391
6392                        result = performClick();
6393                    }
6394                }
6395                break;
6396            }
6397        }
6398        return result;
6399    }
6400
6401    /**
6402     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6403     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6404     * the event).
6405     *
6406     * @param keyCode     A key code that represents the button pressed, from
6407     *                    {@link android.view.KeyEvent}.
6408     * @param repeatCount The number of times the action was made.
6409     * @param event       The KeyEvent object that defines the button action.
6410     */
6411    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6412        return false;
6413    }
6414
6415    /**
6416     * Called on the focused view when a key shortcut event is not handled.
6417     * Override this method to implement local key shortcuts for the View.
6418     * Key shortcuts can also be implemented by setting the
6419     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6420     *
6421     * @param keyCode The value in event.getKeyCode().
6422     * @param event Description of the key event.
6423     * @return If you handled the event, return true. If you want to allow the
6424     *         event to be handled by the next receiver, return false.
6425     */
6426    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6427        return false;
6428    }
6429
6430    /**
6431     * Check whether the called view is a text editor, in which case it
6432     * would make sense to automatically display a soft input window for
6433     * it.  Subclasses should override this if they implement
6434     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6435     * a call on that method would return a non-null InputConnection, and
6436     * they are really a first-class editor that the user would normally
6437     * start typing on when the go into a window containing your view.
6438     *
6439     * <p>The default implementation always returns false.  This does
6440     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6441     * will not be called or the user can not otherwise perform edits on your
6442     * view; it is just a hint to the system that this is not the primary
6443     * purpose of this view.
6444     *
6445     * @return Returns true if this view is a text editor, else false.
6446     */
6447    public boolean onCheckIsTextEditor() {
6448        return false;
6449    }
6450
6451    /**
6452     * Create a new InputConnection for an InputMethod to interact
6453     * with the view.  The default implementation returns null, since it doesn't
6454     * support input methods.  You can override this to implement such support.
6455     * This is only needed for views that take focus and text input.
6456     *
6457     * <p>When implementing this, you probably also want to implement
6458     * {@link #onCheckIsTextEditor()} to indicate you will return a
6459     * non-null InputConnection.
6460     *
6461     * @param outAttrs Fill in with attribute information about the connection.
6462     */
6463    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6464        return null;
6465    }
6466
6467    /**
6468     * Called by the {@link android.view.inputmethod.InputMethodManager}
6469     * when a view who is not the current
6470     * input connection target is trying to make a call on the manager.  The
6471     * default implementation returns false; you can override this to return
6472     * true for certain views if you are performing InputConnection proxying
6473     * to them.
6474     * @param view The View that is making the InputMethodManager call.
6475     * @return Return true to allow the call, false to reject.
6476     */
6477    public boolean checkInputConnectionProxy(View view) {
6478        return false;
6479    }
6480
6481    /**
6482     * Show the context menu for this view. It is not safe to hold on to the
6483     * menu after returning from this method.
6484     *
6485     * You should normally not overload this method. Overload
6486     * {@link #onCreateContextMenu(ContextMenu)} or define an
6487     * {@link OnCreateContextMenuListener} to add items to the context menu.
6488     *
6489     * @param menu The context menu to populate
6490     */
6491    public void createContextMenu(ContextMenu menu) {
6492        ContextMenuInfo menuInfo = getContextMenuInfo();
6493
6494        // Sets the current menu info so all items added to menu will have
6495        // my extra info set.
6496        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6497
6498        onCreateContextMenu(menu);
6499        ListenerInfo li = mListenerInfo;
6500        if (li != null && li.mOnCreateContextMenuListener != null) {
6501            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6502        }
6503
6504        // Clear the extra information so subsequent items that aren't mine don't
6505        // have my extra info.
6506        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6507
6508        if (mParent != null) {
6509            mParent.createContextMenu(menu);
6510        }
6511    }
6512
6513    /**
6514     * Views should implement this if they have extra information to associate
6515     * with the context menu. The return result is supplied as a parameter to
6516     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6517     * callback.
6518     *
6519     * @return Extra information about the item for which the context menu
6520     *         should be shown. This information will vary across different
6521     *         subclasses of View.
6522     */
6523    protected ContextMenuInfo getContextMenuInfo() {
6524        return null;
6525    }
6526
6527    /**
6528     * Views should implement this if the view itself is going to add items to
6529     * the context menu.
6530     *
6531     * @param menu the context menu to populate
6532     */
6533    protected void onCreateContextMenu(ContextMenu menu) {
6534    }
6535
6536    /**
6537     * Implement this method to handle trackball motion events.  The
6538     * <em>relative</em> movement of the trackball since the last event
6539     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6540     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6541     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6542     * they will often be fractional values, representing the more fine-grained
6543     * movement information available from a trackball).
6544     *
6545     * @param event The motion event.
6546     * @return True if the event was handled, false otherwise.
6547     */
6548    public boolean onTrackballEvent(MotionEvent event) {
6549        return false;
6550    }
6551
6552    /**
6553     * Implement this method to handle generic motion events.
6554     * <p>
6555     * Generic motion events describe joystick movements, mouse hovers, track pad
6556     * touches, scroll wheel movements and other input events.  The
6557     * {@link MotionEvent#getSource() source} of the motion event specifies
6558     * the class of input that was received.  Implementations of this method
6559     * must examine the bits in the source before processing the event.
6560     * The following code example shows how this is done.
6561     * </p><p>
6562     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6563     * are delivered to the view under the pointer.  All other generic motion events are
6564     * delivered to the focused view.
6565     * </p>
6566     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6567     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6568     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6569     *             // process the joystick movement...
6570     *             return true;
6571     *         }
6572     *     }
6573     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6574     *         switch (event.getAction()) {
6575     *             case MotionEvent.ACTION_HOVER_MOVE:
6576     *                 // process the mouse hover movement...
6577     *                 return true;
6578     *             case MotionEvent.ACTION_SCROLL:
6579     *                 // process the scroll wheel movement...
6580     *                 return true;
6581     *         }
6582     *     }
6583     *     return super.onGenericMotionEvent(event);
6584     * }</pre>
6585     *
6586     * @param event The generic motion event being processed.
6587     * @return True if the event was handled, false otherwise.
6588     */
6589    public boolean onGenericMotionEvent(MotionEvent event) {
6590        return false;
6591    }
6592
6593    /**
6594     * Implement this method to handle hover events.
6595     * <p>
6596     * This method is called whenever a pointer is hovering into, over, or out of the
6597     * bounds of a view and the view is not currently being touched.
6598     * Hover events are represented as pointer events with action
6599     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6600     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6601     * </p>
6602     * <ul>
6603     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6604     * when the pointer enters the bounds of the view.</li>
6605     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6606     * when the pointer has already entered the bounds of the view and has moved.</li>
6607     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6608     * when the pointer has exited the bounds of the view or when the pointer is
6609     * about to go down due to a button click, tap, or similar user action that
6610     * causes the view to be touched.</li>
6611     * </ul>
6612     * <p>
6613     * The view should implement this method to return true to indicate that it is
6614     * handling the hover event, such as by changing its drawable state.
6615     * </p><p>
6616     * The default implementation calls {@link #setHovered} to update the hovered state
6617     * of the view when a hover enter or hover exit event is received, if the view
6618     * is enabled and is clickable.  The default implementation also sends hover
6619     * accessibility events.
6620     * </p>
6621     *
6622     * @param event The motion event that describes the hover.
6623     * @return True if the view handled the hover event.
6624     *
6625     * @see #isHovered
6626     * @see #setHovered
6627     * @see #onHoverChanged
6628     */
6629    public boolean onHoverEvent(MotionEvent event) {
6630        // The root view may receive hover (or touch) events that are outside the bounds of
6631        // the window.  This code ensures that we only send accessibility events for
6632        // hovers that are actually within the bounds of the root view.
6633        final int action = event.getAction();
6634        if (!mSendingHoverAccessibilityEvents) {
6635            if ((action == MotionEvent.ACTION_HOVER_ENTER
6636                    || action == MotionEvent.ACTION_HOVER_MOVE)
6637                    && !hasHoveredChild()
6638                    && pointInView(event.getX(), event.getY())) {
6639                mSendingHoverAccessibilityEvents = true;
6640                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6641            }
6642        } else {
6643            if (action == MotionEvent.ACTION_HOVER_EXIT
6644                    || (action == MotionEvent.ACTION_HOVER_MOVE
6645                            && !pointInView(event.getX(), event.getY()))) {
6646                mSendingHoverAccessibilityEvents = false;
6647                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6648            }
6649        }
6650
6651        if (isHoverable()) {
6652            switch (action) {
6653                case MotionEvent.ACTION_HOVER_ENTER:
6654                    setHovered(true);
6655                    break;
6656                case MotionEvent.ACTION_HOVER_EXIT:
6657                    setHovered(false);
6658                    break;
6659            }
6660
6661            // Dispatch the event to onGenericMotionEvent before returning true.
6662            // This is to provide compatibility with existing applications that
6663            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6664            // break because of the new default handling for hoverable views
6665            // in onHoverEvent.
6666            // Note that onGenericMotionEvent will be called by default when
6667            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6668            dispatchGenericMotionEventInternal(event);
6669            return true;
6670        }
6671        return false;
6672    }
6673
6674    /**
6675     * Returns true if the view should handle {@link #onHoverEvent}
6676     * by calling {@link #setHovered} to change its hovered state.
6677     *
6678     * @return True if the view is hoverable.
6679     */
6680    private boolean isHoverable() {
6681        final int viewFlags = mViewFlags;
6682        //noinspection SimplifiableIfStatement
6683        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6684            return false;
6685        }
6686
6687        return (viewFlags & CLICKABLE) == CLICKABLE
6688                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6689    }
6690
6691    /**
6692     * Returns true if the view is currently hovered.
6693     *
6694     * @return True if the view is currently hovered.
6695     *
6696     * @see #setHovered
6697     * @see #onHoverChanged
6698     */
6699    @ViewDebug.ExportedProperty
6700    public boolean isHovered() {
6701        return (mPrivateFlags & HOVERED) != 0;
6702    }
6703
6704    /**
6705     * Sets whether the view is currently hovered.
6706     * <p>
6707     * Calling this method also changes the drawable state of the view.  This
6708     * enables the view to react to hover by using different drawable resources
6709     * to change its appearance.
6710     * </p><p>
6711     * The {@link #onHoverChanged} method is called when the hovered state changes.
6712     * </p>
6713     *
6714     * @param hovered True if the view is hovered.
6715     *
6716     * @see #isHovered
6717     * @see #onHoverChanged
6718     */
6719    public void setHovered(boolean hovered) {
6720        if (hovered) {
6721            if ((mPrivateFlags & HOVERED) == 0) {
6722                mPrivateFlags |= HOVERED;
6723                refreshDrawableState();
6724                onHoverChanged(true);
6725            }
6726        } else {
6727            if ((mPrivateFlags & HOVERED) != 0) {
6728                mPrivateFlags &= ~HOVERED;
6729                refreshDrawableState();
6730                onHoverChanged(false);
6731            }
6732        }
6733    }
6734
6735    /**
6736     * Implement this method to handle hover state changes.
6737     * <p>
6738     * This method is called whenever the hover state changes as a result of a
6739     * call to {@link #setHovered}.
6740     * </p>
6741     *
6742     * @param hovered The current hover state, as returned by {@link #isHovered}.
6743     *
6744     * @see #isHovered
6745     * @see #setHovered
6746     */
6747    public void onHoverChanged(boolean hovered) {
6748    }
6749
6750    /**
6751     * Implement this method to handle touch screen motion events.
6752     *
6753     * @param event The motion event.
6754     * @return True if the event was handled, false otherwise.
6755     */
6756    public boolean onTouchEvent(MotionEvent event) {
6757        final int viewFlags = mViewFlags;
6758
6759        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6760            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6761                setPressed(false);
6762            }
6763            // A disabled view that is clickable still consumes the touch
6764            // events, it just doesn't respond to them.
6765            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6766                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6767        }
6768
6769        if (mTouchDelegate != null) {
6770            if (mTouchDelegate.onTouchEvent(event)) {
6771                return true;
6772            }
6773        }
6774
6775        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6776                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6777            switch (event.getAction()) {
6778                case MotionEvent.ACTION_UP:
6779                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6780                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6781                        // take focus if we don't have it already and we should in
6782                        // touch mode.
6783                        boolean focusTaken = false;
6784                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6785                            focusTaken = requestFocus();
6786                        }
6787
6788                        if (prepressed) {
6789                            // The button is being released before we actually
6790                            // showed it as pressed.  Make it show the pressed
6791                            // state now (before scheduling the click) to ensure
6792                            // the user sees it.
6793                            setPressed(true);
6794                       }
6795
6796                        if (!mHasPerformedLongPress) {
6797                            // This is a tap, so remove the longpress check
6798                            removeLongPressCallback();
6799
6800                            // Only perform take click actions if we were in the pressed state
6801                            if (!focusTaken) {
6802                                // Use a Runnable and post this rather than calling
6803                                // performClick directly. This lets other visual state
6804                                // of the view update before click actions start.
6805                                if (mPerformClick == null) {
6806                                    mPerformClick = new PerformClick();
6807                                }
6808                                if (!post(mPerformClick)) {
6809                                    performClick();
6810                                }
6811                            }
6812                        }
6813
6814                        if (mUnsetPressedState == null) {
6815                            mUnsetPressedState = new UnsetPressedState();
6816                        }
6817
6818                        if (prepressed) {
6819                            postDelayed(mUnsetPressedState,
6820                                    ViewConfiguration.getPressedStateDuration());
6821                        } else if (!post(mUnsetPressedState)) {
6822                            // If the post failed, unpress right now
6823                            mUnsetPressedState.run();
6824                        }
6825                        removeTapCallback();
6826                    }
6827                    break;
6828
6829                case MotionEvent.ACTION_DOWN:
6830                    mHasPerformedLongPress = false;
6831
6832                    if (performButtonActionOnTouchDown(event)) {
6833                        break;
6834                    }
6835
6836                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6837                    boolean isInScrollingContainer = isInScrollingContainer();
6838
6839                    // For views inside a scrolling container, delay the pressed feedback for
6840                    // a short period in case this is a scroll.
6841                    if (isInScrollingContainer) {
6842                        mPrivateFlags |= PREPRESSED;
6843                        if (mPendingCheckForTap == null) {
6844                            mPendingCheckForTap = new CheckForTap();
6845                        }
6846                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6847                    } else {
6848                        // Not inside a scrolling container, so show the feedback right away
6849                        setPressed(true);
6850                        checkForLongClick(0);
6851                    }
6852                    break;
6853
6854                case MotionEvent.ACTION_CANCEL:
6855                    setPressed(false);
6856                    removeTapCallback();
6857                    break;
6858
6859                case MotionEvent.ACTION_MOVE:
6860                    final int x = (int) event.getX();
6861                    final int y = (int) event.getY();
6862
6863                    // Be lenient about moving outside of buttons
6864                    if (!pointInView(x, y, mTouchSlop)) {
6865                        // Outside button
6866                        removeTapCallback();
6867                        if ((mPrivateFlags & PRESSED) != 0) {
6868                            // Remove any future long press/tap checks
6869                            removeLongPressCallback();
6870
6871                            setPressed(false);
6872                        }
6873                    }
6874                    break;
6875            }
6876            return true;
6877        }
6878
6879        return false;
6880    }
6881
6882    /**
6883     * @hide
6884     */
6885    public boolean isInScrollingContainer() {
6886        ViewParent p = getParent();
6887        while (p != null && p instanceof ViewGroup) {
6888            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6889                return true;
6890            }
6891            p = p.getParent();
6892        }
6893        return false;
6894    }
6895
6896    /**
6897     * Remove the longpress detection timer.
6898     */
6899    private void removeLongPressCallback() {
6900        if (mPendingCheckForLongPress != null) {
6901          removeCallbacks(mPendingCheckForLongPress);
6902        }
6903    }
6904
6905    /**
6906     * Remove the pending click action
6907     */
6908    private void removePerformClickCallback() {
6909        if (mPerformClick != null) {
6910            removeCallbacks(mPerformClick);
6911        }
6912    }
6913
6914    /**
6915     * Remove the prepress detection timer.
6916     */
6917    private void removeUnsetPressCallback() {
6918        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6919            setPressed(false);
6920            removeCallbacks(mUnsetPressedState);
6921        }
6922    }
6923
6924    /**
6925     * Remove the tap detection timer.
6926     */
6927    private void removeTapCallback() {
6928        if (mPendingCheckForTap != null) {
6929            mPrivateFlags &= ~PREPRESSED;
6930            removeCallbacks(mPendingCheckForTap);
6931        }
6932    }
6933
6934    /**
6935     * Cancels a pending long press.  Your subclass can use this if you
6936     * want the context menu to come up if the user presses and holds
6937     * at the same place, but you don't want it to come up if they press
6938     * and then move around enough to cause scrolling.
6939     */
6940    public void cancelLongPress() {
6941        removeLongPressCallback();
6942
6943        /*
6944         * The prepressed state handled by the tap callback is a display
6945         * construct, but the tap callback will post a long press callback
6946         * less its own timeout. Remove it here.
6947         */
6948        removeTapCallback();
6949    }
6950
6951    /**
6952     * Remove the pending callback for sending a
6953     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6954     */
6955    private void removeSendViewScrolledAccessibilityEventCallback() {
6956        if (mSendViewScrolledAccessibilityEvent != null) {
6957            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6958        }
6959    }
6960
6961    /**
6962     * Sets the TouchDelegate for this View.
6963     */
6964    public void setTouchDelegate(TouchDelegate delegate) {
6965        mTouchDelegate = delegate;
6966    }
6967
6968    /**
6969     * Gets the TouchDelegate for this View.
6970     */
6971    public TouchDelegate getTouchDelegate() {
6972        return mTouchDelegate;
6973    }
6974
6975    /**
6976     * Set flags controlling behavior of this view.
6977     *
6978     * @param flags Constant indicating the value which should be set
6979     * @param mask Constant indicating the bit range that should be changed
6980     */
6981    void setFlags(int flags, int mask) {
6982        int old = mViewFlags;
6983        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6984
6985        int changed = mViewFlags ^ old;
6986        if (changed == 0) {
6987            return;
6988        }
6989        int privateFlags = mPrivateFlags;
6990
6991        /* Check if the FOCUSABLE bit has changed */
6992        if (((changed & FOCUSABLE_MASK) != 0) &&
6993                ((privateFlags & HAS_BOUNDS) !=0)) {
6994            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6995                    && ((privateFlags & FOCUSED) != 0)) {
6996                /* Give up focus if we are no longer focusable */
6997                clearFocus();
6998            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6999                    && ((privateFlags & FOCUSED) == 0)) {
7000                /*
7001                 * Tell the view system that we are now available to take focus
7002                 * if no one else already has it.
7003                 */
7004                if (mParent != null) mParent.focusableViewAvailable(this);
7005            }
7006        }
7007
7008        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7009            if ((changed & VISIBILITY_MASK) != 0) {
7010                /*
7011                 * If this view is becoming visible, invalidate it in case it changed while
7012                 * it was not visible. Marking it drawn ensures that the invalidation will
7013                 * go through.
7014                 */
7015                mPrivateFlags |= DRAWN;
7016                invalidate(true);
7017
7018                needGlobalAttributesUpdate(true);
7019
7020                // a view becoming visible is worth notifying the parent
7021                // about in case nothing has focus.  even if this specific view
7022                // isn't focusable, it may contain something that is, so let
7023                // the root view try to give this focus if nothing else does.
7024                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7025                    mParent.focusableViewAvailable(this);
7026                }
7027            }
7028        }
7029
7030        /* Check if the GONE bit has changed */
7031        if ((changed & GONE) != 0) {
7032            needGlobalAttributesUpdate(false);
7033            requestLayout();
7034
7035            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7036                if (hasFocus()) clearFocus();
7037                destroyDrawingCache();
7038                if (mParent instanceof View) {
7039                    // GONE views noop invalidation, so invalidate the parent
7040                    ((View) mParent).invalidate(true);
7041                }
7042                // Mark the view drawn to ensure that it gets invalidated properly the next
7043                // time it is visible and gets invalidated
7044                mPrivateFlags |= DRAWN;
7045            }
7046            if (mAttachInfo != null) {
7047                mAttachInfo.mViewVisibilityChanged = true;
7048            }
7049        }
7050
7051        /* Check if the VISIBLE bit has changed */
7052        if ((changed & INVISIBLE) != 0) {
7053            needGlobalAttributesUpdate(false);
7054            /*
7055             * If this view is becoming invisible, set the DRAWN flag so that
7056             * the next invalidate() will not be skipped.
7057             */
7058            mPrivateFlags |= DRAWN;
7059
7060            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7061                // root view becoming invisible shouldn't clear focus
7062                if (getRootView() != this) {
7063                    clearFocus();
7064                }
7065            }
7066            if (mAttachInfo != null) {
7067                mAttachInfo.mViewVisibilityChanged = true;
7068            }
7069        }
7070
7071        if ((changed & VISIBILITY_MASK) != 0) {
7072            if (mParent instanceof ViewGroup) {
7073                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7074                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7075                ((View) mParent).invalidate(true);
7076            } else if (mParent != null) {
7077                mParent.invalidateChild(this, null);
7078            }
7079            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7080        }
7081
7082        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7083            destroyDrawingCache();
7084        }
7085
7086        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7087            destroyDrawingCache();
7088            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7089            invalidateParentCaches();
7090        }
7091
7092        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7093            destroyDrawingCache();
7094            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7095        }
7096
7097        if ((changed & DRAW_MASK) != 0) {
7098            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7099                if (mBGDrawable != null) {
7100                    mPrivateFlags &= ~SKIP_DRAW;
7101                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7102                } else {
7103                    mPrivateFlags |= SKIP_DRAW;
7104                }
7105            } else {
7106                mPrivateFlags &= ~SKIP_DRAW;
7107            }
7108            requestLayout();
7109            invalidate(true);
7110        }
7111
7112        if ((changed & KEEP_SCREEN_ON) != 0) {
7113            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7114                mParent.recomputeViewAttributes(this);
7115            }
7116        }
7117    }
7118
7119    /**
7120     * Change the view's z order in the tree, so it's on top of other sibling
7121     * views
7122     */
7123    public void bringToFront() {
7124        if (mParent != null) {
7125            mParent.bringChildToFront(this);
7126        }
7127    }
7128
7129    /**
7130     * This is called in response to an internal scroll in this view (i.e., the
7131     * view scrolled its own contents). This is typically as a result of
7132     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7133     * called.
7134     *
7135     * @param l Current horizontal scroll origin.
7136     * @param t Current vertical scroll origin.
7137     * @param oldl Previous horizontal scroll origin.
7138     * @param oldt Previous vertical scroll origin.
7139     */
7140    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7141        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7142            postSendViewScrolledAccessibilityEventCallback();
7143        }
7144
7145        mBackgroundSizeChanged = true;
7146
7147        final AttachInfo ai = mAttachInfo;
7148        if (ai != null) {
7149            ai.mViewScrollChanged = true;
7150        }
7151    }
7152
7153    /**
7154     * Interface definition for a callback to be invoked when the layout bounds of a view
7155     * changes due to layout processing.
7156     */
7157    public interface OnLayoutChangeListener {
7158        /**
7159         * Called when the focus state of a view has changed.
7160         *
7161         * @param v The view whose state has changed.
7162         * @param left The new value of the view's left property.
7163         * @param top The new value of the view's top property.
7164         * @param right The new value of the view's right property.
7165         * @param bottom The new value of the view's bottom property.
7166         * @param oldLeft The previous value of the view's left property.
7167         * @param oldTop The previous value of the view's top property.
7168         * @param oldRight The previous value of the view's right property.
7169         * @param oldBottom The previous value of the view's bottom property.
7170         */
7171        void onLayoutChange(View v, int left, int top, int right, int bottom,
7172            int oldLeft, int oldTop, int oldRight, int oldBottom);
7173    }
7174
7175    /**
7176     * This is called during layout when the size of this view has changed. If
7177     * you were just added to the view hierarchy, you're called with the old
7178     * values of 0.
7179     *
7180     * @param w Current width of this view.
7181     * @param h Current height of this view.
7182     * @param oldw Old width of this view.
7183     * @param oldh Old height of this view.
7184     */
7185    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7186    }
7187
7188    /**
7189     * Called by draw to draw the child views. This may be overridden
7190     * by derived classes to gain control just before its children are drawn
7191     * (but after its own view has been drawn).
7192     * @param canvas the canvas on which to draw the view
7193     */
7194    protected void dispatchDraw(Canvas canvas) {
7195    }
7196
7197    /**
7198     * Gets the parent of this view. Note that the parent is a
7199     * ViewParent and not necessarily a View.
7200     *
7201     * @return Parent of this view.
7202     */
7203    public final ViewParent getParent() {
7204        return mParent;
7205    }
7206
7207    /**
7208     * Set the horizontal scrolled position of your view. This will cause a call to
7209     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7210     * invalidated.
7211     * @param value the x position to scroll to
7212     */
7213    public void setScrollX(int value) {
7214        scrollTo(value, mScrollY);
7215    }
7216
7217    /**
7218     * Set the vertical scrolled position of your view. This will cause a call to
7219     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7220     * invalidated.
7221     * @param value the y position to scroll to
7222     */
7223    public void setScrollY(int value) {
7224        scrollTo(mScrollX, value);
7225    }
7226
7227    /**
7228     * Return the scrolled left position of this view. This is the left edge of
7229     * the displayed part of your view. You do not need to draw any pixels
7230     * farther left, since those are outside of the frame of your view on
7231     * screen.
7232     *
7233     * @return The left edge of the displayed part of your view, in pixels.
7234     */
7235    public final int getScrollX() {
7236        return mScrollX;
7237    }
7238
7239    /**
7240     * Return the scrolled top position of this view. This is the top edge of
7241     * the displayed part of your view. You do not need to draw any pixels above
7242     * it, since those are outside of the frame of your view on screen.
7243     *
7244     * @return The top edge of the displayed part of your view, in pixels.
7245     */
7246    public final int getScrollY() {
7247        return mScrollY;
7248    }
7249
7250    /**
7251     * Return the width of the your view.
7252     *
7253     * @return The width of your view, in pixels.
7254     */
7255    @ViewDebug.ExportedProperty(category = "layout")
7256    public final int getWidth() {
7257        return mRight - mLeft;
7258    }
7259
7260    /**
7261     * Return the height of your view.
7262     *
7263     * @return The height of your view, in pixels.
7264     */
7265    @ViewDebug.ExportedProperty(category = "layout")
7266    public final int getHeight() {
7267        return mBottom - mTop;
7268    }
7269
7270    /**
7271     * Return the visible drawing bounds of your view. Fills in the output
7272     * rectangle with the values from getScrollX(), getScrollY(),
7273     * getWidth(), and getHeight().
7274     *
7275     * @param outRect The (scrolled) drawing bounds of the view.
7276     */
7277    public void getDrawingRect(Rect outRect) {
7278        outRect.left = mScrollX;
7279        outRect.top = mScrollY;
7280        outRect.right = mScrollX + (mRight - mLeft);
7281        outRect.bottom = mScrollY + (mBottom - mTop);
7282    }
7283
7284    /**
7285     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7286     * raw width component (that is the result is masked by
7287     * {@link #MEASURED_SIZE_MASK}).
7288     *
7289     * @return The raw measured width of this view.
7290     */
7291    public final int getMeasuredWidth() {
7292        return mMeasuredWidth & MEASURED_SIZE_MASK;
7293    }
7294
7295    /**
7296     * Return the full width measurement information for this view as computed
7297     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7298     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7299     * This should be used during measurement and layout calculations only. Use
7300     * {@link #getWidth()} to see how wide a view is after layout.
7301     *
7302     * @return The measured width of this view as a bit mask.
7303     */
7304    public final int getMeasuredWidthAndState() {
7305        return mMeasuredWidth;
7306    }
7307
7308    /**
7309     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7310     * raw width component (that is the result is masked by
7311     * {@link #MEASURED_SIZE_MASK}).
7312     *
7313     * @return The raw measured height of this view.
7314     */
7315    public final int getMeasuredHeight() {
7316        return mMeasuredHeight & MEASURED_SIZE_MASK;
7317    }
7318
7319    /**
7320     * Return the full height measurement information for this view as computed
7321     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7322     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7323     * This should be used during measurement and layout calculations only. Use
7324     * {@link #getHeight()} to see how wide a view is after layout.
7325     *
7326     * @return The measured width of this view as a bit mask.
7327     */
7328    public final int getMeasuredHeightAndState() {
7329        return mMeasuredHeight;
7330    }
7331
7332    /**
7333     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7334     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7335     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7336     * and the height component is at the shifted bits
7337     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7338     */
7339    public final int getMeasuredState() {
7340        return (mMeasuredWidth&MEASURED_STATE_MASK)
7341                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7342                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7343    }
7344
7345    /**
7346     * The transform matrix of this view, which is calculated based on the current
7347     * roation, scale, and pivot properties.
7348     *
7349     * @see #getRotation()
7350     * @see #getScaleX()
7351     * @see #getScaleY()
7352     * @see #getPivotX()
7353     * @see #getPivotY()
7354     * @return The current transform matrix for the view
7355     */
7356    public Matrix getMatrix() {
7357        if (mTransformationInfo != null) {
7358            updateMatrix();
7359            return mTransformationInfo.mMatrix;
7360        }
7361        return Matrix.IDENTITY_MATRIX;
7362    }
7363
7364    /**
7365     * Utility function to determine if the value is far enough away from zero to be
7366     * considered non-zero.
7367     * @param value A floating point value to check for zero-ness
7368     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7369     */
7370    private static boolean nonzero(float value) {
7371        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7372    }
7373
7374    /**
7375     * Returns true if the transform matrix is the identity matrix.
7376     * Recomputes the matrix if necessary.
7377     *
7378     * @return True if the transform matrix is the identity matrix, false otherwise.
7379     */
7380    final boolean hasIdentityMatrix() {
7381        if (mTransformationInfo != null) {
7382            updateMatrix();
7383            return mTransformationInfo.mMatrixIsIdentity;
7384        }
7385        return true;
7386    }
7387
7388    void ensureTransformationInfo() {
7389        if (mTransformationInfo == null) {
7390            mTransformationInfo = new TransformationInfo();
7391        }
7392    }
7393
7394    /**
7395     * Recomputes the transform matrix if necessary.
7396     */
7397    private void updateMatrix() {
7398        final TransformationInfo info = mTransformationInfo;
7399        if (info == null) {
7400            return;
7401        }
7402        if (info.mMatrixDirty) {
7403            // transform-related properties have changed since the last time someone
7404            // asked for the matrix; recalculate it with the current values
7405
7406            // Figure out if we need to update the pivot point
7407            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7408                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7409                    info.mPrevWidth = mRight - mLeft;
7410                    info.mPrevHeight = mBottom - mTop;
7411                    info.mPivotX = info.mPrevWidth / 2f;
7412                    info.mPivotY = info.mPrevHeight / 2f;
7413                }
7414            }
7415            info.mMatrix.reset();
7416            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7417                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7418                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7419                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7420            } else {
7421                if (info.mCamera == null) {
7422                    info.mCamera = new Camera();
7423                    info.matrix3D = new Matrix();
7424                }
7425                info.mCamera.save();
7426                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7427                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7428                info.mCamera.getMatrix(info.matrix3D);
7429                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7430                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7431                        info.mPivotY + info.mTranslationY);
7432                info.mMatrix.postConcat(info.matrix3D);
7433                info.mCamera.restore();
7434            }
7435            info.mMatrixDirty = false;
7436            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7437            info.mInverseMatrixDirty = true;
7438        }
7439    }
7440
7441    /**
7442     * Utility method to retrieve the inverse of the current mMatrix property.
7443     * We cache the matrix to avoid recalculating it when transform properties
7444     * have not changed.
7445     *
7446     * @return The inverse of the current matrix of this view.
7447     */
7448    final Matrix getInverseMatrix() {
7449        final TransformationInfo info = mTransformationInfo;
7450        if (info != null) {
7451            updateMatrix();
7452            if (info.mInverseMatrixDirty) {
7453                if (info.mInverseMatrix == null) {
7454                    info.mInverseMatrix = new Matrix();
7455                }
7456                info.mMatrix.invert(info.mInverseMatrix);
7457                info.mInverseMatrixDirty = false;
7458            }
7459            return info.mInverseMatrix;
7460        }
7461        return Matrix.IDENTITY_MATRIX;
7462    }
7463
7464    /**
7465     * Gets the distance along the Z axis from the camera to this view.
7466     *
7467     * @see #setCameraDistance(float)
7468     *
7469     * @return The distance along the Z axis.
7470     */
7471    public float getCameraDistance() {
7472        ensureTransformationInfo();
7473        final float dpi = mResources.getDisplayMetrics().densityDpi;
7474        final TransformationInfo info = mTransformationInfo;
7475        if (info.mCamera == null) {
7476            info.mCamera = new Camera();
7477            info.matrix3D = new Matrix();
7478        }
7479        return -(info.mCamera.getLocationZ() * dpi);
7480    }
7481
7482    /**
7483     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7484     * views are drawn) from the camera to this view. The camera's distance
7485     * affects 3D transformations, for instance rotations around the X and Y
7486     * axis. If the rotationX or rotationY properties are changed and this view is
7487     * large (more than half the size of the screen), it is recommended to always
7488     * use a camera distance that's greater than the height (X axis rotation) or
7489     * the width (Y axis rotation) of this view.</p>
7490     *
7491     * <p>The distance of the camera from the view plane can have an affect on the
7492     * perspective distortion of the view when it is rotated around the x or y axis.
7493     * For example, a large distance will result in a large viewing angle, and there
7494     * will not be much perspective distortion of the view as it rotates. A short
7495     * distance may cause much more perspective distortion upon rotation, and can
7496     * also result in some drawing artifacts if the rotated view ends up partially
7497     * behind the camera (which is why the recommendation is to use a distance at
7498     * least as far as the size of the view, if the view is to be rotated.)</p>
7499     *
7500     * <p>The distance is expressed in "depth pixels." The default distance depends
7501     * on the screen density. For instance, on a medium density display, the
7502     * default distance is 1280. On a high density display, the default distance
7503     * is 1920.</p>
7504     *
7505     * <p>If you want to specify a distance that leads to visually consistent
7506     * results across various densities, use the following formula:</p>
7507     * <pre>
7508     * float scale = context.getResources().getDisplayMetrics().density;
7509     * view.setCameraDistance(distance * scale);
7510     * </pre>
7511     *
7512     * <p>The density scale factor of a high density display is 1.5,
7513     * and 1920 = 1280 * 1.5.</p>
7514     *
7515     * @param distance The distance in "depth pixels", if negative the opposite
7516     *        value is used
7517     *
7518     * @see #setRotationX(float)
7519     * @see #setRotationY(float)
7520     */
7521    public void setCameraDistance(float distance) {
7522        invalidateViewProperty(true, false);
7523
7524        ensureTransformationInfo();
7525        final float dpi = mResources.getDisplayMetrics().densityDpi;
7526        final TransformationInfo info = mTransformationInfo;
7527        if (info.mCamera == null) {
7528            info.mCamera = new Camera();
7529            info.matrix3D = new Matrix();
7530        }
7531
7532        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7533        info.mMatrixDirty = true;
7534
7535        invalidateViewProperty(false, false);
7536        if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7537            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
7538        }
7539    }
7540
7541    /**
7542     * The degrees that the view is rotated around the pivot point.
7543     *
7544     * @see #setRotation(float)
7545     * @see #getPivotX()
7546     * @see #getPivotY()
7547     *
7548     * @return The degrees of rotation.
7549     */
7550    @ViewDebug.ExportedProperty(category = "drawing")
7551    public float getRotation() {
7552        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7553    }
7554
7555    /**
7556     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7557     * result in clockwise rotation.
7558     *
7559     * @param rotation The degrees of rotation.
7560     *
7561     * @see #getRotation()
7562     * @see #getPivotX()
7563     * @see #getPivotY()
7564     * @see #setRotationX(float)
7565     * @see #setRotationY(float)
7566     *
7567     * @attr ref android.R.styleable#View_rotation
7568     */
7569    public void setRotation(float rotation) {
7570        ensureTransformationInfo();
7571        final TransformationInfo info = mTransformationInfo;
7572        if (info.mRotation != rotation) {
7573            // Double-invalidation is necessary to capture view's old and new areas
7574            invalidateViewProperty(true, false);
7575            info.mRotation = rotation;
7576            info.mMatrixDirty = true;
7577            invalidateViewProperty(false, true);
7578            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7579                mDisplayList.setRotation(rotation);
7580            }
7581        }
7582    }
7583
7584    /**
7585     * The degrees that the view is rotated around the vertical axis through the pivot point.
7586     *
7587     * @see #getPivotX()
7588     * @see #getPivotY()
7589     * @see #setRotationY(float)
7590     *
7591     * @return The degrees of Y rotation.
7592     */
7593    @ViewDebug.ExportedProperty(category = "drawing")
7594    public float getRotationY() {
7595        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7596    }
7597
7598    /**
7599     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7600     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7601     * down the y axis.
7602     *
7603     * When rotating large views, it is recommended to adjust the camera distance
7604     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7605     *
7606     * @param rotationY The degrees of Y rotation.
7607     *
7608     * @see #getRotationY()
7609     * @see #getPivotX()
7610     * @see #getPivotY()
7611     * @see #setRotation(float)
7612     * @see #setRotationX(float)
7613     * @see #setCameraDistance(float)
7614     *
7615     * @attr ref android.R.styleable#View_rotationY
7616     */
7617    public void setRotationY(float rotationY) {
7618        ensureTransformationInfo();
7619        final TransformationInfo info = mTransformationInfo;
7620        if (info.mRotationY != rotationY) {
7621            invalidateViewProperty(true, false);
7622            info.mRotationY = rotationY;
7623            info.mMatrixDirty = true;
7624            invalidateViewProperty(false, true);
7625            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7626                mDisplayList.setRotationY(rotationY);
7627            }
7628        }
7629    }
7630
7631    /**
7632     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7633     *
7634     * @see #getPivotX()
7635     * @see #getPivotY()
7636     * @see #setRotationX(float)
7637     *
7638     * @return The degrees of X rotation.
7639     */
7640    @ViewDebug.ExportedProperty(category = "drawing")
7641    public float getRotationX() {
7642        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7643    }
7644
7645    /**
7646     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7647     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7648     * x axis.
7649     *
7650     * When rotating large views, it is recommended to adjust the camera distance
7651     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7652     *
7653     * @param rotationX The degrees of X rotation.
7654     *
7655     * @see #getRotationX()
7656     * @see #getPivotX()
7657     * @see #getPivotY()
7658     * @see #setRotation(float)
7659     * @see #setRotationY(float)
7660     * @see #setCameraDistance(float)
7661     *
7662     * @attr ref android.R.styleable#View_rotationX
7663     */
7664    public void setRotationX(float rotationX) {
7665        ensureTransformationInfo();
7666        final TransformationInfo info = mTransformationInfo;
7667        if (info.mRotationX != rotationX) {
7668            invalidateViewProperty(true, false);
7669            info.mRotationX = rotationX;
7670            info.mMatrixDirty = true;
7671            invalidateViewProperty(false, true);
7672            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7673                mDisplayList.setRotationX(rotationX);
7674            }
7675        }
7676    }
7677
7678    /**
7679     * The amount that the view is scaled in x around the pivot point, as a proportion of
7680     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7681     *
7682     * <p>By default, this is 1.0f.
7683     *
7684     * @see #getPivotX()
7685     * @see #getPivotY()
7686     * @return The scaling factor.
7687     */
7688    @ViewDebug.ExportedProperty(category = "drawing")
7689    public float getScaleX() {
7690        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7691    }
7692
7693    /**
7694     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7695     * the view's unscaled width. A value of 1 means that no scaling is applied.
7696     *
7697     * @param scaleX The scaling factor.
7698     * @see #getPivotX()
7699     * @see #getPivotY()
7700     *
7701     * @attr ref android.R.styleable#View_scaleX
7702     */
7703    public void setScaleX(float scaleX) {
7704        ensureTransformationInfo();
7705        final TransformationInfo info = mTransformationInfo;
7706        if (info.mScaleX != scaleX) {
7707            invalidateViewProperty(true, false);
7708            info.mScaleX = scaleX;
7709            info.mMatrixDirty = true;
7710            invalidateViewProperty(false, true);
7711            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7712                mDisplayList.setScaleX(scaleX);
7713            }
7714        }
7715    }
7716
7717    /**
7718     * The amount that the view is scaled in y around the pivot point, as a proportion of
7719     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7720     *
7721     * <p>By default, this is 1.0f.
7722     *
7723     * @see #getPivotX()
7724     * @see #getPivotY()
7725     * @return The scaling factor.
7726     */
7727    @ViewDebug.ExportedProperty(category = "drawing")
7728    public float getScaleY() {
7729        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7730    }
7731
7732    /**
7733     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7734     * the view's unscaled width. A value of 1 means that no scaling is applied.
7735     *
7736     * @param scaleY The scaling factor.
7737     * @see #getPivotX()
7738     * @see #getPivotY()
7739     *
7740     * @attr ref android.R.styleable#View_scaleY
7741     */
7742    public void setScaleY(float scaleY) {
7743        ensureTransformationInfo();
7744        final TransformationInfo info = mTransformationInfo;
7745        if (info.mScaleY != scaleY) {
7746            invalidateViewProperty(true, false);
7747            info.mScaleY = scaleY;
7748            info.mMatrixDirty = true;
7749            invalidateViewProperty(false, true);
7750            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7751                mDisplayList.setScaleY(scaleY);
7752            }
7753        }
7754    }
7755
7756    /**
7757     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7758     * and {@link #setScaleX(float) scaled}.
7759     *
7760     * @see #getRotation()
7761     * @see #getScaleX()
7762     * @see #getScaleY()
7763     * @see #getPivotY()
7764     * @return The x location of the pivot point.
7765     */
7766    @ViewDebug.ExportedProperty(category = "drawing")
7767    public float getPivotX() {
7768        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7769    }
7770
7771    /**
7772     * Sets the x location of the point around which the view is
7773     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7774     * By default, the pivot point is centered on the object.
7775     * Setting this property disables this behavior and causes the view to use only the
7776     * explicitly set pivotX and pivotY values.
7777     *
7778     * @param pivotX The x location of the pivot point.
7779     * @see #getRotation()
7780     * @see #getScaleX()
7781     * @see #getScaleY()
7782     * @see #getPivotY()
7783     *
7784     * @attr ref android.R.styleable#View_transformPivotX
7785     */
7786    public void setPivotX(float pivotX) {
7787        ensureTransformationInfo();
7788        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7789        final TransformationInfo info = mTransformationInfo;
7790        if (info.mPivotX != pivotX) {
7791            invalidateViewProperty(true, false);
7792            info.mPivotX = pivotX;
7793            info.mMatrixDirty = true;
7794            invalidateViewProperty(false, true);
7795            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7796                mDisplayList.setPivotX(pivotX);
7797            }
7798        }
7799    }
7800
7801    /**
7802     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7803     * and {@link #setScaleY(float) scaled}.
7804     *
7805     * @see #getRotation()
7806     * @see #getScaleX()
7807     * @see #getScaleY()
7808     * @see #getPivotY()
7809     * @return The y location of the pivot point.
7810     */
7811    @ViewDebug.ExportedProperty(category = "drawing")
7812    public float getPivotY() {
7813        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7814    }
7815
7816    /**
7817     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7818     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7819     * Setting this property disables this behavior and causes the view to use only the
7820     * explicitly set pivotX and pivotY values.
7821     *
7822     * @param pivotY The y location of the pivot point.
7823     * @see #getRotation()
7824     * @see #getScaleX()
7825     * @see #getScaleY()
7826     * @see #getPivotY()
7827     *
7828     * @attr ref android.R.styleable#View_transformPivotY
7829     */
7830    public void setPivotY(float pivotY) {
7831        ensureTransformationInfo();
7832        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7833        final TransformationInfo info = mTransformationInfo;
7834        if (info.mPivotY != pivotY) {
7835            invalidateViewProperty(true, false);
7836            info.mPivotY = pivotY;
7837            info.mMatrixDirty = true;
7838            invalidateViewProperty(false, true);
7839            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7840                mDisplayList.setPivotY(pivotY);
7841            }
7842        }
7843    }
7844
7845    /**
7846     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7847     * completely transparent and 1 means the view is completely opaque.
7848     *
7849     * <p>By default this is 1.0f.
7850     * @return The opacity of the view.
7851     */
7852    @ViewDebug.ExportedProperty(category = "drawing")
7853    public float getAlpha() {
7854        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7855    }
7856
7857    /**
7858     * Returns whether this View has content which overlaps. This function, intended to be
7859     * overridden by specific View types, is an optimization when alpha is set on a view. If
7860     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
7861     * and then composited it into place, which can be expensive. If the view has no overlapping
7862     * rendering, the view can draw each primitive with the appropriate alpha value directly.
7863     * An example of overlapping rendering is a TextView with a background image, such as a
7864     * Button. An example of non-overlapping rendering is a TextView with no background, or
7865     * an ImageView with only the foreground image. The default implementation returns true;
7866     * subclasses should override if they have cases which can be optimized.
7867     *
7868     * @return true if the content in this view might overlap, false otherwise.
7869     */
7870    public boolean hasOverlappingRendering() {
7871        return true;
7872    }
7873
7874    /**
7875     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7876     * completely transparent and 1 means the view is completely opaque.</p>
7877     *
7878     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7879     * responsible for applying the opacity itself. Otherwise, calling this method is
7880     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7881     * setting a hardware layer.</p>
7882     *
7883     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7884     * performance implications. It is generally best to use the alpha property sparingly and
7885     * transiently, as in the case of fading animations.</p>
7886     *
7887     * @param alpha The opacity of the view.
7888     *
7889     * @see #setLayerType(int, android.graphics.Paint)
7890     *
7891     * @attr ref android.R.styleable#View_alpha
7892     */
7893    public void setAlpha(float alpha) {
7894        ensureTransformationInfo();
7895        if (mTransformationInfo.mAlpha != alpha) {
7896            mTransformationInfo.mAlpha = alpha;
7897            if (onSetAlpha((int) (alpha * 255))) {
7898                mPrivateFlags |= ALPHA_SET;
7899                // subclass is handling alpha - don't optimize rendering cache invalidation
7900                invalidateParentCaches();
7901                invalidate(true);
7902            } else {
7903                mPrivateFlags &= ~ALPHA_SET;
7904                invalidateViewProperty(true, false);
7905                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7906                    mDisplayList.setAlpha(alpha);
7907                }
7908            }
7909        }
7910    }
7911
7912    /**
7913     * Faster version of setAlpha() which performs the same steps except there are
7914     * no calls to invalidate(). The caller of this function should perform proper invalidation
7915     * on the parent and this object. The return value indicates whether the subclass handles
7916     * alpha (the return value for onSetAlpha()).
7917     *
7918     * @param alpha The new value for the alpha property
7919     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7920     *         the new value for the alpha property is different from the old value
7921     */
7922    boolean setAlphaNoInvalidation(float alpha) {
7923        ensureTransformationInfo();
7924        if (mTransformationInfo.mAlpha != alpha) {
7925            mTransformationInfo.mAlpha = alpha;
7926            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7927            if (subclassHandlesAlpha) {
7928                mPrivateFlags |= ALPHA_SET;
7929                return true;
7930            } else {
7931                mPrivateFlags &= ~ALPHA_SET;
7932                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7933                    mDisplayList.setAlpha(alpha);
7934                }
7935            }
7936        }
7937        return false;
7938    }
7939
7940    /**
7941     * Top position of this view relative to its parent.
7942     *
7943     * @return The top of this view, in pixels.
7944     */
7945    @ViewDebug.CapturedViewProperty
7946    public final int getTop() {
7947        return mTop;
7948    }
7949
7950    /**
7951     * Sets the top position of this view relative to its parent. This method is meant to be called
7952     * by the layout system and should not generally be called otherwise, because the property
7953     * may be changed at any time by the layout.
7954     *
7955     * @param top The top of this view, in pixels.
7956     */
7957    public final void setTop(int top) {
7958        if (top != mTop) {
7959            updateMatrix();
7960            final boolean matrixIsIdentity = mTransformationInfo == null
7961                    || mTransformationInfo.mMatrixIsIdentity;
7962            if (matrixIsIdentity) {
7963                if (mAttachInfo != null) {
7964                    int minTop;
7965                    int yLoc;
7966                    if (top < mTop) {
7967                        minTop = top;
7968                        yLoc = top - mTop;
7969                    } else {
7970                        minTop = mTop;
7971                        yLoc = 0;
7972                    }
7973                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7974                }
7975            } else {
7976                // Double-invalidation is necessary to capture view's old and new areas
7977                invalidate(true);
7978            }
7979
7980            int width = mRight - mLeft;
7981            int oldHeight = mBottom - mTop;
7982
7983            mTop = top;
7984            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7985                mDisplayList.setTop(mTop);
7986            }
7987
7988            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7989
7990            if (!matrixIsIdentity) {
7991                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7992                    // A change in dimension means an auto-centered pivot point changes, too
7993                    mTransformationInfo.mMatrixDirty = true;
7994                }
7995                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7996                invalidate(true);
7997            }
7998            mBackgroundSizeChanged = true;
7999            invalidateParentIfNeeded();
8000        }
8001    }
8002
8003    /**
8004     * Bottom position of this view relative to its parent.
8005     *
8006     * @return The bottom of this view, in pixels.
8007     */
8008    @ViewDebug.CapturedViewProperty
8009    public final int getBottom() {
8010        return mBottom;
8011    }
8012
8013    /**
8014     * True if this view has changed since the last time being drawn.
8015     *
8016     * @return The dirty state of this view.
8017     */
8018    public boolean isDirty() {
8019        return (mPrivateFlags & DIRTY_MASK) != 0;
8020    }
8021
8022    /**
8023     * Sets the bottom position of this view relative to its parent. This method is meant to be
8024     * called by the layout system and should not generally be called otherwise, because the
8025     * property may be changed at any time by the layout.
8026     *
8027     * @param bottom The bottom of this view, in pixels.
8028     */
8029    public final void setBottom(int bottom) {
8030        if (bottom != mBottom) {
8031            updateMatrix();
8032            final boolean matrixIsIdentity = mTransformationInfo == null
8033                    || mTransformationInfo.mMatrixIsIdentity;
8034            if (matrixIsIdentity) {
8035                if (mAttachInfo != null) {
8036                    int maxBottom;
8037                    if (bottom < mBottom) {
8038                        maxBottom = mBottom;
8039                    } else {
8040                        maxBottom = bottom;
8041                    }
8042                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8043                }
8044            } else {
8045                // Double-invalidation is necessary to capture view's old and new areas
8046                invalidate(true);
8047            }
8048
8049            int width = mRight - mLeft;
8050            int oldHeight = mBottom - mTop;
8051
8052            mBottom = bottom;
8053            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8054                mDisplayList.setBottom(mBottom);
8055            }
8056
8057            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8058
8059            if (!matrixIsIdentity) {
8060                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8061                    // A change in dimension means an auto-centered pivot point changes, too
8062                    mTransformationInfo.mMatrixDirty = true;
8063                }
8064                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8065                invalidate(true);
8066            }
8067            mBackgroundSizeChanged = true;
8068            invalidateParentIfNeeded();
8069        }
8070    }
8071
8072    /**
8073     * Left position of this view relative to its parent.
8074     *
8075     * @return The left edge of this view, in pixels.
8076     */
8077    @ViewDebug.CapturedViewProperty
8078    public final int getLeft() {
8079        return mLeft;
8080    }
8081
8082    /**
8083     * Sets the left position of this view relative to its parent. This method is meant to be called
8084     * by the layout system and should not generally be called otherwise, because the property
8085     * may be changed at any time by the layout.
8086     *
8087     * @param left The bottom of this view, in pixels.
8088     */
8089    public final void setLeft(int left) {
8090        if (left != mLeft) {
8091            updateMatrix();
8092            final boolean matrixIsIdentity = mTransformationInfo == null
8093                    || mTransformationInfo.mMatrixIsIdentity;
8094            if (matrixIsIdentity) {
8095                if (mAttachInfo != null) {
8096                    int minLeft;
8097                    int xLoc;
8098                    if (left < mLeft) {
8099                        minLeft = left;
8100                        xLoc = left - mLeft;
8101                    } else {
8102                        minLeft = mLeft;
8103                        xLoc = 0;
8104                    }
8105                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8106                }
8107            } else {
8108                // Double-invalidation is necessary to capture view's old and new areas
8109                invalidate(true);
8110            }
8111
8112            int oldWidth = mRight - mLeft;
8113            int height = mBottom - mTop;
8114
8115            mLeft = left;
8116            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8117                mDisplayList.setLeft(left);
8118            }
8119
8120            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8121
8122            if (!matrixIsIdentity) {
8123                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8124                    // A change in dimension means an auto-centered pivot point changes, too
8125                    mTransformationInfo.mMatrixDirty = true;
8126                }
8127                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8128                invalidate(true);
8129            }
8130            mBackgroundSizeChanged = true;
8131            invalidateParentIfNeeded();
8132            if (USE_DISPLAY_LIST_PROPERTIES) {
8133
8134            }
8135        }
8136    }
8137
8138    /**
8139     * Right position of this view relative to its parent.
8140     *
8141     * @return The right edge of this view, in pixels.
8142     */
8143    @ViewDebug.CapturedViewProperty
8144    public final int getRight() {
8145        return mRight;
8146    }
8147
8148    /**
8149     * Sets the right position of this view relative to its parent. This method is meant to be called
8150     * by the layout system and should not generally be called otherwise, because the property
8151     * may be changed at any time by the layout.
8152     *
8153     * @param right The bottom of this view, in pixels.
8154     */
8155    public final void setRight(int right) {
8156        if (right != mRight) {
8157            updateMatrix();
8158            final boolean matrixIsIdentity = mTransformationInfo == null
8159                    || mTransformationInfo.mMatrixIsIdentity;
8160            if (matrixIsIdentity) {
8161                if (mAttachInfo != null) {
8162                    int maxRight;
8163                    if (right < mRight) {
8164                        maxRight = mRight;
8165                    } else {
8166                        maxRight = right;
8167                    }
8168                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8169                }
8170            } else {
8171                // Double-invalidation is necessary to capture view's old and new areas
8172                invalidate(true);
8173            }
8174
8175            int oldWidth = mRight - mLeft;
8176            int height = mBottom - mTop;
8177
8178            mRight = right;
8179            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8180                mDisplayList.setRight(mRight);
8181            }
8182
8183            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8184
8185            if (!matrixIsIdentity) {
8186                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8187                    // A change in dimension means an auto-centered pivot point changes, too
8188                    mTransformationInfo.mMatrixDirty = true;
8189                }
8190                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8191                invalidate(true);
8192            }
8193            mBackgroundSizeChanged = true;
8194            invalidateParentIfNeeded();
8195        }
8196    }
8197
8198    /**
8199     * The visual x position of this view, in pixels. This is equivalent to the
8200     * {@link #setTranslationX(float) translationX} property plus the current
8201     * {@link #getLeft() left} property.
8202     *
8203     * @return The visual x position of this view, in pixels.
8204     */
8205    @ViewDebug.ExportedProperty(category = "drawing")
8206    public float getX() {
8207        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8208    }
8209
8210    /**
8211     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8212     * {@link #setTranslationX(float) translationX} property to be the difference between
8213     * the x value passed in and the current {@link #getLeft() left} property.
8214     *
8215     * @param x The visual x position of this view, in pixels.
8216     */
8217    public void setX(float x) {
8218        setTranslationX(x - mLeft);
8219    }
8220
8221    /**
8222     * The visual y position of this view, in pixels. This is equivalent to the
8223     * {@link #setTranslationY(float) translationY} property plus the current
8224     * {@link #getTop() top} property.
8225     *
8226     * @return The visual y position of this view, in pixels.
8227     */
8228    @ViewDebug.ExportedProperty(category = "drawing")
8229    public float getY() {
8230        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8231    }
8232
8233    /**
8234     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8235     * {@link #setTranslationY(float) translationY} property to be the difference between
8236     * the y value passed in and the current {@link #getTop() top} property.
8237     *
8238     * @param y The visual y position of this view, in pixels.
8239     */
8240    public void setY(float y) {
8241        setTranslationY(y - mTop);
8242    }
8243
8244
8245    /**
8246     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8247     * This position is post-layout, in addition to wherever the object's
8248     * layout placed it.
8249     *
8250     * @return The horizontal position of this view relative to its left position, in pixels.
8251     */
8252    @ViewDebug.ExportedProperty(category = "drawing")
8253    public float getTranslationX() {
8254        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8255    }
8256
8257    /**
8258     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8259     * This effectively positions the object post-layout, in addition to wherever the object's
8260     * layout placed it.
8261     *
8262     * @param translationX The horizontal position of this view relative to its left position,
8263     * in pixels.
8264     *
8265     * @attr ref android.R.styleable#View_translationX
8266     */
8267    public void setTranslationX(float translationX) {
8268        ensureTransformationInfo();
8269        final TransformationInfo info = mTransformationInfo;
8270        if (info.mTranslationX != translationX) {
8271            // Double-invalidation is necessary to capture view's old and new areas
8272            invalidateViewProperty(true, false);
8273            info.mTranslationX = translationX;
8274            info.mMatrixDirty = true;
8275            invalidateViewProperty(false, true);
8276            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8277                mDisplayList.setTranslationX(translationX);
8278            }
8279        }
8280    }
8281
8282    /**
8283     * The horizontal location of this view relative to its {@link #getTop() top} position.
8284     * This position is post-layout, in addition to wherever the object's
8285     * layout placed it.
8286     *
8287     * @return The vertical position of this view relative to its top position,
8288     * in pixels.
8289     */
8290    @ViewDebug.ExportedProperty(category = "drawing")
8291    public float getTranslationY() {
8292        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
8293    }
8294
8295    /**
8296     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8297     * This effectively positions the object post-layout, in addition to wherever the object's
8298     * layout placed it.
8299     *
8300     * @param translationY The vertical position of this view relative to its top position,
8301     * in pixels.
8302     *
8303     * @attr ref android.R.styleable#View_translationY
8304     */
8305    public void setTranslationY(float translationY) {
8306        ensureTransformationInfo();
8307        final TransformationInfo info = mTransformationInfo;
8308        if (info.mTranslationY != translationY) {
8309            invalidateViewProperty(true, false);
8310            info.mTranslationY = translationY;
8311            info.mMatrixDirty = true;
8312            invalidateViewProperty(false, true);
8313            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8314                mDisplayList.setTranslationY(translationY);
8315            }
8316        }
8317    }
8318
8319    /**
8320     * Hit rectangle in parent's coordinates
8321     *
8322     * @param outRect The hit rectangle of the view.
8323     */
8324    public void getHitRect(Rect outRect) {
8325        updateMatrix();
8326        final TransformationInfo info = mTransformationInfo;
8327        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8328            outRect.set(mLeft, mTop, mRight, mBottom);
8329        } else {
8330            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8331            tmpRect.set(-info.mPivotX, -info.mPivotY,
8332                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8333            info.mMatrix.mapRect(tmpRect);
8334            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8335                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8336        }
8337    }
8338
8339    /**
8340     * Determines whether the given point, in local coordinates is inside the view.
8341     */
8342    /*package*/ final boolean pointInView(float localX, float localY) {
8343        return localX >= 0 && localX < (mRight - mLeft)
8344                && localY >= 0 && localY < (mBottom - mTop);
8345    }
8346
8347    /**
8348     * Utility method to determine whether the given point, in local coordinates,
8349     * is inside the view, where the area of the view is expanded by the slop factor.
8350     * This method is called while processing touch-move events to determine if the event
8351     * is still within the view.
8352     */
8353    private boolean pointInView(float localX, float localY, float slop) {
8354        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8355                localY < ((mBottom - mTop) + slop);
8356    }
8357
8358    /**
8359     * When a view has focus and the user navigates away from it, the next view is searched for
8360     * starting from the rectangle filled in by this method.
8361     *
8362     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8363     * of the view.  However, if your view maintains some idea of internal selection,
8364     * such as a cursor, or a selected row or column, you should override this method and
8365     * fill in a more specific rectangle.
8366     *
8367     * @param r The rectangle to fill in, in this view's coordinates.
8368     */
8369    public void getFocusedRect(Rect r) {
8370        getDrawingRect(r);
8371    }
8372
8373    /**
8374     * If some part of this view is not clipped by any of its parents, then
8375     * return that area in r in global (root) coordinates. To convert r to local
8376     * coordinates (without taking possible View rotations into account), offset
8377     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8378     * If the view is completely clipped or translated out, return false.
8379     *
8380     * @param r If true is returned, r holds the global coordinates of the
8381     *        visible portion of this view.
8382     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8383     *        between this view and its root. globalOffet may be null.
8384     * @return true if r is non-empty (i.e. part of the view is visible at the
8385     *         root level.
8386     */
8387    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8388        int width = mRight - mLeft;
8389        int height = mBottom - mTop;
8390        if (width > 0 && height > 0) {
8391            r.set(0, 0, width, height);
8392            if (globalOffset != null) {
8393                globalOffset.set(-mScrollX, -mScrollY);
8394            }
8395            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8396        }
8397        return false;
8398    }
8399
8400    public final boolean getGlobalVisibleRect(Rect r) {
8401        return getGlobalVisibleRect(r, null);
8402    }
8403
8404    public final boolean getLocalVisibleRect(Rect r) {
8405        Point offset = new Point();
8406        if (getGlobalVisibleRect(r, offset)) {
8407            r.offset(-offset.x, -offset.y); // make r local
8408            return true;
8409        }
8410        return false;
8411    }
8412
8413    /**
8414     * Offset this view's vertical location by the specified number of pixels.
8415     *
8416     * @param offset the number of pixels to offset the view by
8417     */
8418    public void offsetTopAndBottom(int offset) {
8419        if (offset != 0) {
8420            updateMatrix();
8421            final boolean matrixIsIdentity = mTransformationInfo == null
8422                    || mTransformationInfo.mMatrixIsIdentity;
8423            if (matrixIsIdentity) {
8424                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8425                    invalidateViewProperty(false, false);
8426                } else {
8427                    final ViewParent p = mParent;
8428                    if (p != null && mAttachInfo != null) {
8429                        final Rect r = mAttachInfo.mTmpInvalRect;
8430                        int minTop;
8431                        int maxBottom;
8432                        int yLoc;
8433                        if (offset < 0) {
8434                            minTop = mTop + offset;
8435                            maxBottom = mBottom;
8436                            yLoc = offset;
8437                        } else {
8438                            minTop = mTop;
8439                            maxBottom = mBottom + offset;
8440                            yLoc = 0;
8441                        }
8442                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8443                        p.invalidateChild(this, r);
8444                    }
8445                }
8446            } else {
8447                invalidateViewProperty(false, false);
8448            }
8449
8450            mTop += offset;
8451            mBottom += offset;
8452            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8453                mDisplayList.offsetTopBottom(offset);
8454                invalidateViewProperty(false, false);
8455            } else {
8456                if (!matrixIsIdentity) {
8457                    invalidateViewProperty(false, true);
8458                }
8459                invalidateParentIfNeeded();
8460            }
8461        }
8462    }
8463
8464    /**
8465     * Offset this view's horizontal location by the specified amount of pixels.
8466     *
8467     * @param offset the numer of pixels to offset the view by
8468     */
8469    public void offsetLeftAndRight(int offset) {
8470        if (offset != 0) {
8471            updateMatrix();
8472            final boolean matrixIsIdentity = mTransformationInfo == null
8473                    || mTransformationInfo.mMatrixIsIdentity;
8474            if (matrixIsIdentity) {
8475                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8476                    invalidateViewProperty(false, false);
8477                } else {
8478                    final ViewParent p = mParent;
8479                    if (p != null && mAttachInfo != null) {
8480                        final Rect r = mAttachInfo.mTmpInvalRect;
8481                        int minLeft;
8482                        int maxRight;
8483                        if (offset < 0) {
8484                            minLeft = mLeft + offset;
8485                            maxRight = mRight;
8486                        } else {
8487                            minLeft = mLeft;
8488                            maxRight = mRight + offset;
8489                        }
8490                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8491                        p.invalidateChild(this, r);
8492                    }
8493                }
8494            } else {
8495                invalidateViewProperty(false, false);
8496            }
8497
8498            mLeft += offset;
8499            mRight += offset;
8500            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8501                mDisplayList.offsetLeftRight(offset);
8502                invalidateViewProperty(false, false);
8503            } else {
8504                if (!matrixIsIdentity) {
8505                    invalidateViewProperty(false, true);
8506                }
8507                invalidateParentIfNeeded();
8508            }
8509        }
8510    }
8511
8512    /**
8513     * Get the LayoutParams associated with this view. All views should have
8514     * layout parameters. These supply parameters to the <i>parent</i> of this
8515     * view specifying how it should be arranged. There are many subclasses of
8516     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8517     * of ViewGroup that are responsible for arranging their children.
8518     *
8519     * This method may return null if this View is not attached to a parent
8520     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8521     * was not invoked successfully. When a View is attached to a parent
8522     * ViewGroup, this method must not return null.
8523     *
8524     * @return The LayoutParams associated with this view, or null if no
8525     *         parameters have been set yet
8526     */
8527    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8528    public ViewGroup.LayoutParams getLayoutParams() {
8529        return mLayoutParams;
8530    }
8531
8532    /**
8533     * Set the layout parameters associated with this view. These supply
8534     * parameters to the <i>parent</i> of this view specifying how it should be
8535     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8536     * correspond to the different subclasses of ViewGroup that are responsible
8537     * for arranging their children.
8538     *
8539     * @param params The layout parameters for this view, cannot be null
8540     */
8541    public void setLayoutParams(ViewGroup.LayoutParams params) {
8542        if (params == null) {
8543            throw new NullPointerException("Layout parameters cannot be null");
8544        }
8545        mLayoutParams = params;
8546        if (mParent instanceof ViewGroup) {
8547            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8548        }
8549        requestLayout();
8550    }
8551
8552    /**
8553     * Set the scrolled position of your view. This will cause a call to
8554     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8555     * invalidated.
8556     * @param x the x position to scroll to
8557     * @param y the y position to scroll to
8558     */
8559    public void scrollTo(int x, int y) {
8560        if (mScrollX != x || mScrollY != y) {
8561            int oldX = mScrollX;
8562            int oldY = mScrollY;
8563            mScrollX = x;
8564            mScrollY = y;
8565            invalidateParentCaches();
8566            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8567            if (!awakenScrollBars()) {
8568                invalidate(true);
8569            }
8570        }
8571    }
8572
8573    /**
8574     * Move the scrolled position of your view. This will cause a call to
8575     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8576     * invalidated.
8577     * @param x the amount of pixels to scroll by horizontally
8578     * @param y the amount of pixels to scroll by vertically
8579     */
8580    public void scrollBy(int x, int y) {
8581        scrollTo(mScrollX + x, mScrollY + y);
8582    }
8583
8584    /**
8585     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8586     * animation to fade the scrollbars out after a default delay. If a subclass
8587     * provides animated scrolling, the start delay should equal the duration
8588     * of the scrolling animation.</p>
8589     *
8590     * <p>The animation starts only if at least one of the scrollbars is
8591     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8592     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8593     * this method returns true, and false otherwise. If the animation is
8594     * started, this method calls {@link #invalidate()}; in that case the
8595     * caller should not call {@link #invalidate()}.</p>
8596     *
8597     * <p>This method should be invoked every time a subclass directly updates
8598     * the scroll parameters.</p>
8599     *
8600     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8601     * and {@link #scrollTo(int, int)}.</p>
8602     *
8603     * @return true if the animation is played, false otherwise
8604     *
8605     * @see #awakenScrollBars(int)
8606     * @see #scrollBy(int, int)
8607     * @see #scrollTo(int, int)
8608     * @see #isHorizontalScrollBarEnabled()
8609     * @see #isVerticalScrollBarEnabled()
8610     * @see #setHorizontalScrollBarEnabled(boolean)
8611     * @see #setVerticalScrollBarEnabled(boolean)
8612     */
8613    protected boolean awakenScrollBars() {
8614        return mScrollCache != null &&
8615                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8616    }
8617
8618    /**
8619     * Trigger the scrollbars to draw.
8620     * This method differs from awakenScrollBars() only in its default duration.
8621     * initialAwakenScrollBars() will show the scroll bars for longer than
8622     * usual to give the user more of a chance to notice them.
8623     *
8624     * @return true if the animation is played, false otherwise.
8625     */
8626    private boolean initialAwakenScrollBars() {
8627        return mScrollCache != null &&
8628                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8629    }
8630
8631    /**
8632     * <p>
8633     * Trigger the scrollbars to draw. When invoked this method starts an
8634     * animation to fade the scrollbars out after a fixed delay. If a subclass
8635     * provides animated scrolling, the start delay should equal the duration of
8636     * the scrolling animation.
8637     * </p>
8638     *
8639     * <p>
8640     * The animation starts only if at least one of the scrollbars is enabled,
8641     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8642     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8643     * this method returns true, and false otherwise. If the animation is
8644     * started, this method calls {@link #invalidate()}; in that case the caller
8645     * should not call {@link #invalidate()}.
8646     * </p>
8647     *
8648     * <p>
8649     * This method should be invoked everytime a subclass directly updates the
8650     * scroll parameters.
8651     * </p>
8652     *
8653     * @param startDelay the delay, in milliseconds, after which the animation
8654     *        should start; when the delay is 0, the animation starts
8655     *        immediately
8656     * @return true if the animation is played, false otherwise
8657     *
8658     * @see #scrollBy(int, int)
8659     * @see #scrollTo(int, int)
8660     * @see #isHorizontalScrollBarEnabled()
8661     * @see #isVerticalScrollBarEnabled()
8662     * @see #setHorizontalScrollBarEnabled(boolean)
8663     * @see #setVerticalScrollBarEnabled(boolean)
8664     */
8665    protected boolean awakenScrollBars(int startDelay) {
8666        return awakenScrollBars(startDelay, true);
8667    }
8668
8669    /**
8670     * <p>
8671     * Trigger the scrollbars to draw. When invoked this method starts an
8672     * animation to fade the scrollbars out after a fixed delay. If a subclass
8673     * provides animated scrolling, the start delay should equal the duration of
8674     * the scrolling animation.
8675     * </p>
8676     *
8677     * <p>
8678     * The animation starts only if at least one of the scrollbars is enabled,
8679     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8680     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8681     * this method returns true, and false otherwise. If the animation is
8682     * started, this method calls {@link #invalidate()} if the invalidate parameter
8683     * is set to true; in that case the caller
8684     * should not call {@link #invalidate()}.
8685     * </p>
8686     *
8687     * <p>
8688     * This method should be invoked everytime a subclass directly updates the
8689     * scroll parameters.
8690     * </p>
8691     *
8692     * @param startDelay the delay, in milliseconds, after which the animation
8693     *        should start; when the delay is 0, the animation starts
8694     *        immediately
8695     *
8696     * @param invalidate Wheter this method should call invalidate
8697     *
8698     * @return true if the animation is played, false otherwise
8699     *
8700     * @see #scrollBy(int, int)
8701     * @see #scrollTo(int, int)
8702     * @see #isHorizontalScrollBarEnabled()
8703     * @see #isVerticalScrollBarEnabled()
8704     * @see #setHorizontalScrollBarEnabled(boolean)
8705     * @see #setVerticalScrollBarEnabled(boolean)
8706     */
8707    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8708        final ScrollabilityCache scrollCache = mScrollCache;
8709
8710        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8711            return false;
8712        }
8713
8714        if (scrollCache.scrollBar == null) {
8715            scrollCache.scrollBar = new ScrollBarDrawable();
8716        }
8717
8718        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8719
8720            if (invalidate) {
8721                // Invalidate to show the scrollbars
8722                invalidate(true);
8723            }
8724
8725            if (scrollCache.state == ScrollabilityCache.OFF) {
8726                // FIXME: this is copied from WindowManagerService.
8727                // We should get this value from the system when it
8728                // is possible to do so.
8729                final int KEY_REPEAT_FIRST_DELAY = 750;
8730                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8731            }
8732
8733            // Tell mScrollCache when we should start fading. This may
8734            // extend the fade start time if one was already scheduled
8735            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8736            scrollCache.fadeStartTime = fadeStartTime;
8737            scrollCache.state = ScrollabilityCache.ON;
8738
8739            // Schedule our fader to run, unscheduling any old ones first
8740            if (mAttachInfo != null) {
8741                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8742                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8743            }
8744
8745            return true;
8746        }
8747
8748        return false;
8749    }
8750
8751    /**
8752     * Do not invalidate views which are not visible and which are not running an animation. They
8753     * will not get drawn and they should not set dirty flags as if they will be drawn
8754     */
8755    private boolean skipInvalidate() {
8756        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8757                (!(mParent instanceof ViewGroup) ||
8758                        !((ViewGroup) mParent).isViewTransitioning(this));
8759    }
8760    /**
8761     * Mark the area defined by dirty as needing to be drawn. If the view is
8762     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8763     * in the future. This must be called from a UI thread. To call from a non-UI
8764     * thread, call {@link #postInvalidate()}.
8765     *
8766     * WARNING: This method is destructive to dirty.
8767     * @param dirty the rectangle representing the bounds of the dirty region
8768     */
8769    public void invalidate(Rect dirty) {
8770        if (ViewDebug.TRACE_HIERARCHY) {
8771            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8772        }
8773
8774        if (skipInvalidate()) {
8775            return;
8776        }
8777        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8778                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8779                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8780            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8781            mPrivateFlags |= INVALIDATED;
8782            mPrivateFlags |= DIRTY;
8783            final ViewParent p = mParent;
8784            final AttachInfo ai = mAttachInfo;
8785            //noinspection PointlessBooleanExpression,ConstantConditions
8786            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8787                if (p != null && ai != null && ai.mHardwareAccelerated) {
8788                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8789                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8790                    p.invalidateChild(this, null);
8791                    return;
8792                }
8793            }
8794            if (p != null && ai != null) {
8795                final int scrollX = mScrollX;
8796                final int scrollY = mScrollY;
8797                final Rect r = ai.mTmpInvalRect;
8798                r.set(dirty.left - scrollX, dirty.top - scrollY,
8799                        dirty.right - scrollX, dirty.bottom - scrollY);
8800                mParent.invalidateChild(this, r);
8801            }
8802        }
8803    }
8804
8805    /**
8806     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8807     * The coordinates of the dirty rect are relative to the view.
8808     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8809     * will be called at some point in the future. This must be called from
8810     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8811     * @param l the left position of the dirty region
8812     * @param t the top position of the dirty region
8813     * @param r the right position of the dirty region
8814     * @param b the bottom position of the dirty region
8815     */
8816    public void invalidate(int l, int t, int r, int b) {
8817        if (ViewDebug.TRACE_HIERARCHY) {
8818            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8819        }
8820
8821        if (skipInvalidate()) {
8822            return;
8823        }
8824        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8825                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8826                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8827            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8828            mPrivateFlags |= INVALIDATED;
8829            mPrivateFlags |= DIRTY;
8830            final ViewParent p = mParent;
8831            final AttachInfo ai = mAttachInfo;
8832            //noinspection PointlessBooleanExpression,ConstantConditions
8833            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8834                if (p != null && ai != null && ai.mHardwareAccelerated) {
8835                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8836                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8837                    p.invalidateChild(this, null);
8838                    return;
8839                }
8840            }
8841            if (p != null && ai != null && l < r && t < b) {
8842                final int scrollX = mScrollX;
8843                final int scrollY = mScrollY;
8844                final Rect tmpr = ai.mTmpInvalRect;
8845                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8846                p.invalidateChild(this, tmpr);
8847            }
8848        }
8849    }
8850
8851    /**
8852     * Invalidate the whole view. If the view is visible,
8853     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8854     * the future. This must be called from a UI thread. To call from a non-UI thread,
8855     * call {@link #postInvalidate()}.
8856     */
8857    public void invalidate() {
8858        invalidate(true);
8859    }
8860
8861    /**
8862     * This is where the invalidate() work actually happens. A full invalidate()
8863     * causes the drawing cache to be invalidated, but this function can be called with
8864     * invalidateCache set to false to skip that invalidation step for cases that do not
8865     * need it (for example, a component that remains at the same dimensions with the same
8866     * content).
8867     *
8868     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8869     * well. This is usually true for a full invalidate, but may be set to false if the
8870     * View's contents or dimensions have not changed.
8871     */
8872    void invalidate(boolean invalidateCache) {
8873        if (ViewDebug.TRACE_HIERARCHY) {
8874            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8875        }
8876
8877        if (skipInvalidate()) {
8878            return;
8879        }
8880        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8881                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8882                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8883            mLastIsOpaque = isOpaque();
8884            mPrivateFlags &= ~DRAWN;
8885            mPrivateFlags |= DIRTY;
8886            if (invalidateCache) {
8887                mPrivateFlags |= INVALIDATED;
8888                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8889            }
8890            final AttachInfo ai = mAttachInfo;
8891            final ViewParent p = mParent;
8892            //noinspection PointlessBooleanExpression,ConstantConditions
8893            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8894                if (p != null && ai != null && ai.mHardwareAccelerated) {
8895                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8896                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8897                    p.invalidateChild(this, null);
8898                    return;
8899                }
8900            }
8901
8902            if (p != null && ai != null) {
8903                final Rect r = ai.mTmpInvalRect;
8904                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8905                // Don't call invalidate -- we don't want to internally scroll
8906                // our own bounds
8907                p.invalidateChild(this, r);
8908            }
8909        }
8910    }
8911
8912    /**
8913     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
8914     * set any flags or handle all of the cases handled by the default invalidation methods.
8915     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
8916     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
8917     * walk up the hierarchy, transforming the dirty rect as necessary.
8918     *
8919     * The method also handles normal invalidation logic if display list properties are not
8920     * being used in this view. The invalidateParent and forceRedraw flags are used by that
8921     * backup approach, to handle these cases used in the various property-setting methods.
8922     *
8923     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
8924     * are not being used in this view
8925     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
8926     * list properties are not being used in this view
8927     */
8928    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
8929        if (!USE_DISPLAY_LIST_PROPERTIES || mDisplayList == null ||
8930                (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
8931            if (invalidateParent) {
8932                invalidateParentCaches();
8933            }
8934            if (forceRedraw) {
8935                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8936            }
8937            invalidate(false);
8938        } else {
8939            final AttachInfo ai = mAttachInfo;
8940            final ViewParent p = mParent;
8941            if (p != null && ai != null) {
8942                final Rect r = ai.mTmpInvalRect;
8943                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8944                if (mParent instanceof ViewGroup) {
8945                    ((ViewGroup) mParent).invalidateChildFast(this, r);
8946                } else {
8947                    mParent.invalidateChild(this, r);
8948                }
8949            }
8950        }
8951    }
8952
8953    /**
8954     * Utility method to transform a given Rect by the current matrix of this view.
8955     */
8956    void transformRect(final Rect rect) {
8957        if (!getMatrix().isIdentity()) {
8958            RectF boundingRect = mAttachInfo.mTmpTransformRect;
8959            boundingRect.set(rect);
8960            getMatrix().mapRect(boundingRect);
8961            rect.set((int) (boundingRect.left - 0.5f),
8962                    (int) (boundingRect.top - 0.5f),
8963                    (int) (boundingRect.right + 0.5f),
8964                    (int) (boundingRect.bottom + 0.5f));
8965        }
8966    }
8967
8968    /**
8969     * Used to indicate that the parent of this view should clear its caches. This functionality
8970     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8971     * which is necessary when various parent-managed properties of the view change, such as
8972     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8973     * clears the parent caches and does not causes an invalidate event.
8974     *
8975     * @hide
8976     */
8977    protected void invalidateParentCaches() {
8978        if (mParent instanceof View) {
8979            ((View) mParent).mPrivateFlags |= INVALIDATED;
8980        }
8981    }
8982
8983    /**
8984     * Used to indicate that the parent of this view should be invalidated. This functionality
8985     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8986     * which is necessary when various parent-managed properties of the view change, such as
8987     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8988     * an invalidation event to the parent.
8989     *
8990     * @hide
8991     */
8992    protected void invalidateParentIfNeeded() {
8993        if (isHardwareAccelerated() && mParent instanceof View) {
8994            ((View) mParent).invalidate(true);
8995        }
8996    }
8997
8998    /**
8999     * Indicates whether this View is opaque. An opaque View guarantees that it will
9000     * draw all the pixels overlapping its bounds using a fully opaque color.
9001     *
9002     * Subclasses of View should override this method whenever possible to indicate
9003     * whether an instance is opaque. Opaque Views are treated in a special way by
9004     * the View hierarchy, possibly allowing it to perform optimizations during
9005     * invalidate/draw passes.
9006     *
9007     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9008     */
9009    @ViewDebug.ExportedProperty(category = "drawing")
9010    public boolean isOpaque() {
9011        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9012                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9013                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9014    }
9015
9016    /**
9017     * @hide
9018     */
9019    protected void computeOpaqueFlags() {
9020        // Opaque if:
9021        //   - Has a background
9022        //   - Background is opaque
9023        //   - Doesn't have scrollbars or scrollbars are inside overlay
9024
9025        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
9026            mPrivateFlags |= OPAQUE_BACKGROUND;
9027        } else {
9028            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9029        }
9030
9031        final int flags = mViewFlags;
9032        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9033                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9034            mPrivateFlags |= OPAQUE_SCROLLBARS;
9035        } else {
9036            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9037        }
9038    }
9039
9040    /**
9041     * @hide
9042     */
9043    protected boolean hasOpaqueScrollbars() {
9044        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9045    }
9046
9047    /**
9048     * @return A handler associated with the thread running the View. This
9049     * handler can be used to pump events in the UI events queue.
9050     */
9051    public Handler getHandler() {
9052        if (mAttachInfo != null) {
9053            return mAttachInfo.mHandler;
9054        }
9055        return null;
9056    }
9057
9058    /**
9059     * Gets the view root associated with the View.
9060     * @return The view root, or null if none.
9061     * @hide
9062     */
9063    public ViewRootImpl getViewRootImpl() {
9064        if (mAttachInfo != null) {
9065            return mAttachInfo.mViewRootImpl;
9066        }
9067        return null;
9068    }
9069
9070    /**
9071     * <p>Causes the Runnable to be added to the message queue.
9072     * The runnable will be run on the user interface thread.</p>
9073     *
9074     * <p>This method can be invoked from outside of the UI thread
9075     * only when this View is attached to a window.</p>
9076     *
9077     * @param action The Runnable that will be executed.
9078     *
9079     * @return Returns true if the Runnable was successfully placed in to the
9080     *         message queue.  Returns false on failure, usually because the
9081     *         looper processing the message queue is exiting.
9082     */
9083    public boolean post(Runnable action) {
9084        final AttachInfo attachInfo = mAttachInfo;
9085        if (attachInfo != null) {
9086            return attachInfo.mHandler.post(action);
9087        }
9088        // Assume that post will succeed later
9089        ViewRootImpl.getRunQueue().post(action);
9090        return true;
9091    }
9092
9093    /**
9094     * <p>Causes the Runnable to be added to the message queue, to be run
9095     * after the specified amount of time elapses.
9096     * The runnable will be run on the user interface thread.</p>
9097     *
9098     * <p>This method can be invoked from outside of the UI thread
9099     * only when this View is attached to a window.</p>
9100     *
9101     * @param action The Runnable that will be executed.
9102     * @param delayMillis The delay (in milliseconds) until the Runnable
9103     *        will be executed.
9104     *
9105     * @return true if the Runnable was successfully placed in to the
9106     *         message queue.  Returns false on failure, usually because the
9107     *         looper processing the message queue is exiting.  Note that a
9108     *         result of true does not mean the Runnable will be processed --
9109     *         if the looper is quit before the delivery time of the message
9110     *         occurs then the message will be dropped.
9111     */
9112    public boolean postDelayed(Runnable action, long delayMillis) {
9113        final AttachInfo attachInfo = mAttachInfo;
9114        if (attachInfo != null) {
9115            return attachInfo.mHandler.postDelayed(action, delayMillis);
9116        }
9117        // Assume that post will succeed later
9118        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9119        return true;
9120    }
9121
9122    /**
9123     * <p>Causes the Runnable to execute on the next animation time step.
9124     * The runnable will be run on the user interface thread.</p>
9125     *
9126     * <p>This method can be invoked from outside of the UI thread
9127     * only when this View is attached to a window.</p>
9128     *
9129     * @param action The Runnable that will be executed.
9130     *
9131     * @hide
9132     */
9133    public void postOnAnimation(Runnable action) {
9134        final AttachInfo attachInfo = mAttachInfo;
9135        if (attachInfo != null) {
9136            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9137                    Choreographer.CALLBACK_ANIMATION, action, null);
9138        } else {
9139            // Assume that post will succeed later
9140            ViewRootImpl.getRunQueue().post(action);
9141        }
9142    }
9143
9144    /**
9145     * <p>Causes the Runnable to execute on the next animation time step,
9146     * after the specified amount of time elapses.
9147     * The runnable will be run on the user interface thread.</p>
9148     *
9149     * <p>This method can be invoked from outside of the UI thread
9150     * only when this View is attached to a window.</p>
9151     *
9152     * @param action The Runnable that will be executed.
9153     * @param delayMillis The delay (in milliseconds) until the Runnable
9154     *        will be executed.
9155     *
9156     * @hide
9157     */
9158    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9159        final AttachInfo attachInfo = mAttachInfo;
9160        if (attachInfo != null) {
9161            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9162                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9163        } else {
9164            // Assume that post will succeed later
9165            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9166        }
9167    }
9168
9169    /**
9170     * <p>Removes the specified Runnable from the message queue.</p>
9171     *
9172     * <p>This method can be invoked from outside of the UI thread
9173     * only when this View is attached to a window.</p>
9174     *
9175     * @param action The Runnable to remove from the message handling queue
9176     *
9177     * @return true if this view could ask the Handler to remove the Runnable,
9178     *         false otherwise. When the returned value is true, the Runnable
9179     *         may or may not have been actually removed from the message queue
9180     *         (for instance, if the Runnable was not in the queue already.)
9181     */
9182    public boolean removeCallbacks(Runnable action) {
9183        if (action != null) {
9184            final AttachInfo attachInfo = mAttachInfo;
9185            if (attachInfo != null) {
9186                attachInfo.mHandler.removeCallbacks(action);
9187                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9188                        Choreographer.CALLBACK_ANIMATION, action, null);
9189            } else {
9190                // Assume that post will succeed later
9191                ViewRootImpl.getRunQueue().removeCallbacks(action);
9192            }
9193        }
9194        return true;
9195    }
9196
9197    /**
9198     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9199     * Use this to invalidate the View from a non-UI thread.</p>
9200     *
9201     * <p>This method can be invoked from outside of the UI thread
9202     * only when this View is attached to a window.</p>
9203     *
9204     * @see #invalidate()
9205     */
9206    public void postInvalidate() {
9207        postInvalidateDelayed(0);
9208    }
9209
9210    /**
9211     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9212     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9213     *
9214     * <p>This method can be invoked from outside of the UI thread
9215     * only when this View is attached to a window.</p>
9216     *
9217     * @param left The left coordinate of the rectangle to invalidate.
9218     * @param top The top coordinate of the rectangle to invalidate.
9219     * @param right The right coordinate of the rectangle to invalidate.
9220     * @param bottom The bottom coordinate of the rectangle to invalidate.
9221     *
9222     * @see #invalidate(int, int, int, int)
9223     * @see #invalidate(Rect)
9224     */
9225    public void postInvalidate(int left, int top, int right, int bottom) {
9226        postInvalidateDelayed(0, left, top, right, bottom);
9227    }
9228
9229    /**
9230     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9231     * loop. Waits for the specified amount of time.</p>
9232     *
9233     * <p>This method can be invoked from outside of the UI thread
9234     * only when this View is attached to a window.</p>
9235     *
9236     * @param delayMilliseconds the duration in milliseconds to delay the
9237     *         invalidation by
9238     */
9239    public void postInvalidateDelayed(long delayMilliseconds) {
9240        // We try only with the AttachInfo because there's no point in invalidating
9241        // if we are not attached to our window
9242        final AttachInfo attachInfo = mAttachInfo;
9243        if (attachInfo != null) {
9244            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9245        }
9246    }
9247
9248    /**
9249     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9250     * through the event loop. Waits for the specified amount of time.</p>
9251     *
9252     * <p>This method can be invoked from outside of the UI thread
9253     * only when this View is attached to a window.</p>
9254     *
9255     * @param delayMilliseconds the duration in milliseconds to delay the
9256     *         invalidation by
9257     * @param left The left coordinate of the rectangle to invalidate.
9258     * @param top The top coordinate of the rectangle to invalidate.
9259     * @param right The right coordinate of the rectangle to invalidate.
9260     * @param bottom The bottom coordinate of the rectangle to invalidate.
9261     */
9262    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
9263            int right, int bottom) {
9264
9265        // We try only with the AttachInfo because there's no point in invalidating
9266        // if we are not attached to our window
9267        final AttachInfo attachInfo = mAttachInfo;
9268        if (attachInfo != null) {
9269            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9270            info.target = this;
9271            info.left = left;
9272            info.top = top;
9273            info.right = right;
9274            info.bottom = bottom;
9275
9276            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
9277        }
9278    }
9279
9280    /**
9281     * <p>Cause an invalidate to happen on the next animation time step, typically the
9282     * next display frame.</p>
9283     *
9284     * <p>This method can be invoked from outside of the UI thread
9285     * only when this View is attached to a window.</p>
9286     *
9287     * @hide
9288     */
9289    public void postInvalidateOnAnimation() {
9290        // We try only with the AttachInfo because there's no point in invalidating
9291        // if we are not attached to our window
9292        final AttachInfo attachInfo = mAttachInfo;
9293        if (attachInfo != null) {
9294            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
9295        }
9296    }
9297
9298    /**
9299     * <p>Cause an invalidate of the specified area to happen on the next animation
9300     * time step, typically the next display frame.</p>
9301     *
9302     * <p>This method can be invoked from outside of the UI thread
9303     * only when this View is attached to a window.</p>
9304     *
9305     * @param left The left coordinate of the rectangle to invalidate.
9306     * @param top The top coordinate of the rectangle to invalidate.
9307     * @param right The right coordinate of the rectangle to invalidate.
9308     * @param bottom The bottom coordinate of the rectangle to invalidate.
9309     *
9310     * @hide
9311     */
9312    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
9313        // We try only with the AttachInfo because there's no point in invalidating
9314        // if we are not attached to our window
9315        final AttachInfo attachInfo = mAttachInfo;
9316        if (attachInfo != null) {
9317            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9318            info.target = this;
9319            info.left = left;
9320            info.top = top;
9321            info.right = right;
9322            info.bottom = bottom;
9323
9324            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
9325        }
9326    }
9327
9328    /**
9329     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
9330     * This event is sent at most once every
9331     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
9332     */
9333    private void postSendViewScrolledAccessibilityEventCallback() {
9334        if (mSendViewScrolledAccessibilityEvent == null) {
9335            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
9336        }
9337        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
9338            mSendViewScrolledAccessibilityEvent.mIsPending = true;
9339            postDelayed(mSendViewScrolledAccessibilityEvent,
9340                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
9341        }
9342    }
9343
9344    /**
9345     * Called by a parent to request that a child update its values for mScrollX
9346     * and mScrollY if necessary. This will typically be done if the child is
9347     * animating a scroll using a {@link android.widget.Scroller Scroller}
9348     * object.
9349     */
9350    public void computeScroll() {
9351    }
9352
9353    /**
9354     * <p>Indicate whether the horizontal edges are faded when the view is
9355     * scrolled horizontally.</p>
9356     *
9357     * @return true if the horizontal edges should are faded on scroll, false
9358     *         otherwise
9359     *
9360     * @see #setHorizontalFadingEdgeEnabled(boolean)
9361     * @attr ref android.R.styleable#View_requiresFadingEdge
9362     */
9363    public boolean isHorizontalFadingEdgeEnabled() {
9364        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
9365    }
9366
9367    /**
9368     * <p>Define whether the horizontal edges should be faded when this view
9369     * is scrolled horizontally.</p>
9370     *
9371     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
9372     *                                    be faded when the view is scrolled
9373     *                                    horizontally
9374     *
9375     * @see #isHorizontalFadingEdgeEnabled()
9376     * @attr ref android.R.styleable#View_requiresFadingEdge
9377     */
9378    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
9379        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
9380            if (horizontalFadingEdgeEnabled) {
9381                initScrollCache();
9382            }
9383
9384            mViewFlags ^= FADING_EDGE_HORIZONTAL;
9385        }
9386    }
9387
9388    /**
9389     * <p>Indicate whether the vertical edges are faded when the view is
9390     * scrolled horizontally.</p>
9391     *
9392     * @return true if the vertical edges should are faded on scroll, false
9393     *         otherwise
9394     *
9395     * @see #setVerticalFadingEdgeEnabled(boolean)
9396     * @attr ref android.R.styleable#View_requiresFadingEdge
9397     */
9398    public boolean isVerticalFadingEdgeEnabled() {
9399        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
9400    }
9401
9402    /**
9403     * <p>Define whether the vertical edges should be faded when this view
9404     * is scrolled vertically.</p>
9405     *
9406     * @param verticalFadingEdgeEnabled true if the vertical edges should
9407     *                                  be faded when the view is scrolled
9408     *                                  vertically
9409     *
9410     * @see #isVerticalFadingEdgeEnabled()
9411     * @attr ref android.R.styleable#View_requiresFadingEdge
9412     */
9413    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
9414        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
9415            if (verticalFadingEdgeEnabled) {
9416                initScrollCache();
9417            }
9418
9419            mViewFlags ^= FADING_EDGE_VERTICAL;
9420        }
9421    }
9422
9423    /**
9424     * Returns the strength, or intensity, of the top faded edge. The strength is
9425     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9426     * returns 0.0 or 1.0 but no value in between.
9427     *
9428     * Subclasses should override this method to provide a smoother fade transition
9429     * when scrolling occurs.
9430     *
9431     * @return the intensity of the top fade as a float between 0.0f and 1.0f
9432     */
9433    protected float getTopFadingEdgeStrength() {
9434        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
9435    }
9436
9437    /**
9438     * Returns the strength, or intensity, of the bottom faded edge. The strength is
9439     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9440     * returns 0.0 or 1.0 but no value in between.
9441     *
9442     * Subclasses should override this method to provide a smoother fade transition
9443     * when scrolling occurs.
9444     *
9445     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
9446     */
9447    protected float getBottomFadingEdgeStrength() {
9448        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
9449                computeVerticalScrollRange() ? 1.0f : 0.0f;
9450    }
9451
9452    /**
9453     * Returns the strength, or intensity, of the left faded edge. The strength is
9454     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9455     * returns 0.0 or 1.0 but no value in between.
9456     *
9457     * Subclasses should override this method to provide a smoother fade transition
9458     * when scrolling occurs.
9459     *
9460     * @return the intensity of the left fade as a float between 0.0f and 1.0f
9461     */
9462    protected float getLeftFadingEdgeStrength() {
9463        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
9464    }
9465
9466    /**
9467     * Returns the strength, or intensity, of the right faded edge. The strength is
9468     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9469     * returns 0.0 or 1.0 but no value in between.
9470     *
9471     * Subclasses should override this method to provide a smoother fade transition
9472     * when scrolling occurs.
9473     *
9474     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9475     */
9476    protected float getRightFadingEdgeStrength() {
9477        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9478                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9479    }
9480
9481    /**
9482     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9483     * scrollbar is not drawn by default.</p>
9484     *
9485     * @return true if the horizontal scrollbar should be painted, false
9486     *         otherwise
9487     *
9488     * @see #setHorizontalScrollBarEnabled(boolean)
9489     */
9490    public boolean isHorizontalScrollBarEnabled() {
9491        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9492    }
9493
9494    /**
9495     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9496     * scrollbar is not drawn by default.</p>
9497     *
9498     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9499     *                                   be painted
9500     *
9501     * @see #isHorizontalScrollBarEnabled()
9502     */
9503    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9504        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9505            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9506            computeOpaqueFlags();
9507            resolvePadding();
9508        }
9509    }
9510
9511    /**
9512     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9513     * scrollbar is not drawn by default.</p>
9514     *
9515     * @return true if the vertical scrollbar should be painted, false
9516     *         otherwise
9517     *
9518     * @see #setVerticalScrollBarEnabled(boolean)
9519     */
9520    public boolean isVerticalScrollBarEnabled() {
9521        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9522    }
9523
9524    /**
9525     * <p>Define whether the vertical scrollbar should be drawn or not. The
9526     * scrollbar is not drawn by default.</p>
9527     *
9528     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9529     *                                 be painted
9530     *
9531     * @see #isVerticalScrollBarEnabled()
9532     */
9533    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9534        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9535            mViewFlags ^= SCROLLBARS_VERTICAL;
9536            computeOpaqueFlags();
9537            resolvePadding();
9538        }
9539    }
9540
9541    /**
9542     * @hide
9543     */
9544    protected void recomputePadding() {
9545        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9546    }
9547
9548    /**
9549     * Define whether scrollbars will fade when the view is not scrolling.
9550     *
9551     * @param fadeScrollbars wheter to enable fading
9552     *
9553     */
9554    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9555        initScrollCache();
9556        final ScrollabilityCache scrollabilityCache = mScrollCache;
9557        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9558        if (fadeScrollbars) {
9559            scrollabilityCache.state = ScrollabilityCache.OFF;
9560        } else {
9561            scrollabilityCache.state = ScrollabilityCache.ON;
9562        }
9563    }
9564
9565    /**
9566     *
9567     * Returns true if scrollbars will fade when this view is not scrolling
9568     *
9569     * @return true if scrollbar fading is enabled
9570     */
9571    public boolean isScrollbarFadingEnabled() {
9572        return mScrollCache != null && mScrollCache.fadeScrollBars;
9573    }
9574
9575    /**
9576     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9577     * inset. When inset, they add to the padding of the view. And the scrollbars
9578     * can be drawn inside the padding area or on the edge of the view. For example,
9579     * if a view has a background drawable and you want to draw the scrollbars
9580     * inside the padding specified by the drawable, you can use
9581     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9582     * appear at the edge of the view, ignoring the padding, then you can use
9583     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9584     * @param style the style of the scrollbars. Should be one of
9585     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9586     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9587     * @see #SCROLLBARS_INSIDE_OVERLAY
9588     * @see #SCROLLBARS_INSIDE_INSET
9589     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9590     * @see #SCROLLBARS_OUTSIDE_INSET
9591     */
9592    public void setScrollBarStyle(int style) {
9593        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9594            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9595            computeOpaqueFlags();
9596            resolvePadding();
9597        }
9598    }
9599
9600    /**
9601     * <p>Returns the current scrollbar style.</p>
9602     * @return the current scrollbar style
9603     * @see #SCROLLBARS_INSIDE_OVERLAY
9604     * @see #SCROLLBARS_INSIDE_INSET
9605     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9606     * @see #SCROLLBARS_OUTSIDE_INSET
9607     */
9608    @ViewDebug.ExportedProperty(mapping = {
9609            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9610            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9611            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9612            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9613    })
9614    public int getScrollBarStyle() {
9615        return mViewFlags & SCROLLBARS_STYLE_MASK;
9616    }
9617
9618    /**
9619     * <p>Compute the horizontal range that the horizontal scrollbar
9620     * represents.</p>
9621     *
9622     * <p>The range is expressed in arbitrary units that must be the same as the
9623     * units used by {@link #computeHorizontalScrollExtent()} and
9624     * {@link #computeHorizontalScrollOffset()}.</p>
9625     *
9626     * <p>The default range is the drawing width of this view.</p>
9627     *
9628     * @return the total horizontal range represented by the horizontal
9629     *         scrollbar
9630     *
9631     * @see #computeHorizontalScrollExtent()
9632     * @see #computeHorizontalScrollOffset()
9633     * @see android.widget.ScrollBarDrawable
9634     */
9635    protected int computeHorizontalScrollRange() {
9636        return getWidth();
9637    }
9638
9639    /**
9640     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9641     * within the horizontal range. This value is used to compute the position
9642     * of the thumb within the scrollbar's track.</p>
9643     *
9644     * <p>The range is expressed in arbitrary units that must be the same as the
9645     * units used by {@link #computeHorizontalScrollRange()} and
9646     * {@link #computeHorizontalScrollExtent()}.</p>
9647     *
9648     * <p>The default offset is the scroll offset of this view.</p>
9649     *
9650     * @return the horizontal offset of the scrollbar's thumb
9651     *
9652     * @see #computeHorizontalScrollRange()
9653     * @see #computeHorizontalScrollExtent()
9654     * @see android.widget.ScrollBarDrawable
9655     */
9656    protected int computeHorizontalScrollOffset() {
9657        return mScrollX;
9658    }
9659
9660    /**
9661     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9662     * within the horizontal range. This value is used to compute the length
9663     * of the thumb within the scrollbar's track.</p>
9664     *
9665     * <p>The range is expressed in arbitrary units that must be the same as the
9666     * units used by {@link #computeHorizontalScrollRange()} and
9667     * {@link #computeHorizontalScrollOffset()}.</p>
9668     *
9669     * <p>The default extent is the drawing width of this view.</p>
9670     *
9671     * @return the horizontal extent of the scrollbar's thumb
9672     *
9673     * @see #computeHorizontalScrollRange()
9674     * @see #computeHorizontalScrollOffset()
9675     * @see android.widget.ScrollBarDrawable
9676     */
9677    protected int computeHorizontalScrollExtent() {
9678        return getWidth();
9679    }
9680
9681    /**
9682     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9683     *
9684     * <p>The range is expressed in arbitrary units that must be the same as the
9685     * units used by {@link #computeVerticalScrollExtent()} and
9686     * {@link #computeVerticalScrollOffset()}.</p>
9687     *
9688     * @return the total vertical range represented by the vertical scrollbar
9689     *
9690     * <p>The default range is the drawing height of this view.</p>
9691     *
9692     * @see #computeVerticalScrollExtent()
9693     * @see #computeVerticalScrollOffset()
9694     * @see android.widget.ScrollBarDrawable
9695     */
9696    protected int computeVerticalScrollRange() {
9697        return getHeight();
9698    }
9699
9700    /**
9701     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9702     * within the horizontal range. This value is used to compute the position
9703     * of the thumb within the scrollbar's track.</p>
9704     *
9705     * <p>The range is expressed in arbitrary units that must be the same as the
9706     * units used by {@link #computeVerticalScrollRange()} and
9707     * {@link #computeVerticalScrollExtent()}.</p>
9708     *
9709     * <p>The default offset is the scroll offset of this view.</p>
9710     *
9711     * @return the vertical offset of the scrollbar's thumb
9712     *
9713     * @see #computeVerticalScrollRange()
9714     * @see #computeVerticalScrollExtent()
9715     * @see android.widget.ScrollBarDrawable
9716     */
9717    protected int computeVerticalScrollOffset() {
9718        return mScrollY;
9719    }
9720
9721    /**
9722     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9723     * within the vertical range. This value is used to compute the length
9724     * of the thumb within the scrollbar's track.</p>
9725     *
9726     * <p>The range is expressed in arbitrary units that must be the same as the
9727     * units used by {@link #computeVerticalScrollRange()} and
9728     * {@link #computeVerticalScrollOffset()}.</p>
9729     *
9730     * <p>The default extent is the drawing height of this view.</p>
9731     *
9732     * @return the vertical extent of the scrollbar's thumb
9733     *
9734     * @see #computeVerticalScrollRange()
9735     * @see #computeVerticalScrollOffset()
9736     * @see android.widget.ScrollBarDrawable
9737     */
9738    protected int computeVerticalScrollExtent() {
9739        return getHeight();
9740    }
9741
9742    /**
9743     * Check if this view can be scrolled horizontally in a certain direction.
9744     *
9745     * @param direction Negative to check scrolling left, positive to check scrolling right.
9746     * @return true if this view can be scrolled in the specified direction, false otherwise.
9747     */
9748    public boolean canScrollHorizontally(int direction) {
9749        final int offset = computeHorizontalScrollOffset();
9750        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9751        if (range == 0) return false;
9752        if (direction < 0) {
9753            return offset > 0;
9754        } else {
9755            return offset < range - 1;
9756        }
9757    }
9758
9759    /**
9760     * Check if this view can be scrolled vertically in a certain direction.
9761     *
9762     * @param direction Negative to check scrolling up, positive to check scrolling down.
9763     * @return true if this view can be scrolled in the specified direction, false otherwise.
9764     */
9765    public boolean canScrollVertically(int direction) {
9766        final int offset = computeVerticalScrollOffset();
9767        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9768        if (range == 0) return false;
9769        if (direction < 0) {
9770            return offset > 0;
9771        } else {
9772            return offset < range - 1;
9773        }
9774    }
9775
9776    /**
9777     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9778     * scrollbars are painted only if they have been awakened first.</p>
9779     *
9780     * @param canvas the canvas on which to draw the scrollbars
9781     *
9782     * @see #awakenScrollBars(int)
9783     */
9784    protected final void onDrawScrollBars(Canvas canvas) {
9785        // scrollbars are drawn only when the animation is running
9786        final ScrollabilityCache cache = mScrollCache;
9787        if (cache != null) {
9788
9789            int state = cache.state;
9790
9791            if (state == ScrollabilityCache.OFF) {
9792                return;
9793            }
9794
9795            boolean invalidate = false;
9796
9797            if (state == ScrollabilityCache.FADING) {
9798                // We're fading -- get our fade interpolation
9799                if (cache.interpolatorValues == null) {
9800                    cache.interpolatorValues = new float[1];
9801                }
9802
9803                float[] values = cache.interpolatorValues;
9804
9805                // Stops the animation if we're done
9806                if (cache.scrollBarInterpolator.timeToValues(values) ==
9807                        Interpolator.Result.FREEZE_END) {
9808                    cache.state = ScrollabilityCache.OFF;
9809                } else {
9810                    cache.scrollBar.setAlpha(Math.round(values[0]));
9811                }
9812
9813                // This will make the scroll bars inval themselves after
9814                // drawing. We only want this when we're fading so that
9815                // we prevent excessive redraws
9816                invalidate = true;
9817            } else {
9818                // We're just on -- but we may have been fading before so
9819                // reset alpha
9820                cache.scrollBar.setAlpha(255);
9821            }
9822
9823
9824            final int viewFlags = mViewFlags;
9825
9826            final boolean drawHorizontalScrollBar =
9827                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9828            final boolean drawVerticalScrollBar =
9829                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9830                && !isVerticalScrollBarHidden();
9831
9832            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9833                final int width = mRight - mLeft;
9834                final int height = mBottom - mTop;
9835
9836                final ScrollBarDrawable scrollBar = cache.scrollBar;
9837
9838                final int scrollX = mScrollX;
9839                final int scrollY = mScrollY;
9840                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9841
9842                int left, top, right, bottom;
9843
9844                if (drawHorizontalScrollBar) {
9845                    int size = scrollBar.getSize(false);
9846                    if (size <= 0) {
9847                        size = cache.scrollBarSize;
9848                    }
9849
9850                    scrollBar.setParameters(computeHorizontalScrollRange(),
9851                                            computeHorizontalScrollOffset(),
9852                                            computeHorizontalScrollExtent(), false);
9853                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9854                            getVerticalScrollbarWidth() : 0;
9855                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9856                    left = scrollX + (mPaddingLeft & inside);
9857                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9858                    bottom = top + size;
9859                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9860                    if (invalidate) {
9861                        invalidate(left, top, right, bottom);
9862                    }
9863                }
9864
9865                if (drawVerticalScrollBar) {
9866                    int size = scrollBar.getSize(true);
9867                    if (size <= 0) {
9868                        size = cache.scrollBarSize;
9869                    }
9870
9871                    scrollBar.setParameters(computeVerticalScrollRange(),
9872                                            computeVerticalScrollOffset(),
9873                                            computeVerticalScrollExtent(), true);
9874                    switch (mVerticalScrollbarPosition) {
9875                        default:
9876                        case SCROLLBAR_POSITION_DEFAULT:
9877                        case SCROLLBAR_POSITION_RIGHT:
9878                            left = scrollX + width - size - (mUserPaddingRight & inside);
9879                            break;
9880                        case SCROLLBAR_POSITION_LEFT:
9881                            left = scrollX + (mUserPaddingLeft & inside);
9882                            break;
9883                    }
9884                    top = scrollY + (mPaddingTop & inside);
9885                    right = left + size;
9886                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9887                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9888                    if (invalidate) {
9889                        invalidate(left, top, right, bottom);
9890                    }
9891                }
9892            }
9893        }
9894    }
9895
9896    /**
9897     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9898     * FastScroller is visible.
9899     * @return whether to temporarily hide the vertical scrollbar
9900     * @hide
9901     */
9902    protected boolean isVerticalScrollBarHidden() {
9903        return false;
9904    }
9905
9906    /**
9907     * <p>Draw the horizontal scrollbar if
9908     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9909     *
9910     * @param canvas the canvas on which to draw the scrollbar
9911     * @param scrollBar the scrollbar's drawable
9912     *
9913     * @see #isHorizontalScrollBarEnabled()
9914     * @see #computeHorizontalScrollRange()
9915     * @see #computeHorizontalScrollExtent()
9916     * @see #computeHorizontalScrollOffset()
9917     * @see android.widget.ScrollBarDrawable
9918     * @hide
9919     */
9920    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9921            int l, int t, int r, int b) {
9922        scrollBar.setBounds(l, t, r, b);
9923        scrollBar.draw(canvas);
9924    }
9925
9926    /**
9927     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9928     * returns true.</p>
9929     *
9930     * @param canvas the canvas on which to draw the scrollbar
9931     * @param scrollBar the scrollbar's drawable
9932     *
9933     * @see #isVerticalScrollBarEnabled()
9934     * @see #computeVerticalScrollRange()
9935     * @see #computeVerticalScrollExtent()
9936     * @see #computeVerticalScrollOffset()
9937     * @see android.widget.ScrollBarDrawable
9938     * @hide
9939     */
9940    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9941            int l, int t, int r, int b) {
9942        scrollBar.setBounds(l, t, r, b);
9943        scrollBar.draw(canvas);
9944    }
9945
9946    /**
9947     * Implement this to do your drawing.
9948     *
9949     * @param canvas the canvas on which the background will be drawn
9950     */
9951    protected void onDraw(Canvas canvas) {
9952    }
9953
9954    /*
9955     * Caller is responsible for calling requestLayout if necessary.
9956     * (This allows addViewInLayout to not request a new layout.)
9957     */
9958    void assignParent(ViewParent parent) {
9959        if (mParent == null) {
9960            mParent = parent;
9961        } else if (parent == null) {
9962            mParent = null;
9963        } else {
9964            throw new RuntimeException("view " + this + " being added, but"
9965                    + " it already has a parent");
9966        }
9967    }
9968
9969    /**
9970     * This is called when the view is attached to a window.  At this point it
9971     * has a Surface and will start drawing.  Note that this function is
9972     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9973     * however it may be called any time before the first onDraw -- including
9974     * before or after {@link #onMeasure(int, int)}.
9975     *
9976     * @see #onDetachedFromWindow()
9977     */
9978    protected void onAttachedToWindow() {
9979        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9980            mParent.requestTransparentRegion(this);
9981        }
9982        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9983            initialAwakenScrollBars();
9984            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9985        }
9986        jumpDrawablesToCurrentState();
9987        // Order is important here: LayoutDirection MUST be resolved before Padding
9988        // and TextDirection
9989        resolveLayoutDirection();
9990        resolvePadding();
9991        resolveTextDirection();
9992        if (isFocused()) {
9993            InputMethodManager imm = InputMethodManager.peekInstance();
9994            imm.focusIn(this);
9995        }
9996    }
9997
9998    /**
9999     * @see #onScreenStateChanged(int)
10000     */
10001    void dispatchScreenStateChanged(int screenState) {
10002        onScreenStateChanged(screenState);
10003    }
10004
10005    /**
10006     * This method is called whenever the state of the screen this view is
10007     * attached to changes. A state change will usually occurs when the screen
10008     * turns on or off (whether it happens automatically or the user does it
10009     * manually.)
10010     *
10011     * @param screenState The new state of the screen. Can be either
10012     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10013     */
10014    public void onScreenStateChanged(int screenState) {
10015    }
10016
10017    /**
10018     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10019     */
10020    private boolean hasRtlSupport() {
10021        return mContext.getApplicationInfo().hasRtlSupport();
10022    }
10023
10024    /**
10025     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10026     * that the parent directionality can and will be resolved before its children.
10027     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10028     */
10029    public void resolveLayoutDirection() {
10030        // Clear any previous layout direction resolution
10031        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10032
10033        if (hasRtlSupport()) {
10034            // Set resolved depending on layout direction
10035            switch (getLayoutDirection()) {
10036                case LAYOUT_DIRECTION_INHERIT:
10037                    // If this is root view, no need to look at parent's layout dir.
10038                    if (canResolveLayoutDirection()) {
10039                        ViewGroup viewGroup = ((ViewGroup) mParent);
10040
10041                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10042                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10043                        }
10044                    } else {
10045                        // Nothing to do, LTR by default
10046                    }
10047                    break;
10048                case LAYOUT_DIRECTION_RTL:
10049                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10050                    break;
10051                case LAYOUT_DIRECTION_LOCALE:
10052                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10053                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10054                    }
10055                    break;
10056                default:
10057                    // Nothing to do, LTR by default
10058            }
10059        }
10060
10061        // Set to resolved
10062        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10063        onResolvedLayoutDirectionChanged();
10064        // Resolve padding
10065        resolvePadding();
10066    }
10067
10068    /**
10069     * Called when layout direction has been resolved.
10070     *
10071     * The default implementation does nothing.
10072     */
10073    public void onResolvedLayoutDirectionChanged() {
10074    }
10075
10076    /**
10077     * Resolve padding depending on layout direction.
10078     */
10079    public void resolvePadding() {
10080        // If the user specified the absolute padding (either with android:padding or
10081        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10082        // use the default padding or the padding from the background drawable
10083        // (stored at this point in mPadding*)
10084        int resolvedLayoutDirection = getResolvedLayoutDirection();
10085        switch (resolvedLayoutDirection) {
10086            case LAYOUT_DIRECTION_RTL:
10087                // Start user padding override Right user padding. Otherwise, if Right user
10088                // padding is not defined, use the default Right padding. If Right user padding
10089                // is defined, just use it.
10090                if (mUserPaddingStart >= 0) {
10091                    mUserPaddingRight = mUserPaddingStart;
10092                } else if (mUserPaddingRight < 0) {
10093                    mUserPaddingRight = mPaddingRight;
10094                }
10095                if (mUserPaddingEnd >= 0) {
10096                    mUserPaddingLeft = mUserPaddingEnd;
10097                } else if (mUserPaddingLeft < 0) {
10098                    mUserPaddingLeft = mPaddingLeft;
10099                }
10100                break;
10101            case LAYOUT_DIRECTION_LTR:
10102            default:
10103                // Start user padding override Left user padding. Otherwise, if Left user
10104                // padding is not defined, use the default left padding. If Left user padding
10105                // is defined, just use it.
10106                if (mUserPaddingStart >= 0) {
10107                    mUserPaddingLeft = mUserPaddingStart;
10108                } else if (mUserPaddingLeft < 0) {
10109                    mUserPaddingLeft = mPaddingLeft;
10110                }
10111                if (mUserPaddingEnd >= 0) {
10112                    mUserPaddingRight = mUserPaddingEnd;
10113                } else if (mUserPaddingRight < 0) {
10114                    mUserPaddingRight = mPaddingRight;
10115                }
10116        }
10117
10118        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
10119
10120        if(isPaddingRelative()) {
10121            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
10122        } else {
10123            recomputePadding();
10124        }
10125        onPaddingChanged(resolvedLayoutDirection);
10126    }
10127
10128    /**
10129     * Resolve padding depending on the layout direction. Subclasses that care about
10130     * padding resolution should override this method. The default implementation does
10131     * nothing.
10132     *
10133     * @param layoutDirection the direction of the layout
10134     *
10135     * @see {@link #LAYOUT_DIRECTION_LTR}
10136     * @see {@link #LAYOUT_DIRECTION_RTL}
10137     */
10138    public void onPaddingChanged(int layoutDirection) {
10139    }
10140
10141    /**
10142     * Check if layout direction resolution can be done.
10143     *
10144     * @return true if layout direction resolution can be done otherwise return false.
10145     */
10146    public boolean canResolveLayoutDirection() {
10147        switch (getLayoutDirection()) {
10148            case LAYOUT_DIRECTION_INHERIT:
10149                return (mParent != null) && (mParent instanceof ViewGroup);
10150            default:
10151                return true;
10152        }
10153    }
10154
10155    /**
10156     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
10157     * when reset is done.
10158     */
10159    public void resetResolvedLayoutDirection() {
10160        // Reset the current resolved bits
10161        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10162        onResolvedLayoutDirectionReset();
10163        // Reset also the text direction
10164        resetResolvedTextDirection();
10165    }
10166
10167    /**
10168     * Called during reset of resolved layout direction.
10169     *
10170     * Subclasses need to override this method to clear cached information that depends on the
10171     * resolved layout direction, or to inform child views that inherit their layout direction.
10172     *
10173     * The default implementation does nothing.
10174     */
10175    public void onResolvedLayoutDirectionReset() {
10176    }
10177
10178    /**
10179     * Check if a Locale uses an RTL script.
10180     *
10181     * @param locale Locale to check
10182     * @return true if the Locale uses an RTL script.
10183     */
10184    protected static boolean isLayoutDirectionRtl(Locale locale) {
10185        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
10186    }
10187
10188    /**
10189     * This is called when the view is detached from a window.  At this point it
10190     * no longer has a surface for drawing.
10191     *
10192     * @see #onAttachedToWindow()
10193     */
10194    protected void onDetachedFromWindow() {
10195        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
10196
10197        removeUnsetPressCallback();
10198        removeLongPressCallback();
10199        removePerformClickCallback();
10200        removeSendViewScrolledAccessibilityEventCallback();
10201
10202        destroyDrawingCache();
10203
10204        destroyLayer(false);
10205
10206        if (mAttachInfo != null) {
10207            if (mDisplayList != null) {
10208                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
10209            }
10210            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
10211        } else {
10212            if (mDisplayList != null) {
10213                // Should never happen
10214                mDisplayList.invalidate();
10215            }
10216        }
10217
10218        mCurrentAnimation = null;
10219
10220        resetResolvedLayoutDirection();
10221    }
10222
10223    /**
10224     * @return The number of times this view has been attached to a window
10225     */
10226    protected int getWindowAttachCount() {
10227        return mWindowAttachCount;
10228    }
10229
10230    /**
10231     * Retrieve a unique token identifying the window this view is attached to.
10232     * @return Return the window's token for use in
10233     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
10234     */
10235    public IBinder getWindowToken() {
10236        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
10237    }
10238
10239    /**
10240     * Retrieve a unique token identifying the top-level "real" window of
10241     * the window that this view is attached to.  That is, this is like
10242     * {@link #getWindowToken}, except if the window this view in is a panel
10243     * window (attached to another containing window), then the token of
10244     * the containing window is returned instead.
10245     *
10246     * @return Returns the associated window token, either
10247     * {@link #getWindowToken()} or the containing window's token.
10248     */
10249    public IBinder getApplicationWindowToken() {
10250        AttachInfo ai = mAttachInfo;
10251        if (ai != null) {
10252            IBinder appWindowToken = ai.mPanelParentWindowToken;
10253            if (appWindowToken == null) {
10254                appWindowToken = ai.mWindowToken;
10255            }
10256            return appWindowToken;
10257        }
10258        return null;
10259    }
10260
10261    /**
10262     * Retrieve private session object this view hierarchy is using to
10263     * communicate with the window manager.
10264     * @return the session object to communicate with the window manager
10265     */
10266    /*package*/ IWindowSession getWindowSession() {
10267        return mAttachInfo != null ? mAttachInfo.mSession : null;
10268    }
10269
10270    /**
10271     * @param info the {@link android.view.View.AttachInfo} to associated with
10272     *        this view
10273     */
10274    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
10275        //System.out.println("Attached! " + this);
10276        mAttachInfo = info;
10277        mWindowAttachCount++;
10278        // We will need to evaluate the drawable state at least once.
10279        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
10280        if (mFloatingTreeObserver != null) {
10281            info.mTreeObserver.merge(mFloatingTreeObserver);
10282            mFloatingTreeObserver = null;
10283        }
10284        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
10285            mAttachInfo.mScrollContainers.add(this);
10286            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
10287        }
10288        performCollectViewAttributes(mAttachInfo, visibility);
10289        onAttachedToWindow();
10290
10291        ListenerInfo li = mListenerInfo;
10292        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10293                li != null ? li.mOnAttachStateChangeListeners : null;
10294        if (listeners != null && listeners.size() > 0) {
10295            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10296            // perform the dispatching. The iterator is a safe guard against listeners that
10297            // could mutate the list by calling the various add/remove methods. This prevents
10298            // the array from being modified while we iterate it.
10299            for (OnAttachStateChangeListener listener : listeners) {
10300                listener.onViewAttachedToWindow(this);
10301            }
10302        }
10303
10304        int vis = info.mWindowVisibility;
10305        if (vis != GONE) {
10306            onWindowVisibilityChanged(vis);
10307        }
10308        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
10309            // If nobody has evaluated the drawable state yet, then do it now.
10310            refreshDrawableState();
10311        }
10312    }
10313
10314    void dispatchDetachedFromWindow() {
10315        AttachInfo info = mAttachInfo;
10316        if (info != null) {
10317            int vis = info.mWindowVisibility;
10318            if (vis != GONE) {
10319                onWindowVisibilityChanged(GONE);
10320            }
10321        }
10322
10323        onDetachedFromWindow();
10324
10325        ListenerInfo li = mListenerInfo;
10326        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10327                li != null ? li.mOnAttachStateChangeListeners : null;
10328        if (listeners != null && listeners.size() > 0) {
10329            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10330            // perform the dispatching. The iterator is a safe guard against listeners that
10331            // could mutate the list by calling the various add/remove methods. This prevents
10332            // the array from being modified while we iterate it.
10333            for (OnAttachStateChangeListener listener : listeners) {
10334                listener.onViewDetachedFromWindow(this);
10335            }
10336        }
10337
10338        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
10339            mAttachInfo.mScrollContainers.remove(this);
10340            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
10341        }
10342
10343        mAttachInfo = null;
10344    }
10345
10346    /**
10347     * Store this view hierarchy's frozen state into the given container.
10348     *
10349     * @param container The SparseArray in which to save the view's state.
10350     *
10351     * @see #restoreHierarchyState(android.util.SparseArray)
10352     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10353     * @see #onSaveInstanceState()
10354     */
10355    public void saveHierarchyState(SparseArray<Parcelable> container) {
10356        dispatchSaveInstanceState(container);
10357    }
10358
10359    /**
10360     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
10361     * this view and its children. May be overridden to modify how freezing happens to a
10362     * view's children; for example, some views may want to not store state for their children.
10363     *
10364     * @param container The SparseArray in which to save the view's state.
10365     *
10366     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10367     * @see #saveHierarchyState(android.util.SparseArray)
10368     * @see #onSaveInstanceState()
10369     */
10370    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
10371        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
10372            mPrivateFlags &= ~SAVE_STATE_CALLED;
10373            Parcelable state = onSaveInstanceState();
10374            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10375                throw new IllegalStateException(
10376                        "Derived class did not call super.onSaveInstanceState()");
10377            }
10378            if (state != null) {
10379                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
10380                // + ": " + state);
10381                container.put(mID, state);
10382            }
10383        }
10384    }
10385
10386    /**
10387     * Hook allowing a view to generate a representation of its internal state
10388     * that can later be used to create a new instance with that same state.
10389     * This state should only contain information that is not persistent or can
10390     * not be reconstructed later. For example, you will never store your
10391     * current position on screen because that will be computed again when a
10392     * new instance of the view is placed in its view hierarchy.
10393     * <p>
10394     * Some examples of things you may store here: the current cursor position
10395     * in a text view (but usually not the text itself since that is stored in a
10396     * content provider or other persistent storage), the currently selected
10397     * item in a list view.
10398     *
10399     * @return Returns a Parcelable object containing the view's current dynamic
10400     *         state, or null if there is nothing interesting to save. The
10401     *         default implementation returns null.
10402     * @see #onRestoreInstanceState(android.os.Parcelable)
10403     * @see #saveHierarchyState(android.util.SparseArray)
10404     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10405     * @see #setSaveEnabled(boolean)
10406     */
10407    protected Parcelable onSaveInstanceState() {
10408        mPrivateFlags |= SAVE_STATE_CALLED;
10409        return BaseSavedState.EMPTY_STATE;
10410    }
10411
10412    /**
10413     * Restore this view hierarchy's frozen state from the given container.
10414     *
10415     * @param container The SparseArray which holds previously frozen states.
10416     *
10417     * @see #saveHierarchyState(android.util.SparseArray)
10418     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10419     * @see #onRestoreInstanceState(android.os.Parcelable)
10420     */
10421    public void restoreHierarchyState(SparseArray<Parcelable> container) {
10422        dispatchRestoreInstanceState(container);
10423    }
10424
10425    /**
10426     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
10427     * state for this view and its children. May be overridden to modify how restoring
10428     * happens to a view's children; for example, some views may want to not store state
10429     * for their children.
10430     *
10431     * @param container The SparseArray which holds previously saved state.
10432     *
10433     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10434     * @see #restoreHierarchyState(android.util.SparseArray)
10435     * @see #onRestoreInstanceState(android.os.Parcelable)
10436     */
10437    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
10438        if (mID != NO_ID) {
10439            Parcelable state = container.get(mID);
10440            if (state != null) {
10441                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
10442                // + ": " + state);
10443                mPrivateFlags &= ~SAVE_STATE_CALLED;
10444                onRestoreInstanceState(state);
10445                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10446                    throw new IllegalStateException(
10447                            "Derived class did not call super.onRestoreInstanceState()");
10448                }
10449            }
10450        }
10451    }
10452
10453    /**
10454     * Hook allowing a view to re-apply a representation of its internal state that had previously
10455     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
10456     * null state.
10457     *
10458     * @param state The frozen state that had previously been returned by
10459     *        {@link #onSaveInstanceState}.
10460     *
10461     * @see #onSaveInstanceState()
10462     * @see #restoreHierarchyState(android.util.SparseArray)
10463     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10464     */
10465    protected void onRestoreInstanceState(Parcelable state) {
10466        mPrivateFlags |= SAVE_STATE_CALLED;
10467        if (state != BaseSavedState.EMPTY_STATE && state != null) {
10468            throw new IllegalArgumentException("Wrong state class, expecting View State but "
10469                    + "received " + state.getClass().toString() + " instead. This usually happens "
10470                    + "when two views of different type have the same id in the same hierarchy. "
10471                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
10472                    + "other views do not use the same id.");
10473        }
10474    }
10475
10476    /**
10477     * <p>Return the time at which the drawing of the view hierarchy started.</p>
10478     *
10479     * @return the drawing start time in milliseconds
10480     */
10481    public long getDrawingTime() {
10482        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
10483    }
10484
10485    /**
10486     * <p>Enables or disables the duplication of the parent's state into this view. When
10487     * duplication is enabled, this view gets its drawable state from its parent rather
10488     * than from its own internal properties.</p>
10489     *
10490     * <p>Note: in the current implementation, setting this property to true after the
10491     * view was added to a ViewGroup might have no effect at all. This property should
10492     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
10493     *
10494     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
10495     * property is enabled, an exception will be thrown.</p>
10496     *
10497     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
10498     * parent, these states should not be affected by this method.</p>
10499     *
10500     * @param enabled True to enable duplication of the parent's drawable state, false
10501     *                to disable it.
10502     *
10503     * @see #getDrawableState()
10504     * @see #isDuplicateParentStateEnabled()
10505     */
10506    public void setDuplicateParentStateEnabled(boolean enabled) {
10507        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
10508    }
10509
10510    /**
10511     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
10512     *
10513     * @return True if this view's drawable state is duplicated from the parent,
10514     *         false otherwise
10515     *
10516     * @see #getDrawableState()
10517     * @see #setDuplicateParentStateEnabled(boolean)
10518     */
10519    public boolean isDuplicateParentStateEnabled() {
10520        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10521    }
10522
10523    /**
10524     * <p>Specifies the type of layer backing this view. The layer can be
10525     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10526     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10527     *
10528     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10529     * instance that controls how the layer is composed on screen. The following
10530     * properties of the paint are taken into account when composing the layer:</p>
10531     * <ul>
10532     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10533     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10534     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10535     * </ul>
10536     *
10537     * <p>If this view has an alpha value set to < 1.0 by calling
10538     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10539     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10540     * equivalent to setting a hardware layer on this view and providing a paint with
10541     * the desired alpha value.<p>
10542     *
10543     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10544     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10545     * for more information on when and how to use layers.</p>
10546     *
10547     * @param layerType The ype of layer to use with this view, must be one of
10548     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10549     *        {@link #LAYER_TYPE_HARDWARE}
10550     * @param paint The paint used to compose the layer. This argument is optional
10551     *        and can be null. It is ignored when the layer type is
10552     *        {@link #LAYER_TYPE_NONE}
10553     *
10554     * @see #getLayerType()
10555     * @see #LAYER_TYPE_NONE
10556     * @see #LAYER_TYPE_SOFTWARE
10557     * @see #LAYER_TYPE_HARDWARE
10558     * @see #setAlpha(float)
10559     *
10560     * @attr ref android.R.styleable#View_layerType
10561     */
10562    public void setLayerType(int layerType, Paint paint) {
10563        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10564            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10565                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10566        }
10567
10568        if (layerType == mLayerType) {
10569            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10570                mLayerPaint = paint == null ? new Paint() : paint;
10571                invalidateParentCaches();
10572                invalidate(true);
10573            }
10574            return;
10575        }
10576
10577        // Destroy any previous software drawing cache if needed
10578        switch (mLayerType) {
10579            case LAYER_TYPE_HARDWARE:
10580                destroyLayer(false);
10581                // fall through - non-accelerated views may use software layer mechanism instead
10582            case LAYER_TYPE_SOFTWARE:
10583                destroyDrawingCache();
10584                break;
10585            default:
10586                break;
10587        }
10588
10589        mLayerType = layerType;
10590        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10591        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10592        mLocalDirtyRect = layerDisabled ? null : new Rect();
10593
10594        invalidateParentCaches();
10595        invalidate(true);
10596    }
10597
10598    /**
10599     * Indicates whether this view has a static layer. A view with layer type
10600     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10601     * dynamic.
10602     */
10603    boolean hasStaticLayer() {
10604        return true;
10605    }
10606
10607    /**
10608     * Indicates what type of layer is currently associated with this view. By default
10609     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10610     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10611     * for more information on the different types of layers.
10612     *
10613     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10614     *         {@link #LAYER_TYPE_HARDWARE}
10615     *
10616     * @see #setLayerType(int, android.graphics.Paint)
10617     * @see #buildLayer()
10618     * @see #LAYER_TYPE_NONE
10619     * @see #LAYER_TYPE_SOFTWARE
10620     * @see #LAYER_TYPE_HARDWARE
10621     */
10622    public int getLayerType() {
10623        return mLayerType;
10624    }
10625
10626    /**
10627     * Forces this view's layer to be created and this view to be rendered
10628     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10629     * invoking this method will have no effect.
10630     *
10631     * This method can for instance be used to render a view into its layer before
10632     * starting an animation. If this view is complex, rendering into the layer
10633     * before starting the animation will avoid skipping frames.
10634     *
10635     * @throws IllegalStateException If this view is not attached to a window
10636     *
10637     * @see #setLayerType(int, android.graphics.Paint)
10638     */
10639    public void buildLayer() {
10640        if (mLayerType == LAYER_TYPE_NONE) return;
10641
10642        if (mAttachInfo == null) {
10643            throw new IllegalStateException("This view must be attached to a window first");
10644        }
10645
10646        switch (mLayerType) {
10647            case LAYER_TYPE_HARDWARE:
10648                if (mAttachInfo.mHardwareRenderer != null &&
10649                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10650                        mAttachInfo.mHardwareRenderer.validate()) {
10651                    getHardwareLayer();
10652                }
10653                break;
10654            case LAYER_TYPE_SOFTWARE:
10655                buildDrawingCache(true);
10656                break;
10657        }
10658    }
10659
10660    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10661    void flushLayer() {
10662        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10663            mHardwareLayer.flush();
10664        }
10665    }
10666
10667    /**
10668     * <p>Returns a hardware layer that can be used to draw this view again
10669     * without executing its draw method.</p>
10670     *
10671     * @return A HardwareLayer ready to render, or null if an error occurred.
10672     */
10673    HardwareLayer getHardwareLayer() {
10674        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10675                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10676            return null;
10677        }
10678
10679        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10680
10681        final int width = mRight - mLeft;
10682        final int height = mBottom - mTop;
10683
10684        if (width == 0 || height == 0) {
10685            return null;
10686        }
10687
10688        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10689            if (mHardwareLayer == null) {
10690                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10691                        width, height, isOpaque());
10692                mLocalDirtyRect.set(0, 0, width, height);
10693            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10694                mHardwareLayer.resize(width, height);
10695                mLocalDirtyRect.set(0, 0, width, height);
10696            }
10697
10698            // The layer is not valid if the underlying GPU resources cannot be allocated
10699            if (!mHardwareLayer.isValid()) {
10700                return null;
10701            }
10702
10703            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
10704            mLocalDirtyRect.setEmpty();
10705        }
10706
10707        return mHardwareLayer;
10708    }
10709
10710    /**
10711     * Destroys this View's hardware layer if possible.
10712     *
10713     * @return True if the layer was destroyed, false otherwise.
10714     *
10715     * @see #setLayerType(int, android.graphics.Paint)
10716     * @see #LAYER_TYPE_HARDWARE
10717     */
10718    boolean destroyLayer(boolean valid) {
10719        if (mHardwareLayer != null) {
10720            AttachInfo info = mAttachInfo;
10721            if (info != null && info.mHardwareRenderer != null &&
10722                    info.mHardwareRenderer.isEnabled() &&
10723                    (valid || info.mHardwareRenderer.validate())) {
10724                mHardwareLayer.destroy();
10725                mHardwareLayer = null;
10726
10727                invalidate(true);
10728                invalidateParentCaches();
10729            }
10730            return true;
10731        }
10732        return false;
10733    }
10734
10735    /**
10736     * Destroys all hardware rendering resources. This method is invoked
10737     * when the system needs to reclaim resources. Upon execution of this
10738     * method, you should free any OpenGL resources created by the view.
10739     *
10740     * Note: you <strong>must</strong> call
10741     * <code>super.destroyHardwareResources()</code> when overriding
10742     * this method.
10743     *
10744     * @hide
10745     */
10746    protected void destroyHardwareResources() {
10747        destroyLayer(true);
10748    }
10749
10750    /**
10751     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10752     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10753     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10754     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10755     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10756     * null.</p>
10757     *
10758     * <p>Enabling the drawing cache is similar to
10759     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10760     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10761     * drawing cache has no effect on rendering because the system uses a different mechanism
10762     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10763     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10764     * for information on how to enable software and hardware layers.</p>
10765     *
10766     * <p>This API can be used to manually generate
10767     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10768     * {@link #getDrawingCache()}.</p>
10769     *
10770     * @param enabled true to enable the drawing cache, false otherwise
10771     *
10772     * @see #isDrawingCacheEnabled()
10773     * @see #getDrawingCache()
10774     * @see #buildDrawingCache()
10775     * @see #setLayerType(int, android.graphics.Paint)
10776     */
10777    public void setDrawingCacheEnabled(boolean enabled) {
10778        mCachingFailed = false;
10779        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10780    }
10781
10782    /**
10783     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10784     *
10785     * @return true if the drawing cache is enabled
10786     *
10787     * @see #setDrawingCacheEnabled(boolean)
10788     * @see #getDrawingCache()
10789     */
10790    @ViewDebug.ExportedProperty(category = "drawing")
10791    public boolean isDrawingCacheEnabled() {
10792        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10793    }
10794
10795    /**
10796     * Debugging utility which recursively outputs the dirty state of a view and its
10797     * descendants.
10798     *
10799     * @hide
10800     */
10801    @SuppressWarnings({"UnusedDeclaration"})
10802    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10803        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10804                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10805                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10806                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10807        if (clear) {
10808            mPrivateFlags &= clearMask;
10809        }
10810        if (this instanceof ViewGroup) {
10811            ViewGroup parent = (ViewGroup) this;
10812            final int count = parent.getChildCount();
10813            for (int i = 0; i < count; i++) {
10814                final View child = parent.getChildAt(i);
10815                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10816            }
10817        }
10818    }
10819
10820    /**
10821     * This method is used by ViewGroup to cause its children to restore or recreate their
10822     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10823     * to recreate its own display list, which would happen if it went through the normal
10824     * draw/dispatchDraw mechanisms.
10825     *
10826     * @hide
10827     */
10828    protected void dispatchGetDisplayList() {}
10829
10830    /**
10831     * A view that is not attached or hardware accelerated cannot create a display list.
10832     * This method checks these conditions and returns the appropriate result.
10833     *
10834     * @return true if view has the ability to create a display list, false otherwise.
10835     *
10836     * @hide
10837     */
10838    public boolean canHaveDisplayList() {
10839        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10840    }
10841
10842    /**
10843     * @return The HardwareRenderer associated with that view or null if hardware rendering
10844     * is not supported or this this has not been attached to a window.
10845     *
10846     * @hide
10847     */
10848    public HardwareRenderer getHardwareRenderer() {
10849        if (mAttachInfo != null) {
10850            return mAttachInfo.mHardwareRenderer;
10851        }
10852        return null;
10853    }
10854
10855    /**
10856     * Returns a DisplayList. If the incoming displayList is null, one will be created.
10857     * Otherwise, the same display list will be returned (after having been rendered into
10858     * along the way, depending on the invalidation state of the view).
10859     *
10860     * @param displayList The previous version of this displayList, could be null.
10861     * @param isLayer Whether the requester of the display list is a layer. If so,
10862     * the view will avoid creating a layer inside the resulting display list.
10863     * @return A new or reused DisplayList object.
10864     */
10865    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
10866        if (!canHaveDisplayList()) {
10867            return null;
10868        }
10869
10870        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10871                displayList == null || !displayList.isValid() ||
10872                (!isLayer && mRecreateDisplayList))) {
10873            // Don't need to recreate the display list, just need to tell our
10874            // children to restore/recreate theirs
10875            if (displayList != null && displayList.isValid() &&
10876                    !isLayer && !mRecreateDisplayList) {
10877                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10878                mPrivateFlags &= ~DIRTY_MASK;
10879                dispatchGetDisplayList();
10880
10881                return displayList;
10882            }
10883
10884            if (!isLayer) {
10885                // If we got here, we're recreating it. Mark it as such to ensure that
10886                // we copy in child display lists into ours in drawChild()
10887                mRecreateDisplayList = true;
10888            }
10889            if (displayList == null) {
10890                final String name = getClass().getSimpleName();
10891                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10892                // If we're creating a new display list, make sure our parent gets invalidated
10893                // since they will need to recreate their display list to account for this
10894                // new child display list.
10895                invalidateParentCaches();
10896            }
10897
10898            boolean caching = false;
10899            final HardwareCanvas canvas = displayList.start();
10900            int restoreCount = 0;
10901            int width = mRight - mLeft;
10902            int height = mBottom - mTop;
10903
10904            try {
10905                canvas.setViewport(width, height);
10906                // The dirty rect should always be null for a display list
10907                canvas.onPreDraw(null);
10908                int layerType = (
10909                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
10910                        getLayerType() : LAYER_TYPE_NONE;
10911                if (!isLayer && layerType != LAYER_TYPE_NONE && USE_DISPLAY_LIST_PROPERTIES) {
10912                    if (layerType == LAYER_TYPE_HARDWARE) {
10913                        final HardwareLayer layer = getHardwareLayer();
10914                        if (layer != null && layer.isValid()) {
10915                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
10916                        } else {
10917                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
10918                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
10919                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
10920                        }
10921                        caching = true;
10922                    } else {
10923                        buildDrawingCache(true);
10924                        Bitmap cache = getDrawingCache(true);
10925                        if (cache != null) {
10926                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
10927                            caching = true;
10928                        }
10929                    }
10930                } else {
10931
10932                    computeScroll();
10933
10934                    if (!USE_DISPLAY_LIST_PROPERTIES) {
10935                        restoreCount = canvas.save();
10936                    }
10937                    canvas.translate(-mScrollX, -mScrollY);
10938                    if (!isLayer) {
10939                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10940                        mPrivateFlags &= ~DIRTY_MASK;
10941                    }
10942
10943                    // Fast path for layouts with no backgrounds
10944                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10945                        dispatchDraw(canvas);
10946                    } else {
10947                        draw(canvas);
10948                    }
10949                }
10950            } finally {
10951                if (USE_DISPLAY_LIST_PROPERTIES) {
10952                    canvas.restoreToCount(restoreCount);
10953                }
10954                canvas.onPostDraw();
10955
10956                displayList.end();
10957                if (USE_DISPLAY_LIST_PROPERTIES) {
10958                    displayList.setCaching(caching);
10959                }
10960                if (isLayer && USE_DISPLAY_LIST_PROPERTIES) {
10961                    displayList.setLeftTopRightBottom(0, 0, width, height);
10962                } else {
10963                    setDisplayListProperties(displayList);
10964                }
10965            }
10966        } else if (!isLayer) {
10967            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10968            mPrivateFlags &= ~DIRTY_MASK;
10969        }
10970
10971        return displayList;
10972    }
10973
10974    /**
10975     * Get the DisplayList for the HardwareLayer
10976     *
10977     * @param layer The HardwareLayer whose DisplayList we want
10978     * @return A DisplayList fopr the specified HardwareLayer
10979     */
10980    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
10981        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
10982        layer.setDisplayList(displayList);
10983        return displayList;
10984    }
10985
10986
10987    /**
10988     * <p>Returns a display list that can be used to draw this view again
10989     * without executing its draw method.</p>
10990     *
10991     * @return A DisplayList ready to replay, or null if caching is not enabled.
10992     *
10993     * @hide
10994     */
10995    public DisplayList getDisplayList() {
10996        mDisplayList = getDisplayList(mDisplayList, false);
10997        return mDisplayList;
10998    }
10999
11000    /**
11001     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11002     *
11003     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11004     *
11005     * @see #getDrawingCache(boolean)
11006     */
11007    public Bitmap getDrawingCache() {
11008        return getDrawingCache(false);
11009    }
11010
11011    /**
11012     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11013     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11014     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11015     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11016     * request the drawing cache by calling this method and draw it on screen if the
11017     * returned bitmap is not null.</p>
11018     *
11019     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11020     * this method will create a bitmap of the same size as this view. Because this bitmap
11021     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11022     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11023     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11024     * size than the view. This implies that your application must be able to handle this
11025     * size.</p>
11026     *
11027     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11028     *        the current density of the screen when the application is in compatibility
11029     *        mode.
11030     *
11031     * @return A bitmap representing this view or null if cache is disabled.
11032     *
11033     * @see #setDrawingCacheEnabled(boolean)
11034     * @see #isDrawingCacheEnabled()
11035     * @see #buildDrawingCache(boolean)
11036     * @see #destroyDrawingCache()
11037     */
11038    public Bitmap getDrawingCache(boolean autoScale) {
11039        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11040            return null;
11041        }
11042        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11043            buildDrawingCache(autoScale);
11044        }
11045        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11046    }
11047
11048    /**
11049     * <p>Frees the resources used by the drawing cache. If you call
11050     * {@link #buildDrawingCache()} manually without calling
11051     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11052     * should cleanup the cache with this method afterwards.</p>
11053     *
11054     * @see #setDrawingCacheEnabled(boolean)
11055     * @see #buildDrawingCache()
11056     * @see #getDrawingCache()
11057     */
11058    public void destroyDrawingCache() {
11059        if (mDrawingCache != null) {
11060            mDrawingCache.recycle();
11061            mDrawingCache = null;
11062        }
11063        if (mUnscaledDrawingCache != null) {
11064            mUnscaledDrawingCache.recycle();
11065            mUnscaledDrawingCache = null;
11066        }
11067    }
11068
11069    /**
11070     * Setting a solid background color for the drawing cache's bitmaps will improve
11071     * performance and memory usage. Note, though that this should only be used if this
11072     * view will always be drawn on top of a solid color.
11073     *
11074     * @param color The background color to use for the drawing cache's bitmap
11075     *
11076     * @see #setDrawingCacheEnabled(boolean)
11077     * @see #buildDrawingCache()
11078     * @see #getDrawingCache()
11079     */
11080    public void setDrawingCacheBackgroundColor(int color) {
11081        if (color != mDrawingCacheBackgroundColor) {
11082            mDrawingCacheBackgroundColor = color;
11083            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11084        }
11085    }
11086
11087    /**
11088     * @see #setDrawingCacheBackgroundColor(int)
11089     *
11090     * @return The background color to used for the drawing cache's bitmap
11091     */
11092    public int getDrawingCacheBackgroundColor() {
11093        return mDrawingCacheBackgroundColor;
11094    }
11095
11096    /**
11097     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11098     *
11099     * @see #buildDrawingCache(boolean)
11100     */
11101    public void buildDrawingCache() {
11102        buildDrawingCache(false);
11103    }
11104
11105    /**
11106     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
11107     *
11108     * <p>If you call {@link #buildDrawingCache()} manually without calling
11109     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11110     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
11111     *
11112     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11113     * this method will create a bitmap of the same size as this view. Because this bitmap
11114     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11115     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11116     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11117     * size than the view. This implies that your application must be able to handle this
11118     * size.</p>
11119     *
11120     * <p>You should avoid calling this method when hardware acceleration is enabled. If
11121     * you do not need the drawing cache bitmap, calling this method will increase memory
11122     * usage and cause the view to be rendered in software once, thus negatively impacting
11123     * performance.</p>
11124     *
11125     * @see #getDrawingCache()
11126     * @see #destroyDrawingCache()
11127     */
11128    public void buildDrawingCache(boolean autoScale) {
11129        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
11130                mDrawingCache == null : mUnscaledDrawingCache == null)) {
11131            mCachingFailed = false;
11132
11133            if (ViewDebug.TRACE_HIERARCHY) {
11134                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
11135            }
11136
11137            int width = mRight - mLeft;
11138            int height = mBottom - mTop;
11139
11140            final AttachInfo attachInfo = mAttachInfo;
11141            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
11142
11143            if (autoScale && scalingRequired) {
11144                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
11145                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
11146            }
11147
11148            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
11149            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
11150            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
11151
11152            if (width <= 0 || height <= 0 ||
11153                     // Projected bitmap size in bytes
11154                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
11155                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
11156                destroyDrawingCache();
11157                mCachingFailed = true;
11158                return;
11159            }
11160
11161            boolean clear = true;
11162            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
11163
11164            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
11165                Bitmap.Config quality;
11166                if (!opaque) {
11167                    // Never pick ARGB_4444 because it looks awful
11168                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
11169                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
11170                        case DRAWING_CACHE_QUALITY_AUTO:
11171                            quality = Bitmap.Config.ARGB_8888;
11172                            break;
11173                        case DRAWING_CACHE_QUALITY_LOW:
11174                            quality = Bitmap.Config.ARGB_8888;
11175                            break;
11176                        case DRAWING_CACHE_QUALITY_HIGH:
11177                            quality = Bitmap.Config.ARGB_8888;
11178                            break;
11179                        default:
11180                            quality = Bitmap.Config.ARGB_8888;
11181                            break;
11182                    }
11183                } else {
11184                    // Optimization for translucent windows
11185                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
11186                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
11187                }
11188
11189                // Try to cleanup memory
11190                if (bitmap != null) bitmap.recycle();
11191
11192                try {
11193                    bitmap = Bitmap.createBitmap(width, height, quality);
11194                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
11195                    if (autoScale) {
11196                        mDrawingCache = bitmap;
11197                    } else {
11198                        mUnscaledDrawingCache = bitmap;
11199                    }
11200                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
11201                } catch (OutOfMemoryError e) {
11202                    // If there is not enough memory to create the bitmap cache, just
11203                    // ignore the issue as bitmap caches are not required to draw the
11204                    // view hierarchy
11205                    if (autoScale) {
11206                        mDrawingCache = null;
11207                    } else {
11208                        mUnscaledDrawingCache = null;
11209                    }
11210                    mCachingFailed = true;
11211                    return;
11212                }
11213
11214                clear = drawingCacheBackgroundColor != 0;
11215            }
11216
11217            Canvas canvas;
11218            if (attachInfo != null) {
11219                canvas = attachInfo.mCanvas;
11220                if (canvas == null) {
11221                    canvas = new Canvas();
11222                }
11223                canvas.setBitmap(bitmap);
11224                // Temporarily clobber the cached Canvas in case one of our children
11225                // is also using a drawing cache. Without this, the children would
11226                // steal the canvas by attaching their own bitmap to it and bad, bad
11227                // thing would happen (invisible views, corrupted drawings, etc.)
11228                attachInfo.mCanvas = null;
11229            } else {
11230                // This case should hopefully never or seldom happen
11231                canvas = new Canvas(bitmap);
11232            }
11233
11234            if (clear) {
11235                bitmap.eraseColor(drawingCacheBackgroundColor);
11236            }
11237
11238            computeScroll();
11239            final int restoreCount = canvas.save();
11240
11241            if (autoScale && scalingRequired) {
11242                final float scale = attachInfo.mApplicationScale;
11243                canvas.scale(scale, scale);
11244            }
11245
11246            canvas.translate(-mScrollX, -mScrollY);
11247
11248            mPrivateFlags |= DRAWN;
11249            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
11250                    mLayerType != LAYER_TYPE_NONE) {
11251                mPrivateFlags |= DRAWING_CACHE_VALID;
11252            }
11253
11254            // Fast path for layouts with no backgrounds
11255            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11256                if (ViewDebug.TRACE_HIERARCHY) {
11257                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11258                }
11259                mPrivateFlags &= ~DIRTY_MASK;
11260                dispatchDraw(canvas);
11261            } else {
11262                draw(canvas);
11263            }
11264
11265            canvas.restoreToCount(restoreCount);
11266            canvas.setBitmap(null);
11267
11268            if (attachInfo != null) {
11269                // Restore the cached Canvas for our siblings
11270                attachInfo.mCanvas = canvas;
11271            }
11272        }
11273    }
11274
11275    /**
11276     * Create a snapshot of the view into a bitmap.  We should probably make
11277     * some form of this public, but should think about the API.
11278     */
11279    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
11280        int width = mRight - mLeft;
11281        int height = mBottom - mTop;
11282
11283        final AttachInfo attachInfo = mAttachInfo;
11284        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
11285        width = (int) ((width * scale) + 0.5f);
11286        height = (int) ((height * scale) + 0.5f);
11287
11288        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
11289        if (bitmap == null) {
11290            throw new OutOfMemoryError();
11291        }
11292
11293        Resources resources = getResources();
11294        if (resources != null) {
11295            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
11296        }
11297
11298        Canvas canvas;
11299        if (attachInfo != null) {
11300            canvas = attachInfo.mCanvas;
11301            if (canvas == null) {
11302                canvas = new Canvas();
11303            }
11304            canvas.setBitmap(bitmap);
11305            // Temporarily clobber the cached Canvas in case one of our children
11306            // is also using a drawing cache. Without this, the children would
11307            // steal the canvas by attaching their own bitmap to it and bad, bad
11308            // things would happen (invisible views, corrupted drawings, etc.)
11309            attachInfo.mCanvas = null;
11310        } else {
11311            // This case should hopefully never or seldom happen
11312            canvas = new Canvas(bitmap);
11313        }
11314
11315        if ((backgroundColor & 0xff000000) != 0) {
11316            bitmap.eraseColor(backgroundColor);
11317        }
11318
11319        computeScroll();
11320        final int restoreCount = canvas.save();
11321        canvas.scale(scale, scale);
11322        canvas.translate(-mScrollX, -mScrollY);
11323
11324        // Temporarily remove the dirty mask
11325        int flags = mPrivateFlags;
11326        mPrivateFlags &= ~DIRTY_MASK;
11327
11328        // Fast path for layouts with no backgrounds
11329        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11330            dispatchDraw(canvas);
11331        } else {
11332            draw(canvas);
11333        }
11334
11335        mPrivateFlags = flags;
11336
11337        canvas.restoreToCount(restoreCount);
11338        canvas.setBitmap(null);
11339
11340        if (attachInfo != null) {
11341            // Restore the cached Canvas for our siblings
11342            attachInfo.mCanvas = canvas;
11343        }
11344
11345        return bitmap;
11346    }
11347
11348    /**
11349     * Indicates whether this View is currently in edit mode. A View is usually
11350     * in edit mode when displayed within a developer tool. For instance, if
11351     * this View is being drawn by a visual user interface builder, this method
11352     * should return true.
11353     *
11354     * Subclasses should check the return value of this method to provide
11355     * different behaviors if their normal behavior might interfere with the
11356     * host environment. For instance: the class spawns a thread in its
11357     * constructor, the drawing code relies on device-specific features, etc.
11358     *
11359     * This method is usually checked in the drawing code of custom widgets.
11360     *
11361     * @return True if this View is in edit mode, false otherwise.
11362     */
11363    public boolean isInEditMode() {
11364        return false;
11365    }
11366
11367    /**
11368     * If the View draws content inside its padding and enables fading edges,
11369     * it needs to support padding offsets. Padding offsets are added to the
11370     * fading edges to extend the length of the fade so that it covers pixels
11371     * drawn inside the padding.
11372     *
11373     * Subclasses of this class should override this method if they need
11374     * to draw content inside the padding.
11375     *
11376     * @return True if padding offset must be applied, false otherwise.
11377     *
11378     * @see #getLeftPaddingOffset()
11379     * @see #getRightPaddingOffset()
11380     * @see #getTopPaddingOffset()
11381     * @see #getBottomPaddingOffset()
11382     *
11383     * @since CURRENT
11384     */
11385    protected boolean isPaddingOffsetRequired() {
11386        return false;
11387    }
11388
11389    /**
11390     * Amount by which to extend the left fading region. Called only when
11391     * {@link #isPaddingOffsetRequired()} returns true.
11392     *
11393     * @return The left padding offset in pixels.
11394     *
11395     * @see #isPaddingOffsetRequired()
11396     *
11397     * @since CURRENT
11398     */
11399    protected int getLeftPaddingOffset() {
11400        return 0;
11401    }
11402
11403    /**
11404     * Amount by which to extend the right fading region. Called only when
11405     * {@link #isPaddingOffsetRequired()} returns true.
11406     *
11407     * @return The right padding offset in pixels.
11408     *
11409     * @see #isPaddingOffsetRequired()
11410     *
11411     * @since CURRENT
11412     */
11413    protected int getRightPaddingOffset() {
11414        return 0;
11415    }
11416
11417    /**
11418     * Amount by which to extend the top fading region. Called only when
11419     * {@link #isPaddingOffsetRequired()} returns true.
11420     *
11421     * @return The top padding offset in pixels.
11422     *
11423     * @see #isPaddingOffsetRequired()
11424     *
11425     * @since CURRENT
11426     */
11427    protected int getTopPaddingOffset() {
11428        return 0;
11429    }
11430
11431    /**
11432     * Amount by which to extend the bottom fading region. Called only when
11433     * {@link #isPaddingOffsetRequired()} returns true.
11434     *
11435     * @return The bottom padding offset in pixels.
11436     *
11437     * @see #isPaddingOffsetRequired()
11438     *
11439     * @since CURRENT
11440     */
11441    protected int getBottomPaddingOffset() {
11442        return 0;
11443    }
11444
11445    /**
11446     * @hide
11447     * @param offsetRequired
11448     */
11449    protected int getFadeTop(boolean offsetRequired) {
11450        int top = mPaddingTop;
11451        if (offsetRequired) top += getTopPaddingOffset();
11452        return top;
11453    }
11454
11455    /**
11456     * @hide
11457     * @param offsetRequired
11458     */
11459    protected int getFadeHeight(boolean offsetRequired) {
11460        int padding = mPaddingTop;
11461        if (offsetRequired) padding += getTopPaddingOffset();
11462        return mBottom - mTop - mPaddingBottom - padding;
11463    }
11464
11465    /**
11466     * <p>Indicates whether this view is attached to a hardware accelerated
11467     * window or not.</p>
11468     *
11469     * <p>Even if this method returns true, it does not mean that every call
11470     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
11471     * accelerated {@link android.graphics.Canvas}. For instance, if this view
11472     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
11473     * window is hardware accelerated,
11474     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
11475     * return false, and this method will return true.</p>
11476     *
11477     * @return True if the view is attached to a window and the window is
11478     *         hardware accelerated; false in any other case.
11479     */
11480    public boolean isHardwareAccelerated() {
11481        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
11482    }
11483
11484    /**
11485     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
11486     * case of an active Animation being run on the view.
11487     */
11488    private boolean drawAnimation(ViewGroup parent, long drawingTime,
11489            Animation a, boolean scalingRequired) {
11490        Transformation invalidationTransform;
11491        final int flags = parent.mGroupFlags;
11492        final boolean initialized = a.isInitialized();
11493        if (!initialized) {
11494            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
11495            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
11496            onAnimationStart();
11497        }
11498
11499        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
11500        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
11501            if (parent.mInvalidationTransformation == null) {
11502                parent.mInvalidationTransformation = new Transformation();
11503            }
11504            invalidationTransform = parent.mInvalidationTransformation;
11505            a.getTransformation(drawingTime, invalidationTransform, 1f);
11506        } else {
11507            invalidationTransform = parent.mChildTransformation;
11508        }
11509        if (more) {
11510            if (!a.willChangeBounds()) {
11511                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
11512                        parent.FLAG_OPTIMIZE_INVALIDATE) {
11513                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
11514                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
11515                    // The child need to draw an animation, potentially offscreen, so
11516                    // make sure we do not cancel invalidate requests
11517                    parent.mPrivateFlags |= DRAW_ANIMATION;
11518                    parent.invalidate(mLeft, mTop, mRight, mBottom);
11519                }
11520            } else {
11521                if (parent.mInvalidateRegion == null) {
11522                    parent.mInvalidateRegion = new RectF();
11523                }
11524                final RectF region = parent.mInvalidateRegion;
11525                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
11526                        invalidationTransform);
11527
11528                // The child need to draw an animation, potentially offscreen, so
11529                // make sure we do not cancel invalidate requests
11530                parent.mPrivateFlags |= DRAW_ANIMATION;
11531
11532                final int left = mLeft + (int) region.left;
11533                final int top = mTop + (int) region.top;
11534                parent.invalidate(left, top, left + (int) (region.width() + .5f),
11535                        top + (int) (region.height() + .5f));
11536            }
11537        }
11538        return more;
11539    }
11540
11541    void setDisplayListProperties() {
11542        setDisplayListProperties(mDisplayList);
11543    }
11544
11545    /**
11546     * This method is called by getDisplayList() when a display list is created or re-rendered.
11547     * It sets or resets the current value of all properties on that display list (resetting is
11548     * necessary when a display list is being re-created, because we need to make sure that
11549     * previously-set transform values
11550     */
11551    void setDisplayListProperties(DisplayList displayList) {
11552        if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) {
11553            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
11554            displayList.setHasOverlappingRendering(hasOverlappingRendering());
11555            if (mParent instanceof ViewGroup) {
11556                displayList.setClipChildren(
11557                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
11558            }
11559            float alpha = 1;
11560            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
11561                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
11562                ViewGroup parentVG = (ViewGroup) mParent;
11563                final boolean hasTransform =
11564                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
11565                if (hasTransform) {
11566                    Transformation transform = parentVG.mChildTransformation;
11567                    final int transformType = parentVG.mChildTransformation.getTransformationType();
11568                    if (transformType != Transformation.TYPE_IDENTITY) {
11569                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
11570                            alpha = transform.getAlpha();
11571                        }
11572                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
11573                            displayList.setStaticMatrix(transform.getMatrix());
11574                        }
11575                    }
11576                }
11577            }
11578            if (mTransformationInfo != null) {
11579                alpha *= mTransformationInfo.mAlpha;
11580                if (alpha < 1) {
11581                    final int multipliedAlpha = (int) (255 * alpha);
11582                    if (onSetAlpha(multipliedAlpha)) {
11583                        alpha = 1;
11584                    }
11585                }
11586                displayList.setTransformationInfo(alpha,
11587                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
11588                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
11589                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
11590                        mTransformationInfo.mScaleY);
11591                if (mTransformationInfo.mCamera == null) {
11592                    mTransformationInfo.mCamera = new Camera();
11593                    mTransformationInfo.matrix3D = new Matrix();
11594                }
11595                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
11596                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
11597                    displayList.setPivotX(getPivotX());
11598                    displayList.setPivotY(getPivotY());
11599                }
11600            } else if (alpha < 1) {
11601                displayList.setAlpha(alpha);
11602            }
11603        }
11604    }
11605
11606    /**
11607     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
11608     * This draw() method is an implementation detail and is not intended to be overridden or
11609     * to be called from anywhere else other than ViewGroup.drawChild().
11610     */
11611    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
11612        boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null &&
11613                mAttachInfo.mHardwareAccelerated;
11614        boolean more = false;
11615        final boolean childHasIdentityMatrix = hasIdentityMatrix();
11616        final int flags = parent.mGroupFlags;
11617
11618        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
11619            parent.mChildTransformation.clear();
11620            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11621        }
11622
11623        Transformation transformToApply = null;
11624        boolean concatMatrix = false;
11625
11626        boolean scalingRequired = false;
11627        boolean caching;
11628        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11629
11630        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11631        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
11632                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
11633            caching = true;
11634            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
11635            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11636        } else {
11637            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11638        }
11639
11640        final Animation a = getAnimation();
11641        if (a != null) {
11642            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11643            concatMatrix = a.willChangeTransformationMatrix();
11644            transformToApply = parent.mChildTransformation;
11645        } else if (!useDisplayListProperties &&
11646                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
11647            final boolean hasTransform =
11648                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11649            if (hasTransform) {
11650                final int transformType = parent.mChildTransformation.getTransformationType();
11651                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11652                        parent.mChildTransformation : null;
11653                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11654            }
11655        }
11656
11657        concatMatrix |= !childHasIdentityMatrix;
11658
11659        // Sets the flag as early as possible to allow draw() implementations
11660        // to call invalidate() successfully when doing animations
11661        mPrivateFlags |= DRAWN;
11662
11663        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11664                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11665            return more;
11666        }
11667
11668        if (hardwareAccelerated) {
11669            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11670            // retain the flag's value temporarily in the mRecreateDisplayList flag
11671            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11672            mPrivateFlags &= ~INVALIDATED;
11673        }
11674
11675        computeScroll();
11676
11677        final int sx = mScrollX;
11678        final int sy = mScrollY;
11679
11680        DisplayList displayList = null;
11681        Bitmap cache = null;
11682        boolean hasDisplayList = false;
11683        if (caching) {
11684            if (!hardwareAccelerated) {
11685                if (layerType != LAYER_TYPE_NONE) {
11686                    layerType = LAYER_TYPE_SOFTWARE;
11687                    buildDrawingCache(true);
11688                }
11689                cache = getDrawingCache(true);
11690            } else {
11691                switch (layerType) {
11692                    case LAYER_TYPE_SOFTWARE:
11693                        if (useDisplayListProperties) {
11694                            hasDisplayList = canHaveDisplayList();
11695                        } else {
11696                            buildDrawingCache(true);
11697                            cache = getDrawingCache(true);
11698                        }
11699                        break;
11700                    case LAYER_TYPE_HARDWARE:
11701                        if (useDisplayListProperties) {
11702                            hasDisplayList = canHaveDisplayList();
11703                        }
11704                        break;
11705                    case LAYER_TYPE_NONE:
11706                        // Delay getting the display list until animation-driven alpha values are
11707                        // set up and possibly passed on to the view
11708                        hasDisplayList = canHaveDisplayList();
11709                        break;
11710                }
11711            }
11712        }
11713        useDisplayListProperties &= hasDisplayList;
11714        if (useDisplayListProperties) {
11715            displayList = getDisplayList();
11716            if (!displayList.isValid()) {
11717                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11718                // to getDisplayList(), the display list will be marked invalid and we should not
11719                // try to use it again.
11720                displayList = null;
11721                hasDisplayList = false;
11722                useDisplayListProperties = false;
11723            }
11724        }
11725
11726        final boolean hasNoCache = cache == null || hasDisplayList;
11727        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11728                layerType != LAYER_TYPE_HARDWARE;
11729
11730        int restoreTo = -1;
11731        if (!useDisplayListProperties || transformToApply != null) {
11732            restoreTo = canvas.save();
11733        }
11734        if (offsetForScroll) {
11735            canvas.translate(mLeft - sx, mTop - sy);
11736        } else {
11737            if (!useDisplayListProperties) {
11738                canvas.translate(mLeft, mTop);
11739            }
11740            if (scalingRequired) {
11741                if (useDisplayListProperties) {
11742                    // TODO: Might not need this if we put everything inside the DL
11743                    restoreTo = canvas.save();
11744                }
11745                // mAttachInfo cannot be null, otherwise scalingRequired == false
11746                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11747                canvas.scale(scale, scale);
11748            }
11749        }
11750
11751        float alpha = useDisplayListProperties ? 1 : getAlpha();
11752        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
11753            if (transformToApply != null || !childHasIdentityMatrix) {
11754                int transX = 0;
11755                int transY = 0;
11756
11757                if (offsetForScroll) {
11758                    transX = -sx;
11759                    transY = -sy;
11760                }
11761
11762                if (transformToApply != null) {
11763                    if (concatMatrix) {
11764                        if (useDisplayListProperties) {
11765                            displayList.setAnimationMatrix(transformToApply.getMatrix());
11766                        } else {
11767                            // Undo the scroll translation, apply the transformation matrix,
11768                            // then redo the scroll translate to get the correct result.
11769                            canvas.translate(-transX, -transY);
11770                            canvas.concat(transformToApply.getMatrix());
11771                            canvas.translate(transX, transY);
11772                        }
11773                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11774                    }
11775
11776                    float transformAlpha = transformToApply.getAlpha();
11777                    if (transformAlpha < 1) {
11778                        alpha *= transformToApply.getAlpha();
11779                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11780                    }
11781                }
11782
11783                if (!childHasIdentityMatrix && !useDisplayListProperties) {
11784                    canvas.translate(-transX, -transY);
11785                    canvas.concat(getMatrix());
11786                    canvas.translate(transX, transY);
11787                }
11788            }
11789
11790            if (alpha < 1) {
11791                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11792                if (hasNoCache) {
11793                    final int multipliedAlpha = (int) (255 * alpha);
11794                    if (!onSetAlpha(multipliedAlpha)) {
11795                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11796                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
11797                                layerType != LAYER_TYPE_NONE) {
11798                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11799                        }
11800                        if (useDisplayListProperties) {
11801                            displayList.setAlpha(alpha * getAlpha());
11802                        } else  if (layerType == LAYER_TYPE_NONE) {
11803                            final int scrollX = hasDisplayList ? 0 : sx;
11804                            final int scrollY = hasDisplayList ? 0 : sy;
11805                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11806                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11807                        }
11808                    } else {
11809                        // Alpha is handled by the child directly, clobber the layer's alpha
11810                        mPrivateFlags |= ALPHA_SET;
11811                    }
11812                }
11813            }
11814        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11815            onSetAlpha(255);
11816            mPrivateFlags &= ~ALPHA_SET;
11817        }
11818
11819        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
11820                !useDisplayListProperties) {
11821            if (offsetForScroll) {
11822                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11823            } else {
11824                if (!scalingRequired || cache == null) {
11825                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11826                } else {
11827                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11828                }
11829            }
11830        }
11831
11832        if (!useDisplayListProperties && hasDisplayList) {
11833            displayList = getDisplayList();
11834            if (!displayList.isValid()) {
11835                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11836                // to getDisplayList(), the display list will be marked invalid and we should not
11837                // try to use it again.
11838                displayList = null;
11839                hasDisplayList = false;
11840            }
11841        }
11842
11843        if (hasNoCache) {
11844            boolean layerRendered = false;
11845            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
11846                final HardwareLayer layer = getHardwareLayer();
11847                if (layer != null && layer.isValid()) {
11848                    mLayerPaint.setAlpha((int) (alpha * 255));
11849                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11850                    layerRendered = true;
11851                } else {
11852                    final int scrollX = hasDisplayList ? 0 : sx;
11853                    final int scrollY = hasDisplayList ? 0 : sy;
11854                    canvas.saveLayer(scrollX, scrollY,
11855                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11856                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11857                }
11858            }
11859
11860            if (!layerRendered) {
11861                if (!hasDisplayList) {
11862                    // Fast path for layouts with no backgrounds
11863                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11864                        if (ViewDebug.TRACE_HIERARCHY) {
11865                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11866                        }
11867                        mPrivateFlags &= ~DIRTY_MASK;
11868                        dispatchDraw(canvas);
11869                    } else {
11870                        draw(canvas);
11871                    }
11872                } else {
11873                    mPrivateFlags &= ~DIRTY_MASK;
11874                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11875                            mRight - mLeft, mBottom - mTop, null, flags);
11876                }
11877            }
11878        } else if (cache != null) {
11879            mPrivateFlags &= ~DIRTY_MASK;
11880            Paint cachePaint;
11881
11882            if (layerType == LAYER_TYPE_NONE) {
11883                cachePaint = parent.mCachePaint;
11884                if (cachePaint == null) {
11885                    cachePaint = new Paint();
11886                    cachePaint.setDither(false);
11887                    parent.mCachePaint = cachePaint;
11888                }
11889                if (alpha < 1) {
11890                    cachePaint.setAlpha((int) (alpha * 255));
11891                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
11892                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
11893                    cachePaint.setAlpha(255);
11894                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
11895                }
11896            } else {
11897                cachePaint = mLayerPaint;
11898                cachePaint.setAlpha((int) (alpha * 255));
11899            }
11900            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11901        }
11902
11903        if (restoreTo >= 0) {
11904            canvas.restoreToCount(restoreTo);
11905        }
11906
11907        if (a != null && !more) {
11908            if (!hardwareAccelerated && !a.getFillAfter()) {
11909                onSetAlpha(255);
11910            }
11911            parent.finishAnimatingView(this, a);
11912        }
11913
11914        if (more && hardwareAccelerated) {
11915            // invalidation is the trigger to recreate display lists, so if we're using
11916            // display lists to render, force an invalidate to allow the animation to
11917            // continue drawing another frame
11918            parent.invalidate(true);
11919            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11920                // alpha animations should cause the child to recreate its display list
11921                invalidate(true);
11922            }
11923        }
11924
11925        mRecreateDisplayList = false;
11926
11927        return more;
11928    }
11929
11930    /**
11931     * Manually render this view (and all of its children) to the given Canvas.
11932     * The view must have already done a full layout before this function is
11933     * called.  When implementing a view, implement
11934     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11935     * If you do need to override this method, call the superclass version.
11936     *
11937     * @param canvas The Canvas to which the View is rendered.
11938     */
11939    public void draw(Canvas canvas) {
11940        if (ViewDebug.TRACE_HIERARCHY) {
11941            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11942        }
11943
11944        final int privateFlags = mPrivateFlags;
11945        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11946                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11947        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11948
11949        /*
11950         * Draw traversal performs several drawing steps which must be executed
11951         * in the appropriate order:
11952         *
11953         *      1. Draw the background
11954         *      2. If necessary, save the canvas' layers to prepare for fading
11955         *      3. Draw view's content
11956         *      4. Draw children
11957         *      5. If necessary, draw the fading edges and restore layers
11958         *      6. Draw decorations (scrollbars for instance)
11959         */
11960
11961        // Step 1, draw the background, if needed
11962        int saveCount;
11963
11964        if (!dirtyOpaque) {
11965            final Drawable background = mBGDrawable;
11966            if (background != null) {
11967                final int scrollX = mScrollX;
11968                final int scrollY = mScrollY;
11969
11970                if (mBackgroundSizeChanged) {
11971                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11972                    mBackgroundSizeChanged = false;
11973                }
11974
11975                if ((scrollX | scrollY) == 0) {
11976                    background.draw(canvas);
11977                } else {
11978                    canvas.translate(scrollX, scrollY);
11979                    background.draw(canvas);
11980                    canvas.translate(-scrollX, -scrollY);
11981                }
11982            }
11983        }
11984
11985        // skip step 2 & 5 if possible (common case)
11986        final int viewFlags = mViewFlags;
11987        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11988        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11989        if (!verticalEdges && !horizontalEdges) {
11990            // Step 3, draw the content
11991            if (!dirtyOpaque) onDraw(canvas);
11992
11993            // Step 4, draw the children
11994            dispatchDraw(canvas);
11995
11996            // Step 6, draw decorations (scrollbars)
11997            onDrawScrollBars(canvas);
11998
11999            // we're done...
12000            return;
12001        }
12002
12003        /*
12004         * Here we do the full fledged routine...
12005         * (this is an uncommon case where speed matters less,
12006         * this is why we repeat some of the tests that have been
12007         * done above)
12008         */
12009
12010        boolean drawTop = false;
12011        boolean drawBottom = false;
12012        boolean drawLeft = false;
12013        boolean drawRight = false;
12014
12015        float topFadeStrength = 0.0f;
12016        float bottomFadeStrength = 0.0f;
12017        float leftFadeStrength = 0.0f;
12018        float rightFadeStrength = 0.0f;
12019
12020        // Step 2, save the canvas' layers
12021        int paddingLeft = mPaddingLeft;
12022
12023        final boolean offsetRequired = isPaddingOffsetRequired();
12024        if (offsetRequired) {
12025            paddingLeft += getLeftPaddingOffset();
12026        }
12027
12028        int left = mScrollX + paddingLeft;
12029        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12030        int top = mScrollY + getFadeTop(offsetRequired);
12031        int bottom = top + getFadeHeight(offsetRequired);
12032
12033        if (offsetRequired) {
12034            right += getRightPaddingOffset();
12035            bottom += getBottomPaddingOffset();
12036        }
12037
12038        final ScrollabilityCache scrollabilityCache = mScrollCache;
12039        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12040        int length = (int) fadeHeight;
12041
12042        // clip the fade length if top and bottom fades overlap
12043        // overlapping fades produce odd-looking artifacts
12044        if (verticalEdges && (top + length > bottom - length)) {
12045            length = (bottom - top) / 2;
12046        }
12047
12048        // also clip horizontal fades if necessary
12049        if (horizontalEdges && (left + length > right - length)) {
12050            length = (right - left) / 2;
12051        }
12052
12053        if (verticalEdges) {
12054            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12055            drawTop = topFadeStrength * fadeHeight > 1.0f;
12056            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12057            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12058        }
12059
12060        if (horizontalEdges) {
12061            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12062            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12063            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12064            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12065        }
12066
12067        saveCount = canvas.getSaveCount();
12068
12069        int solidColor = getSolidColor();
12070        if (solidColor == 0) {
12071            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12072
12073            if (drawTop) {
12074                canvas.saveLayer(left, top, right, top + length, null, flags);
12075            }
12076
12077            if (drawBottom) {
12078                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12079            }
12080
12081            if (drawLeft) {
12082                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12083            }
12084
12085            if (drawRight) {
12086                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12087            }
12088        } else {
12089            scrollabilityCache.setFadeColor(solidColor);
12090        }
12091
12092        // Step 3, draw the content
12093        if (!dirtyOpaque) onDraw(canvas);
12094
12095        // Step 4, draw the children
12096        dispatchDraw(canvas);
12097
12098        // Step 5, draw the fade effect and restore layers
12099        final Paint p = scrollabilityCache.paint;
12100        final Matrix matrix = scrollabilityCache.matrix;
12101        final Shader fade = scrollabilityCache.shader;
12102
12103        if (drawTop) {
12104            matrix.setScale(1, fadeHeight * topFadeStrength);
12105            matrix.postTranslate(left, top);
12106            fade.setLocalMatrix(matrix);
12107            canvas.drawRect(left, top, right, top + length, p);
12108        }
12109
12110        if (drawBottom) {
12111            matrix.setScale(1, fadeHeight * bottomFadeStrength);
12112            matrix.postRotate(180);
12113            matrix.postTranslate(left, bottom);
12114            fade.setLocalMatrix(matrix);
12115            canvas.drawRect(left, bottom - length, right, bottom, p);
12116        }
12117
12118        if (drawLeft) {
12119            matrix.setScale(1, fadeHeight * leftFadeStrength);
12120            matrix.postRotate(-90);
12121            matrix.postTranslate(left, top);
12122            fade.setLocalMatrix(matrix);
12123            canvas.drawRect(left, top, left + length, bottom, p);
12124        }
12125
12126        if (drawRight) {
12127            matrix.setScale(1, fadeHeight * rightFadeStrength);
12128            matrix.postRotate(90);
12129            matrix.postTranslate(right, top);
12130            fade.setLocalMatrix(matrix);
12131            canvas.drawRect(right - length, top, right, bottom, p);
12132        }
12133
12134        canvas.restoreToCount(saveCount);
12135
12136        // Step 6, draw decorations (scrollbars)
12137        onDrawScrollBars(canvas);
12138    }
12139
12140    /**
12141     * Override this if your view is known to always be drawn on top of a solid color background,
12142     * and needs to draw fading edges. Returning a non-zero color enables the view system to
12143     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
12144     * should be set to 0xFF.
12145     *
12146     * @see #setVerticalFadingEdgeEnabled(boolean)
12147     * @see #setHorizontalFadingEdgeEnabled(boolean)
12148     *
12149     * @return The known solid color background for this view, or 0 if the color may vary
12150     */
12151    @ViewDebug.ExportedProperty(category = "drawing")
12152    public int getSolidColor() {
12153        return 0;
12154    }
12155
12156    /**
12157     * Build a human readable string representation of the specified view flags.
12158     *
12159     * @param flags the view flags to convert to a string
12160     * @return a String representing the supplied flags
12161     */
12162    private static String printFlags(int flags) {
12163        String output = "";
12164        int numFlags = 0;
12165        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
12166            output += "TAKES_FOCUS";
12167            numFlags++;
12168        }
12169
12170        switch (flags & VISIBILITY_MASK) {
12171        case INVISIBLE:
12172            if (numFlags > 0) {
12173                output += " ";
12174            }
12175            output += "INVISIBLE";
12176            // USELESS HERE numFlags++;
12177            break;
12178        case GONE:
12179            if (numFlags > 0) {
12180                output += " ";
12181            }
12182            output += "GONE";
12183            // USELESS HERE numFlags++;
12184            break;
12185        default:
12186            break;
12187        }
12188        return output;
12189    }
12190
12191    /**
12192     * Build a human readable string representation of the specified private
12193     * view flags.
12194     *
12195     * @param privateFlags the private view flags to convert to a string
12196     * @return a String representing the supplied flags
12197     */
12198    private static String printPrivateFlags(int privateFlags) {
12199        String output = "";
12200        int numFlags = 0;
12201
12202        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
12203            output += "WANTS_FOCUS";
12204            numFlags++;
12205        }
12206
12207        if ((privateFlags & FOCUSED) == FOCUSED) {
12208            if (numFlags > 0) {
12209                output += " ";
12210            }
12211            output += "FOCUSED";
12212            numFlags++;
12213        }
12214
12215        if ((privateFlags & SELECTED) == SELECTED) {
12216            if (numFlags > 0) {
12217                output += " ";
12218            }
12219            output += "SELECTED";
12220            numFlags++;
12221        }
12222
12223        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
12224            if (numFlags > 0) {
12225                output += " ";
12226            }
12227            output += "IS_ROOT_NAMESPACE";
12228            numFlags++;
12229        }
12230
12231        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
12232            if (numFlags > 0) {
12233                output += " ";
12234            }
12235            output += "HAS_BOUNDS";
12236            numFlags++;
12237        }
12238
12239        if ((privateFlags & DRAWN) == DRAWN) {
12240            if (numFlags > 0) {
12241                output += " ";
12242            }
12243            output += "DRAWN";
12244            // USELESS HERE numFlags++;
12245        }
12246        return output;
12247    }
12248
12249    /**
12250     * <p>Indicates whether or not this view's layout will be requested during
12251     * the next hierarchy layout pass.</p>
12252     *
12253     * @return true if the layout will be forced during next layout pass
12254     */
12255    public boolean isLayoutRequested() {
12256        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
12257    }
12258
12259    /**
12260     * Assign a size and position to a view and all of its
12261     * descendants
12262     *
12263     * <p>This is the second phase of the layout mechanism.
12264     * (The first is measuring). In this phase, each parent calls
12265     * layout on all of its children to position them.
12266     * This is typically done using the child measurements
12267     * that were stored in the measure pass().</p>
12268     *
12269     * <p>Derived classes should not override this method.
12270     * Derived classes with children should override
12271     * onLayout. In that method, they should
12272     * call layout on each of their children.</p>
12273     *
12274     * @param l Left position, relative to parent
12275     * @param t Top position, relative to parent
12276     * @param r Right position, relative to parent
12277     * @param b Bottom position, relative to parent
12278     */
12279    @SuppressWarnings({"unchecked"})
12280    public void layout(int l, int t, int r, int b) {
12281        int oldL = mLeft;
12282        int oldT = mTop;
12283        int oldB = mBottom;
12284        int oldR = mRight;
12285        boolean changed = setFrame(l, t, r, b);
12286        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
12287            if (ViewDebug.TRACE_HIERARCHY) {
12288                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
12289            }
12290
12291            onLayout(changed, l, t, r, b);
12292            mPrivateFlags &= ~LAYOUT_REQUIRED;
12293
12294            ListenerInfo li = mListenerInfo;
12295            if (li != null && li.mOnLayoutChangeListeners != null) {
12296                ArrayList<OnLayoutChangeListener> listenersCopy =
12297                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
12298                int numListeners = listenersCopy.size();
12299                for (int i = 0; i < numListeners; ++i) {
12300                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
12301                }
12302            }
12303        }
12304        mPrivateFlags &= ~FORCE_LAYOUT;
12305    }
12306
12307    /**
12308     * Called from layout when this view should
12309     * assign a size and position to each of its children.
12310     *
12311     * Derived classes with children should override
12312     * this method and call layout on each of
12313     * their children.
12314     * @param changed This is a new size or position for this view
12315     * @param left Left position, relative to parent
12316     * @param top Top position, relative to parent
12317     * @param right Right position, relative to parent
12318     * @param bottom Bottom position, relative to parent
12319     */
12320    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
12321    }
12322
12323    /**
12324     * Assign a size and position to this view.
12325     *
12326     * This is called from layout.
12327     *
12328     * @param left Left position, relative to parent
12329     * @param top Top position, relative to parent
12330     * @param right Right position, relative to parent
12331     * @param bottom Bottom position, relative to parent
12332     * @return true if the new size and position are different than the
12333     *         previous ones
12334     * {@hide}
12335     */
12336    protected boolean setFrame(int left, int top, int right, int bottom) {
12337        boolean changed = false;
12338
12339        if (DBG) {
12340            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
12341                    + right + "," + bottom + ")");
12342        }
12343
12344        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
12345            changed = true;
12346
12347            // Remember our drawn bit
12348            int drawn = mPrivateFlags & DRAWN;
12349
12350            int oldWidth = mRight - mLeft;
12351            int oldHeight = mBottom - mTop;
12352            int newWidth = right - left;
12353            int newHeight = bottom - top;
12354            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
12355
12356            // Invalidate our old position
12357            invalidate(sizeChanged);
12358
12359            mLeft = left;
12360            mTop = top;
12361            mRight = right;
12362            mBottom = bottom;
12363            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
12364                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12365            }
12366
12367            mPrivateFlags |= HAS_BOUNDS;
12368
12369
12370            if (sizeChanged) {
12371                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
12372                    // A change in dimension means an auto-centered pivot point changes, too
12373                    if (mTransformationInfo != null) {
12374                        mTransformationInfo.mMatrixDirty = true;
12375                    }
12376                }
12377                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
12378            }
12379
12380            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
12381                // If we are visible, force the DRAWN bit to on so that
12382                // this invalidate will go through (at least to our parent).
12383                // This is because someone may have invalidated this view
12384                // before this call to setFrame came in, thereby clearing
12385                // the DRAWN bit.
12386                mPrivateFlags |= DRAWN;
12387                invalidate(sizeChanged);
12388                // parent display list may need to be recreated based on a change in the bounds
12389                // of any child
12390                invalidateParentCaches();
12391            }
12392
12393            // Reset drawn bit to original value (invalidate turns it off)
12394            mPrivateFlags |= drawn;
12395
12396            mBackgroundSizeChanged = true;
12397        }
12398        return changed;
12399    }
12400
12401    /**
12402     * Finalize inflating a view from XML.  This is called as the last phase
12403     * of inflation, after all child views have been added.
12404     *
12405     * <p>Even if the subclass overrides onFinishInflate, they should always be
12406     * sure to call the super method, so that we get called.
12407     */
12408    protected void onFinishInflate() {
12409    }
12410
12411    /**
12412     * Returns the resources associated with this view.
12413     *
12414     * @return Resources object.
12415     */
12416    public Resources getResources() {
12417        return mResources;
12418    }
12419
12420    /**
12421     * Invalidates the specified Drawable.
12422     *
12423     * @param drawable the drawable to invalidate
12424     */
12425    public void invalidateDrawable(Drawable drawable) {
12426        if (verifyDrawable(drawable)) {
12427            final Rect dirty = drawable.getBounds();
12428            final int scrollX = mScrollX;
12429            final int scrollY = mScrollY;
12430
12431            invalidate(dirty.left + scrollX, dirty.top + scrollY,
12432                    dirty.right + scrollX, dirty.bottom + scrollY);
12433        }
12434    }
12435
12436    /**
12437     * Schedules an action on a drawable to occur at a specified time.
12438     *
12439     * @param who the recipient of the action
12440     * @param what the action to run on the drawable
12441     * @param when the time at which the action must occur. Uses the
12442     *        {@link SystemClock#uptimeMillis} timebase.
12443     */
12444    public void scheduleDrawable(Drawable who, Runnable what, long when) {
12445        if (verifyDrawable(who) && what != null) {
12446            final long delay = when - SystemClock.uptimeMillis();
12447            if (mAttachInfo != null) {
12448                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12449                        Choreographer.CALLBACK_ANIMATION, what, who,
12450                        Choreographer.subtractFrameDelay(delay));
12451            } else {
12452                ViewRootImpl.getRunQueue().postDelayed(what, delay);
12453            }
12454        }
12455    }
12456
12457    /**
12458     * Cancels a scheduled action on a drawable.
12459     *
12460     * @param who the recipient of the action
12461     * @param what the action to cancel
12462     */
12463    public void unscheduleDrawable(Drawable who, Runnable what) {
12464        if (verifyDrawable(who) && what != null) {
12465            if (mAttachInfo != null) {
12466                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12467                        Choreographer.CALLBACK_ANIMATION, what, who);
12468            } else {
12469                ViewRootImpl.getRunQueue().removeCallbacks(what);
12470            }
12471        }
12472    }
12473
12474    /**
12475     * Unschedule any events associated with the given Drawable.  This can be
12476     * used when selecting a new Drawable into a view, so that the previous
12477     * one is completely unscheduled.
12478     *
12479     * @param who The Drawable to unschedule.
12480     *
12481     * @see #drawableStateChanged
12482     */
12483    public void unscheduleDrawable(Drawable who) {
12484        if (mAttachInfo != null && who != null) {
12485            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12486                    Choreographer.CALLBACK_ANIMATION, null, who);
12487        }
12488    }
12489
12490    /**
12491    * Return the layout direction of a given Drawable.
12492    *
12493    * @param who the Drawable to query
12494    */
12495    public int getResolvedLayoutDirection(Drawable who) {
12496        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
12497    }
12498
12499    /**
12500     * If your view subclass is displaying its own Drawable objects, it should
12501     * override this function and return true for any Drawable it is
12502     * displaying.  This allows animations for those drawables to be
12503     * scheduled.
12504     *
12505     * <p>Be sure to call through to the super class when overriding this
12506     * function.
12507     *
12508     * @param who The Drawable to verify.  Return true if it is one you are
12509     *            displaying, else return the result of calling through to the
12510     *            super class.
12511     *
12512     * @return boolean If true than the Drawable is being displayed in the
12513     *         view; else false and it is not allowed to animate.
12514     *
12515     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
12516     * @see #drawableStateChanged()
12517     */
12518    protected boolean verifyDrawable(Drawable who) {
12519        return who == mBGDrawable;
12520    }
12521
12522    /**
12523     * This function is called whenever the state of the view changes in such
12524     * a way that it impacts the state of drawables being shown.
12525     *
12526     * <p>Be sure to call through to the superclass when overriding this
12527     * function.
12528     *
12529     * @see Drawable#setState(int[])
12530     */
12531    protected void drawableStateChanged() {
12532        Drawable d = mBGDrawable;
12533        if (d != null && d.isStateful()) {
12534            d.setState(getDrawableState());
12535        }
12536    }
12537
12538    /**
12539     * Call this to force a view to update its drawable state. This will cause
12540     * drawableStateChanged to be called on this view. Views that are interested
12541     * in the new state should call getDrawableState.
12542     *
12543     * @see #drawableStateChanged
12544     * @see #getDrawableState
12545     */
12546    public void refreshDrawableState() {
12547        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
12548        drawableStateChanged();
12549
12550        ViewParent parent = mParent;
12551        if (parent != null) {
12552            parent.childDrawableStateChanged(this);
12553        }
12554    }
12555
12556    /**
12557     * Return an array of resource IDs of the drawable states representing the
12558     * current state of the view.
12559     *
12560     * @return The current drawable state
12561     *
12562     * @see Drawable#setState(int[])
12563     * @see #drawableStateChanged()
12564     * @see #onCreateDrawableState(int)
12565     */
12566    public final int[] getDrawableState() {
12567        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
12568            return mDrawableState;
12569        } else {
12570            mDrawableState = onCreateDrawableState(0);
12571            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
12572            return mDrawableState;
12573        }
12574    }
12575
12576    /**
12577     * Generate the new {@link android.graphics.drawable.Drawable} state for
12578     * this view. This is called by the view
12579     * system when the cached Drawable state is determined to be invalid.  To
12580     * retrieve the current state, you should use {@link #getDrawableState}.
12581     *
12582     * @param extraSpace if non-zero, this is the number of extra entries you
12583     * would like in the returned array in which you can place your own
12584     * states.
12585     *
12586     * @return Returns an array holding the current {@link Drawable} state of
12587     * the view.
12588     *
12589     * @see #mergeDrawableStates(int[], int[])
12590     */
12591    protected int[] onCreateDrawableState(int extraSpace) {
12592        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
12593                mParent instanceof View) {
12594            return ((View) mParent).onCreateDrawableState(extraSpace);
12595        }
12596
12597        int[] drawableState;
12598
12599        int privateFlags = mPrivateFlags;
12600
12601        int viewStateIndex = 0;
12602        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
12603        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
12604        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
12605        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
12606        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
12607        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
12608        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
12609                HardwareRenderer.isAvailable()) {
12610            // This is set if HW acceleration is requested, even if the current
12611            // process doesn't allow it.  This is just to allow app preview
12612            // windows to better match their app.
12613            viewStateIndex |= VIEW_STATE_ACCELERATED;
12614        }
12615        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
12616
12617        final int privateFlags2 = mPrivateFlags2;
12618        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
12619        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
12620
12621        drawableState = VIEW_STATE_SETS[viewStateIndex];
12622
12623        //noinspection ConstantIfStatement
12624        if (false) {
12625            Log.i("View", "drawableStateIndex=" + viewStateIndex);
12626            Log.i("View", toString()
12627                    + " pressed=" + ((privateFlags & PRESSED) != 0)
12628                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
12629                    + " fo=" + hasFocus()
12630                    + " sl=" + ((privateFlags & SELECTED) != 0)
12631                    + " wf=" + hasWindowFocus()
12632                    + ": " + Arrays.toString(drawableState));
12633        }
12634
12635        if (extraSpace == 0) {
12636            return drawableState;
12637        }
12638
12639        final int[] fullState;
12640        if (drawableState != null) {
12641            fullState = new int[drawableState.length + extraSpace];
12642            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
12643        } else {
12644            fullState = new int[extraSpace];
12645        }
12646
12647        return fullState;
12648    }
12649
12650    /**
12651     * Merge your own state values in <var>additionalState</var> into the base
12652     * state values <var>baseState</var> that were returned by
12653     * {@link #onCreateDrawableState(int)}.
12654     *
12655     * @param baseState The base state values returned by
12656     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
12657     * own additional state values.
12658     *
12659     * @param additionalState The additional state values you would like
12660     * added to <var>baseState</var>; this array is not modified.
12661     *
12662     * @return As a convenience, the <var>baseState</var> array you originally
12663     * passed into the function is returned.
12664     *
12665     * @see #onCreateDrawableState(int)
12666     */
12667    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
12668        final int N = baseState.length;
12669        int i = N - 1;
12670        while (i >= 0 && baseState[i] == 0) {
12671            i--;
12672        }
12673        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12674        return baseState;
12675    }
12676
12677    /**
12678     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12679     * on all Drawable objects associated with this view.
12680     */
12681    public void jumpDrawablesToCurrentState() {
12682        if (mBGDrawable != null) {
12683            mBGDrawable.jumpToCurrentState();
12684        }
12685    }
12686
12687    /**
12688     * Sets the background color for this view.
12689     * @param color the color of the background
12690     */
12691    @RemotableViewMethod
12692    public void setBackgroundColor(int color) {
12693        if (mBGDrawable instanceof ColorDrawable) {
12694            ((ColorDrawable) mBGDrawable).setColor(color);
12695        } else {
12696            setBackgroundDrawable(new ColorDrawable(color));
12697        }
12698    }
12699
12700    /**
12701     * Set the background to a given resource. The resource should refer to
12702     * a Drawable object or 0 to remove the background.
12703     * @param resid The identifier of the resource.
12704     * @attr ref android.R.styleable#View_background
12705     */
12706    @RemotableViewMethod
12707    public void setBackgroundResource(int resid) {
12708        if (resid != 0 && resid == mBackgroundResource) {
12709            return;
12710        }
12711
12712        Drawable d= null;
12713        if (resid != 0) {
12714            d = mResources.getDrawable(resid);
12715        }
12716        setBackgroundDrawable(d);
12717
12718        mBackgroundResource = resid;
12719    }
12720
12721    /**
12722     * Set the background to a given Drawable, or remove the background. If the
12723     * background has padding, this View's padding is set to the background's
12724     * padding. However, when a background is removed, this View's padding isn't
12725     * touched. If setting the padding is desired, please use
12726     * {@link #setPadding(int, int, int, int)}.
12727     *
12728     * @param d The Drawable to use as the background, or null to remove the
12729     *        background
12730     */
12731    public void setBackgroundDrawable(Drawable d) {
12732        if (d == mBGDrawable) {
12733            return;
12734        }
12735
12736        boolean requestLayout = false;
12737
12738        mBackgroundResource = 0;
12739
12740        /*
12741         * Regardless of whether we're setting a new background or not, we want
12742         * to clear the previous drawable.
12743         */
12744        if (mBGDrawable != null) {
12745            mBGDrawable.setCallback(null);
12746            unscheduleDrawable(mBGDrawable);
12747        }
12748
12749        if (d != null) {
12750            Rect padding = sThreadLocal.get();
12751            if (padding == null) {
12752                padding = new Rect();
12753                sThreadLocal.set(padding);
12754            }
12755            if (d.getPadding(padding)) {
12756                switch (d.getResolvedLayoutDirectionSelf()) {
12757                    case LAYOUT_DIRECTION_RTL:
12758                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12759                        break;
12760                    case LAYOUT_DIRECTION_LTR:
12761                    default:
12762                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12763                }
12764            }
12765
12766            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12767            // if it has a different minimum size, we should layout again
12768            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12769                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12770                requestLayout = true;
12771            }
12772
12773            d.setCallback(this);
12774            if (d.isStateful()) {
12775                d.setState(getDrawableState());
12776            }
12777            d.setVisible(getVisibility() == VISIBLE, false);
12778            mBGDrawable = d;
12779
12780            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12781                mPrivateFlags &= ~SKIP_DRAW;
12782                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12783                requestLayout = true;
12784            }
12785        } else {
12786            /* Remove the background */
12787            mBGDrawable = null;
12788
12789            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12790                /*
12791                 * This view ONLY drew the background before and we're removing
12792                 * the background, so now it won't draw anything
12793                 * (hence we SKIP_DRAW)
12794                 */
12795                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12796                mPrivateFlags |= SKIP_DRAW;
12797            }
12798
12799            /*
12800             * When the background is set, we try to apply its padding to this
12801             * View. When the background is removed, we don't touch this View's
12802             * padding. This is noted in the Javadocs. Hence, we don't need to
12803             * requestLayout(), the invalidate() below is sufficient.
12804             */
12805
12806            // The old background's minimum size could have affected this
12807            // View's layout, so let's requestLayout
12808            requestLayout = true;
12809        }
12810
12811        computeOpaqueFlags();
12812
12813        if (requestLayout) {
12814            requestLayout();
12815        }
12816
12817        mBackgroundSizeChanged = true;
12818        invalidate(true);
12819    }
12820
12821    /**
12822     * Gets the background drawable
12823     * @return The drawable used as the background for this view, if any.
12824     */
12825    public Drawable getBackground() {
12826        return mBGDrawable;
12827    }
12828
12829    /**
12830     * Sets the padding. The view may add on the space required to display
12831     * the scrollbars, depending on the style and visibility of the scrollbars.
12832     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12833     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12834     * from the values set in this call.
12835     *
12836     * @attr ref android.R.styleable#View_padding
12837     * @attr ref android.R.styleable#View_paddingBottom
12838     * @attr ref android.R.styleable#View_paddingLeft
12839     * @attr ref android.R.styleable#View_paddingRight
12840     * @attr ref android.R.styleable#View_paddingTop
12841     * @param left the left padding in pixels
12842     * @param top the top padding in pixels
12843     * @param right the right padding in pixels
12844     * @param bottom the bottom padding in pixels
12845     */
12846    public void setPadding(int left, int top, int right, int bottom) {
12847        mUserPaddingStart = -1;
12848        mUserPaddingEnd = -1;
12849        mUserPaddingRelative = false;
12850
12851        internalSetPadding(left, top, right, bottom);
12852    }
12853
12854    private void internalSetPadding(int left, int top, int right, int bottom) {
12855        mUserPaddingLeft = left;
12856        mUserPaddingRight = right;
12857        mUserPaddingBottom = bottom;
12858
12859        final int viewFlags = mViewFlags;
12860        boolean changed = false;
12861
12862        // Common case is there are no scroll bars.
12863        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12864            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12865                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12866                        ? 0 : getVerticalScrollbarWidth();
12867                switch (mVerticalScrollbarPosition) {
12868                    case SCROLLBAR_POSITION_DEFAULT:
12869                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12870                            left += offset;
12871                        } else {
12872                            right += offset;
12873                        }
12874                        break;
12875                    case SCROLLBAR_POSITION_RIGHT:
12876                        right += offset;
12877                        break;
12878                    case SCROLLBAR_POSITION_LEFT:
12879                        left += offset;
12880                        break;
12881                }
12882            }
12883            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12884                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12885                        ? 0 : getHorizontalScrollbarHeight();
12886            }
12887        }
12888
12889        if (mPaddingLeft != left) {
12890            changed = true;
12891            mPaddingLeft = left;
12892        }
12893        if (mPaddingTop != top) {
12894            changed = true;
12895            mPaddingTop = top;
12896        }
12897        if (mPaddingRight != right) {
12898            changed = true;
12899            mPaddingRight = right;
12900        }
12901        if (mPaddingBottom != bottom) {
12902            changed = true;
12903            mPaddingBottom = bottom;
12904        }
12905
12906        if (changed) {
12907            requestLayout();
12908        }
12909    }
12910
12911    /**
12912     * Sets the relative padding. The view may add on the space required to display
12913     * the scrollbars, depending on the style and visibility of the scrollbars.
12914     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12915     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12916     * from the values set in this call.
12917     *
12918     * @attr ref android.R.styleable#View_padding
12919     * @attr ref android.R.styleable#View_paddingBottom
12920     * @attr ref android.R.styleable#View_paddingStart
12921     * @attr ref android.R.styleable#View_paddingEnd
12922     * @attr ref android.R.styleable#View_paddingTop
12923     * @param start the start padding in pixels
12924     * @param top the top padding in pixels
12925     * @param end the end padding in pixels
12926     * @param bottom the bottom padding in pixels
12927     */
12928    public void setPaddingRelative(int start, int top, int end, int bottom) {
12929        mUserPaddingStart = start;
12930        mUserPaddingEnd = end;
12931        mUserPaddingRelative = true;
12932
12933        switch(getResolvedLayoutDirection()) {
12934            case LAYOUT_DIRECTION_RTL:
12935                internalSetPadding(end, top, start, bottom);
12936                break;
12937            case LAYOUT_DIRECTION_LTR:
12938            default:
12939                internalSetPadding(start, top, end, bottom);
12940        }
12941    }
12942
12943    /**
12944     * Returns the top padding of this view.
12945     *
12946     * @return the top padding in pixels
12947     */
12948    public int getPaddingTop() {
12949        return mPaddingTop;
12950    }
12951
12952    /**
12953     * Returns the bottom padding of this view. If there are inset and enabled
12954     * scrollbars, this value may include the space required to display the
12955     * scrollbars as well.
12956     *
12957     * @return the bottom padding in pixels
12958     */
12959    public int getPaddingBottom() {
12960        return mPaddingBottom;
12961    }
12962
12963    /**
12964     * Returns the left padding of this view. If there are inset and enabled
12965     * scrollbars, this value may include the space required to display the
12966     * scrollbars as well.
12967     *
12968     * @return the left padding in pixels
12969     */
12970    public int getPaddingLeft() {
12971        return mPaddingLeft;
12972    }
12973
12974    /**
12975     * Returns the start padding of this view depending on its resolved layout direction.
12976     * If there are inset and enabled scrollbars, this value may include the space
12977     * required to display the scrollbars as well.
12978     *
12979     * @return the start padding in pixels
12980     */
12981    public int getPaddingStart() {
12982        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12983                mPaddingRight : mPaddingLeft;
12984    }
12985
12986    /**
12987     * Returns the right padding of this view. If there are inset and enabled
12988     * scrollbars, this value may include the space required to display the
12989     * scrollbars as well.
12990     *
12991     * @return the right padding in pixels
12992     */
12993    public int getPaddingRight() {
12994        return mPaddingRight;
12995    }
12996
12997    /**
12998     * Returns the end padding of this view depending on its resolved layout direction.
12999     * If there are inset and enabled scrollbars, this value may include the space
13000     * required to display the scrollbars as well.
13001     *
13002     * @return the end padding in pixels
13003     */
13004    public int getPaddingEnd() {
13005        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13006                mPaddingLeft : mPaddingRight;
13007    }
13008
13009    /**
13010     * Return if the padding as been set thru relative values
13011     * {@link #setPaddingRelative(int, int, int, int)} or thru
13012     * @attr ref android.R.styleable#View_paddingStart or
13013     * @attr ref android.R.styleable#View_paddingEnd
13014     *
13015     * @return true if the padding is relative or false if it is not.
13016     */
13017    public boolean isPaddingRelative() {
13018        return mUserPaddingRelative;
13019    }
13020
13021    /**
13022     * Changes the selection state of this view. A view can be selected or not.
13023     * Note that selection is not the same as focus. Views are typically
13024     * selected in the context of an AdapterView like ListView or GridView;
13025     * the selected view is the view that is highlighted.
13026     *
13027     * @param selected true if the view must be selected, false otherwise
13028     */
13029    public void setSelected(boolean selected) {
13030        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13031            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13032            if (!selected) resetPressedState();
13033            invalidate(true);
13034            refreshDrawableState();
13035            dispatchSetSelected(selected);
13036        }
13037    }
13038
13039    /**
13040     * Dispatch setSelected to all of this View's children.
13041     *
13042     * @see #setSelected(boolean)
13043     *
13044     * @param selected The new selected state
13045     */
13046    protected void dispatchSetSelected(boolean selected) {
13047    }
13048
13049    /**
13050     * Indicates the selection state of this view.
13051     *
13052     * @return true if the view is selected, false otherwise
13053     */
13054    @ViewDebug.ExportedProperty
13055    public boolean isSelected() {
13056        return (mPrivateFlags & SELECTED) != 0;
13057    }
13058
13059    /**
13060     * Changes the activated state of this view. A view can be activated or not.
13061     * Note that activation is not the same as selection.  Selection is
13062     * a transient property, representing the view (hierarchy) the user is
13063     * currently interacting with.  Activation is a longer-term state that the
13064     * user can move views in and out of.  For example, in a list view with
13065     * single or multiple selection enabled, the views in the current selection
13066     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13067     * here.)  The activated state is propagated down to children of the view it
13068     * is set on.
13069     *
13070     * @param activated true if the view must be activated, false otherwise
13071     */
13072    public void setActivated(boolean activated) {
13073        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13074            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13075            invalidate(true);
13076            refreshDrawableState();
13077            dispatchSetActivated(activated);
13078        }
13079    }
13080
13081    /**
13082     * Dispatch setActivated to all of this View's children.
13083     *
13084     * @see #setActivated(boolean)
13085     *
13086     * @param activated The new activated state
13087     */
13088    protected void dispatchSetActivated(boolean activated) {
13089    }
13090
13091    /**
13092     * Indicates the activation state of this view.
13093     *
13094     * @return true if the view is activated, false otherwise
13095     */
13096    @ViewDebug.ExportedProperty
13097    public boolean isActivated() {
13098        return (mPrivateFlags & ACTIVATED) != 0;
13099    }
13100
13101    /**
13102     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
13103     * observer can be used to get notifications when global events, like
13104     * layout, happen.
13105     *
13106     * The returned ViewTreeObserver observer is not guaranteed to remain
13107     * valid for the lifetime of this View. If the caller of this method keeps
13108     * a long-lived reference to ViewTreeObserver, it should always check for
13109     * the return value of {@link ViewTreeObserver#isAlive()}.
13110     *
13111     * @return The ViewTreeObserver for this view's hierarchy.
13112     */
13113    public ViewTreeObserver getViewTreeObserver() {
13114        if (mAttachInfo != null) {
13115            return mAttachInfo.mTreeObserver;
13116        }
13117        if (mFloatingTreeObserver == null) {
13118            mFloatingTreeObserver = new ViewTreeObserver();
13119        }
13120        return mFloatingTreeObserver;
13121    }
13122
13123    /**
13124     * <p>Finds the topmost view in the current view hierarchy.</p>
13125     *
13126     * @return the topmost view containing this view
13127     */
13128    public View getRootView() {
13129        if (mAttachInfo != null) {
13130            final View v = mAttachInfo.mRootView;
13131            if (v != null) {
13132                return v;
13133            }
13134        }
13135
13136        View parent = this;
13137
13138        while (parent.mParent != null && parent.mParent instanceof View) {
13139            parent = (View) parent.mParent;
13140        }
13141
13142        return parent;
13143    }
13144
13145    /**
13146     * <p>Computes the coordinates of this view on the screen. The argument
13147     * must be an array of two integers. After the method returns, the array
13148     * contains the x and y location in that order.</p>
13149     *
13150     * @param location an array of two integers in which to hold the coordinates
13151     */
13152    public void getLocationOnScreen(int[] location) {
13153        getLocationInWindow(location);
13154
13155        final AttachInfo info = mAttachInfo;
13156        if (info != null) {
13157            location[0] += info.mWindowLeft;
13158            location[1] += info.mWindowTop;
13159        }
13160    }
13161
13162    /**
13163     * <p>Computes the coordinates of this view in its window. The argument
13164     * must be an array of two integers. After the method returns, the array
13165     * contains the x and y location in that order.</p>
13166     *
13167     * @param location an array of two integers in which to hold the coordinates
13168     */
13169    public void getLocationInWindow(int[] location) {
13170        if (location == null || location.length < 2) {
13171            throw new IllegalArgumentException("location must be an array of two integers");
13172        }
13173
13174        if (mAttachInfo == null) {
13175            // When the view is not attached to a window, this method does not make sense
13176            location[0] = location[1] = 0;
13177            return;
13178        }
13179
13180        float[] position = mAttachInfo.mTmpTransformLocation;
13181        position[0] = position[1] = 0.0f;
13182
13183        if (!hasIdentityMatrix()) {
13184            getMatrix().mapPoints(position);
13185        }
13186
13187        position[0] += mLeft;
13188        position[1] += mTop;
13189
13190        ViewParent viewParent = mParent;
13191        while (viewParent instanceof View) {
13192            final View view = (View) viewParent;
13193
13194            position[0] -= view.mScrollX;
13195            position[1] -= view.mScrollY;
13196
13197            if (!view.hasIdentityMatrix()) {
13198                view.getMatrix().mapPoints(position);
13199            }
13200
13201            position[0] += view.mLeft;
13202            position[1] += view.mTop;
13203
13204            viewParent = view.mParent;
13205        }
13206
13207        if (viewParent instanceof ViewRootImpl) {
13208            // *cough*
13209            final ViewRootImpl vr = (ViewRootImpl) viewParent;
13210            position[1] -= vr.mCurScrollY;
13211        }
13212
13213        location[0] = (int) (position[0] + 0.5f);
13214        location[1] = (int) (position[1] + 0.5f);
13215    }
13216
13217    /**
13218     * {@hide}
13219     * @param id the id of the view to be found
13220     * @return the view of the specified id, null if cannot be found
13221     */
13222    protected View findViewTraversal(int id) {
13223        if (id == mID) {
13224            return this;
13225        }
13226        return null;
13227    }
13228
13229    /**
13230     * {@hide}
13231     * @param tag the tag of the view to be found
13232     * @return the view of specified tag, null if cannot be found
13233     */
13234    protected View findViewWithTagTraversal(Object tag) {
13235        if (tag != null && tag.equals(mTag)) {
13236            return this;
13237        }
13238        return null;
13239    }
13240
13241    /**
13242     * {@hide}
13243     * @param predicate The predicate to evaluate.
13244     * @param childToSkip If not null, ignores this child during the recursive traversal.
13245     * @return The first view that matches the predicate or null.
13246     */
13247    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
13248        if (predicate.apply(this)) {
13249            return this;
13250        }
13251        return null;
13252    }
13253
13254    /**
13255     * Look for a child view with the given id.  If this view has the given
13256     * id, return this view.
13257     *
13258     * @param id The id to search for.
13259     * @return The view that has the given id in the hierarchy or null
13260     */
13261    public final View findViewById(int id) {
13262        if (id < 0) {
13263            return null;
13264        }
13265        return findViewTraversal(id);
13266    }
13267
13268    /**
13269     * Finds a view by its unuque and stable accessibility id.
13270     *
13271     * @param accessibilityId The searched accessibility id.
13272     * @return The found view.
13273     */
13274    final View findViewByAccessibilityId(int accessibilityId) {
13275        if (accessibilityId < 0) {
13276            return null;
13277        }
13278        return findViewByAccessibilityIdTraversal(accessibilityId);
13279    }
13280
13281    /**
13282     * Performs the traversal to find a view by its unuque and stable accessibility id.
13283     *
13284     * <strong>Note:</strong>This method does not stop at the root namespace
13285     * boundary since the user can touch the screen at an arbitrary location
13286     * potentially crossing the root namespace bounday which will send an
13287     * accessibility event to accessibility services and they should be able
13288     * to obtain the event source. Also accessibility ids are guaranteed to be
13289     * unique in the window.
13290     *
13291     * @param accessibilityId The accessibility id.
13292     * @return The found view.
13293     */
13294    View findViewByAccessibilityIdTraversal(int accessibilityId) {
13295        if (getAccessibilityViewId() == accessibilityId) {
13296            return this;
13297        }
13298        return null;
13299    }
13300
13301    /**
13302     * Look for a child view with the given tag.  If this view has the given
13303     * tag, return this view.
13304     *
13305     * @param tag The tag to search for, using "tag.equals(getTag())".
13306     * @return The View that has the given tag in the hierarchy or null
13307     */
13308    public final View findViewWithTag(Object tag) {
13309        if (tag == null) {
13310            return null;
13311        }
13312        return findViewWithTagTraversal(tag);
13313    }
13314
13315    /**
13316     * {@hide}
13317     * Look for a child view that matches the specified predicate.
13318     * If this view matches the predicate, return this view.
13319     *
13320     * @param predicate The predicate to evaluate.
13321     * @return The first view that matches the predicate or null.
13322     */
13323    public final View findViewByPredicate(Predicate<View> predicate) {
13324        return findViewByPredicateTraversal(predicate, null);
13325    }
13326
13327    /**
13328     * {@hide}
13329     * Look for a child view that matches the specified predicate,
13330     * starting with the specified view and its descendents and then
13331     * recusively searching the ancestors and siblings of that view
13332     * until this view is reached.
13333     *
13334     * This method is useful in cases where the predicate does not match
13335     * a single unique view (perhaps multiple views use the same id)
13336     * and we are trying to find the view that is "closest" in scope to the
13337     * starting view.
13338     *
13339     * @param start The view to start from.
13340     * @param predicate The predicate to evaluate.
13341     * @return The first view that matches the predicate or null.
13342     */
13343    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
13344        View childToSkip = null;
13345        for (;;) {
13346            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
13347            if (view != null || start == this) {
13348                return view;
13349            }
13350
13351            ViewParent parent = start.getParent();
13352            if (parent == null || !(parent instanceof View)) {
13353                return null;
13354            }
13355
13356            childToSkip = start;
13357            start = (View) parent;
13358        }
13359    }
13360
13361    /**
13362     * Sets the identifier for this view. The identifier does not have to be
13363     * unique in this view's hierarchy. The identifier should be a positive
13364     * number.
13365     *
13366     * @see #NO_ID
13367     * @see #getId()
13368     * @see #findViewById(int)
13369     *
13370     * @param id a number used to identify the view
13371     *
13372     * @attr ref android.R.styleable#View_id
13373     */
13374    public void setId(int id) {
13375        mID = id;
13376    }
13377
13378    /**
13379     * {@hide}
13380     *
13381     * @param isRoot true if the view belongs to the root namespace, false
13382     *        otherwise
13383     */
13384    public void setIsRootNamespace(boolean isRoot) {
13385        if (isRoot) {
13386            mPrivateFlags |= IS_ROOT_NAMESPACE;
13387        } else {
13388            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
13389        }
13390    }
13391
13392    /**
13393     * {@hide}
13394     *
13395     * @return true if the view belongs to the root namespace, false otherwise
13396     */
13397    public boolean isRootNamespace() {
13398        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
13399    }
13400
13401    /**
13402     * Returns this view's identifier.
13403     *
13404     * @return a positive integer used to identify the view or {@link #NO_ID}
13405     *         if the view has no ID
13406     *
13407     * @see #setId(int)
13408     * @see #findViewById(int)
13409     * @attr ref android.R.styleable#View_id
13410     */
13411    @ViewDebug.CapturedViewProperty
13412    public int getId() {
13413        return mID;
13414    }
13415
13416    /**
13417     * Returns this view's tag.
13418     *
13419     * @return the Object stored in this view as a tag
13420     *
13421     * @see #setTag(Object)
13422     * @see #getTag(int)
13423     */
13424    @ViewDebug.ExportedProperty
13425    public Object getTag() {
13426        return mTag;
13427    }
13428
13429    /**
13430     * Sets the tag associated with this view. A tag can be used to mark
13431     * a view in its hierarchy and does not have to be unique within the
13432     * hierarchy. Tags can also be used to store data within a view without
13433     * resorting to another data structure.
13434     *
13435     * @param tag an Object to tag the view with
13436     *
13437     * @see #getTag()
13438     * @see #setTag(int, Object)
13439     */
13440    public void setTag(final Object tag) {
13441        mTag = tag;
13442    }
13443
13444    /**
13445     * Returns the tag associated with this view and the specified key.
13446     *
13447     * @param key The key identifying the tag
13448     *
13449     * @return the Object stored in this view as a tag
13450     *
13451     * @see #setTag(int, Object)
13452     * @see #getTag()
13453     */
13454    public Object getTag(int key) {
13455        if (mKeyedTags != null) return mKeyedTags.get(key);
13456        return null;
13457    }
13458
13459    /**
13460     * Sets a tag associated with this view and a key. A tag can be used
13461     * to mark a view in its hierarchy and does not have to be unique within
13462     * the hierarchy. Tags can also be used to store data within a view
13463     * without resorting to another data structure.
13464     *
13465     * The specified key should be an id declared in the resources of the
13466     * application to ensure it is unique (see the <a
13467     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
13468     * Keys identified as belonging to
13469     * the Android framework or not associated with any package will cause
13470     * an {@link IllegalArgumentException} to be thrown.
13471     *
13472     * @param key The key identifying the tag
13473     * @param tag An Object to tag the view with
13474     *
13475     * @throws IllegalArgumentException If they specified key is not valid
13476     *
13477     * @see #setTag(Object)
13478     * @see #getTag(int)
13479     */
13480    public void setTag(int key, final Object tag) {
13481        // If the package id is 0x00 or 0x01, it's either an undefined package
13482        // or a framework id
13483        if ((key >>> 24) < 2) {
13484            throw new IllegalArgumentException("The key must be an application-specific "
13485                    + "resource id.");
13486        }
13487
13488        setKeyedTag(key, tag);
13489    }
13490
13491    /**
13492     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
13493     * framework id.
13494     *
13495     * @hide
13496     */
13497    public void setTagInternal(int key, Object tag) {
13498        if ((key >>> 24) != 0x1) {
13499            throw new IllegalArgumentException("The key must be a framework-specific "
13500                    + "resource id.");
13501        }
13502
13503        setKeyedTag(key, tag);
13504    }
13505
13506    private void setKeyedTag(int key, Object tag) {
13507        if (mKeyedTags == null) {
13508            mKeyedTags = new SparseArray<Object>();
13509        }
13510
13511        mKeyedTags.put(key, tag);
13512    }
13513
13514    /**
13515     * @param consistency The type of consistency. See ViewDebug for more information.
13516     *
13517     * @hide
13518     */
13519    protected boolean dispatchConsistencyCheck(int consistency) {
13520        return onConsistencyCheck(consistency);
13521    }
13522
13523    /**
13524     * Method that subclasses should implement to check their consistency. The type of
13525     * consistency check is indicated by the bit field passed as a parameter.
13526     *
13527     * @param consistency The type of consistency. See ViewDebug for more information.
13528     *
13529     * @throws IllegalStateException if the view is in an inconsistent state.
13530     *
13531     * @hide
13532     */
13533    protected boolean onConsistencyCheck(int consistency) {
13534        boolean result = true;
13535
13536        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
13537        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
13538
13539        if (checkLayout) {
13540            if (getParent() == null) {
13541                result = false;
13542                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13543                        "View " + this + " does not have a parent.");
13544            }
13545
13546            if (mAttachInfo == null) {
13547                result = false;
13548                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13549                        "View " + this + " is not attached to a window.");
13550            }
13551        }
13552
13553        if (checkDrawing) {
13554            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
13555            // from their draw() method
13556
13557            if ((mPrivateFlags & DRAWN) != DRAWN &&
13558                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
13559                result = false;
13560                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13561                        "View " + this + " was invalidated but its drawing cache is valid.");
13562            }
13563        }
13564
13565        return result;
13566    }
13567
13568    /**
13569     * Prints information about this view in the log output, with the tag
13570     * {@link #VIEW_LOG_TAG}.
13571     *
13572     * @hide
13573     */
13574    public void debug() {
13575        debug(0);
13576    }
13577
13578    /**
13579     * Prints information about this view in the log output, with the tag
13580     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
13581     * indentation defined by the <code>depth</code>.
13582     *
13583     * @param depth the indentation level
13584     *
13585     * @hide
13586     */
13587    protected void debug(int depth) {
13588        String output = debugIndent(depth - 1);
13589
13590        output += "+ " + this;
13591        int id = getId();
13592        if (id != -1) {
13593            output += " (id=" + id + ")";
13594        }
13595        Object tag = getTag();
13596        if (tag != null) {
13597            output += " (tag=" + tag + ")";
13598        }
13599        Log.d(VIEW_LOG_TAG, output);
13600
13601        if ((mPrivateFlags & FOCUSED) != 0) {
13602            output = debugIndent(depth) + " FOCUSED";
13603            Log.d(VIEW_LOG_TAG, output);
13604        }
13605
13606        output = debugIndent(depth);
13607        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
13608                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
13609                + "} ";
13610        Log.d(VIEW_LOG_TAG, output);
13611
13612        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
13613                || mPaddingBottom != 0) {
13614            output = debugIndent(depth);
13615            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
13616                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
13617            Log.d(VIEW_LOG_TAG, output);
13618        }
13619
13620        output = debugIndent(depth);
13621        output += "mMeasureWidth=" + mMeasuredWidth +
13622                " mMeasureHeight=" + mMeasuredHeight;
13623        Log.d(VIEW_LOG_TAG, output);
13624
13625        output = debugIndent(depth);
13626        if (mLayoutParams == null) {
13627            output += "BAD! no layout params";
13628        } else {
13629            output = mLayoutParams.debug(output);
13630        }
13631        Log.d(VIEW_LOG_TAG, output);
13632
13633        output = debugIndent(depth);
13634        output += "flags={";
13635        output += View.printFlags(mViewFlags);
13636        output += "}";
13637        Log.d(VIEW_LOG_TAG, output);
13638
13639        output = debugIndent(depth);
13640        output += "privateFlags={";
13641        output += View.printPrivateFlags(mPrivateFlags);
13642        output += "}";
13643        Log.d(VIEW_LOG_TAG, output);
13644    }
13645
13646    /**
13647     * Creates a string of whitespaces used for indentation.
13648     *
13649     * @param depth the indentation level
13650     * @return a String containing (depth * 2 + 3) * 2 white spaces
13651     *
13652     * @hide
13653     */
13654    protected static String debugIndent(int depth) {
13655        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
13656        for (int i = 0; i < (depth * 2) + 3; i++) {
13657            spaces.append(' ').append(' ');
13658        }
13659        return spaces.toString();
13660    }
13661
13662    /**
13663     * <p>Return the offset of the widget's text baseline from the widget's top
13664     * boundary. If this widget does not support baseline alignment, this
13665     * method returns -1. </p>
13666     *
13667     * @return the offset of the baseline within the widget's bounds or -1
13668     *         if baseline alignment is not supported
13669     */
13670    @ViewDebug.ExportedProperty(category = "layout")
13671    public int getBaseline() {
13672        return -1;
13673    }
13674
13675    /**
13676     * Call this when something has changed which has invalidated the
13677     * layout of this view. This will schedule a layout pass of the view
13678     * tree.
13679     */
13680    public void requestLayout() {
13681        if (ViewDebug.TRACE_HIERARCHY) {
13682            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13683        }
13684
13685        mPrivateFlags |= FORCE_LAYOUT;
13686        mPrivateFlags |= INVALIDATED;
13687
13688        if (mLayoutParams != null) {
13689            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
13690        }
13691
13692        if (mParent != null && !mParent.isLayoutRequested()) {
13693            mParent.requestLayout();
13694        }
13695    }
13696
13697    /**
13698     * Forces this view to be laid out during the next layout pass.
13699     * This method does not call requestLayout() or forceLayout()
13700     * on the parent.
13701     */
13702    public void forceLayout() {
13703        mPrivateFlags |= FORCE_LAYOUT;
13704        mPrivateFlags |= INVALIDATED;
13705    }
13706
13707    /**
13708     * <p>
13709     * This is called to find out how big a view should be. The parent
13710     * supplies constraint information in the width and height parameters.
13711     * </p>
13712     *
13713     * <p>
13714     * The actual measurement work of a view is performed in
13715     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13716     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13717     * </p>
13718     *
13719     *
13720     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13721     *        parent
13722     * @param heightMeasureSpec Vertical space requirements as imposed by the
13723     *        parent
13724     *
13725     * @see #onMeasure(int, int)
13726     */
13727    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13728        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13729                widthMeasureSpec != mOldWidthMeasureSpec ||
13730                heightMeasureSpec != mOldHeightMeasureSpec) {
13731
13732            // first clears the measured dimension flag
13733            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13734
13735            if (ViewDebug.TRACE_HIERARCHY) {
13736                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13737            }
13738
13739            // measure ourselves, this should set the measured dimension flag back
13740            onMeasure(widthMeasureSpec, heightMeasureSpec);
13741
13742            // flag not set, setMeasuredDimension() was not invoked, we raise
13743            // an exception to warn the developer
13744            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13745                throw new IllegalStateException("onMeasure() did not set the"
13746                        + " measured dimension by calling"
13747                        + " setMeasuredDimension()");
13748            }
13749
13750            mPrivateFlags |= LAYOUT_REQUIRED;
13751        }
13752
13753        mOldWidthMeasureSpec = widthMeasureSpec;
13754        mOldHeightMeasureSpec = heightMeasureSpec;
13755    }
13756
13757    /**
13758     * <p>
13759     * Measure the view and its content to determine the measured width and the
13760     * measured height. This method is invoked by {@link #measure(int, int)} and
13761     * should be overriden by subclasses to provide accurate and efficient
13762     * measurement of their contents.
13763     * </p>
13764     *
13765     * <p>
13766     * <strong>CONTRACT:</strong> When overriding this method, you
13767     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13768     * measured width and height of this view. Failure to do so will trigger an
13769     * <code>IllegalStateException</code>, thrown by
13770     * {@link #measure(int, int)}. Calling the superclass'
13771     * {@link #onMeasure(int, int)} is a valid use.
13772     * </p>
13773     *
13774     * <p>
13775     * The base class implementation of measure defaults to the background size,
13776     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13777     * override {@link #onMeasure(int, int)} to provide better measurements of
13778     * their content.
13779     * </p>
13780     *
13781     * <p>
13782     * If this method is overridden, it is the subclass's responsibility to make
13783     * sure the measured height and width are at least the view's minimum height
13784     * and width ({@link #getSuggestedMinimumHeight()} and
13785     * {@link #getSuggestedMinimumWidth()}).
13786     * </p>
13787     *
13788     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13789     *                         The requirements are encoded with
13790     *                         {@link android.view.View.MeasureSpec}.
13791     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13792     *                         The requirements are encoded with
13793     *                         {@link android.view.View.MeasureSpec}.
13794     *
13795     * @see #getMeasuredWidth()
13796     * @see #getMeasuredHeight()
13797     * @see #setMeasuredDimension(int, int)
13798     * @see #getSuggestedMinimumHeight()
13799     * @see #getSuggestedMinimumWidth()
13800     * @see android.view.View.MeasureSpec#getMode(int)
13801     * @see android.view.View.MeasureSpec#getSize(int)
13802     */
13803    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13804        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13805                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13806    }
13807
13808    /**
13809     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13810     * measured width and measured height. Failing to do so will trigger an
13811     * exception at measurement time.</p>
13812     *
13813     * @param measuredWidth The measured width of this view.  May be a complex
13814     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13815     * {@link #MEASURED_STATE_TOO_SMALL}.
13816     * @param measuredHeight The measured height of this view.  May be a complex
13817     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13818     * {@link #MEASURED_STATE_TOO_SMALL}.
13819     */
13820    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13821        mMeasuredWidth = measuredWidth;
13822        mMeasuredHeight = measuredHeight;
13823
13824        mPrivateFlags |= MEASURED_DIMENSION_SET;
13825    }
13826
13827    /**
13828     * Merge two states as returned by {@link #getMeasuredState()}.
13829     * @param curState The current state as returned from a view or the result
13830     * of combining multiple views.
13831     * @param newState The new view state to combine.
13832     * @return Returns a new integer reflecting the combination of the two
13833     * states.
13834     */
13835    public static int combineMeasuredStates(int curState, int newState) {
13836        return curState | newState;
13837    }
13838
13839    /**
13840     * Version of {@link #resolveSizeAndState(int, int, int)}
13841     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13842     */
13843    public static int resolveSize(int size, int measureSpec) {
13844        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13845    }
13846
13847    /**
13848     * Utility to reconcile a desired size and state, with constraints imposed
13849     * by a MeasureSpec.  Will take the desired size, unless a different size
13850     * is imposed by the constraints.  The returned value is a compound integer,
13851     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13852     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13853     * size is smaller than the size the view wants to be.
13854     *
13855     * @param size How big the view wants to be
13856     * @param measureSpec Constraints imposed by the parent
13857     * @return Size information bit mask as defined by
13858     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13859     */
13860    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13861        int result = size;
13862        int specMode = MeasureSpec.getMode(measureSpec);
13863        int specSize =  MeasureSpec.getSize(measureSpec);
13864        switch (specMode) {
13865        case MeasureSpec.UNSPECIFIED:
13866            result = size;
13867            break;
13868        case MeasureSpec.AT_MOST:
13869            if (specSize < size) {
13870                result = specSize | MEASURED_STATE_TOO_SMALL;
13871            } else {
13872                result = size;
13873            }
13874            break;
13875        case MeasureSpec.EXACTLY:
13876            result = specSize;
13877            break;
13878        }
13879        return result | (childMeasuredState&MEASURED_STATE_MASK);
13880    }
13881
13882    /**
13883     * Utility to return a default size. Uses the supplied size if the
13884     * MeasureSpec imposed no constraints. Will get larger if allowed
13885     * by the MeasureSpec.
13886     *
13887     * @param size Default size for this view
13888     * @param measureSpec Constraints imposed by the parent
13889     * @return The size this view should be.
13890     */
13891    public static int getDefaultSize(int size, int measureSpec) {
13892        int result = size;
13893        int specMode = MeasureSpec.getMode(measureSpec);
13894        int specSize = MeasureSpec.getSize(measureSpec);
13895
13896        switch (specMode) {
13897        case MeasureSpec.UNSPECIFIED:
13898            result = size;
13899            break;
13900        case MeasureSpec.AT_MOST:
13901        case MeasureSpec.EXACTLY:
13902            result = specSize;
13903            break;
13904        }
13905        return result;
13906    }
13907
13908    /**
13909     * Returns the suggested minimum height that the view should use. This
13910     * returns the maximum of the view's minimum height
13911     * and the background's minimum height
13912     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13913     * <p>
13914     * When being used in {@link #onMeasure(int, int)}, the caller should still
13915     * ensure the returned height is within the requirements of the parent.
13916     *
13917     * @return The suggested minimum height of the view.
13918     */
13919    protected int getSuggestedMinimumHeight() {
13920        int suggestedMinHeight = mMinHeight;
13921
13922        if (mBGDrawable != null) {
13923            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13924            if (suggestedMinHeight < bgMinHeight) {
13925                suggestedMinHeight = bgMinHeight;
13926            }
13927        }
13928
13929        return suggestedMinHeight;
13930    }
13931
13932    /**
13933     * Returns the suggested minimum width that the view should use. This
13934     * returns the maximum of the view's minimum width)
13935     * and the background's minimum width
13936     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13937     * <p>
13938     * When being used in {@link #onMeasure(int, int)}, the caller should still
13939     * ensure the returned width is within the requirements of the parent.
13940     *
13941     * @return The suggested minimum width of the view.
13942     */
13943    protected int getSuggestedMinimumWidth() {
13944        int suggestedMinWidth = mMinWidth;
13945
13946        if (mBGDrawable != null) {
13947            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13948            if (suggestedMinWidth < bgMinWidth) {
13949                suggestedMinWidth = bgMinWidth;
13950            }
13951        }
13952
13953        return suggestedMinWidth;
13954    }
13955
13956    /**
13957     * Sets the minimum height of the view. It is not guaranteed the view will
13958     * be able to achieve this minimum height (for example, if its parent layout
13959     * constrains it with less available height).
13960     *
13961     * @param minHeight The minimum height the view will try to be.
13962     */
13963    public void setMinimumHeight(int minHeight) {
13964        mMinHeight = minHeight;
13965    }
13966
13967    /**
13968     * Sets the minimum width of the view. It is not guaranteed the view will
13969     * be able to achieve this minimum width (for example, if its parent layout
13970     * constrains it with less available width).
13971     *
13972     * @param minWidth The minimum width the view will try to be.
13973     */
13974    public void setMinimumWidth(int minWidth) {
13975        mMinWidth = minWidth;
13976    }
13977
13978    /**
13979     * Get the animation currently associated with this view.
13980     *
13981     * @return The animation that is currently playing or
13982     *         scheduled to play for this view.
13983     */
13984    public Animation getAnimation() {
13985        return mCurrentAnimation;
13986    }
13987
13988    /**
13989     * Start the specified animation now.
13990     *
13991     * @param animation the animation to start now
13992     */
13993    public void startAnimation(Animation animation) {
13994        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13995        setAnimation(animation);
13996        invalidateParentCaches();
13997        invalidate(true);
13998    }
13999
14000    /**
14001     * Cancels any animations for this view.
14002     */
14003    public void clearAnimation() {
14004        if (mCurrentAnimation != null) {
14005            mCurrentAnimation.detach();
14006        }
14007        mCurrentAnimation = null;
14008        invalidateParentIfNeeded();
14009    }
14010
14011    /**
14012     * Sets the next animation to play for this view.
14013     * If you want the animation to play immediately, use
14014     * startAnimation. This method provides allows fine-grained
14015     * control over the start time and invalidation, but you
14016     * must make sure that 1) the animation has a start time set, and
14017     * 2) the view will be invalidated when the animation is supposed to
14018     * start.
14019     *
14020     * @param animation The next animation, or null.
14021     */
14022    public void setAnimation(Animation animation) {
14023        mCurrentAnimation = animation;
14024        if (animation != null) {
14025            animation.reset();
14026        }
14027    }
14028
14029    /**
14030     * Invoked by a parent ViewGroup to notify the start of the animation
14031     * currently associated with this view. If you override this method,
14032     * always call super.onAnimationStart();
14033     *
14034     * @see #setAnimation(android.view.animation.Animation)
14035     * @see #getAnimation()
14036     */
14037    protected void onAnimationStart() {
14038        mPrivateFlags |= ANIMATION_STARTED;
14039    }
14040
14041    /**
14042     * Invoked by a parent ViewGroup to notify the end of the animation
14043     * currently associated with this view. If you override this method,
14044     * always call super.onAnimationEnd();
14045     *
14046     * @see #setAnimation(android.view.animation.Animation)
14047     * @see #getAnimation()
14048     */
14049    protected void onAnimationEnd() {
14050        mPrivateFlags &= ~ANIMATION_STARTED;
14051    }
14052
14053    /**
14054     * Invoked if there is a Transform that involves alpha. Subclass that can
14055     * draw themselves with the specified alpha should return true, and then
14056     * respect that alpha when their onDraw() is called. If this returns false
14057     * then the view may be redirected to draw into an offscreen buffer to
14058     * fulfill the request, which will look fine, but may be slower than if the
14059     * subclass handles it internally. The default implementation returns false.
14060     *
14061     * @param alpha The alpha (0..255) to apply to the view's drawing
14062     * @return true if the view can draw with the specified alpha.
14063     */
14064    protected boolean onSetAlpha(int alpha) {
14065        return false;
14066    }
14067
14068    /**
14069     * This is used by the RootView to perform an optimization when
14070     * the view hierarchy contains one or several SurfaceView.
14071     * SurfaceView is always considered transparent, but its children are not,
14072     * therefore all View objects remove themselves from the global transparent
14073     * region (passed as a parameter to this function).
14074     *
14075     * @param region The transparent region for this ViewAncestor (window).
14076     *
14077     * @return Returns true if the effective visibility of the view at this
14078     * point is opaque, regardless of the transparent region; returns false
14079     * if it is possible for underlying windows to be seen behind the view.
14080     *
14081     * {@hide}
14082     */
14083    public boolean gatherTransparentRegion(Region region) {
14084        final AttachInfo attachInfo = mAttachInfo;
14085        if (region != null && attachInfo != null) {
14086            final int pflags = mPrivateFlags;
14087            if ((pflags & SKIP_DRAW) == 0) {
14088                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
14089                // remove it from the transparent region.
14090                final int[] location = attachInfo.mTransparentLocation;
14091                getLocationInWindow(location);
14092                region.op(location[0], location[1], location[0] + mRight - mLeft,
14093                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
14094            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
14095                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
14096                // exists, so we remove the background drawable's non-transparent
14097                // parts from this transparent region.
14098                applyDrawableToTransparentRegion(mBGDrawable, region);
14099            }
14100        }
14101        return true;
14102    }
14103
14104    /**
14105     * Play a sound effect for this view.
14106     *
14107     * <p>The framework will play sound effects for some built in actions, such as
14108     * clicking, but you may wish to play these effects in your widget,
14109     * for instance, for internal navigation.
14110     *
14111     * <p>The sound effect will only be played if sound effects are enabled by the user, and
14112     * {@link #isSoundEffectsEnabled()} is true.
14113     *
14114     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
14115     */
14116    public void playSoundEffect(int soundConstant) {
14117        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
14118            return;
14119        }
14120        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
14121    }
14122
14123    /**
14124     * BZZZTT!!1!
14125     *
14126     * <p>Provide haptic feedback to the user for this view.
14127     *
14128     * <p>The framework will provide haptic feedback for some built in actions,
14129     * such as long presses, but you may wish to provide feedback for your
14130     * own widget.
14131     *
14132     * <p>The feedback will only be performed if
14133     * {@link #isHapticFeedbackEnabled()} is true.
14134     *
14135     * @param feedbackConstant One of the constants defined in
14136     * {@link HapticFeedbackConstants}
14137     */
14138    public boolean performHapticFeedback(int feedbackConstant) {
14139        return performHapticFeedback(feedbackConstant, 0);
14140    }
14141
14142    /**
14143     * BZZZTT!!1!
14144     *
14145     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
14146     *
14147     * @param feedbackConstant One of the constants defined in
14148     * {@link HapticFeedbackConstants}
14149     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
14150     */
14151    public boolean performHapticFeedback(int feedbackConstant, int flags) {
14152        if (mAttachInfo == null) {
14153            return false;
14154        }
14155        //noinspection SimplifiableIfStatement
14156        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
14157                && !isHapticFeedbackEnabled()) {
14158            return false;
14159        }
14160        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
14161                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
14162    }
14163
14164    /**
14165     * Request that the visibility of the status bar be changed.
14166     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14167     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
14168     */
14169    public void setSystemUiVisibility(int visibility) {
14170        if (visibility != mSystemUiVisibility) {
14171            mSystemUiVisibility = visibility;
14172            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
14173                mParent.recomputeViewAttributes(this);
14174            }
14175        }
14176    }
14177
14178    /**
14179     * Returns the status bar visibility that this view has requested.
14180     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14181     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
14182     */
14183    public int getSystemUiVisibility() {
14184        return mSystemUiVisibility;
14185    }
14186
14187    /**
14188     * Returns the current system UI visibility that is currently set for
14189     * the entire window.  This is the combination of the
14190     * {@link #setSystemUiVisibility(int)} values supplied by all of the
14191     * views in the window.
14192     */
14193    public int getWindowSystemUiVisibility() {
14194        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
14195    }
14196
14197    /**
14198     * Override to find out when the window's requested system UI visibility
14199     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
14200     * This is different from the callbacks recieved through
14201     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
14202     * in that this is only telling you about the local request of the window,
14203     * not the actual values applied by the system.
14204     */
14205    public void onWindowSystemUiVisibilityChanged(int visible) {
14206    }
14207
14208    /**
14209     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
14210     * the view hierarchy.
14211     */
14212    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
14213        onWindowSystemUiVisibilityChanged(visible);
14214    }
14215
14216    /**
14217     * Set a listener to receive callbacks when the visibility of the system bar changes.
14218     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
14219     */
14220    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
14221        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
14222        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
14223            mParent.recomputeViewAttributes(this);
14224        }
14225    }
14226
14227    /**
14228     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
14229     * the view hierarchy.
14230     */
14231    public void dispatchSystemUiVisibilityChanged(int visibility) {
14232        ListenerInfo li = mListenerInfo;
14233        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
14234            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
14235                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
14236        }
14237    }
14238
14239    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
14240        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
14241        if (val != mSystemUiVisibility) {
14242            setSystemUiVisibility(val);
14243        }
14244    }
14245
14246    /**
14247     * Creates an image that the system displays during the drag and drop
14248     * operation. This is called a &quot;drag shadow&quot;. The default implementation
14249     * for a DragShadowBuilder based on a View returns an image that has exactly the same
14250     * appearance as the given View. The default also positions the center of the drag shadow
14251     * directly under the touch point. If no View is provided (the constructor with no parameters
14252     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
14253     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
14254     * default is an invisible drag shadow.
14255     * <p>
14256     * You are not required to use the View you provide to the constructor as the basis of the
14257     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
14258     * anything you want as the drag shadow.
14259     * </p>
14260     * <p>
14261     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
14262     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
14263     *  size and position of the drag shadow. It uses this data to construct a
14264     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
14265     *  so that your application can draw the shadow image in the Canvas.
14266     * </p>
14267     *
14268     * <div class="special reference">
14269     * <h3>Developer Guides</h3>
14270     * <p>For a guide to implementing drag and drop features, read the
14271     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14272     * </div>
14273     */
14274    public static class DragShadowBuilder {
14275        private final WeakReference<View> mView;
14276
14277        /**
14278         * Constructs a shadow image builder based on a View. By default, the resulting drag
14279         * shadow will have the same appearance and dimensions as the View, with the touch point
14280         * over the center of the View.
14281         * @param view A View. Any View in scope can be used.
14282         */
14283        public DragShadowBuilder(View view) {
14284            mView = new WeakReference<View>(view);
14285        }
14286
14287        /**
14288         * Construct a shadow builder object with no associated View.  This
14289         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
14290         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
14291         * to supply the drag shadow's dimensions and appearance without
14292         * reference to any View object. If they are not overridden, then the result is an
14293         * invisible drag shadow.
14294         */
14295        public DragShadowBuilder() {
14296            mView = new WeakReference<View>(null);
14297        }
14298
14299        /**
14300         * Returns the View object that had been passed to the
14301         * {@link #View.DragShadowBuilder(View)}
14302         * constructor.  If that View parameter was {@code null} or if the
14303         * {@link #View.DragShadowBuilder()}
14304         * constructor was used to instantiate the builder object, this method will return
14305         * null.
14306         *
14307         * @return The View object associate with this builder object.
14308         */
14309        @SuppressWarnings({"JavadocReference"})
14310        final public View getView() {
14311            return mView.get();
14312        }
14313
14314        /**
14315         * Provides the metrics for the shadow image. These include the dimensions of
14316         * the shadow image, and the point within that shadow that should
14317         * be centered under the touch location while dragging.
14318         * <p>
14319         * The default implementation sets the dimensions of the shadow to be the
14320         * same as the dimensions of the View itself and centers the shadow under
14321         * the touch point.
14322         * </p>
14323         *
14324         * @param shadowSize A {@link android.graphics.Point} containing the width and height
14325         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
14326         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
14327         * image.
14328         *
14329         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
14330         * shadow image that should be underneath the touch point during the drag and drop
14331         * operation. Your application must set {@link android.graphics.Point#x} to the
14332         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
14333         */
14334        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
14335            final View view = mView.get();
14336            if (view != null) {
14337                shadowSize.set(view.getWidth(), view.getHeight());
14338                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
14339            } else {
14340                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
14341            }
14342        }
14343
14344        /**
14345         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
14346         * based on the dimensions it received from the
14347         * {@link #onProvideShadowMetrics(Point, Point)} callback.
14348         *
14349         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
14350         */
14351        public void onDrawShadow(Canvas canvas) {
14352            final View view = mView.get();
14353            if (view != null) {
14354                view.draw(canvas);
14355            } else {
14356                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
14357            }
14358        }
14359    }
14360
14361    /**
14362     * Starts a drag and drop operation. When your application calls this method, it passes a
14363     * {@link android.view.View.DragShadowBuilder} object to the system. The
14364     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
14365     * to get metrics for the drag shadow, and then calls the object's
14366     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
14367     * <p>
14368     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
14369     *  drag events to all the View objects in your application that are currently visible. It does
14370     *  this either by calling the View object's drag listener (an implementation of
14371     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
14372     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
14373     *  Both are passed a {@link android.view.DragEvent} object that has a
14374     *  {@link android.view.DragEvent#getAction()} value of
14375     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
14376     * </p>
14377     * <p>
14378     * Your application can invoke startDrag() on any attached View object. The View object does not
14379     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
14380     * be related to the View the user selected for dragging.
14381     * </p>
14382     * @param data A {@link android.content.ClipData} object pointing to the data to be
14383     * transferred by the drag and drop operation.
14384     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
14385     * drag shadow.
14386     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
14387     * drop operation. This Object is put into every DragEvent object sent by the system during the
14388     * current drag.
14389     * <p>
14390     * myLocalState is a lightweight mechanism for the sending information from the dragged View
14391     * to the target Views. For example, it can contain flags that differentiate between a
14392     * a copy operation and a move operation.
14393     * </p>
14394     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
14395     * so the parameter should be set to 0.
14396     * @return {@code true} if the method completes successfully, or
14397     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
14398     * do a drag, and so no drag operation is in progress.
14399     */
14400    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
14401            Object myLocalState, int flags) {
14402        if (ViewDebug.DEBUG_DRAG) {
14403            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
14404        }
14405        boolean okay = false;
14406
14407        Point shadowSize = new Point();
14408        Point shadowTouchPoint = new Point();
14409        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
14410
14411        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
14412                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
14413            throw new IllegalStateException("Drag shadow dimensions must not be negative");
14414        }
14415
14416        if (ViewDebug.DEBUG_DRAG) {
14417            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
14418                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
14419        }
14420        Surface surface = new Surface();
14421        try {
14422            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
14423                    flags, shadowSize.x, shadowSize.y, surface);
14424            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
14425                    + " surface=" + surface);
14426            if (token != null) {
14427                Canvas canvas = surface.lockCanvas(null);
14428                try {
14429                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
14430                    shadowBuilder.onDrawShadow(canvas);
14431                } finally {
14432                    surface.unlockCanvasAndPost(canvas);
14433                }
14434
14435                final ViewRootImpl root = getViewRootImpl();
14436
14437                // Cache the local state object for delivery with DragEvents
14438                root.setLocalDragState(myLocalState);
14439
14440                // repurpose 'shadowSize' for the last touch point
14441                root.getLastTouchPoint(shadowSize);
14442
14443                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
14444                        shadowSize.x, shadowSize.y,
14445                        shadowTouchPoint.x, shadowTouchPoint.y, data);
14446                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
14447
14448                // Off and running!  Release our local surface instance; the drag
14449                // shadow surface is now managed by the system process.
14450                surface.release();
14451            }
14452        } catch (Exception e) {
14453            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
14454            surface.destroy();
14455        }
14456
14457        return okay;
14458    }
14459
14460    /**
14461     * Handles drag events sent by the system following a call to
14462     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
14463     *<p>
14464     * When the system calls this method, it passes a
14465     * {@link android.view.DragEvent} object. A call to
14466     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
14467     * in DragEvent. The method uses these to determine what is happening in the drag and drop
14468     * operation.
14469     * @param event The {@link android.view.DragEvent} sent by the system.
14470     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
14471     * in DragEvent, indicating the type of drag event represented by this object.
14472     * @return {@code true} if the method was successful, otherwise {@code false}.
14473     * <p>
14474     *  The method should return {@code true} in response to an action type of
14475     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
14476     *  operation.
14477     * </p>
14478     * <p>
14479     *  The method should also return {@code true} in response to an action type of
14480     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
14481     *  {@code false} if it didn't.
14482     * </p>
14483     */
14484    public boolean onDragEvent(DragEvent event) {
14485        return false;
14486    }
14487
14488    /**
14489     * Detects if this View is enabled and has a drag event listener.
14490     * If both are true, then it calls the drag event listener with the
14491     * {@link android.view.DragEvent} it received. If the drag event listener returns
14492     * {@code true}, then dispatchDragEvent() returns {@code true}.
14493     * <p>
14494     * For all other cases, the method calls the
14495     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
14496     * method and returns its result.
14497     * </p>
14498     * <p>
14499     * This ensures that a drag event is always consumed, even if the View does not have a drag
14500     * event listener. However, if the View has a listener and the listener returns true, then
14501     * onDragEvent() is not called.
14502     * </p>
14503     */
14504    public boolean dispatchDragEvent(DragEvent event) {
14505        //noinspection SimplifiableIfStatement
14506        ListenerInfo li = mListenerInfo;
14507        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
14508                && li.mOnDragListener.onDrag(this, event)) {
14509            return true;
14510        }
14511        return onDragEvent(event);
14512    }
14513
14514    boolean canAcceptDrag() {
14515        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
14516    }
14517
14518    /**
14519     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
14520     * it is ever exposed at all.
14521     * @hide
14522     */
14523    public void onCloseSystemDialogs(String reason) {
14524    }
14525
14526    /**
14527     * Given a Drawable whose bounds have been set to draw into this view,
14528     * update a Region being computed for
14529     * {@link #gatherTransparentRegion(android.graphics.Region)} so
14530     * that any non-transparent parts of the Drawable are removed from the
14531     * given transparent region.
14532     *
14533     * @param dr The Drawable whose transparency is to be applied to the region.
14534     * @param region A Region holding the current transparency information,
14535     * where any parts of the region that are set are considered to be
14536     * transparent.  On return, this region will be modified to have the
14537     * transparency information reduced by the corresponding parts of the
14538     * Drawable that are not transparent.
14539     * {@hide}
14540     */
14541    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
14542        if (DBG) {
14543            Log.i("View", "Getting transparent region for: " + this);
14544        }
14545        final Region r = dr.getTransparentRegion();
14546        final Rect db = dr.getBounds();
14547        final AttachInfo attachInfo = mAttachInfo;
14548        if (r != null && attachInfo != null) {
14549            final int w = getRight()-getLeft();
14550            final int h = getBottom()-getTop();
14551            if (db.left > 0) {
14552                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
14553                r.op(0, 0, db.left, h, Region.Op.UNION);
14554            }
14555            if (db.right < w) {
14556                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
14557                r.op(db.right, 0, w, h, Region.Op.UNION);
14558            }
14559            if (db.top > 0) {
14560                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
14561                r.op(0, 0, w, db.top, Region.Op.UNION);
14562            }
14563            if (db.bottom < h) {
14564                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
14565                r.op(0, db.bottom, w, h, Region.Op.UNION);
14566            }
14567            final int[] location = attachInfo.mTransparentLocation;
14568            getLocationInWindow(location);
14569            r.translate(location[0], location[1]);
14570            region.op(r, Region.Op.INTERSECT);
14571        } else {
14572            region.op(db, Region.Op.DIFFERENCE);
14573        }
14574    }
14575
14576    private void checkForLongClick(int delayOffset) {
14577        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
14578            mHasPerformedLongPress = false;
14579
14580            if (mPendingCheckForLongPress == null) {
14581                mPendingCheckForLongPress = new CheckForLongPress();
14582            }
14583            mPendingCheckForLongPress.rememberWindowAttachCount();
14584            postDelayed(mPendingCheckForLongPress,
14585                    ViewConfiguration.getLongPressTimeout() - delayOffset);
14586        }
14587    }
14588
14589    /**
14590     * Inflate a view from an XML resource.  This convenience method wraps the {@link
14591     * LayoutInflater} class, which provides a full range of options for view inflation.
14592     *
14593     * @param context The Context object for your activity or application.
14594     * @param resource The resource ID to inflate
14595     * @param root A view group that will be the parent.  Used to properly inflate the
14596     * layout_* parameters.
14597     * @see LayoutInflater
14598     */
14599    public static View inflate(Context context, int resource, ViewGroup root) {
14600        LayoutInflater factory = LayoutInflater.from(context);
14601        return factory.inflate(resource, root);
14602    }
14603
14604    /**
14605     * Scroll the view with standard behavior for scrolling beyond the normal
14606     * content boundaries. Views that call this method should override
14607     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
14608     * results of an over-scroll operation.
14609     *
14610     * Views can use this method to handle any touch or fling-based scrolling.
14611     *
14612     * @param deltaX Change in X in pixels
14613     * @param deltaY Change in Y in pixels
14614     * @param scrollX Current X scroll value in pixels before applying deltaX
14615     * @param scrollY Current Y scroll value in pixels before applying deltaY
14616     * @param scrollRangeX Maximum content scroll range along the X axis
14617     * @param scrollRangeY Maximum content scroll range along the Y axis
14618     * @param maxOverScrollX Number of pixels to overscroll by in either direction
14619     *          along the X axis.
14620     * @param maxOverScrollY Number of pixels to overscroll by in either direction
14621     *          along the Y axis.
14622     * @param isTouchEvent true if this scroll operation is the result of a touch event.
14623     * @return true if scrolling was clamped to an over-scroll boundary along either
14624     *          axis, false otherwise.
14625     */
14626    @SuppressWarnings({"UnusedParameters"})
14627    protected boolean overScrollBy(int deltaX, int deltaY,
14628            int scrollX, int scrollY,
14629            int scrollRangeX, int scrollRangeY,
14630            int maxOverScrollX, int maxOverScrollY,
14631            boolean isTouchEvent) {
14632        final int overScrollMode = mOverScrollMode;
14633        final boolean canScrollHorizontal =
14634                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
14635        final boolean canScrollVertical =
14636                computeVerticalScrollRange() > computeVerticalScrollExtent();
14637        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
14638                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
14639        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
14640                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
14641
14642        int newScrollX = scrollX + deltaX;
14643        if (!overScrollHorizontal) {
14644            maxOverScrollX = 0;
14645        }
14646
14647        int newScrollY = scrollY + deltaY;
14648        if (!overScrollVertical) {
14649            maxOverScrollY = 0;
14650        }
14651
14652        // Clamp values if at the limits and record
14653        final int left = -maxOverScrollX;
14654        final int right = maxOverScrollX + scrollRangeX;
14655        final int top = -maxOverScrollY;
14656        final int bottom = maxOverScrollY + scrollRangeY;
14657
14658        boolean clampedX = false;
14659        if (newScrollX > right) {
14660            newScrollX = right;
14661            clampedX = true;
14662        } else if (newScrollX < left) {
14663            newScrollX = left;
14664            clampedX = true;
14665        }
14666
14667        boolean clampedY = false;
14668        if (newScrollY > bottom) {
14669            newScrollY = bottom;
14670            clampedY = true;
14671        } else if (newScrollY < top) {
14672            newScrollY = top;
14673            clampedY = true;
14674        }
14675
14676        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
14677
14678        return clampedX || clampedY;
14679    }
14680
14681    /**
14682     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
14683     * respond to the results of an over-scroll operation.
14684     *
14685     * @param scrollX New X scroll value in pixels
14686     * @param scrollY New Y scroll value in pixels
14687     * @param clampedX True if scrollX was clamped to an over-scroll boundary
14688     * @param clampedY True if scrollY was clamped to an over-scroll boundary
14689     */
14690    protected void onOverScrolled(int scrollX, int scrollY,
14691            boolean clampedX, boolean clampedY) {
14692        // Intentionally empty.
14693    }
14694
14695    /**
14696     * Returns the over-scroll mode for this view. The result will be
14697     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14698     * (allow over-scrolling only if the view content is larger than the container),
14699     * or {@link #OVER_SCROLL_NEVER}.
14700     *
14701     * @return This view's over-scroll mode.
14702     */
14703    public int getOverScrollMode() {
14704        return mOverScrollMode;
14705    }
14706
14707    /**
14708     * Set the over-scroll mode for this view. Valid over-scroll modes are
14709     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14710     * (allow over-scrolling only if the view content is larger than the container),
14711     * or {@link #OVER_SCROLL_NEVER}.
14712     *
14713     * Setting the over-scroll mode of a view will have an effect only if the
14714     * view is capable of scrolling.
14715     *
14716     * @param overScrollMode The new over-scroll mode for this view.
14717     */
14718    public void setOverScrollMode(int overScrollMode) {
14719        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14720                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14721                overScrollMode != OVER_SCROLL_NEVER) {
14722            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14723        }
14724        mOverScrollMode = overScrollMode;
14725    }
14726
14727    /**
14728     * Gets a scale factor that determines the distance the view should scroll
14729     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14730     * @return The vertical scroll scale factor.
14731     * @hide
14732     */
14733    protected float getVerticalScrollFactor() {
14734        if (mVerticalScrollFactor == 0) {
14735            TypedValue outValue = new TypedValue();
14736            if (!mContext.getTheme().resolveAttribute(
14737                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14738                throw new IllegalStateException(
14739                        "Expected theme to define listPreferredItemHeight.");
14740            }
14741            mVerticalScrollFactor = outValue.getDimension(
14742                    mContext.getResources().getDisplayMetrics());
14743        }
14744        return mVerticalScrollFactor;
14745    }
14746
14747    /**
14748     * Gets a scale factor that determines the distance the view should scroll
14749     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14750     * @return The horizontal scroll scale factor.
14751     * @hide
14752     */
14753    protected float getHorizontalScrollFactor() {
14754        // TODO: Should use something else.
14755        return getVerticalScrollFactor();
14756    }
14757
14758    /**
14759     * Return the value specifying the text direction or policy that was set with
14760     * {@link #setTextDirection(int)}.
14761     *
14762     * @return the defined text direction. It can be one of:
14763     *
14764     * {@link #TEXT_DIRECTION_INHERIT},
14765     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14766     * {@link #TEXT_DIRECTION_ANY_RTL},
14767     * {@link #TEXT_DIRECTION_LTR},
14768     * {@link #TEXT_DIRECTION_RTL},
14769     * {@link #TEXT_DIRECTION_LOCALE},
14770     */
14771    @ViewDebug.ExportedProperty(category = "text", mapping = {
14772            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
14773            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
14774            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
14775            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
14776            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
14777            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
14778    })
14779    public int getTextDirection() {
14780        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
14781    }
14782
14783    /**
14784     * Set the text direction.
14785     *
14786     * @param textDirection the direction to set. Should be one of:
14787     *
14788     * {@link #TEXT_DIRECTION_INHERIT},
14789     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14790     * {@link #TEXT_DIRECTION_ANY_RTL},
14791     * {@link #TEXT_DIRECTION_LTR},
14792     * {@link #TEXT_DIRECTION_RTL},
14793     * {@link #TEXT_DIRECTION_LOCALE},
14794     */
14795    public void setTextDirection(int textDirection) {
14796        if (getTextDirection() != textDirection) {
14797            // Reset the current text direction and the resolved one
14798            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
14799            resetResolvedTextDirection();
14800            // Set the new text direction
14801            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
14802            requestLayout();
14803            invalidate(true);
14804        }
14805    }
14806
14807    /**
14808     * Return the resolved text direction.
14809     *
14810     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
14811     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
14812     * up the parent chain of the view. if there is no parent, then it will return the default
14813     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
14814     *
14815     * @return the resolved text direction. Returns one of:
14816     *
14817     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14818     * {@link #TEXT_DIRECTION_ANY_RTL},
14819     * {@link #TEXT_DIRECTION_LTR},
14820     * {@link #TEXT_DIRECTION_RTL},
14821     * {@link #TEXT_DIRECTION_LOCALE},
14822     */
14823    public int getResolvedTextDirection() {
14824        // The text direction will be resolved only if needed
14825        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
14826            resolveTextDirection();
14827        }
14828        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
14829    }
14830
14831    /**
14832     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
14833     * resolution is done.
14834     */
14835    public void resolveTextDirection() {
14836        // Reset any previous text direction resolution
14837        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
14838
14839        if (hasRtlSupport()) {
14840            // Set resolved text direction flag depending on text direction flag
14841            final int textDirection = getTextDirection();
14842            switch(textDirection) {
14843                case TEXT_DIRECTION_INHERIT:
14844                    if (canResolveTextDirection()) {
14845                        ViewGroup viewGroup = ((ViewGroup) mParent);
14846
14847                        // Set current resolved direction to the same value as the parent's one
14848                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
14849                        switch (parentResolvedDirection) {
14850                            case TEXT_DIRECTION_FIRST_STRONG:
14851                            case TEXT_DIRECTION_ANY_RTL:
14852                            case TEXT_DIRECTION_LTR:
14853                            case TEXT_DIRECTION_RTL:
14854                            case TEXT_DIRECTION_LOCALE:
14855                                mPrivateFlags2 |=
14856                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
14857                                break;
14858                            default:
14859                                // Default resolved direction is "first strong" heuristic
14860                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14861                        }
14862                    } else {
14863                        // We cannot do the resolution if there is no parent, so use the default one
14864                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14865                    }
14866                    break;
14867                case TEXT_DIRECTION_FIRST_STRONG:
14868                case TEXT_DIRECTION_ANY_RTL:
14869                case TEXT_DIRECTION_LTR:
14870                case TEXT_DIRECTION_RTL:
14871                case TEXT_DIRECTION_LOCALE:
14872                    // Resolved direction is the same as text direction
14873                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
14874                    break;
14875                default:
14876                    // Default resolved direction is "first strong" heuristic
14877                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14878            }
14879        } else {
14880            // Default resolved direction is "first strong" heuristic
14881            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14882        }
14883
14884        // Set to resolved
14885        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
14886        onResolvedTextDirectionChanged();
14887    }
14888
14889    /**
14890     * Called when text direction has been resolved. Subclasses that care about text direction
14891     * resolution should override this method.
14892     *
14893     * The default implementation does nothing.
14894     */
14895    public void onResolvedTextDirectionChanged() {
14896    }
14897
14898    /**
14899     * Check if text direction resolution can be done.
14900     *
14901     * @return true if text direction resolution can be done otherwise return false.
14902     */
14903    public boolean canResolveTextDirection() {
14904        switch (getTextDirection()) {
14905            case TEXT_DIRECTION_INHERIT:
14906                return (mParent != null) && (mParent instanceof ViewGroup);
14907            default:
14908                return true;
14909        }
14910    }
14911
14912    /**
14913     * Reset resolved text direction. Text direction can be resolved with a call to
14914     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
14915     * reset is done.
14916     */
14917    public void resetResolvedTextDirection() {
14918        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
14919        onResolvedTextDirectionReset();
14920    }
14921
14922    /**
14923     * Called when text direction is reset. Subclasses that care about text direction reset should
14924     * override this method and do a reset of the text direction of their children. The default
14925     * implementation does nothing.
14926     */
14927    public void onResolvedTextDirectionReset() {
14928    }
14929
14930    //
14931    // Properties
14932    //
14933    /**
14934     * A Property wrapper around the <code>alpha</code> functionality handled by the
14935     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14936     */
14937    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14938        @Override
14939        public void setValue(View object, float value) {
14940            object.setAlpha(value);
14941        }
14942
14943        @Override
14944        public Float get(View object) {
14945            return object.getAlpha();
14946        }
14947    };
14948
14949    /**
14950     * A Property wrapper around the <code>translationX</code> functionality handled by the
14951     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14952     */
14953    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14954        @Override
14955        public void setValue(View object, float value) {
14956            object.setTranslationX(value);
14957        }
14958
14959                @Override
14960        public Float get(View object) {
14961            return object.getTranslationX();
14962        }
14963    };
14964
14965    /**
14966     * A Property wrapper around the <code>translationY</code> functionality handled by the
14967     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14968     */
14969    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14970        @Override
14971        public void setValue(View object, float value) {
14972            object.setTranslationY(value);
14973        }
14974
14975        @Override
14976        public Float get(View object) {
14977            return object.getTranslationY();
14978        }
14979    };
14980
14981    /**
14982     * A Property wrapper around the <code>x</code> functionality handled by the
14983     * {@link View#setX(float)} and {@link View#getX()} methods.
14984     */
14985    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14986        @Override
14987        public void setValue(View object, float value) {
14988            object.setX(value);
14989        }
14990
14991        @Override
14992        public Float get(View object) {
14993            return object.getX();
14994        }
14995    };
14996
14997    /**
14998     * A Property wrapper around the <code>y</code> functionality handled by the
14999     * {@link View#setY(float)} and {@link View#getY()} methods.
15000     */
15001    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
15002        @Override
15003        public void setValue(View object, float value) {
15004            object.setY(value);
15005        }
15006
15007        @Override
15008        public Float get(View object) {
15009            return object.getY();
15010        }
15011    };
15012
15013    /**
15014     * A Property wrapper around the <code>rotation</code> functionality handled by the
15015     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
15016     */
15017    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
15018        @Override
15019        public void setValue(View object, float value) {
15020            object.setRotation(value);
15021        }
15022
15023        @Override
15024        public Float get(View object) {
15025            return object.getRotation();
15026        }
15027    };
15028
15029    /**
15030     * A Property wrapper around the <code>rotationX</code> functionality handled by the
15031     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
15032     */
15033    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
15034        @Override
15035        public void setValue(View object, float value) {
15036            object.setRotationX(value);
15037        }
15038
15039        @Override
15040        public Float get(View object) {
15041            return object.getRotationX();
15042        }
15043    };
15044
15045    /**
15046     * A Property wrapper around the <code>rotationY</code> functionality handled by the
15047     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
15048     */
15049    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
15050        @Override
15051        public void setValue(View object, float value) {
15052            object.setRotationY(value);
15053        }
15054
15055        @Override
15056        public Float get(View object) {
15057            return object.getRotationY();
15058        }
15059    };
15060
15061    /**
15062     * A Property wrapper around the <code>scaleX</code> functionality handled by the
15063     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
15064     */
15065    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
15066        @Override
15067        public void setValue(View object, float value) {
15068            object.setScaleX(value);
15069        }
15070
15071        @Override
15072        public Float get(View object) {
15073            return object.getScaleX();
15074        }
15075    };
15076
15077    /**
15078     * A Property wrapper around the <code>scaleY</code> functionality handled by the
15079     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
15080     */
15081    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
15082        @Override
15083        public void setValue(View object, float value) {
15084            object.setScaleY(value);
15085        }
15086
15087        @Override
15088        public Float get(View object) {
15089            return object.getScaleY();
15090        }
15091    };
15092
15093    /**
15094     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
15095     * Each MeasureSpec represents a requirement for either the width or the height.
15096     * A MeasureSpec is comprised of a size and a mode. There are three possible
15097     * modes:
15098     * <dl>
15099     * <dt>UNSPECIFIED</dt>
15100     * <dd>
15101     * The parent has not imposed any constraint on the child. It can be whatever size
15102     * it wants.
15103     * </dd>
15104     *
15105     * <dt>EXACTLY</dt>
15106     * <dd>
15107     * The parent has determined an exact size for the child. The child is going to be
15108     * given those bounds regardless of how big it wants to be.
15109     * </dd>
15110     *
15111     * <dt>AT_MOST</dt>
15112     * <dd>
15113     * The child can be as large as it wants up to the specified size.
15114     * </dd>
15115     * </dl>
15116     *
15117     * MeasureSpecs are implemented as ints to reduce object allocation. This class
15118     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
15119     */
15120    public static class MeasureSpec {
15121        private static final int MODE_SHIFT = 30;
15122        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
15123
15124        /**
15125         * Measure specification mode: The parent has not imposed any constraint
15126         * on the child. It can be whatever size it wants.
15127         */
15128        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
15129
15130        /**
15131         * Measure specification mode: The parent has determined an exact size
15132         * for the child. The child is going to be given those bounds regardless
15133         * of how big it wants to be.
15134         */
15135        public static final int EXACTLY     = 1 << MODE_SHIFT;
15136
15137        /**
15138         * Measure specification mode: The child can be as large as it wants up
15139         * to the specified size.
15140         */
15141        public static final int AT_MOST     = 2 << MODE_SHIFT;
15142
15143        /**
15144         * Creates a measure specification based on the supplied size and mode.
15145         *
15146         * The mode must always be one of the following:
15147         * <ul>
15148         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
15149         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
15150         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
15151         * </ul>
15152         *
15153         * @param size the size of the measure specification
15154         * @param mode the mode of the measure specification
15155         * @return the measure specification based on size and mode
15156         */
15157        public static int makeMeasureSpec(int size, int mode) {
15158            return size + mode;
15159        }
15160
15161        /**
15162         * Extracts the mode from the supplied measure specification.
15163         *
15164         * @param measureSpec the measure specification to extract the mode from
15165         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
15166         *         {@link android.view.View.MeasureSpec#AT_MOST} or
15167         *         {@link android.view.View.MeasureSpec#EXACTLY}
15168         */
15169        public static int getMode(int measureSpec) {
15170            return (measureSpec & MODE_MASK);
15171        }
15172
15173        /**
15174         * Extracts the size from the supplied measure specification.
15175         *
15176         * @param measureSpec the measure specification to extract the size from
15177         * @return the size in pixels defined in the supplied measure specification
15178         */
15179        public static int getSize(int measureSpec) {
15180            return (measureSpec & ~MODE_MASK);
15181        }
15182
15183        /**
15184         * Returns a String representation of the specified measure
15185         * specification.
15186         *
15187         * @param measureSpec the measure specification to convert to a String
15188         * @return a String with the following format: "MeasureSpec: MODE SIZE"
15189         */
15190        public static String toString(int measureSpec) {
15191            int mode = getMode(measureSpec);
15192            int size = getSize(measureSpec);
15193
15194            StringBuilder sb = new StringBuilder("MeasureSpec: ");
15195
15196            if (mode == UNSPECIFIED)
15197                sb.append("UNSPECIFIED ");
15198            else if (mode == EXACTLY)
15199                sb.append("EXACTLY ");
15200            else if (mode == AT_MOST)
15201                sb.append("AT_MOST ");
15202            else
15203                sb.append(mode).append(" ");
15204
15205            sb.append(size);
15206            return sb.toString();
15207        }
15208    }
15209
15210    class CheckForLongPress implements Runnable {
15211
15212        private int mOriginalWindowAttachCount;
15213
15214        public void run() {
15215            if (isPressed() && (mParent != null)
15216                    && mOriginalWindowAttachCount == mWindowAttachCount) {
15217                if (performLongClick()) {
15218                    mHasPerformedLongPress = true;
15219                }
15220            }
15221        }
15222
15223        public void rememberWindowAttachCount() {
15224            mOriginalWindowAttachCount = mWindowAttachCount;
15225        }
15226    }
15227
15228    private final class CheckForTap implements Runnable {
15229        public void run() {
15230            mPrivateFlags &= ~PREPRESSED;
15231            setPressed(true);
15232            checkForLongClick(ViewConfiguration.getTapTimeout());
15233        }
15234    }
15235
15236    private final class PerformClick implements Runnable {
15237        public void run() {
15238            performClick();
15239        }
15240    }
15241
15242    /** @hide */
15243    public void hackTurnOffWindowResizeAnim(boolean off) {
15244        mAttachInfo.mTurnOffWindowResizeAnim = off;
15245    }
15246
15247    /**
15248     * This method returns a ViewPropertyAnimator object, which can be used to animate
15249     * specific properties on this View.
15250     *
15251     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
15252     */
15253    public ViewPropertyAnimator animate() {
15254        if (mAnimator == null) {
15255            mAnimator = new ViewPropertyAnimator(this);
15256        }
15257        return mAnimator;
15258    }
15259
15260    /**
15261     * Interface definition for a callback to be invoked when a key event is
15262     * dispatched to this view. The callback will be invoked before the key
15263     * event is given to the view.
15264     */
15265    public interface OnKeyListener {
15266        /**
15267         * Called when a key is dispatched to a view. This allows listeners to
15268         * get a chance to respond before the target view.
15269         *
15270         * @param v The view the key has been dispatched to.
15271         * @param keyCode The code for the physical key that was pressed
15272         * @param event The KeyEvent object containing full information about
15273         *        the event.
15274         * @return True if the listener has consumed the event, false otherwise.
15275         */
15276        boolean onKey(View v, int keyCode, KeyEvent event);
15277    }
15278
15279    /**
15280     * Interface definition for a callback to be invoked when a touch event is
15281     * dispatched to this view. The callback will be invoked before the touch
15282     * event is given to the view.
15283     */
15284    public interface OnTouchListener {
15285        /**
15286         * Called when a touch event is dispatched to a view. This allows listeners to
15287         * get a chance to respond before the target view.
15288         *
15289         * @param v The view the touch event has been dispatched to.
15290         * @param event The MotionEvent object containing full information about
15291         *        the event.
15292         * @return True if the listener has consumed the event, false otherwise.
15293         */
15294        boolean onTouch(View v, MotionEvent event);
15295    }
15296
15297    /**
15298     * Interface definition for a callback to be invoked when a hover event is
15299     * dispatched to this view. The callback will be invoked before the hover
15300     * event is given to the view.
15301     */
15302    public interface OnHoverListener {
15303        /**
15304         * Called when a hover event is dispatched to a view. This allows listeners to
15305         * get a chance to respond before the target view.
15306         *
15307         * @param v The view the hover event has been dispatched to.
15308         * @param event The MotionEvent object containing full information about
15309         *        the event.
15310         * @return True if the listener has consumed the event, false otherwise.
15311         */
15312        boolean onHover(View v, MotionEvent event);
15313    }
15314
15315    /**
15316     * Interface definition for a callback to be invoked when a generic motion event is
15317     * dispatched to this view. The callback will be invoked before the generic motion
15318     * event is given to the view.
15319     */
15320    public interface OnGenericMotionListener {
15321        /**
15322         * Called when a generic motion event is dispatched to a view. This allows listeners to
15323         * get a chance to respond before the target view.
15324         *
15325         * @param v The view the generic motion event has been dispatched to.
15326         * @param event The MotionEvent object containing full information about
15327         *        the event.
15328         * @return True if the listener has consumed the event, false otherwise.
15329         */
15330        boolean onGenericMotion(View v, MotionEvent event);
15331    }
15332
15333    /**
15334     * Interface definition for a callback to be invoked when a view has been clicked and held.
15335     */
15336    public interface OnLongClickListener {
15337        /**
15338         * Called when a view has been clicked and held.
15339         *
15340         * @param v The view that was clicked and held.
15341         *
15342         * @return true if the callback consumed the long click, false otherwise.
15343         */
15344        boolean onLongClick(View v);
15345    }
15346
15347    /**
15348     * Interface definition for a callback to be invoked when a drag is being dispatched
15349     * to this view.  The callback will be invoked before the hosting view's own
15350     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
15351     * onDrag(event) behavior, it should return 'false' from this callback.
15352     *
15353     * <div class="special reference">
15354     * <h3>Developer Guides</h3>
15355     * <p>For a guide to implementing drag and drop features, read the
15356     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15357     * </div>
15358     */
15359    public interface OnDragListener {
15360        /**
15361         * Called when a drag event is dispatched to a view. This allows listeners
15362         * to get a chance to override base View behavior.
15363         *
15364         * @param v The View that received the drag event.
15365         * @param event The {@link android.view.DragEvent} object for the drag event.
15366         * @return {@code true} if the drag event was handled successfully, or {@code false}
15367         * if the drag event was not handled. Note that {@code false} will trigger the View
15368         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
15369         */
15370        boolean onDrag(View v, DragEvent event);
15371    }
15372
15373    /**
15374     * Interface definition for a callback to be invoked when the focus state of
15375     * a view changed.
15376     */
15377    public interface OnFocusChangeListener {
15378        /**
15379         * Called when the focus state of a view has changed.
15380         *
15381         * @param v The view whose state has changed.
15382         * @param hasFocus The new focus state of v.
15383         */
15384        void onFocusChange(View v, boolean hasFocus);
15385    }
15386
15387    /**
15388     * Interface definition for a callback to be invoked when a view is clicked.
15389     */
15390    public interface OnClickListener {
15391        /**
15392         * Called when a view has been clicked.
15393         *
15394         * @param v The view that was clicked.
15395         */
15396        void onClick(View v);
15397    }
15398
15399    /**
15400     * Interface definition for a callback to be invoked when the context menu
15401     * for this view is being built.
15402     */
15403    public interface OnCreateContextMenuListener {
15404        /**
15405         * Called when the context menu for this view is being built. It is not
15406         * safe to hold onto the menu after this method returns.
15407         *
15408         * @param menu The context menu that is being built
15409         * @param v The view for which the context menu is being built
15410         * @param menuInfo Extra information about the item for which the
15411         *            context menu should be shown. This information will vary
15412         *            depending on the class of v.
15413         */
15414        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
15415    }
15416
15417    /**
15418     * Interface definition for a callback to be invoked when the status bar changes
15419     * visibility.  This reports <strong>global</strong> changes to the system UI
15420     * state, not just what the application is requesting.
15421     *
15422     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
15423     */
15424    public interface OnSystemUiVisibilityChangeListener {
15425        /**
15426         * Called when the status bar changes visibility because of a call to
15427         * {@link View#setSystemUiVisibility(int)}.
15428         *
15429         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
15430         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
15431         * <strong>global</strong> state of the UI visibility flags, not what your
15432         * app is currently applying.
15433         */
15434        public void onSystemUiVisibilityChange(int visibility);
15435    }
15436
15437    /**
15438     * Interface definition for a callback to be invoked when this view is attached
15439     * or detached from its window.
15440     */
15441    public interface OnAttachStateChangeListener {
15442        /**
15443         * Called when the view is attached to a window.
15444         * @param v The view that was attached
15445         */
15446        public void onViewAttachedToWindow(View v);
15447        /**
15448         * Called when the view is detached from a window.
15449         * @param v The view that was detached
15450         */
15451        public void onViewDetachedFromWindow(View v);
15452    }
15453
15454    private final class UnsetPressedState implements Runnable {
15455        public void run() {
15456            setPressed(false);
15457        }
15458    }
15459
15460    /**
15461     * Base class for derived classes that want to save and restore their own
15462     * state in {@link android.view.View#onSaveInstanceState()}.
15463     */
15464    public static class BaseSavedState extends AbsSavedState {
15465        /**
15466         * Constructor used when reading from a parcel. Reads the state of the superclass.
15467         *
15468         * @param source
15469         */
15470        public BaseSavedState(Parcel source) {
15471            super(source);
15472        }
15473
15474        /**
15475         * Constructor called by derived classes when creating their SavedState objects
15476         *
15477         * @param superState The state of the superclass of this view
15478         */
15479        public BaseSavedState(Parcelable superState) {
15480            super(superState);
15481        }
15482
15483        public static final Parcelable.Creator<BaseSavedState> CREATOR =
15484                new Parcelable.Creator<BaseSavedState>() {
15485            public BaseSavedState createFromParcel(Parcel in) {
15486                return new BaseSavedState(in);
15487            }
15488
15489            public BaseSavedState[] newArray(int size) {
15490                return new BaseSavedState[size];
15491            }
15492        };
15493    }
15494
15495    /**
15496     * A set of information given to a view when it is attached to its parent
15497     * window.
15498     */
15499    static class AttachInfo {
15500        interface Callbacks {
15501            void playSoundEffect(int effectId);
15502            boolean performHapticFeedback(int effectId, boolean always);
15503        }
15504
15505        /**
15506         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
15507         * to a Handler. This class contains the target (View) to invalidate and
15508         * the coordinates of the dirty rectangle.
15509         *
15510         * For performance purposes, this class also implements a pool of up to
15511         * POOL_LIMIT objects that get reused. This reduces memory allocations
15512         * whenever possible.
15513         */
15514        static class InvalidateInfo implements Poolable<InvalidateInfo> {
15515            private static final int POOL_LIMIT = 10;
15516            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
15517                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
15518                        public InvalidateInfo newInstance() {
15519                            return new InvalidateInfo();
15520                        }
15521
15522                        public void onAcquired(InvalidateInfo element) {
15523                        }
15524
15525                        public void onReleased(InvalidateInfo element) {
15526                            element.target = null;
15527                        }
15528                    }, POOL_LIMIT)
15529            );
15530
15531            private InvalidateInfo mNext;
15532            private boolean mIsPooled;
15533
15534            View target;
15535
15536            int left;
15537            int top;
15538            int right;
15539            int bottom;
15540
15541            public void setNextPoolable(InvalidateInfo element) {
15542                mNext = element;
15543            }
15544
15545            public InvalidateInfo getNextPoolable() {
15546                return mNext;
15547            }
15548
15549            static InvalidateInfo acquire() {
15550                return sPool.acquire();
15551            }
15552
15553            void release() {
15554                sPool.release(this);
15555            }
15556
15557            public boolean isPooled() {
15558                return mIsPooled;
15559            }
15560
15561            public void setPooled(boolean isPooled) {
15562                mIsPooled = isPooled;
15563            }
15564        }
15565
15566        final IWindowSession mSession;
15567
15568        final IWindow mWindow;
15569
15570        final IBinder mWindowToken;
15571
15572        final Callbacks mRootCallbacks;
15573
15574        HardwareCanvas mHardwareCanvas;
15575
15576        /**
15577         * The top view of the hierarchy.
15578         */
15579        View mRootView;
15580
15581        IBinder mPanelParentWindowToken;
15582        Surface mSurface;
15583
15584        boolean mHardwareAccelerated;
15585        boolean mHardwareAccelerationRequested;
15586        HardwareRenderer mHardwareRenderer;
15587
15588        boolean mScreenOn;
15589
15590        /**
15591         * Scale factor used by the compatibility mode
15592         */
15593        float mApplicationScale;
15594
15595        /**
15596         * Indicates whether the application is in compatibility mode
15597         */
15598        boolean mScalingRequired;
15599
15600        /**
15601         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
15602         */
15603        boolean mTurnOffWindowResizeAnim;
15604
15605        /**
15606         * Left position of this view's window
15607         */
15608        int mWindowLeft;
15609
15610        /**
15611         * Top position of this view's window
15612         */
15613        int mWindowTop;
15614
15615        /**
15616         * Indicates whether views need to use 32-bit drawing caches
15617         */
15618        boolean mUse32BitDrawingCache;
15619
15620        /**
15621         * For windows that are full-screen but using insets to layout inside
15622         * of the screen decorations, these are the current insets for the
15623         * content of the window.
15624         */
15625        final Rect mContentInsets = new Rect();
15626
15627        /**
15628         * For windows that are full-screen but using insets to layout inside
15629         * of the screen decorations, these are the current insets for the
15630         * actual visible parts of the window.
15631         */
15632        final Rect mVisibleInsets = new Rect();
15633
15634        /**
15635         * The internal insets given by this window.  This value is
15636         * supplied by the client (through
15637         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
15638         * be given to the window manager when changed to be used in laying
15639         * out windows behind it.
15640         */
15641        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
15642                = new ViewTreeObserver.InternalInsetsInfo();
15643
15644        /**
15645         * All views in the window's hierarchy that serve as scroll containers,
15646         * used to determine if the window can be resized or must be panned
15647         * to adjust for a soft input area.
15648         */
15649        final ArrayList<View> mScrollContainers = new ArrayList<View>();
15650
15651        final KeyEvent.DispatcherState mKeyDispatchState
15652                = new KeyEvent.DispatcherState();
15653
15654        /**
15655         * Indicates whether the view's window currently has the focus.
15656         */
15657        boolean mHasWindowFocus;
15658
15659        /**
15660         * The current visibility of the window.
15661         */
15662        int mWindowVisibility;
15663
15664        /**
15665         * Indicates the time at which drawing started to occur.
15666         */
15667        long mDrawingTime;
15668
15669        /**
15670         * Indicates whether or not ignoring the DIRTY_MASK flags.
15671         */
15672        boolean mIgnoreDirtyState;
15673
15674        /**
15675         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
15676         * to avoid clearing that flag prematurely.
15677         */
15678        boolean mSetIgnoreDirtyState = false;
15679
15680        /**
15681         * Indicates whether the view's window is currently in touch mode.
15682         */
15683        boolean mInTouchMode;
15684
15685        /**
15686         * Indicates that ViewAncestor should trigger a global layout change
15687         * the next time it performs a traversal
15688         */
15689        boolean mRecomputeGlobalAttributes;
15690
15691        /**
15692         * Always report new attributes at next traversal.
15693         */
15694        boolean mForceReportNewAttributes;
15695
15696        /**
15697         * Set during a traveral if any views want to keep the screen on.
15698         */
15699        boolean mKeepScreenOn;
15700
15701        /**
15702         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
15703         */
15704        int mSystemUiVisibility;
15705
15706        /**
15707         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
15708         * attached.
15709         */
15710        boolean mHasSystemUiListeners;
15711
15712        /**
15713         * Set if the visibility of any views has changed.
15714         */
15715        boolean mViewVisibilityChanged;
15716
15717        /**
15718         * Set to true if a view has been scrolled.
15719         */
15720        boolean mViewScrollChanged;
15721
15722        /**
15723         * Global to the view hierarchy used as a temporary for dealing with
15724         * x/y points in the transparent region computations.
15725         */
15726        final int[] mTransparentLocation = new int[2];
15727
15728        /**
15729         * Global to the view hierarchy used as a temporary for dealing with
15730         * x/y points in the ViewGroup.invalidateChild implementation.
15731         */
15732        final int[] mInvalidateChildLocation = new int[2];
15733
15734
15735        /**
15736         * Global to the view hierarchy used as a temporary for dealing with
15737         * x/y location when view is transformed.
15738         */
15739        final float[] mTmpTransformLocation = new float[2];
15740
15741        /**
15742         * The view tree observer used to dispatch global events like
15743         * layout, pre-draw, touch mode change, etc.
15744         */
15745        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
15746
15747        /**
15748         * A Canvas used by the view hierarchy to perform bitmap caching.
15749         */
15750        Canvas mCanvas;
15751
15752        /**
15753         * The view root impl.
15754         */
15755        final ViewRootImpl mViewRootImpl;
15756
15757        /**
15758         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
15759         * handler can be used to pump events in the UI events queue.
15760         */
15761        final Handler mHandler;
15762
15763        /**
15764         * Temporary for use in computing invalidate rectangles while
15765         * calling up the hierarchy.
15766         */
15767        final Rect mTmpInvalRect = new Rect();
15768
15769        /**
15770         * Temporary for use in computing hit areas with transformed views
15771         */
15772        final RectF mTmpTransformRect = new RectF();
15773
15774        /**
15775         * Temporary list for use in collecting focusable descendents of a view.
15776         */
15777        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
15778
15779        /**
15780         * The id of the window for accessibility purposes.
15781         */
15782        int mAccessibilityWindowId = View.NO_ID;
15783
15784        /**
15785         * Creates a new set of attachment information with the specified
15786         * events handler and thread.
15787         *
15788         * @param handler the events handler the view must use
15789         */
15790        AttachInfo(IWindowSession session, IWindow window,
15791                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
15792            mSession = session;
15793            mWindow = window;
15794            mWindowToken = window.asBinder();
15795            mViewRootImpl = viewRootImpl;
15796            mHandler = handler;
15797            mRootCallbacks = effectPlayer;
15798        }
15799    }
15800
15801    /**
15802     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15803     * is supported. This avoids keeping too many unused fields in most
15804     * instances of View.</p>
15805     */
15806    private static class ScrollabilityCache implements Runnable {
15807
15808        /**
15809         * Scrollbars are not visible
15810         */
15811        public static final int OFF = 0;
15812
15813        /**
15814         * Scrollbars are visible
15815         */
15816        public static final int ON = 1;
15817
15818        /**
15819         * Scrollbars are fading away
15820         */
15821        public static final int FADING = 2;
15822
15823        public boolean fadeScrollBars;
15824
15825        public int fadingEdgeLength;
15826        public int scrollBarDefaultDelayBeforeFade;
15827        public int scrollBarFadeDuration;
15828
15829        public int scrollBarSize;
15830        public ScrollBarDrawable scrollBar;
15831        public float[] interpolatorValues;
15832        public View host;
15833
15834        public final Paint paint;
15835        public final Matrix matrix;
15836        public Shader shader;
15837
15838        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15839
15840        private static final float[] OPAQUE = { 255 };
15841        private static final float[] TRANSPARENT = { 0.0f };
15842
15843        /**
15844         * When fading should start. This time moves into the future every time
15845         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15846         */
15847        public long fadeStartTime;
15848
15849
15850        /**
15851         * The current state of the scrollbars: ON, OFF, or FADING
15852         */
15853        public int state = OFF;
15854
15855        private int mLastColor;
15856
15857        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15858            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15859            scrollBarSize = configuration.getScaledScrollBarSize();
15860            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15861            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15862
15863            paint = new Paint();
15864            matrix = new Matrix();
15865            // use use a height of 1, and then wack the matrix each time we
15866            // actually use it.
15867            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15868
15869            paint.setShader(shader);
15870            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15871            this.host = host;
15872        }
15873
15874        public void setFadeColor(int color) {
15875            if (color != 0 && color != mLastColor) {
15876                mLastColor = color;
15877                color |= 0xFF000000;
15878
15879                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15880                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15881
15882                paint.setShader(shader);
15883                // Restore the default transfer mode (src_over)
15884                paint.setXfermode(null);
15885            }
15886        }
15887
15888        public void run() {
15889            long now = AnimationUtils.currentAnimationTimeMillis();
15890            if (now >= fadeStartTime) {
15891
15892                // the animation fades the scrollbars out by changing
15893                // the opacity (alpha) from fully opaque to fully
15894                // transparent
15895                int nextFrame = (int) now;
15896                int framesCount = 0;
15897
15898                Interpolator interpolator = scrollBarInterpolator;
15899
15900                // Start opaque
15901                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15902
15903                // End transparent
15904                nextFrame += scrollBarFadeDuration;
15905                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15906
15907                state = FADING;
15908
15909                // Kick off the fade animation
15910                host.invalidate(true);
15911            }
15912        }
15913    }
15914
15915    /**
15916     * Resuable callback for sending
15917     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15918     */
15919    private class SendViewScrolledAccessibilityEvent implements Runnable {
15920        public volatile boolean mIsPending;
15921
15922        public void run() {
15923            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15924            mIsPending = false;
15925        }
15926    }
15927
15928    /**
15929     * <p>
15930     * This class represents a delegate that can be registered in a {@link View}
15931     * to enhance accessibility support via composition rather via inheritance.
15932     * It is specifically targeted to widget developers that extend basic View
15933     * classes i.e. classes in package android.view, that would like their
15934     * applications to be backwards compatible.
15935     * </p>
15936     * <div class="special reference">
15937     * <h3>Developer Guides</h3>
15938     * <p>For more information about making applications accessible, read the
15939     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
15940     * developer guide.</p>
15941     * </div>
15942     * <p>
15943     * A scenario in which a developer would like to use an accessibility delegate
15944     * is overriding a method introduced in a later API version then the minimal API
15945     * version supported by the application. For example, the method
15946     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15947     * in API version 4 when the accessibility APIs were first introduced. If a
15948     * developer would like his application to run on API version 4 devices (assuming
15949     * all other APIs used by the application are version 4 or lower) and take advantage
15950     * of this method, instead of overriding the method which would break the application's
15951     * backwards compatibility, he can override the corresponding method in this
15952     * delegate and register the delegate in the target View if the API version of
15953     * the system is high enough i.e. the API version is same or higher to the API
15954     * version that introduced
15955     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15956     * </p>
15957     * <p>
15958     * Here is an example implementation:
15959     * </p>
15960     * <code><pre><p>
15961     * if (Build.VERSION.SDK_INT >= 14) {
15962     *     // If the API version is equal of higher than the version in
15963     *     // which onInitializeAccessibilityNodeInfo was introduced we
15964     *     // register a delegate with a customized implementation.
15965     *     View view = findViewById(R.id.view_id);
15966     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15967     *         public void onInitializeAccessibilityNodeInfo(View host,
15968     *                 AccessibilityNodeInfo info) {
15969     *             // Let the default implementation populate the info.
15970     *             super.onInitializeAccessibilityNodeInfo(host, info);
15971     *             // Set some other information.
15972     *             info.setEnabled(host.isEnabled());
15973     *         }
15974     *     });
15975     * }
15976     * </code></pre></p>
15977     * <p>
15978     * This delegate contains methods that correspond to the accessibility methods
15979     * in View. If a delegate has been specified the implementation in View hands
15980     * off handling to the corresponding method in this delegate. The default
15981     * implementation the delegate methods behaves exactly as the corresponding
15982     * method in View for the case of no accessibility delegate been set. Hence,
15983     * to customize the behavior of a View method, clients can override only the
15984     * corresponding delegate method without altering the behavior of the rest
15985     * accessibility related methods of the host view.
15986     * </p>
15987     */
15988    public static class AccessibilityDelegate {
15989
15990        /**
15991         * Sends an accessibility event of the given type. If accessibility is not
15992         * enabled this method has no effect.
15993         * <p>
15994         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15995         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15996         * been set.
15997         * </p>
15998         *
15999         * @param host The View hosting the delegate.
16000         * @param eventType The type of the event to send.
16001         *
16002         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
16003         */
16004        public void sendAccessibilityEvent(View host, int eventType) {
16005            host.sendAccessibilityEventInternal(eventType);
16006        }
16007
16008        /**
16009         * Sends an accessibility event. This method behaves exactly as
16010         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
16011         * empty {@link AccessibilityEvent} and does not perform a check whether
16012         * accessibility is enabled.
16013         * <p>
16014         * The default implementation behaves as
16015         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
16016         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
16017         * the case of no accessibility delegate been set.
16018         * </p>
16019         *
16020         * @param host The View hosting the delegate.
16021         * @param event The event to send.
16022         *
16023         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
16024         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
16025         */
16026        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
16027            host.sendAccessibilityEventUncheckedInternal(event);
16028        }
16029
16030        /**
16031         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
16032         * to its children for adding their text content to the event.
16033         * <p>
16034         * The default implementation behaves as
16035         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
16036         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
16037         * the case of no accessibility delegate been set.
16038         * </p>
16039         *
16040         * @param host The View hosting the delegate.
16041         * @param event The event.
16042         * @return True if the event population was completed.
16043         *
16044         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
16045         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
16046         */
16047        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
16048            return host.dispatchPopulateAccessibilityEventInternal(event);
16049        }
16050
16051        /**
16052         * Gives a chance to the host View to populate the accessibility event with its
16053         * text content.
16054         * <p>
16055         * The default implementation behaves as
16056         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
16057         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
16058         * the case of no accessibility delegate been set.
16059         * </p>
16060         *
16061         * @param host The View hosting the delegate.
16062         * @param event The accessibility event which to populate.
16063         *
16064         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
16065         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
16066         */
16067        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
16068            host.onPopulateAccessibilityEventInternal(event);
16069        }
16070
16071        /**
16072         * Initializes an {@link AccessibilityEvent} with information about the
16073         * the host View which is the event source.
16074         * <p>
16075         * The default implementation behaves as
16076         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
16077         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
16078         * the case of no accessibility delegate been set.
16079         * </p>
16080         *
16081         * @param host The View hosting the delegate.
16082         * @param event The event to initialize.
16083         *
16084         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
16085         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
16086         */
16087        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
16088            host.onInitializeAccessibilityEventInternal(event);
16089        }
16090
16091        /**
16092         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
16093         * <p>
16094         * The default implementation behaves as
16095         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
16096         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
16097         * the case of no accessibility delegate been set.
16098         * </p>
16099         *
16100         * @param host The View hosting the delegate.
16101         * @param info The instance to initialize.
16102         *
16103         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
16104         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
16105         */
16106        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
16107            host.onInitializeAccessibilityNodeInfoInternal(info);
16108        }
16109
16110        /**
16111         * Called when a child of the host View has requested sending an
16112         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
16113         * to augment the event.
16114         * <p>
16115         * The default implementation behaves as
16116         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
16117         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
16118         * the case of no accessibility delegate been set.
16119         * </p>
16120         *
16121         * @param host The View hosting the delegate.
16122         * @param child The child which requests sending the event.
16123         * @param event The event to be sent.
16124         * @return True if the event should be sent
16125         *
16126         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
16127         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
16128         */
16129        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
16130                AccessibilityEvent event) {
16131            return host.onRequestSendAccessibilityEventInternal(child, event);
16132        }
16133
16134        /**
16135         * Gets the provider for managing a virtual view hierarchy rooted at this View
16136         * and reported to {@link android.accessibilityservice.AccessibilityService}s
16137         * that explore the window content.
16138         * <p>
16139         * The default implementation behaves as
16140         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
16141         * the case of no accessibility delegate been set.
16142         * </p>
16143         *
16144         * @return The provider.
16145         *
16146         * @see AccessibilityNodeProvider
16147         */
16148        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
16149            return null;
16150        }
16151    }
16152}
16153