View.java revision c529d8d8c709aed9c9e6d87af3ce2eb4c73da4bf
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.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.animation.Animation;
65import android.view.animation.AnimationUtils;
66import android.view.inputmethod.EditorInfo;
67import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
69import android.widget.ScrollBarDrawable;
70
71import com.android.internal.R;
72import com.android.internal.util.Predicate;
73import com.android.internal.view.menu.MenuBuilder;
74
75import java.lang.ref.WeakReference;
76import java.lang.reflect.InvocationTargetException;
77import java.lang.reflect.Method;
78import java.util.ArrayList;
79import java.util.Arrays;
80import java.util.Locale;
81import java.util.WeakHashMap;
82import java.util.concurrent.CopyOnWriteArrayList;
83
84/**
85 * <p>
86 * This class represents the basic building block for user interface components. A View
87 * occupies a rectangular area on the screen and is responsible for drawing and
88 * event handling. View is the base class for <em>widgets</em>, which are
89 * used to create interactive UI components (buttons, text fields, etc.). The
90 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
91 * are invisible containers that hold other Views (or other ViewGroups) and define
92 * their layout properties.
93 * </p>
94 *
95 * <div class="special">
96 * <p>For an introduction to using this class to develop your
97 * application's user interface, read the Developer Guide documentation on
98 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
99 * include:
100 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
104 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
105 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
106 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
107 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
108 * </p>
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} method and queried by calling
347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
349 * </p>
350 *
351 * <p>
352 * Even though a view can define a padding, it does not provide any support for
353 * margins. However, view groups provide such a support. Refer to
354 * {@link android.view.ViewGroup} and
355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
356 * </p>
357 *
358 * <a name="Layout"></a>
359 * <h3>Layout</h3>
360 * <p>
361 * Layout is a two pass process: a measure pass and a layout pass. The measuring
362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
363 * of the view tree. Each view pushes dimension specifications down the tree
364 * during the recursion. At the end of the measure pass, every view has stored
365 * its measurements. The second pass happens in
366 * {@link #layout(int,int,int,int)} and is also top-down. During
367 * this pass each parent is responsible for positioning all of its children
368 * using the sizes computed in the measure pass.
369 * </p>
370 *
371 * <p>
372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
373 * {@link #getMeasuredHeight()} values must be set, along with those for all of
374 * that view's descendants. A view's measured width and measured height values
375 * must respect the constraints imposed by the view's parents. This guarantees
376 * that at the end of the measure pass, all parents accept all of their
377 * children's measurements. A parent view may call measure() more than once on
378 * its children. For example, the parent may measure each child once with
379 * unspecified dimensions to find out how big they want to be, then call
380 * measure() on them again with actual numbers if the sum of all the children's
381 * unconstrained sizes is too big or too small.
382 * </p>
383 *
384 * <p>
385 * The measure pass uses two classes to communicate dimensions. The
386 * {@link MeasureSpec} class is used by views to tell their parents how they
387 * want to be measured and positioned. The base LayoutParams class just
388 * describes how big the view wants to be for both width and height. For each
389 * dimension, it can specify one of:
390 * <ul>
391 * <li> an exact number
392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
393 * (minus padding)
394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
395 * enclose its content (plus padding).
396 * </ul>
397 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
399 * an X and Y value.
400 * </p>
401 *
402 * <p>
403 * MeasureSpecs are used to push requirements down the tree from parent to
404 * child. A MeasureSpec can be in one of three modes:
405 * <ul>
406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
407 * of a child view. For example, a LinearLayout may call measure() on its child
408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
409 * tall the child view wants to be given a width of 240 pixels.
410 * <li>EXACTLY: This is used by the parent to impose an exact size on the
411 * child. The child must use this size, and guarantee that all of its
412 * descendants will fit within this size.
413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
414 * child. The child must gurantee that it and all of its descendants will fit
415 * within this size.
416 * </ul>
417 * </p>
418 *
419 * <p>
420 * To intiate a layout, call {@link #requestLayout}. This method is typically
421 * called by a view on itself when it believes that is can no longer fit within
422 * its current bounds.
423 * </p>
424 *
425 * <a name="Drawing"></a>
426 * <h3>Drawing</h3>
427 * <p>
428 * Drawing is handled by walking the tree and rendering each view that
429 * intersects the the invalid region. Because the tree is traversed in-order,
430 * this means that parents will draw before (i.e., behind) their children, with
431 * siblings drawn in the order they appear in the tree.
432 * If you set a background drawable for a View, then the View will draw it for you
433 * before calling back to its <code>onDraw()</code> method.
434 * </p>
435 *
436 * <p>
437 * Note that the framework will not draw views that are not in the invalid region.
438 * </p>
439 *
440 * <p>
441 * To force a view to draw, call {@link #invalidate()}.
442 * </p>
443 *
444 * <a name="EventHandlingThreading"></a>
445 * <h3>Event Handling and Threading</h3>
446 * <p>
447 * The basic cycle of a view is as follows:
448 * <ol>
449 * <li>An event comes in and is dispatched to the appropriate view. The view
450 * handles the event and notifies any listeners.</li>
451 * <li>If in the course of processing the event, the view's bounds may need
452 * to be changed, the view will call {@link #requestLayout()}.</li>
453 * <li>Similarly, if in the course of processing the event the view's appearance
454 * may need to be changed, the view will call {@link #invalidate()}.</li>
455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
456 * the framework will take care of measuring, laying out, and drawing the tree
457 * as appropriate.</li>
458 * </ol>
459 * </p>
460 *
461 * <p><em>Note: The entire view tree is single threaded. You must always be on
462 * the UI thread when calling any method on any view.</em>
463 * If you are doing work on other threads and want to update the state of a view
464 * from that thread, you should use a {@link Handler}.
465 * </p>
466 *
467 * <a name="FocusHandling"></a>
468 * <h3>Focus Handling</h3>
469 * <p>
470 * The framework will handle routine focus movement in response to user input.
471 * This includes changing the focus as views are removed or hidden, or as new
472 * views become available. Views indicate their willingness to take focus
473 * through the {@link #isFocusable} method. To change whether a view can take
474 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
476 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
477 * </p>
478 * <p>
479 * Focus movement is based on an algorithm which finds the nearest neighbor in a
480 * given direction. In rare cases, the default algorithm may not match the
481 * intended behavior of the developer. In these situations, you can provide
482 * explicit overrides by using these XML attributes in the layout file:
483 * <pre>
484 * nextFocusDown
485 * nextFocusLeft
486 * nextFocusRight
487 * nextFocusUp
488 * </pre>
489 * </p>
490 *
491 *
492 * <p>
493 * To get a particular view to take focus, call {@link #requestFocus()}.
494 * </p>
495 *
496 * <a name="TouchMode"></a>
497 * <h3>Touch Mode</h3>
498 * <p>
499 * When a user is navigating a user interface via directional keys such as a D-pad, it is
500 * necessary to give focus to actionable items such as buttons so the user can see
501 * what will take input.  If the device has touch capabilities, however, and the user
502 * begins interacting with the interface by touching it, it is no longer necessary to
503 * always highlight, or give focus to, a particular view.  This motivates a mode
504 * for interaction named 'touch mode'.
505 * </p>
506 * <p>
507 * For a touch capable device, once the user touches the screen, the device
508 * will enter touch mode.  From this point onward, only views for which
509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
510 * Other views that are touchable, like buttons, will not take focus when touched; they will
511 * only fire the on click listeners.
512 * </p>
513 * <p>
514 * Any time a user hits a directional key, such as a D-pad direction, the view device will
515 * exit touch mode, and find a view to take focus, so that the user may resume interacting
516 * with the user interface without touching the screen again.
517 * </p>
518 * <p>
519 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
520 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
521 * </p>
522 *
523 * <a name="Scrolling"></a>
524 * <h3>Scrolling</h3>
525 * <p>
526 * The framework provides basic support for views that wish to internally
527 * scroll their content. This includes keeping track of the X and Y scroll
528 * offset as well as mechanisms for drawing scrollbars. See
529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
530 * {@link #awakenScrollBars()} for more details.
531 * </p>
532 *
533 * <a name="Tags"></a>
534 * <h3>Tags</h3>
535 * <p>
536 * Unlike IDs, tags are not used to identify views. Tags are essentially an
537 * extra piece of information that can be associated with a view. They are most
538 * often used as a convenience to store data related to views in the views
539 * themselves rather than by putting them in a separate structure.
540 * </p>
541 *
542 * <a name="Animation"></a>
543 * <h3>Animation</h3>
544 * <p>
545 * You can attach an {@link Animation} object to a view using
546 * {@link #setAnimation(Animation)} or
547 * {@link #startAnimation(Animation)}. The animation can alter the scale,
548 * rotation, translation and alpha of a view over time. If the animation is
549 * attached to a view that has children, the animation will affect the entire
550 * subtree rooted by that node. When an animation is started, the framework will
551 * take care of redrawing the appropriate views until the animation completes.
552 * </p>
553 * <p>
554 * Starting with Android 3.0, the preferred way of animating views is to use the
555 * {@link android.animation} package APIs.
556 * </p>
557 *
558 * <a name="Security"></a>
559 * <h3>Security</h3>
560 * <p>
561 * Sometimes it is essential that an application be able to verify that an action
562 * is being performed with the full knowledge and consent of the user, such as
563 * granting a permission request, making a purchase or clicking on an advertisement.
564 * Unfortunately, a malicious application could try to spoof the user into
565 * performing these actions, unaware, by concealing the intended purpose of the view.
566 * As a remedy, the framework offers a touch filtering mechanism that can be used to
567 * improve the security of views that provide access to sensitive functionality.
568 * </p><p>
569 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
570 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
571 * will discard touches that are received whenever the view's window is obscured by
572 * another visible window.  As a result, the view will not receive touches whenever a
573 * toast, dialog or other window appears above the view's window.
574 * </p><p>
575 * For more fine-grained control over security, consider overriding the
576 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
577 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
578 * </p>
579 *
580 * @attr ref android.R.styleable#View_alpha
581 * @attr ref android.R.styleable#View_background
582 * @attr ref android.R.styleable#View_clickable
583 * @attr ref android.R.styleable#View_contentDescription
584 * @attr ref android.R.styleable#View_drawingCacheQuality
585 * @attr ref android.R.styleable#View_duplicateParentState
586 * @attr ref android.R.styleable#View_id
587 * @attr ref android.R.styleable#View_fadingEdge
588 * @attr ref android.R.styleable#View_fadingEdgeLength
589 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
590 * @attr ref android.R.styleable#View_fitsSystemWindows
591 * @attr ref android.R.styleable#View_isScrollContainer
592 * @attr ref android.R.styleable#View_focusable
593 * @attr ref android.R.styleable#View_focusableInTouchMode
594 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
595 * @attr ref android.R.styleable#View_keepScreenOn
596 * @attr ref android.R.styleable#View_layerType
597 * @attr ref android.R.styleable#View_longClickable
598 * @attr ref android.R.styleable#View_minHeight
599 * @attr ref android.R.styleable#View_minWidth
600 * @attr ref android.R.styleable#View_nextFocusDown
601 * @attr ref android.R.styleable#View_nextFocusLeft
602 * @attr ref android.R.styleable#View_nextFocusRight
603 * @attr ref android.R.styleable#View_nextFocusUp
604 * @attr ref android.R.styleable#View_onClick
605 * @attr ref android.R.styleable#View_padding
606 * @attr ref android.R.styleable#View_paddingBottom
607 * @attr ref android.R.styleable#View_paddingLeft
608 * @attr ref android.R.styleable#View_paddingRight
609 * @attr ref android.R.styleable#View_paddingTop
610 * @attr ref android.R.styleable#View_saveEnabled
611 * @attr ref android.R.styleable#View_rotation
612 * @attr ref android.R.styleable#View_rotationX
613 * @attr ref android.R.styleable#View_rotationY
614 * @attr ref android.R.styleable#View_scaleX
615 * @attr ref android.R.styleable#View_scaleY
616 * @attr ref android.R.styleable#View_scrollX
617 * @attr ref android.R.styleable#View_scrollY
618 * @attr ref android.R.styleable#View_scrollbarSize
619 * @attr ref android.R.styleable#View_scrollbarStyle
620 * @attr ref android.R.styleable#View_scrollbars
621 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
622 * @attr ref android.R.styleable#View_scrollbarFadeDuration
623 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
624 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
625 * @attr ref android.R.styleable#View_scrollbarThumbVertical
626 * @attr ref android.R.styleable#View_scrollbarTrackVertical
627 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
628 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
629 * @attr ref android.R.styleable#View_soundEffectsEnabled
630 * @attr ref android.R.styleable#View_tag
631 * @attr ref android.R.styleable#View_transformPivotX
632 * @attr ref android.R.styleable#View_transformPivotY
633 * @attr ref android.R.styleable#View_translationX
634 * @attr ref android.R.styleable#View_translationY
635 * @attr ref android.R.styleable#View_visibility
636 *
637 * @see android.view.ViewGroup
638 */
639public class View implements Drawable.Callback2, KeyEvent.Callback, AccessibilityEventSource {
640    private static final boolean DBG = false;
641
642    /**
643     * The logging tag used by this class with android.util.Log.
644     */
645    protected static final String VIEW_LOG_TAG = "View";
646
647    /**
648     * Used to mark a View that has no ID.
649     */
650    public static final int NO_ID = -1;
651
652    /**
653     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
654     * calling setFlags.
655     */
656    private static final int NOT_FOCUSABLE = 0x00000000;
657
658    /**
659     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
660     * setFlags.
661     */
662    private static final int FOCUSABLE = 0x00000001;
663
664    /**
665     * Mask for use with setFlags indicating bits used for focus.
666     */
667    private static final int FOCUSABLE_MASK = 0x00000001;
668
669    /**
670     * This view will adjust its padding to fit sytem windows (e.g. status bar)
671     */
672    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
673
674    /**
675     * This view is visible.
676     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
677     * android:visibility}.
678     */
679    public static final int VISIBLE = 0x00000000;
680
681    /**
682     * This view is invisible, but it still takes up space for layout purposes.
683     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
684     * android:visibility}.
685     */
686    public static final int INVISIBLE = 0x00000004;
687
688    /**
689     * This view is invisible, and it doesn't take any space for layout
690     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
691     * android:visibility}.
692     */
693    public static final int GONE = 0x00000008;
694
695    /**
696     * Mask for use with setFlags indicating bits used for visibility.
697     * {@hide}
698     */
699    static final int VISIBILITY_MASK = 0x0000000C;
700
701    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
702
703    /**
704     * This view is enabled. Intrepretation varies by subclass.
705     * Use with ENABLED_MASK when calling setFlags.
706     * {@hide}
707     */
708    static final int ENABLED = 0x00000000;
709
710    /**
711     * This view is disabled. Intrepretation varies by subclass.
712     * Use with ENABLED_MASK when calling setFlags.
713     * {@hide}
714     */
715    static final int DISABLED = 0x00000020;
716
717   /**
718    * Mask for use with setFlags indicating bits used for indicating whether
719    * this view is enabled
720    * {@hide}
721    */
722    static final int ENABLED_MASK = 0x00000020;
723
724    /**
725     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
726     * called and further optimizations will be performed. It is okay to have
727     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
728     * {@hide}
729     */
730    static final int WILL_NOT_DRAW = 0x00000080;
731
732    /**
733     * Mask for use with setFlags indicating bits used for indicating whether
734     * this view is will draw
735     * {@hide}
736     */
737    static final int DRAW_MASK = 0x00000080;
738
739    /**
740     * <p>This view doesn't show scrollbars.</p>
741     * {@hide}
742     */
743    static final int SCROLLBARS_NONE = 0x00000000;
744
745    /**
746     * <p>This view shows horizontal scrollbars.</p>
747     * {@hide}
748     */
749    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
750
751    /**
752     * <p>This view shows vertical scrollbars.</p>
753     * {@hide}
754     */
755    static final int SCROLLBARS_VERTICAL = 0x00000200;
756
757    /**
758     * <p>Mask for use with setFlags indicating bits used for indicating which
759     * scrollbars are enabled.</p>
760     * {@hide}
761     */
762    static final int SCROLLBARS_MASK = 0x00000300;
763
764    /**
765     * Indicates that the view should filter touches when its window is obscured.
766     * Refer to the class comments for more information about this security feature.
767     * {@hide}
768     */
769    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
770
771    // note flag value 0x00000800 is now available for next flags...
772
773    /**
774     * <p>This view doesn't show fading edges.</p>
775     * {@hide}
776     */
777    static final int FADING_EDGE_NONE = 0x00000000;
778
779    /**
780     * <p>This view shows horizontal fading edges.</p>
781     * {@hide}
782     */
783    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
784
785    /**
786     * <p>This view shows vertical fading edges.</p>
787     * {@hide}
788     */
789    static final int FADING_EDGE_VERTICAL = 0x00002000;
790
791    /**
792     * <p>Mask for use with setFlags indicating bits used for indicating which
793     * fading edges are enabled.</p>
794     * {@hide}
795     */
796    static final int FADING_EDGE_MASK = 0x00003000;
797
798    /**
799     * <p>Indicates this view can be clicked. When clickable, a View reacts
800     * to clicks by notifying the OnClickListener.<p>
801     * {@hide}
802     */
803    static final int CLICKABLE = 0x00004000;
804
805    /**
806     * <p>Indicates this view is caching its drawing into a bitmap.</p>
807     * {@hide}
808     */
809    static final int DRAWING_CACHE_ENABLED = 0x00008000;
810
811    /**
812     * <p>Indicates that no icicle should be saved for this view.<p>
813     * {@hide}
814     */
815    static final int SAVE_DISABLED = 0x000010000;
816
817    /**
818     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
819     * property.</p>
820     * {@hide}
821     */
822    static final int SAVE_DISABLED_MASK = 0x000010000;
823
824    /**
825     * <p>Indicates that no drawing cache should ever be created for this view.<p>
826     * {@hide}
827     */
828    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
829
830    /**
831     * <p>Indicates this view can take / keep focus when int touch mode.</p>
832     * {@hide}
833     */
834    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
835
836    /**
837     * <p>Enables low quality mode for the drawing cache.</p>
838     */
839    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
840
841    /**
842     * <p>Enables high quality mode for the drawing cache.</p>
843     */
844    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
845
846    /**
847     * <p>Enables automatic quality mode for the drawing cache.</p>
848     */
849    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
850
851    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
852            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
853    };
854
855    /**
856     * <p>Mask for use with setFlags indicating bits used for the cache
857     * quality property.</p>
858     * {@hide}
859     */
860    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
861
862    /**
863     * <p>
864     * Indicates this view can be long clicked. When long clickable, a View
865     * reacts to long clicks by notifying the OnLongClickListener or showing a
866     * context menu.
867     * </p>
868     * {@hide}
869     */
870    static final int LONG_CLICKABLE = 0x00200000;
871
872    /**
873     * <p>Indicates that this view gets its drawable states from its direct parent
874     * and ignores its original internal states.</p>
875     *
876     * @hide
877     */
878    static final int DUPLICATE_PARENT_STATE = 0x00400000;
879
880    /**
881     * The scrollbar style to display the scrollbars inside the content area,
882     * without increasing the padding. The scrollbars will be overlaid with
883     * translucency on the view's content.
884     */
885    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
886
887    /**
888     * The scrollbar style to display the scrollbars inside the padded area,
889     * increasing the padding of the view. The scrollbars will not overlap the
890     * content area of the view.
891     */
892    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
893
894    /**
895     * The scrollbar style to display the scrollbars at the edge of the view,
896     * without increasing the padding. The scrollbars will be overlaid with
897     * translucency.
898     */
899    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
900
901    /**
902     * The scrollbar style to display the scrollbars at the edge of the view,
903     * increasing the padding of the view. The scrollbars will only overlap the
904     * background, if any.
905     */
906    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
907
908    /**
909     * Mask to check if the scrollbar style is overlay or inset.
910     * {@hide}
911     */
912    static final int SCROLLBARS_INSET_MASK = 0x01000000;
913
914    /**
915     * Mask to check if the scrollbar style is inside or outside.
916     * {@hide}
917     */
918    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
919
920    /**
921     * Mask for scrollbar style.
922     * {@hide}
923     */
924    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
925
926    /**
927     * View flag indicating that the screen should remain on while the
928     * window containing this view is visible to the user.  This effectively
929     * takes care of automatically setting the WindowManager's
930     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
931     */
932    public static final int KEEP_SCREEN_ON = 0x04000000;
933
934    /**
935     * View flag indicating whether this view should have sound effects enabled
936     * for events such as clicking and touching.
937     */
938    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
939
940    /**
941     * View flag indicating whether this view should have haptic feedback
942     * enabled for events such as long presses.
943     */
944    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
945
946    /**
947     * <p>Indicates that the view hierarchy should stop saving state when
948     * it reaches this view.  If state saving is initiated immediately at
949     * the view, it will be allowed.
950     * {@hide}
951     */
952    static final int PARENT_SAVE_DISABLED = 0x20000000;
953
954    /**
955     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
956     * {@hide}
957     */
958    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
959
960    /**
961     * Horizontal direction of this view is from Left to Right.
962     * Use with {@link #setLayoutDirection}.
963     * {@hide}
964     */
965    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
966
967    /**
968     * Horizontal direction of this view is from Right to Left.
969     * Use with {@link #setLayoutDirection}.
970     * {@hide}
971     */
972    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
973
974    /**
975     * Horizontal direction of this view is inherited from its parent.
976     * Use with {@link #setLayoutDirection}.
977     * {@hide}
978     */
979    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
980
981    /**
982     * Horizontal direction of this view is from deduced from the default language
983     * script for the locale. Use with {@link #setLayoutDirection}.
984     * {@hide}
985     */
986    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
987
988    /**
989     * Mask for use with setFlags indicating bits used for horizontalDirection.
990     * {@hide}
991     */
992    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
993
994    /*
995     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
996     * flag value.
997     * {@hide}
998     */
999    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
1000        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
1001
1002    /**
1003     * Default horizontalDirection.
1004     * {@hide}
1005     */
1006    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1007
1008    /**
1009     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1010     * should add all focusable Views regardless if they are focusable in touch mode.
1011     */
1012    public static final int FOCUSABLES_ALL = 0x00000000;
1013
1014    /**
1015     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1016     * should add only Views focusable in touch mode.
1017     */
1018    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1019
1020    /**
1021     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1022     * item.
1023     */
1024    public static final int FOCUS_BACKWARD = 0x00000001;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1028     * item.
1029     */
1030    public static final int FOCUS_FORWARD = 0x00000002;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus to the left.
1034     */
1035    public static final int FOCUS_LEFT = 0x00000011;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus up.
1039     */
1040    public static final int FOCUS_UP = 0x00000021;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus to the right.
1044     */
1045    public static final int FOCUS_RIGHT = 0x00000042;
1046
1047    /**
1048     * Use with {@link #focusSearch(int)}. Move focus down.
1049     */
1050    public static final int FOCUS_DOWN = 0x00000082;
1051
1052    /**
1053     * Bits of {@link #getMeasuredWidthAndState()} and
1054     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1055     */
1056    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1057
1058    /**
1059     * Bits of {@link #getMeasuredWidthAndState()} and
1060     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1061     */
1062    public static final int MEASURED_STATE_MASK = 0xff000000;
1063
1064    /**
1065     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1066     * for functions that combine both width and height into a single int,
1067     * such as {@link #getMeasuredState()} and the childState argument of
1068     * {@link #resolveSizeAndState(int, int, int)}.
1069     */
1070    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1071
1072    /**
1073     * Bit of {@link #getMeasuredWidthAndState()} and
1074     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1075     * is smaller that the space the view would like to have.
1076     */
1077    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1078
1079    /**
1080     * Base View state sets
1081     */
1082    // Singles
1083    /**
1084     * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
1092    /**
1093     * Indicates the view is enabled. States are used with
1094     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1095     * view depending on its state.
1096     *
1097     * @see android.graphics.drawable.Drawable
1098     * @see #getDrawableState()
1099     */
1100    protected static final int[] ENABLED_STATE_SET;
1101    /**
1102     * Indicates the view is focused. States are used with
1103     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1104     * view depending on its state.
1105     *
1106     * @see android.graphics.drawable.Drawable
1107     * @see #getDrawableState()
1108     */
1109    protected static final int[] FOCUSED_STATE_SET;
1110    /**
1111     * Indicates the view is selected. States are used with
1112     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1113     * view depending on its state.
1114     *
1115     * @see android.graphics.drawable.Drawable
1116     * @see #getDrawableState()
1117     */
1118    protected static final int[] SELECTED_STATE_SET;
1119    /**
1120     * Indicates the view is pressed. States are used with
1121     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1122     * view depending on its state.
1123     *
1124     * @see android.graphics.drawable.Drawable
1125     * @see #getDrawableState()
1126     * @hide
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Temporary Rect currently for use in setBackground().  This will probably
1488     * be extended in the future to hold our own class with more than just
1489     * a Rect. :)
1490     */
1491    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1492
1493    /**
1494     * Map used to store views' tags.
1495     */
1496    private static WeakHashMap<View, SparseArray<Object>> sTags;
1497
1498    /**
1499     * Lock used to access sTags.
1500     */
1501    private static final Object sTagsLock = new Object();
1502
1503    /**
1504     * The next available accessiiblity id.
1505     */
1506    private static int sNextAccessibilityViewId;
1507
1508    /**
1509     * The animation currently associated with this view.
1510     * @hide
1511     */
1512    protected Animation mCurrentAnimation = null;
1513
1514    /**
1515     * Width as measured during measure pass.
1516     * {@hide}
1517     */
1518    @ViewDebug.ExportedProperty(category = "measurement")
1519    int mMeasuredWidth;
1520
1521    /**
1522     * Height as measured during measure pass.
1523     * {@hide}
1524     */
1525    @ViewDebug.ExportedProperty(category = "measurement")
1526    int mMeasuredHeight;
1527
1528    /**
1529     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1530     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1531     * its display list. This flag, used only when hw accelerated, allows us to clear the
1532     * flag while retaining this information until it's needed (at getDisplayList() time and
1533     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1534     *
1535     * {@hide}
1536     */
1537    boolean mRecreateDisplayList = false;
1538
1539    /**
1540     * The view's identifier.
1541     * {@hide}
1542     *
1543     * @see #setId(int)
1544     * @see #getId()
1545     */
1546    @ViewDebug.ExportedProperty(resolveId = true)
1547    int mID = NO_ID;
1548
1549    /**
1550     * The stable ID of this view for accessibility porposes.
1551     */
1552    int mAccessibilityViewId = NO_ID;
1553
1554    /**
1555     * The view's tag.
1556     * {@hide}
1557     *
1558     * @see #setTag(Object)
1559     * @see #getTag()
1560     */
1561    protected Object mTag;
1562
1563    // for mPrivateFlags:
1564    /** {@hide} */
1565    static final int WANTS_FOCUS                    = 0x00000001;
1566    /** {@hide} */
1567    static final int FOCUSED                        = 0x00000002;
1568    /** {@hide} */
1569    static final int SELECTED                       = 0x00000004;
1570    /** {@hide} */
1571    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1572    /** {@hide} */
1573    static final int HAS_BOUNDS                     = 0x00000010;
1574    /** {@hide} */
1575    static final int DRAWN                          = 0x00000020;
1576    /**
1577     * When this flag is set, this view is running an animation on behalf of its
1578     * children and should therefore not cancel invalidate requests, even if they
1579     * lie outside of this view's bounds.
1580     *
1581     * {@hide}
1582     */
1583    static final int DRAW_ANIMATION                 = 0x00000040;
1584    /** {@hide} */
1585    static final int SKIP_DRAW                      = 0x00000080;
1586    /** {@hide} */
1587    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1588    /** {@hide} */
1589    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1590    /** {@hide} */
1591    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1592    /** {@hide} */
1593    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1594    /** {@hide} */
1595    static final int FORCE_LAYOUT                   = 0x00001000;
1596    /** {@hide} */
1597    static final int LAYOUT_REQUIRED                = 0x00002000;
1598
1599    private static final int PRESSED                = 0x00004000;
1600
1601    /** {@hide} */
1602    static final int DRAWING_CACHE_VALID            = 0x00008000;
1603    /**
1604     * Flag used to indicate that this view should be drawn once more (and only once
1605     * more) after its animation has completed.
1606     * {@hide}
1607     */
1608    static final int ANIMATION_STARTED              = 0x00010000;
1609
1610    private static final int SAVE_STATE_CALLED      = 0x00020000;
1611
1612    /**
1613     * Indicates that the View returned true when onSetAlpha() was called and that
1614     * the alpha must be restored.
1615     * {@hide}
1616     */
1617    static final int ALPHA_SET                      = 0x00040000;
1618
1619    /**
1620     * Set by {@link #setScrollContainer(boolean)}.
1621     */
1622    static final int SCROLL_CONTAINER               = 0x00080000;
1623
1624    /**
1625     * Set by {@link #setScrollContainer(boolean)}.
1626     */
1627    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1628
1629    /**
1630     * View flag indicating whether this view was invalidated (fully or partially.)
1631     *
1632     * @hide
1633     */
1634    static final int DIRTY                          = 0x00200000;
1635
1636    /**
1637     * View flag indicating whether this view was invalidated by an opaque
1638     * invalidate request.
1639     *
1640     * @hide
1641     */
1642    static final int DIRTY_OPAQUE                   = 0x00400000;
1643
1644    /**
1645     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1646     *
1647     * @hide
1648     */
1649    static final int DIRTY_MASK                     = 0x00600000;
1650
1651    /**
1652     * Indicates whether the background is opaque.
1653     *
1654     * @hide
1655     */
1656    static final int OPAQUE_BACKGROUND              = 0x00800000;
1657
1658    /**
1659     * Indicates whether the scrollbars are opaque.
1660     *
1661     * @hide
1662     */
1663    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1664
1665    /**
1666     * Indicates whether the view is opaque.
1667     *
1668     * @hide
1669     */
1670    static final int OPAQUE_MASK                    = 0x01800000;
1671
1672    /**
1673     * Indicates a prepressed state;
1674     * the short time between ACTION_DOWN and recognizing
1675     * a 'real' press. Prepressed is used to recognize quick taps
1676     * even when they are shorter than ViewConfiguration.getTapTimeout().
1677     *
1678     * @hide
1679     */
1680    private static final int PREPRESSED             = 0x02000000;
1681
1682    /**
1683     * Indicates whether the view is temporarily detached.
1684     *
1685     * @hide
1686     */
1687    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1688
1689    /**
1690     * Indicates that we should awaken scroll bars once attached
1691     *
1692     * @hide
1693     */
1694    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1695
1696    /**
1697     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1698     * @hide
1699     */
1700    private static final int HOVERED              = 0x10000000;
1701
1702    /**
1703     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1704     * for transform operations
1705     *
1706     * @hide
1707     */
1708    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1709
1710    /** {@hide} */
1711    static final int ACTIVATED                    = 0x40000000;
1712
1713    /**
1714     * Indicates that this view was specifically invalidated, not just dirtied because some
1715     * child view was invalidated. The flag is used to determine when we need to recreate
1716     * a view's display list (as opposed to just returning a reference to its existing
1717     * display list).
1718     *
1719     * @hide
1720     */
1721    static final int INVALIDATED                  = 0x80000000;
1722
1723    /* Masks for mPrivateFlags2 */
1724
1725    /**
1726     * Indicates that this view has reported that it can accept the current drag's content.
1727     * Cleared when the drag operation concludes.
1728     * @hide
1729     */
1730    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1731
1732    /**
1733     * Indicates that this view is currently directly under the drag location in a
1734     * drag-and-drop operation involving content that it can accept.  Cleared when
1735     * the drag exits the view, or when the drag operation concludes.
1736     * @hide
1737     */
1738    static final int DRAG_HOVERED                 = 0x00000002;
1739
1740    /**
1741     * Indicates whether the view layout direction has been resolved and drawn to the
1742     * right-to-left direction.
1743     *
1744     * @hide
1745     */
1746    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1747
1748    /**
1749     * Indicates whether the view layout direction has been resolved.
1750     *
1751     * @hide
1752     */
1753    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1754
1755
1756    /* End of masks for mPrivateFlags2 */
1757
1758    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1759
1760    /**
1761     * Always allow a user to over-scroll this view, provided it is a
1762     * view that can scroll.
1763     *
1764     * @see #getOverScrollMode()
1765     * @see #setOverScrollMode(int)
1766     */
1767    public static final int OVER_SCROLL_ALWAYS = 0;
1768
1769    /**
1770     * Allow a user to over-scroll this view only if the content is large
1771     * enough to meaningfully scroll, provided it is a view that can scroll.
1772     *
1773     * @see #getOverScrollMode()
1774     * @see #setOverScrollMode(int)
1775     */
1776    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1777
1778    /**
1779     * Never allow a user to over-scroll this view.
1780     *
1781     * @see #getOverScrollMode()
1782     * @see #setOverScrollMode(int)
1783     */
1784    public static final int OVER_SCROLL_NEVER = 2;
1785
1786    /**
1787     * View has requested the system UI (status bar) to be visible (the default).
1788     *
1789     * @see #setSystemUiVisibility(int)
1790     */
1791    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1792
1793    /**
1794     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1795     *
1796     * This is for use in games, book readers, video players, or any other "immersive" application
1797     * where the usual system chrome is deemed too distracting.
1798     *
1799     * In low profile mode, the status bar and/or navigation icons may dim.
1800     *
1801     * @see #setSystemUiVisibility(int)
1802     */
1803    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1804
1805    /**
1806     * View has requested that the system navigation be temporarily hidden.
1807     *
1808     * This is an even less obtrusive state than that called for by
1809     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1810     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1811     * those to disappear. This is useful (in conjunction with the
1812     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1813     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1814     * window flags) for displaying content using every last pixel on the display.
1815     *
1816     * There is a limitation: because navigation controls are so important, the least user
1817     * interaction will cause them to reappear immediately.
1818     *
1819     * @see #setSystemUiVisibility(int)
1820     */
1821    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1822
1823    /**
1824     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1825     */
1826    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1827
1828    /**
1829     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1830     */
1831    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1832
1833    /**
1834     * @hide
1835     *
1836     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1837     * out of the public fields to keep the undefined bits out of the developer's way.
1838     *
1839     * Flag to make the status bar not expandable.  Unless you also
1840     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1841     */
1842    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1843
1844    /**
1845     * @hide
1846     *
1847     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1848     * out of the public fields to keep the undefined bits out of the developer's way.
1849     *
1850     * Flag to hide notification icons and scrolling ticker text.
1851     */
1852    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1853
1854    /**
1855     * @hide
1856     *
1857     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1858     * out of the public fields to keep the undefined bits out of the developer's way.
1859     *
1860     * Flag to disable incoming notification alerts.  This will not block
1861     * icons, but it will block sound, vibrating and other visual or aural notifications.
1862     */
1863    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1864
1865    /**
1866     * @hide
1867     *
1868     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1869     * out of the public fields to keep the undefined bits out of the developer's way.
1870     *
1871     * Flag to hide only the scrolling ticker.  Note that
1872     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1873     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1874     */
1875    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1876
1877    /**
1878     * @hide
1879     *
1880     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1881     * out of the public fields to keep the undefined bits out of the developer's way.
1882     *
1883     * Flag to hide the center system info area.
1884     */
1885    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1886
1887    /**
1888     * @hide
1889     *
1890     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1891     * out of the public fields to keep the undefined bits out of the developer's way.
1892     *
1893     * Flag to hide only the navigation buttons.  Don't use this
1894     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1895     *
1896     * THIS DOES NOT DISABLE THE BACK BUTTON
1897     */
1898    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1899
1900    /**
1901     * @hide
1902     *
1903     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1904     * out of the public fields to keep the undefined bits out of the developer's way.
1905     *
1906     * Flag to hide only the back button.  Don't use this
1907     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1908     */
1909    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1910
1911    /**
1912     * @hide
1913     *
1914     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1915     * out of the public fields to keep the undefined bits out of the developer's way.
1916     *
1917     * Flag to hide only the clock.  You might use this if your activity has
1918     * its own clock making the status bar's clock redundant.
1919     */
1920    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1921
1922    /**
1923     * @hide
1924     */
1925    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1926
1927    /**
1928     * Controls the over-scroll mode for this view.
1929     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1930     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1931     * and {@link #OVER_SCROLL_NEVER}.
1932     */
1933    private int mOverScrollMode;
1934
1935    /**
1936     * The parent this view is attached to.
1937     * {@hide}
1938     *
1939     * @see #getParent()
1940     */
1941    protected ViewParent mParent;
1942
1943    /**
1944     * {@hide}
1945     */
1946    AttachInfo mAttachInfo;
1947
1948    /**
1949     * {@hide}
1950     */
1951    @ViewDebug.ExportedProperty(flagMapping = {
1952        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1953                name = "FORCE_LAYOUT"),
1954        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1955                name = "LAYOUT_REQUIRED"),
1956        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1957            name = "DRAWING_CACHE_INVALID", outputIf = false),
1958        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1959        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1960        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1961        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1962    })
1963    int mPrivateFlags;
1964    int mPrivateFlags2;
1965
1966    /**
1967     * This view's request for the visibility of the status bar.
1968     * @hide
1969     */
1970    @ViewDebug.ExportedProperty(flagMapping = {
1971        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
1972                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
1973                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
1974        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1975                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1976                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
1977        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
1978                                equals = SYSTEM_UI_FLAG_VISIBLE,
1979                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
1980    })
1981    int mSystemUiVisibility;
1982
1983    /**
1984     * Count of how many windows this view has been attached to.
1985     */
1986    int mWindowAttachCount;
1987
1988    /**
1989     * The layout parameters associated with this view and used by the parent
1990     * {@link android.view.ViewGroup} to determine how this view should be
1991     * laid out.
1992     * {@hide}
1993     */
1994    protected ViewGroup.LayoutParams mLayoutParams;
1995
1996    /**
1997     * The view flags hold various views states.
1998     * {@hide}
1999     */
2000    @ViewDebug.ExportedProperty
2001    int mViewFlags;
2002
2003    /**
2004     * The transform matrix for the View. This transform is calculated internally
2005     * based on the rotation, scaleX, and scaleY properties. The identity matrix
2006     * is used by default. Do *not* use this variable directly; instead call
2007     * getMatrix(), which will automatically recalculate the matrix if necessary
2008     * to get the correct matrix based on the latest rotation and scale properties.
2009     */
2010    private final Matrix mMatrix = new Matrix();
2011
2012    /**
2013     * The transform matrix for the View. This transform is calculated internally
2014     * based on the rotation, scaleX, and scaleY properties. The identity matrix
2015     * is used by default. Do *not* use this variable directly; instead call
2016     * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2017     * to get the correct matrix based on the latest rotation and scale properties.
2018     */
2019    private Matrix mInverseMatrix;
2020
2021    /**
2022     * An internal variable that tracks whether we need to recalculate the
2023     * transform matrix, based on whether the rotation or scaleX/Y properties
2024     * have changed since the matrix was last calculated.
2025     */
2026    boolean mMatrixDirty = false;
2027
2028    /**
2029     * An internal variable that tracks whether we need to recalculate the
2030     * transform matrix, based on whether the rotation or scaleX/Y properties
2031     * have changed since the matrix was last calculated.
2032     */
2033    private boolean mInverseMatrixDirty = true;
2034
2035    /**
2036     * A variable that tracks whether we need to recalculate the
2037     * transform matrix, based on whether the rotation or scaleX/Y properties
2038     * have changed since the matrix was last calculated. This variable
2039     * is only valid after a call to updateMatrix() or to a function that
2040     * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2041     */
2042    private boolean mMatrixIsIdentity = true;
2043
2044    /**
2045     * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2046     */
2047    private Camera mCamera = null;
2048
2049    /**
2050     * This matrix is used when computing the matrix for 3D rotations.
2051     */
2052    private Matrix matrix3D = null;
2053
2054    /**
2055     * These prev values are used to recalculate a centered pivot point when necessary. The
2056     * pivot point is only used in matrix operations (when rotation, scale, or translation are
2057     * set), so thes values are only used then as well.
2058     */
2059    private int mPrevWidth = -1;
2060    private int mPrevHeight = -1;
2061
2062    private boolean mLastIsOpaque;
2063
2064    /**
2065     * Convenience value to check for float values that are close enough to zero to be considered
2066     * zero.
2067     */
2068    private static final float NONZERO_EPSILON = .001f;
2069
2070    /**
2071     * The degrees rotation around the vertical axis through the pivot point.
2072     */
2073    @ViewDebug.ExportedProperty
2074    float mRotationY = 0f;
2075
2076    /**
2077     * The degrees rotation around the horizontal axis through the pivot point.
2078     */
2079    @ViewDebug.ExportedProperty
2080    float mRotationX = 0f;
2081
2082    /**
2083     * The degrees rotation around the pivot point.
2084     */
2085    @ViewDebug.ExportedProperty
2086    float mRotation = 0f;
2087
2088    /**
2089     * The amount of translation of the object away from its left property (post-layout).
2090     */
2091    @ViewDebug.ExportedProperty
2092    float mTranslationX = 0f;
2093
2094    /**
2095     * The amount of translation of the object away from its top property (post-layout).
2096     */
2097    @ViewDebug.ExportedProperty
2098    float mTranslationY = 0f;
2099
2100    /**
2101     * The amount of scale in the x direction around the pivot point. A
2102     * value of 1 means no scaling is applied.
2103     */
2104    @ViewDebug.ExportedProperty
2105    float mScaleX = 1f;
2106
2107    /**
2108     * The amount of scale in the y direction around the pivot point. A
2109     * value of 1 means no scaling is applied.
2110     */
2111    @ViewDebug.ExportedProperty
2112    float mScaleY = 1f;
2113
2114    /**
2115     * The amount of scale in the x direction around the pivot point. A
2116     * value of 1 means no scaling is applied.
2117     */
2118    @ViewDebug.ExportedProperty
2119    float mPivotX = 0f;
2120
2121    /**
2122     * The amount of scale in the y direction around the pivot point. A
2123     * value of 1 means no scaling is applied.
2124     */
2125    @ViewDebug.ExportedProperty
2126    float mPivotY = 0f;
2127
2128    /**
2129     * The opacity of the View. This is a value from 0 to 1, where 0 means
2130     * completely transparent and 1 means completely opaque.
2131     */
2132    @ViewDebug.ExportedProperty
2133    float mAlpha = 1f;
2134
2135    /**
2136     * The distance in pixels from the left edge of this view's parent
2137     * to the left edge of this view.
2138     * {@hide}
2139     */
2140    @ViewDebug.ExportedProperty(category = "layout")
2141    protected int mLeft;
2142    /**
2143     * The distance in pixels from the left edge of this view's parent
2144     * to the right edge of this view.
2145     * {@hide}
2146     */
2147    @ViewDebug.ExportedProperty(category = "layout")
2148    protected int mRight;
2149    /**
2150     * The distance in pixels from the top edge of this view's parent
2151     * to the top edge of this view.
2152     * {@hide}
2153     */
2154    @ViewDebug.ExportedProperty(category = "layout")
2155    protected int mTop;
2156    /**
2157     * The distance in pixels from the top edge of this view's parent
2158     * to the bottom edge of this view.
2159     * {@hide}
2160     */
2161    @ViewDebug.ExportedProperty(category = "layout")
2162    protected int mBottom;
2163
2164    /**
2165     * The offset, in pixels, by which the content of this view is scrolled
2166     * horizontally.
2167     * {@hide}
2168     */
2169    @ViewDebug.ExportedProperty(category = "scrolling")
2170    protected int mScrollX;
2171    /**
2172     * The offset, in pixels, by which the content of this view is scrolled
2173     * vertically.
2174     * {@hide}
2175     */
2176    @ViewDebug.ExportedProperty(category = "scrolling")
2177    protected int mScrollY;
2178
2179    /**
2180     * The left padding in pixels, that is the distance in pixels between the
2181     * left edge of this view and the left edge of its content.
2182     * {@hide}
2183     */
2184    @ViewDebug.ExportedProperty(category = "padding")
2185    protected int mPaddingLeft;
2186    /**
2187     * The right padding in pixels, that is the distance in pixels between the
2188     * right edge of this view and the right edge of its content.
2189     * {@hide}
2190     */
2191    @ViewDebug.ExportedProperty(category = "padding")
2192    protected int mPaddingRight;
2193    /**
2194     * The top padding in pixels, that is the distance in pixels between the
2195     * top edge of this view and the top edge of its content.
2196     * {@hide}
2197     */
2198    @ViewDebug.ExportedProperty(category = "padding")
2199    protected int mPaddingTop;
2200    /**
2201     * The bottom padding in pixels, that is the distance in pixels between the
2202     * bottom edge of this view and the bottom edge of its content.
2203     * {@hide}
2204     */
2205    @ViewDebug.ExportedProperty(category = "padding")
2206    protected int mPaddingBottom;
2207
2208    /**
2209     * Briefly describes the view and is primarily used for accessibility support.
2210     */
2211    private CharSequence mContentDescription;
2212
2213    /**
2214     * Cache the paddingRight set by the user to append to the scrollbar's size.
2215     *
2216     * @hide
2217     */
2218    @ViewDebug.ExportedProperty(category = "padding")
2219    protected int mUserPaddingRight;
2220
2221    /**
2222     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2223     *
2224     * @hide
2225     */
2226    @ViewDebug.ExportedProperty(category = "padding")
2227    protected int mUserPaddingBottom;
2228
2229    /**
2230     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2231     *
2232     * @hide
2233     */
2234    @ViewDebug.ExportedProperty(category = "padding")
2235    protected int mUserPaddingLeft;
2236
2237    /**
2238     * Cache if the user padding is relative.
2239     *
2240     */
2241    @ViewDebug.ExportedProperty(category = "padding")
2242    boolean mUserPaddingRelative;
2243
2244    /**
2245     * Cache the paddingStart set by the user to append to the scrollbar's size.
2246     *
2247     */
2248    @ViewDebug.ExportedProperty(category = "padding")
2249    int mUserPaddingStart;
2250
2251    /**
2252     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2253     *
2254     */
2255    @ViewDebug.ExportedProperty(category = "padding")
2256    int mUserPaddingEnd;
2257
2258    /**
2259     * @hide
2260     */
2261    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2262    /**
2263     * @hide
2264     */
2265    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2266
2267    private Resources mResources = null;
2268
2269    private Drawable mBGDrawable;
2270
2271    private int mBackgroundResource;
2272    private boolean mBackgroundSizeChanged;
2273
2274    /**
2275     * Listener used to dispatch focus change events.
2276     * This field should be made private, so it is hidden from the SDK.
2277     * {@hide}
2278     */
2279    protected OnFocusChangeListener mOnFocusChangeListener;
2280
2281    /**
2282     * Listeners for layout change events.
2283     */
2284    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2285
2286    /**
2287     * Listeners for attach events.
2288     */
2289    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2290
2291    /**
2292     * Listener used to dispatch click events.
2293     * This field should be made private, so it is hidden from the SDK.
2294     * {@hide}
2295     */
2296    protected OnClickListener mOnClickListener;
2297
2298    /**
2299     * Listener used to dispatch long click events.
2300     * This field should be made private, so it is hidden from the SDK.
2301     * {@hide}
2302     */
2303    protected OnLongClickListener mOnLongClickListener;
2304
2305    /**
2306     * Listener used to build the context menu.
2307     * This field should be made private, so it is hidden from the SDK.
2308     * {@hide}
2309     */
2310    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2311
2312    private OnKeyListener mOnKeyListener;
2313
2314    private OnTouchListener mOnTouchListener;
2315
2316    private OnHoverListener mOnHoverListener;
2317
2318    private OnGenericMotionListener mOnGenericMotionListener;
2319
2320    private OnDragListener mOnDragListener;
2321
2322    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2323
2324    /**
2325     * The application environment this view lives in.
2326     * This field should be made private, so it is hidden from the SDK.
2327     * {@hide}
2328     */
2329    protected Context mContext;
2330
2331    private ScrollabilityCache mScrollCache;
2332
2333    private int[] mDrawableState = null;
2334
2335    /**
2336     * Set to true when drawing cache is enabled and cannot be created.
2337     *
2338     * @hide
2339     */
2340    public boolean mCachingFailed;
2341
2342    private Bitmap mDrawingCache;
2343    private Bitmap mUnscaledDrawingCache;
2344    private HardwareLayer mHardwareLayer;
2345    DisplayList mDisplayList;
2346
2347    /**
2348     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2349     * the user may specify which view to go to next.
2350     */
2351    private int mNextFocusLeftId = View.NO_ID;
2352
2353    /**
2354     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2355     * the user may specify which view to go to next.
2356     */
2357    private int mNextFocusRightId = View.NO_ID;
2358
2359    /**
2360     * When this view has focus and the next focus is {@link #FOCUS_UP},
2361     * the user may specify which view to go to next.
2362     */
2363    private int mNextFocusUpId = View.NO_ID;
2364
2365    /**
2366     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2367     * the user may specify which view to go to next.
2368     */
2369    private int mNextFocusDownId = View.NO_ID;
2370
2371    /**
2372     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2373     * the user may specify which view to go to next.
2374     */
2375    int mNextFocusForwardId = View.NO_ID;
2376
2377    private CheckForLongPress mPendingCheckForLongPress;
2378    private CheckForTap mPendingCheckForTap = null;
2379    private PerformClick mPerformClick;
2380    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2381
2382    private UnsetPressedState mUnsetPressedState;
2383
2384    /**
2385     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2386     * up event while a long press is invoked as soon as the long press duration is reached, so
2387     * a long press could be performed before the tap is checked, in which case the tap's action
2388     * should not be invoked.
2389     */
2390    private boolean mHasPerformedLongPress;
2391
2392    /**
2393     * The minimum height of the view. We'll try our best to have the height
2394     * of this view to at least this amount.
2395     */
2396    @ViewDebug.ExportedProperty(category = "measurement")
2397    private int mMinHeight;
2398
2399    /**
2400     * The minimum width of the view. We'll try our best to have the width
2401     * of this view to at least this amount.
2402     */
2403    @ViewDebug.ExportedProperty(category = "measurement")
2404    private int mMinWidth;
2405
2406    /**
2407     * The delegate to handle touch events that are physically in this view
2408     * but should be handled by another view.
2409     */
2410    private TouchDelegate mTouchDelegate = null;
2411
2412    /**
2413     * Solid color to use as a background when creating the drawing cache. Enables
2414     * the cache to use 16 bit bitmaps instead of 32 bit.
2415     */
2416    private int mDrawingCacheBackgroundColor = 0;
2417
2418    /**
2419     * Special tree observer used when mAttachInfo is null.
2420     */
2421    private ViewTreeObserver mFloatingTreeObserver;
2422
2423    /**
2424     * Cache the touch slop from the context that created the view.
2425     */
2426    private int mTouchSlop;
2427
2428    /**
2429     * Object that handles automatic animation of view properties.
2430     */
2431    private ViewPropertyAnimator mAnimator = null;
2432
2433    /**
2434     * Flag indicating that a drag can cross window boundaries.  When
2435     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2436     * with this flag set, all visible applications will be able to participate
2437     * in the drag operation and receive the dragged content.
2438     *
2439     * @hide
2440     */
2441    public static final int DRAG_FLAG_GLOBAL = 1;
2442
2443    /**
2444     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2445     */
2446    private float mVerticalScrollFactor;
2447
2448    /**
2449     * Position of the vertical scroll bar.
2450     */
2451    private int mVerticalScrollbarPosition;
2452
2453    /**
2454     * Position the scroll bar at the default position as determined by the system.
2455     */
2456    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2457
2458    /**
2459     * Position the scroll bar along the left edge.
2460     */
2461    public static final int SCROLLBAR_POSITION_LEFT = 1;
2462
2463    /**
2464     * Position the scroll bar along the right edge.
2465     */
2466    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2467
2468    /**
2469     * Indicates that the view does not have a layer.
2470     *
2471     * @see #getLayerType()
2472     * @see #setLayerType(int, android.graphics.Paint)
2473     * @see #LAYER_TYPE_SOFTWARE
2474     * @see #LAYER_TYPE_HARDWARE
2475     */
2476    public static final int LAYER_TYPE_NONE = 0;
2477
2478    /**
2479     * <p>Indicates that the view has a software layer. A software layer is backed
2480     * by a bitmap and causes the view to be rendered using Android's software
2481     * rendering pipeline, even if hardware acceleration is enabled.</p>
2482     *
2483     * <p>Software layers have various usages:</p>
2484     * <p>When the application is not using hardware acceleration, a software layer
2485     * is useful to apply a specific color filter and/or blending mode and/or
2486     * translucency to a view and all its children.</p>
2487     * <p>When the application is using hardware acceleration, a software layer
2488     * is useful to render drawing primitives not supported by the hardware
2489     * accelerated pipeline. It can also be used to cache a complex view tree
2490     * into a texture and reduce the complexity of drawing operations. For instance,
2491     * when animating a complex view tree with a translation, a software layer can
2492     * be used to render the view tree only once.</p>
2493     * <p>Software layers should be avoided when the affected view tree updates
2494     * often. Every update will require to re-render the software layer, which can
2495     * potentially be slow (particularly when hardware acceleration is turned on
2496     * since the layer will have to be uploaded into a hardware texture after every
2497     * update.)</p>
2498     *
2499     * @see #getLayerType()
2500     * @see #setLayerType(int, android.graphics.Paint)
2501     * @see #LAYER_TYPE_NONE
2502     * @see #LAYER_TYPE_HARDWARE
2503     */
2504    public static final int LAYER_TYPE_SOFTWARE = 1;
2505
2506    /**
2507     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2508     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2509     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2510     * rendering pipeline, but only if hardware acceleration is turned on for the
2511     * view hierarchy. When hardware acceleration is turned off, hardware layers
2512     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2513     *
2514     * <p>A hardware layer is useful to apply a specific color filter and/or
2515     * blending mode and/or translucency to a view and all its children.</p>
2516     * <p>A hardware layer can be used to cache a complex view tree into a
2517     * texture and reduce the complexity of drawing operations. For instance,
2518     * when animating a complex view tree with a translation, a hardware layer can
2519     * be used to render the view tree only once.</p>
2520     * <p>A hardware layer can also be used to increase the rendering quality when
2521     * rotation transformations are applied on a view. It can also be used to
2522     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2523     *
2524     * @see #getLayerType()
2525     * @see #setLayerType(int, android.graphics.Paint)
2526     * @see #LAYER_TYPE_NONE
2527     * @see #LAYER_TYPE_SOFTWARE
2528     */
2529    public static final int LAYER_TYPE_HARDWARE = 2;
2530
2531    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2532            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2533            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2534            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2535    })
2536    int mLayerType = LAYER_TYPE_NONE;
2537    Paint mLayerPaint;
2538    Rect mLocalDirtyRect;
2539
2540    /**
2541     * Set to true when the view is sending hover accessibility events because it
2542     * is the innermost hovered view.
2543     */
2544    private boolean mSendingHoverAccessibilityEvents;
2545
2546    /**
2547     * Text direction is inherited thru {@link ViewGroup}
2548     * @hide
2549     */
2550    public static final int TEXT_DIRECTION_INHERIT = 0;
2551
2552    /**
2553     * Text direction is using "first strong algorithm". The first strong directional character
2554     * determines the paragraph direction. If there is no strong directional character, the
2555     * paragraph direction is the view's resolved ayout direction.
2556     *
2557     * @hide
2558     */
2559    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2560
2561    /**
2562     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2563     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2564     * If there are neither, the paragraph direction is the view's resolved layout direction.
2565     *
2566     * @hide
2567     */
2568    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2569
2570    /**
2571     * Text direction is the same as the one held by a 60% majority of the characters. If there is
2572     * no majority then the paragraph direction is the resolved layout direction of the View.
2573     *
2574     * @hide
2575     */
2576    public static final int TEXT_DIRECTION_CHAR_COUNT = 3;
2577
2578    /**
2579     * Text direction is forced to LTR.
2580     *
2581     * @hide
2582     */
2583    public static final int TEXT_DIRECTION_LTR = 4;
2584
2585    /**
2586     * Text direction is forced to RTL.
2587     *
2588     * @hide
2589     */
2590    public static final int TEXT_DIRECTION_RTL = 5;
2591
2592    /**
2593     * Default text direction is inherited
2594     */
2595    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2596
2597    /**
2598     * The text direction that has been defined by {@link #setTextDirection(int)}.
2599     *
2600     * {@hide}
2601     */
2602    @ViewDebug.ExportedProperty(category = "text", mapping = {
2603            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2604            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2605            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2606            @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"),
2607            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2608            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2609    })
2610    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2611
2612    /**
2613     * The resolved text direction.  This needs resolution if the value is
2614     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if that is
2615     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2616     * chain of the view.
2617     *
2618     * {@hide}
2619     */
2620    @ViewDebug.ExportedProperty(category = "text", mapping = {
2621            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2622            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2623            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2624            @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"),
2625            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2626            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2627    })
2628    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2629
2630    /**
2631     * Consistency verifier for debugging purposes.
2632     * @hide
2633     */
2634    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2635            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2636                    new InputEventConsistencyVerifier(this, 0) : null;
2637
2638    /**
2639     * Simple constructor to use when creating a view from code.
2640     *
2641     * @param context The Context the view is running in, through which it can
2642     *        access the current theme, resources, etc.
2643     */
2644    public View(Context context) {
2645        mContext = context;
2646        mResources = context != null ? context.getResources() : null;
2647        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2648        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2649        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2650        mUserPaddingStart = -1;
2651        mUserPaddingEnd = -1;
2652        mUserPaddingRelative = false;
2653    }
2654
2655    /**
2656     * Constructor that is called when inflating a view from XML. This is called
2657     * when a view is being constructed from an XML file, supplying attributes
2658     * that were specified in the XML file. This version uses a default style of
2659     * 0, so the only attribute values applied are those in the Context's Theme
2660     * and the given AttributeSet.
2661     *
2662     * <p>
2663     * The method onFinishInflate() will be called after all children have been
2664     * added.
2665     *
2666     * @param context The Context the view is running in, through which it can
2667     *        access the current theme, resources, etc.
2668     * @param attrs The attributes of the XML tag that is inflating the view.
2669     * @see #View(Context, AttributeSet, int)
2670     */
2671    public View(Context context, AttributeSet attrs) {
2672        this(context, attrs, 0);
2673    }
2674
2675    /**
2676     * Perform inflation from XML and apply a class-specific base style. This
2677     * constructor of View allows subclasses to use their own base style when
2678     * they are inflating. For example, a Button class's constructor would call
2679     * this version of the super class constructor and supply
2680     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2681     * the theme's button style to modify all of the base view attributes (in
2682     * particular its background) as well as the Button class's attributes.
2683     *
2684     * @param context The Context the view is running in, through which it can
2685     *        access the current theme, resources, etc.
2686     * @param attrs The attributes of the XML tag that is inflating the view.
2687     * @param defStyle The default style to apply to this view. If 0, no style
2688     *        will be applied (beyond what is included in the theme). This may
2689     *        either be an attribute resource, whose value will be retrieved
2690     *        from the current theme, or an explicit style resource.
2691     * @see #View(Context, AttributeSet)
2692     */
2693    public View(Context context, AttributeSet attrs, int defStyle) {
2694        this(context);
2695
2696        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2697                defStyle, 0);
2698
2699        Drawable background = null;
2700
2701        int leftPadding = -1;
2702        int topPadding = -1;
2703        int rightPadding = -1;
2704        int bottomPadding = -1;
2705        int startPadding = -1;
2706        int endPadding = -1;
2707
2708        int padding = -1;
2709
2710        int viewFlagValues = 0;
2711        int viewFlagMasks = 0;
2712
2713        boolean setScrollContainer = false;
2714
2715        int x = 0;
2716        int y = 0;
2717
2718        float tx = 0;
2719        float ty = 0;
2720        float rotation = 0;
2721        float rotationX = 0;
2722        float rotationY = 0;
2723        float sx = 1f;
2724        float sy = 1f;
2725        boolean transformSet = false;
2726
2727        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2728
2729        int overScrollMode = mOverScrollMode;
2730        final int N = a.getIndexCount();
2731        for (int i = 0; i < N; i++) {
2732            int attr = a.getIndex(i);
2733            switch (attr) {
2734                case com.android.internal.R.styleable.View_background:
2735                    background = a.getDrawable(attr);
2736                    break;
2737                case com.android.internal.R.styleable.View_padding:
2738                    padding = a.getDimensionPixelSize(attr, -1);
2739                    break;
2740                 case com.android.internal.R.styleable.View_paddingLeft:
2741                    leftPadding = a.getDimensionPixelSize(attr, -1);
2742                    break;
2743                case com.android.internal.R.styleable.View_paddingTop:
2744                    topPadding = a.getDimensionPixelSize(attr, -1);
2745                    break;
2746                case com.android.internal.R.styleable.View_paddingRight:
2747                    rightPadding = a.getDimensionPixelSize(attr, -1);
2748                    break;
2749                case com.android.internal.R.styleable.View_paddingBottom:
2750                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2751                    break;
2752                case com.android.internal.R.styleable.View_paddingStart:
2753                    startPadding = a.getDimensionPixelSize(attr, -1);
2754                    break;
2755                case com.android.internal.R.styleable.View_paddingEnd:
2756                    endPadding = a.getDimensionPixelSize(attr, -1);
2757                    break;
2758                case com.android.internal.R.styleable.View_scrollX:
2759                    x = a.getDimensionPixelOffset(attr, 0);
2760                    break;
2761                case com.android.internal.R.styleable.View_scrollY:
2762                    y = a.getDimensionPixelOffset(attr, 0);
2763                    break;
2764                case com.android.internal.R.styleable.View_alpha:
2765                    setAlpha(a.getFloat(attr, 1f));
2766                    break;
2767                case com.android.internal.R.styleable.View_transformPivotX:
2768                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2769                    break;
2770                case com.android.internal.R.styleable.View_transformPivotY:
2771                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2772                    break;
2773                case com.android.internal.R.styleable.View_translationX:
2774                    tx = a.getDimensionPixelOffset(attr, 0);
2775                    transformSet = true;
2776                    break;
2777                case com.android.internal.R.styleable.View_translationY:
2778                    ty = a.getDimensionPixelOffset(attr, 0);
2779                    transformSet = true;
2780                    break;
2781                case com.android.internal.R.styleable.View_rotation:
2782                    rotation = a.getFloat(attr, 0);
2783                    transformSet = true;
2784                    break;
2785                case com.android.internal.R.styleable.View_rotationX:
2786                    rotationX = a.getFloat(attr, 0);
2787                    transformSet = true;
2788                    break;
2789                case com.android.internal.R.styleable.View_rotationY:
2790                    rotationY = a.getFloat(attr, 0);
2791                    transformSet = true;
2792                    break;
2793                case com.android.internal.R.styleable.View_scaleX:
2794                    sx = a.getFloat(attr, 1f);
2795                    transformSet = true;
2796                    break;
2797                case com.android.internal.R.styleable.View_scaleY:
2798                    sy = a.getFloat(attr, 1f);
2799                    transformSet = true;
2800                    break;
2801                case com.android.internal.R.styleable.View_id:
2802                    mID = a.getResourceId(attr, NO_ID);
2803                    break;
2804                case com.android.internal.R.styleable.View_tag:
2805                    mTag = a.getText(attr);
2806                    break;
2807                case com.android.internal.R.styleable.View_fitsSystemWindows:
2808                    if (a.getBoolean(attr, false)) {
2809                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2810                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2811                    }
2812                    break;
2813                case com.android.internal.R.styleable.View_focusable:
2814                    if (a.getBoolean(attr, false)) {
2815                        viewFlagValues |= FOCUSABLE;
2816                        viewFlagMasks |= FOCUSABLE_MASK;
2817                    }
2818                    break;
2819                case com.android.internal.R.styleable.View_focusableInTouchMode:
2820                    if (a.getBoolean(attr, false)) {
2821                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2822                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2823                    }
2824                    break;
2825                case com.android.internal.R.styleable.View_clickable:
2826                    if (a.getBoolean(attr, false)) {
2827                        viewFlagValues |= CLICKABLE;
2828                        viewFlagMasks |= CLICKABLE;
2829                    }
2830                    break;
2831                case com.android.internal.R.styleable.View_longClickable:
2832                    if (a.getBoolean(attr, false)) {
2833                        viewFlagValues |= LONG_CLICKABLE;
2834                        viewFlagMasks |= LONG_CLICKABLE;
2835                    }
2836                    break;
2837                case com.android.internal.R.styleable.View_saveEnabled:
2838                    if (!a.getBoolean(attr, true)) {
2839                        viewFlagValues |= SAVE_DISABLED;
2840                        viewFlagMasks |= SAVE_DISABLED_MASK;
2841                    }
2842                    break;
2843                case com.android.internal.R.styleable.View_duplicateParentState:
2844                    if (a.getBoolean(attr, false)) {
2845                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2846                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2847                    }
2848                    break;
2849                case com.android.internal.R.styleable.View_visibility:
2850                    final int visibility = a.getInt(attr, 0);
2851                    if (visibility != 0) {
2852                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2853                        viewFlagMasks |= VISIBILITY_MASK;
2854                    }
2855                    break;
2856                case com.android.internal.R.styleable.View_layoutDirection:
2857                    // Clear any HORIZONTAL_DIRECTION flag already set
2858                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2859                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2860                    final int layoutDirection = a.getInt(attr, -1);
2861                    if (layoutDirection != -1) {
2862                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2863                    } else {
2864                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2865                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2866                    }
2867                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2868                    break;
2869                case com.android.internal.R.styleable.View_drawingCacheQuality:
2870                    final int cacheQuality = a.getInt(attr, 0);
2871                    if (cacheQuality != 0) {
2872                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2873                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2874                    }
2875                    break;
2876                case com.android.internal.R.styleable.View_contentDescription:
2877                    mContentDescription = a.getString(attr);
2878                    break;
2879                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2880                    if (!a.getBoolean(attr, true)) {
2881                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2882                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2883                    }
2884                    break;
2885                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2886                    if (!a.getBoolean(attr, true)) {
2887                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2888                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2889                    }
2890                    break;
2891                case R.styleable.View_scrollbars:
2892                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2893                    if (scrollbars != SCROLLBARS_NONE) {
2894                        viewFlagValues |= scrollbars;
2895                        viewFlagMasks |= SCROLLBARS_MASK;
2896                        initializeScrollbars(a);
2897                    }
2898                    break;
2899                case R.styleable.View_fadingEdge:
2900                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2901                    if (fadingEdge != FADING_EDGE_NONE) {
2902                        viewFlagValues |= fadingEdge;
2903                        viewFlagMasks |= FADING_EDGE_MASK;
2904                        initializeFadingEdge(a);
2905                    }
2906                    break;
2907                case R.styleable.View_scrollbarStyle:
2908                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2909                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2910                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2911                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2912                    }
2913                    break;
2914                case R.styleable.View_isScrollContainer:
2915                    setScrollContainer = true;
2916                    if (a.getBoolean(attr, false)) {
2917                        setScrollContainer(true);
2918                    }
2919                    break;
2920                case com.android.internal.R.styleable.View_keepScreenOn:
2921                    if (a.getBoolean(attr, false)) {
2922                        viewFlagValues |= KEEP_SCREEN_ON;
2923                        viewFlagMasks |= KEEP_SCREEN_ON;
2924                    }
2925                    break;
2926                case R.styleable.View_filterTouchesWhenObscured:
2927                    if (a.getBoolean(attr, false)) {
2928                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2929                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2930                    }
2931                    break;
2932                case R.styleable.View_nextFocusLeft:
2933                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2934                    break;
2935                case R.styleable.View_nextFocusRight:
2936                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2937                    break;
2938                case R.styleable.View_nextFocusUp:
2939                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2940                    break;
2941                case R.styleable.View_nextFocusDown:
2942                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2943                    break;
2944                case R.styleable.View_nextFocusForward:
2945                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2946                    break;
2947                case R.styleable.View_minWidth:
2948                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2949                    break;
2950                case R.styleable.View_minHeight:
2951                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2952                    break;
2953                case R.styleable.View_onClick:
2954                    if (context.isRestricted()) {
2955                        throw new IllegalStateException("The android:onClick attribute cannot "
2956                                + "be used within a restricted context");
2957                    }
2958
2959                    final String handlerName = a.getString(attr);
2960                    if (handlerName != null) {
2961                        setOnClickListener(new OnClickListener() {
2962                            private Method mHandler;
2963
2964                            public void onClick(View v) {
2965                                if (mHandler == null) {
2966                                    try {
2967                                        mHandler = getContext().getClass().getMethod(handlerName,
2968                                                View.class);
2969                                    } catch (NoSuchMethodException e) {
2970                                        int id = getId();
2971                                        String idText = id == NO_ID ? "" : " with id '"
2972                                                + getContext().getResources().getResourceEntryName(
2973                                                    id) + "'";
2974                                        throw new IllegalStateException("Could not find a method " +
2975                                                handlerName + "(View) in the activity "
2976                                                + getContext().getClass() + " for onClick handler"
2977                                                + " on view " + View.this.getClass() + idText, e);
2978                                    }
2979                                }
2980
2981                                try {
2982                                    mHandler.invoke(getContext(), View.this);
2983                                } catch (IllegalAccessException e) {
2984                                    throw new IllegalStateException("Could not execute non "
2985                                            + "public method of the activity", e);
2986                                } catch (InvocationTargetException e) {
2987                                    throw new IllegalStateException("Could not execute "
2988                                            + "method of the activity", e);
2989                                }
2990                            }
2991                        });
2992                    }
2993                    break;
2994                case R.styleable.View_overScrollMode:
2995                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2996                    break;
2997                case R.styleable.View_verticalScrollbarPosition:
2998                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2999                    break;
3000                case R.styleable.View_layerType:
3001                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3002                    break;
3003                case R.styleable.View_textDirection:
3004                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3005                    break;
3006            }
3007        }
3008
3009        setOverScrollMode(overScrollMode);
3010
3011        if (background != null) {
3012            setBackgroundDrawable(background);
3013        }
3014
3015        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3016
3017        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3018        // layout direction). Those cached values will be used later during padding resolution.
3019        mUserPaddingStart = startPadding;
3020        mUserPaddingEnd = endPadding;
3021
3022        if (padding >= 0) {
3023            leftPadding = padding;
3024            topPadding = padding;
3025            rightPadding = padding;
3026            bottomPadding = padding;
3027        }
3028
3029        // If the user specified the padding (either with android:padding or
3030        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3031        // use the default padding or the padding from the background drawable
3032        // (stored at this point in mPadding*)
3033        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3034                topPadding >= 0 ? topPadding : mPaddingTop,
3035                rightPadding >= 0 ? rightPadding : mPaddingRight,
3036                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3037
3038        if (viewFlagMasks != 0) {
3039            setFlags(viewFlagValues, viewFlagMasks);
3040        }
3041
3042        // Needs to be called after mViewFlags is set
3043        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3044            recomputePadding();
3045        }
3046
3047        if (x != 0 || y != 0) {
3048            scrollTo(x, y);
3049        }
3050
3051        if (transformSet) {
3052            setTranslationX(tx);
3053            setTranslationY(ty);
3054            setRotation(rotation);
3055            setRotationX(rotationX);
3056            setRotationY(rotationY);
3057            setScaleX(sx);
3058            setScaleY(sy);
3059        }
3060
3061        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3062            setScrollContainer(true);
3063        }
3064
3065        computeOpaqueFlags();
3066
3067        a.recycle();
3068    }
3069
3070    /**
3071     * Non-public constructor for use in testing
3072     */
3073    View() {
3074    }
3075
3076    /**
3077     * <p>
3078     * Initializes the fading edges from a given set of styled attributes. This
3079     * method should be called by subclasses that need fading edges and when an
3080     * instance of these subclasses is created programmatically rather than
3081     * being inflated from XML. This method is automatically called when the XML
3082     * is inflated.
3083     * </p>
3084     *
3085     * @param a the styled attributes set to initialize the fading edges from
3086     */
3087    protected void initializeFadingEdge(TypedArray a) {
3088        initScrollCache();
3089
3090        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3091                R.styleable.View_fadingEdgeLength,
3092                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3093    }
3094
3095    /**
3096     * Returns the size of the vertical faded edges used to indicate that more
3097     * content in this view is visible.
3098     *
3099     * @return The size in pixels of the vertical faded edge or 0 if vertical
3100     *         faded edges are not enabled for this view.
3101     * @attr ref android.R.styleable#View_fadingEdgeLength
3102     */
3103    public int getVerticalFadingEdgeLength() {
3104        if (isVerticalFadingEdgeEnabled()) {
3105            ScrollabilityCache cache = mScrollCache;
3106            if (cache != null) {
3107                return cache.fadingEdgeLength;
3108            }
3109        }
3110        return 0;
3111    }
3112
3113    /**
3114     * Set the size of the faded edge used to indicate that more content in this
3115     * view is available.  Will not change whether the fading edge is enabled; use
3116     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3117     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3118     * for the vertical or horizontal fading edges.
3119     *
3120     * @param length The size in pixels of the faded edge used to indicate that more
3121     *        content in this view is visible.
3122     */
3123    public void setFadingEdgeLength(int length) {
3124        initScrollCache();
3125        mScrollCache.fadingEdgeLength = length;
3126    }
3127
3128    /**
3129     * Returns the size of the horizontal faded edges used to indicate that more
3130     * content in this view is visible.
3131     *
3132     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3133     *         faded edges are not enabled for this view.
3134     * @attr ref android.R.styleable#View_fadingEdgeLength
3135     */
3136    public int getHorizontalFadingEdgeLength() {
3137        if (isHorizontalFadingEdgeEnabled()) {
3138            ScrollabilityCache cache = mScrollCache;
3139            if (cache != null) {
3140                return cache.fadingEdgeLength;
3141            }
3142        }
3143        return 0;
3144    }
3145
3146    /**
3147     * Returns the width of the vertical scrollbar.
3148     *
3149     * @return The width in pixels of the vertical scrollbar or 0 if there
3150     *         is no vertical scrollbar.
3151     */
3152    public int getVerticalScrollbarWidth() {
3153        ScrollabilityCache cache = mScrollCache;
3154        if (cache != null) {
3155            ScrollBarDrawable scrollBar = cache.scrollBar;
3156            if (scrollBar != null) {
3157                int size = scrollBar.getSize(true);
3158                if (size <= 0) {
3159                    size = cache.scrollBarSize;
3160                }
3161                return size;
3162            }
3163            return 0;
3164        }
3165        return 0;
3166    }
3167
3168    /**
3169     * Returns the height of the horizontal scrollbar.
3170     *
3171     * @return The height in pixels of the horizontal scrollbar or 0 if
3172     *         there is no horizontal scrollbar.
3173     */
3174    protected int getHorizontalScrollbarHeight() {
3175        ScrollabilityCache cache = mScrollCache;
3176        if (cache != null) {
3177            ScrollBarDrawable scrollBar = cache.scrollBar;
3178            if (scrollBar != null) {
3179                int size = scrollBar.getSize(false);
3180                if (size <= 0) {
3181                    size = cache.scrollBarSize;
3182                }
3183                return size;
3184            }
3185            return 0;
3186        }
3187        return 0;
3188    }
3189
3190    /**
3191     * <p>
3192     * Initializes the scrollbars from a given set of styled attributes. This
3193     * method should be called by subclasses that need scrollbars and when an
3194     * instance of these subclasses is created programmatically rather than
3195     * being inflated from XML. This method is automatically called when the XML
3196     * is inflated.
3197     * </p>
3198     *
3199     * @param a the styled attributes set to initialize the scrollbars from
3200     */
3201    protected void initializeScrollbars(TypedArray a) {
3202        initScrollCache();
3203
3204        final ScrollabilityCache scrollabilityCache = mScrollCache;
3205
3206        if (scrollabilityCache.scrollBar == null) {
3207            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3208        }
3209
3210        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3211
3212        if (!fadeScrollbars) {
3213            scrollabilityCache.state = ScrollabilityCache.ON;
3214        }
3215        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3216
3217
3218        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3219                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3220                        .getScrollBarFadeDuration());
3221        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3222                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3223                ViewConfiguration.getScrollDefaultDelay());
3224
3225
3226        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3227                com.android.internal.R.styleable.View_scrollbarSize,
3228                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3229
3230        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3231        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3232
3233        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3234        if (thumb != null) {
3235            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3236        }
3237
3238        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3239                false);
3240        if (alwaysDraw) {
3241            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3242        }
3243
3244        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3245        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3246
3247        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3248        if (thumb != null) {
3249            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3250        }
3251
3252        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3253                false);
3254        if (alwaysDraw) {
3255            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3256        }
3257
3258        // Re-apply user/background padding so that scrollbar(s) get added
3259        resolvePadding();
3260    }
3261
3262    /**
3263     * <p>
3264     * Initalizes the scrollability cache if necessary.
3265     * </p>
3266     */
3267    private void initScrollCache() {
3268        if (mScrollCache == null) {
3269            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3270        }
3271    }
3272
3273    /**
3274     * Set the position of the vertical scroll bar. Should be one of
3275     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3276     * {@link #SCROLLBAR_POSITION_RIGHT}.
3277     *
3278     * @param position Where the vertical scroll bar should be positioned.
3279     */
3280    public void setVerticalScrollbarPosition(int position) {
3281        if (mVerticalScrollbarPosition != position) {
3282            mVerticalScrollbarPosition = position;
3283            computeOpaqueFlags();
3284            resolvePadding();
3285        }
3286    }
3287
3288    /**
3289     * @return The position where the vertical scroll bar will show, if applicable.
3290     * @see #setVerticalScrollbarPosition(int)
3291     */
3292    public int getVerticalScrollbarPosition() {
3293        return mVerticalScrollbarPosition;
3294    }
3295
3296    /**
3297     * Register a callback to be invoked when focus of this view changed.
3298     *
3299     * @param l The callback that will run.
3300     */
3301    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3302        mOnFocusChangeListener = l;
3303    }
3304
3305    /**
3306     * Add a listener that will be called when the bounds of the view change due to
3307     * layout processing.
3308     *
3309     * @param listener The listener that will be called when layout bounds change.
3310     */
3311    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3312        if (mOnLayoutChangeListeners == null) {
3313            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3314        }
3315        mOnLayoutChangeListeners.add(listener);
3316    }
3317
3318    /**
3319     * Remove a listener for layout changes.
3320     *
3321     * @param listener The listener for layout bounds change.
3322     */
3323    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3324        if (mOnLayoutChangeListeners == null) {
3325            return;
3326        }
3327        mOnLayoutChangeListeners.remove(listener);
3328    }
3329
3330    /**
3331     * Add a listener for attach state changes.
3332     *
3333     * This listener will be called whenever this view is attached or detached
3334     * from a window. Remove the listener using
3335     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3336     *
3337     * @param listener Listener to attach
3338     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3339     */
3340    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3341        if (mOnAttachStateChangeListeners == null) {
3342            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3343        }
3344        mOnAttachStateChangeListeners.add(listener);
3345    }
3346
3347    /**
3348     * Remove a listener for attach state changes. The listener will receive no further
3349     * notification of window attach/detach events.
3350     *
3351     * @param listener Listener to remove
3352     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3353     */
3354    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3355        if (mOnAttachStateChangeListeners == null) {
3356            return;
3357        }
3358        mOnAttachStateChangeListeners.remove(listener);
3359    }
3360
3361    /**
3362     * Returns the focus-change callback registered for this view.
3363     *
3364     * @return The callback, or null if one is not registered.
3365     */
3366    public OnFocusChangeListener getOnFocusChangeListener() {
3367        return mOnFocusChangeListener;
3368    }
3369
3370    /**
3371     * Register a callback to be invoked when this view is clicked. If this view is not
3372     * clickable, it becomes clickable.
3373     *
3374     * @param l The callback that will run
3375     *
3376     * @see #setClickable(boolean)
3377     */
3378    public void setOnClickListener(OnClickListener l) {
3379        if (!isClickable()) {
3380            setClickable(true);
3381        }
3382        mOnClickListener = l;
3383    }
3384
3385    /**
3386     * Register a callback to be invoked when this view is clicked and held. If this view is not
3387     * long clickable, it becomes long clickable.
3388     *
3389     * @param l The callback that will run
3390     *
3391     * @see #setLongClickable(boolean)
3392     */
3393    public void setOnLongClickListener(OnLongClickListener l) {
3394        if (!isLongClickable()) {
3395            setLongClickable(true);
3396        }
3397        mOnLongClickListener = l;
3398    }
3399
3400    /**
3401     * Register a callback to be invoked when the context menu for this view is
3402     * being built. If this view is not long clickable, it becomes long clickable.
3403     *
3404     * @param l The callback that will run
3405     *
3406     */
3407    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3408        if (!isLongClickable()) {
3409            setLongClickable(true);
3410        }
3411        mOnCreateContextMenuListener = l;
3412    }
3413
3414    /**
3415     * Call this view's OnClickListener, if it is defined.
3416     *
3417     * @return True there was an assigned OnClickListener that was called, false
3418     *         otherwise is returned.
3419     */
3420    public boolean performClick() {
3421        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3422
3423        if (mOnClickListener != null) {
3424            playSoundEffect(SoundEffectConstants.CLICK);
3425            mOnClickListener.onClick(this);
3426            return true;
3427        }
3428
3429        return false;
3430    }
3431
3432    /**
3433     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3434     * OnLongClickListener did not consume the event.
3435     *
3436     * @return True if one of the above receivers consumed the event, false otherwise.
3437     */
3438    public boolean performLongClick() {
3439        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3440
3441        boolean handled = false;
3442        if (mOnLongClickListener != null) {
3443            handled = mOnLongClickListener.onLongClick(View.this);
3444        }
3445        if (!handled) {
3446            handled = showContextMenu();
3447        }
3448        if (handled) {
3449            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3450        }
3451        return handled;
3452    }
3453
3454    /**
3455     * Performs button-related actions during a touch down event.
3456     *
3457     * @param event The event.
3458     * @return True if the down was consumed.
3459     *
3460     * @hide
3461     */
3462    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3463        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3464            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3465                return true;
3466            }
3467        }
3468        return false;
3469    }
3470
3471    /**
3472     * Bring up the context menu for this view.
3473     *
3474     * @return Whether a context menu was displayed.
3475     */
3476    public boolean showContextMenu() {
3477        return getParent().showContextMenuForChild(this);
3478    }
3479
3480    /**
3481     * Bring up the context menu for this view, referring to the item under the specified point.
3482     *
3483     * @param x The referenced x coordinate.
3484     * @param y The referenced y coordinate.
3485     * @param metaState The keyboard modifiers that were pressed.
3486     * @return Whether a context menu was displayed.
3487     *
3488     * @hide
3489     */
3490    public boolean showContextMenu(float x, float y, int metaState) {
3491        return showContextMenu();
3492    }
3493
3494    /**
3495     * Start an action mode.
3496     *
3497     * @param callback Callback that will control the lifecycle of the action mode
3498     * @return The new action mode if it is started, null otherwise
3499     *
3500     * @see ActionMode
3501     */
3502    public ActionMode startActionMode(ActionMode.Callback callback) {
3503        return getParent().startActionModeForChild(this, callback);
3504    }
3505
3506    /**
3507     * Register a callback to be invoked when a key is pressed in this view.
3508     * @param l the key listener to attach to this view
3509     */
3510    public void setOnKeyListener(OnKeyListener l) {
3511        mOnKeyListener = l;
3512    }
3513
3514    /**
3515     * Register a callback to be invoked when a touch event is sent to this view.
3516     * @param l the touch listener to attach to this view
3517     */
3518    public void setOnTouchListener(OnTouchListener l) {
3519        mOnTouchListener = l;
3520    }
3521
3522    /**
3523     * Register a callback to be invoked when a generic motion event is sent to this view.
3524     * @param l the generic motion listener to attach to this view
3525     */
3526    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3527        mOnGenericMotionListener = l;
3528    }
3529
3530    /**
3531     * Register a callback to be invoked when a hover event is sent to this view.
3532     * @param l the hover listener to attach to this view
3533     */
3534    public void setOnHoverListener(OnHoverListener l) {
3535        mOnHoverListener = l;
3536    }
3537
3538    /**
3539     * Register a drag event listener callback object for this View. The parameter is
3540     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3541     * View, the system calls the
3542     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3543     * @param l An implementation of {@link android.view.View.OnDragListener}.
3544     */
3545    public void setOnDragListener(OnDragListener l) {
3546        mOnDragListener = l;
3547    }
3548
3549    /**
3550     * Give this view focus. This will cause
3551     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3552     *
3553     * Note: this does not check whether this {@link View} should get focus, it just
3554     * gives it focus no matter what.  It should only be called internally by framework
3555     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3556     *
3557     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3558     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3559     *        focus moved when requestFocus() is called. It may not always
3560     *        apply, in which case use the default View.FOCUS_DOWN.
3561     * @param previouslyFocusedRect The rectangle of the view that had focus
3562     *        prior in this View's coordinate system.
3563     */
3564    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3565        if (DBG) {
3566            System.out.println(this + " requestFocus()");
3567        }
3568
3569        if ((mPrivateFlags & FOCUSED) == 0) {
3570            mPrivateFlags |= FOCUSED;
3571
3572            if (mParent != null) {
3573                mParent.requestChildFocus(this, this);
3574            }
3575
3576            onFocusChanged(true, direction, previouslyFocusedRect);
3577            refreshDrawableState();
3578        }
3579    }
3580
3581    /**
3582     * Request that a rectangle of this view be visible on the screen,
3583     * scrolling if necessary just enough.
3584     *
3585     * <p>A View should call this if it maintains some notion of which part
3586     * of its content is interesting.  For example, a text editing view
3587     * should call this when its cursor moves.
3588     *
3589     * @param rectangle The rectangle.
3590     * @return Whether any parent scrolled.
3591     */
3592    public boolean requestRectangleOnScreen(Rect rectangle) {
3593        return requestRectangleOnScreen(rectangle, false);
3594    }
3595
3596    /**
3597     * Request that a rectangle of this view be visible on the screen,
3598     * scrolling if necessary just enough.
3599     *
3600     * <p>A View should call this if it maintains some notion of which part
3601     * of its content is interesting.  For example, a text editing view
3602     * should call this when its cursor moves.
3603     *
3604     * <p>When <code>immediate</code> is set to true, scrolling will not be
3605     * animated.
3606     *
3607     * @param rectangle The rectangle.
3608     * @param immediate True to forbid animated scrolling, false otherwise
3609     * @return Whether any parent scrolled.
3610     */
3611    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3612        View child = this;
3613        ViewParent parent = mParent;
3614        boolean scrolled = false;
3615        while (parent != null) {
3616            scrolled |= parent.requestChildRectangleOnScreen(child,
3617                    rectangle, immediate);
3618
3619            // offset rect so next call has the rectangle in the
3620            // coordinate system of its direct child.
3621            rectangle.offset(child.getLeft(), child.getTop());
3622            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3623
3624            if (!(parent instanceof View)) {
3625                break;
3626            }
3627
3628            child = (View) parent;
3629            parent = child.getParent();
3630        }
3631        return scrolled;
3632    }
3633
3634    /**
3635     * Called when this view wants to give up focus. This will cause
3636     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3637     */
3638    public void clearFocus() {
3639        if (DBG) {
3640            System.out.println(this + " clearFocus()");
3641        }
3642
3643        if ((mPrivateFlags & FOCUSED) != 0) {
3644            mPrivateFlags &= ~FOCUSED;
3645
3646            if (mParent != null) {
3647                mParent.clearChildFocus(this);
3648            }
3649
3650            onFocusChanged(false, 0, null);
3651            refreshDrawableState();
3652        }
3653    }
3654
3655    /**
3656     * Called to clear the focus of a view that is about to be removed.
3657     * Doesn't call clearChildFocus, which prevents this view from taking
3658     * focus again before it has been removed from the parent
3659     */
3660    void clearFocusForRemoval() {
3661        if ((mPrivateFlags & FOCUSED) != 0) {
3662            mPrivateFlags &= ~FOCUSED;
3663
3664            onFocusChanged(false, 0, null);
3665            refreshDrawableState();
3666        }
3667    }
3668
3669    /**
3670     * Called internally by the view system when a new view is getting focus.
3671     * This is what clears the old focus.
3672     */
3673    void unFocus() {
3674        if (DBG) {
3675            System.out.println(this + " unFocus()");
3676        }
3677
3678        if ((mPrivateFlags & FOCUSED) != 0) {
3679            mPrivateFlags &= ~FOCUSED;
3680
3681            onFocusChanged(false, 0, null);
3682            refreshDrawableState();
3683        }
3684    }
3685
3686    /**
3687     * Returns true if this view has focus iteself, or is the ancestor of the
3688     * view that has focus.
3689     *
3690     * @return True if this view has or contains focus, false otherwise.
3691     */
3692    @ViewDebug.ExportedProperty(category = "focus")
3693    public boolean hasFocus() {
3694        return (mPrivateFlags & FOCUSED) != 0;
3695    }
3696
3697    /**
3698     * Returns true if this view is focusable or if it contains a reachable View
3699     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3700     * is a View whose parents do not block descendants focus.
3701     *
3702     * Only {@link #VISIBLE} views are considered focusable.
3703     *
3704     * @return True if the view is focusable or if the view contains a focusable
3705     *         View, false otherwise.
3706     *
3707     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3708     */
3709    public boolean hasFocusable() {
3710        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3711    }
3712
3713    /**
3714     * Called by the view system when the focus state of this view changes.
3715     * When the focus change event is caused by directional navigation, direction
3716     * and previouslyFocusedRect provide insight into where the focus is coming from.
3717     * When overriding, be sure to call up through to the super class so that
3718     * the standard focus handling will occur.
3719     *
3720     * @param gainFocus True if the View has focus; false otherwise.
3721     * @param direction The direction focus has moved when requestFocus()
3722     *                  is called to give this view focus. Values are
3723     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3724     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3725     *                  It may not always apply, in which case use the default.
3726     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3727     *        system, of the previously focused view.  If applicable, this will be
3728     *        passed in as finer grained information about where the focus is coming
3729     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3730     */
3731    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3732        if (gainFocus) {
3733            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3734        }
3735
3736        InputMethodManager imm = InputMethodManager.peekInstance();
3737        if (!gainFocus) {
3738            if (isPressed()) {
3739                setPressed(false);
3740            }
3741            if (imm != null && mAttachInfo != null
3742                    && mAttachInfo.mHasWindowFocus) {
3743                imm.focusOut(this);
3744            }
3745            onFocusLost();
3746        } else if (imm != null && mAttachInfo != null
3747                && mAttachInfo.mHasWindowFocus) {
3748            imm.focusIn(this);
3749        }
3750
3751        invalidate(true);
3752        if (mOnFocusChangeListener != null) {
3753            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3754        }
3755
3756        if (mAttachInfo != null) {
3757            mAttachInfo.mKeyDispatchState.reset(this);
3758        }
3759    }
3760
3761    /**
3762     * Sends an accessibility event of the given type. If accessiiblity is
3763     * not enabled this method has no effect. The default implementation calls
3764     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3765     * to populate information about the event source (this View), then calls
3766     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3767     * populate the text content of the event source including its descendants,
3768     * and last calls
3769     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3770     * on its parent to resuest sending of the event to interested parties.
3771     *
3772     * @param eventType The type of the event to send.
3773     *
3774     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3775     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3776     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3777     */
3778    public void sendAccessibilityEvent(int eventType) {
3779        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3780            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3781        }
3782    }
3783
3784    /**
3785     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3786     * takes as an argument an empty {@link AccessibilityEvent} and does not
3787     * perfrom a check whether accessibility is enabled.
3788     *
3789     * @param event The event to send.
3790     *
3791     * @see #sendAccessibilityEvent(int)
3792     */
3793    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3794        if (!isShown()) {
3795            return;
3796        }
3797        onInitializeAccessibilityEvent(event);
3798        dispatchPopulateAccessibilityEvent(event);
3799        // In the beginning we called #isShown(), so we know that getParent() is not null.
3800        getParent().requestSendAccessibilityEvent(this, event);
3801    }
3802
3803    /**
3804     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3805     * to its children for adding their text content to the event. Note that the
3806     * event text is populated in a separate dispatch path since we add to the
3807     * event not only the text of the source but also the text of all its descendants.
3808     * </p>
3809     * A typical implementation will call
3810     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3811     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3812     * on each child. Override this method if custom population of the event text
3813     * content is required.
3814     *
3815     * @param event The event.
3816     *
3817     * @return True if the event population was completed.
3818     */
3819    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3820        onPopulateAccessibilityEvent(event);
3821        return false;
3822    }
3823
3824    /**
3825     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3826     * giving a chance to this View to populate the accessibility event with its
3827     * text content. While the implementation is free to modify other event
3828     * attributes this should be performed in
3829     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3830     * <p>
3831     * Example: Adding formatted date string to an accessibility event in addition
3832     *          to the text added by the super implementation.
3833     * </p><p><pre><code>
3834     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3835     *     super.onPopulateAccessibilityEvent(event);
3836     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3837     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3838     *         mCurrentDate.getTimeInMillis(), flags);
3839     *     event.getText().add(selectedDateUtterance);
3840     * }
3841     * </code></pre></p>
3842     *
3843     * @param event The accessibility event which to populate.
3844     *
3845     * @see #sendAccessibilityEvent(int)
3846     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3847     */
3848    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3849    }
3850
3851    /**
3852     * Initializes an {@link AccessibilityEvent} with information about the
3853     * the type of the event and this View which is the event source. In other
3854     * words, the source of an accessibility event is the view whose state
3855     * change triggered firing the event.
3856     * <p>
3857     * Example: Setting the password property of an event in addition
3858     *          to properties set by the super implementation.
3859     * </p><p><pre><code>
3860     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3861     *    super.onInitializeAccessibilityEvent(event);
3862     *    event.setPassword(true);
3863     * }
3864     * </code></pre></p>
3865     * @param event The event to initialeze.
3866     *
3867     * @see #sendAccessibilityEvent(int)
3868     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3869     */
3870    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3871        event.setSource(this);
3872        event.setClassName(getClass().getName());
3873        event.setPackageName(getContext().getPackageName());
3874        event.setEnabled(isEnabled());
3875        event.setContentDescription(mContentDescription);
3876
3877        final int eventType = event.getEventType();
3878        switch (eventType) {
3879            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
3880                if (mAttachInfo != null) {
3881                    ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3882                    getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
3883                            FOCUSABLES_ALL);
3884                    event.setItemCount(focusablesTempList.size());
3885                    event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3886                    focusablesTempList.clear();
3887                }
3888            } break;
3889            case AccessibilityEvent.TYPE_VIEW_SCROLLED: {
3890                event.setScrollX(mScrollX);
3891                event.setScrollY(mScrollY);
3892                event.setItemCount(getHeight());
3893            } break;
3894        }
3895    }
3896
3897    /**
3898     * Returns an {@link AccessibilityNodeInfo} representing this view from the
3899     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
3900     * This method is responsible for obtaining an accessibility node info from a
3901     * pool of reusable instances and calling
3902     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
3903     * initialize the former.
3904     * <p>
3905     * Note: The client is responsible for recycling the obtained instance by calling
3906     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
3907     * </p>
3908     * @return A populated {@link AccessibilityNodeInfo}.
3909     *
3910     * @see AccessibilityNodeInfo
3911     */
3912    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
3913        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
3914        onInitializeAccessibilityNodeInfo(info);
3915        return info;
3916    }
3917
3918    /**
3919     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
3920     * The base implementation sets:
3921     * <ul>
3922     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
3923     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
3924     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
3925     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
3926     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
3927     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
3928     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
3929     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
3930     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
3931     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
3932     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
3933     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
3934     * </ul>
3935     * <p>
3936     * Subclasses should override this method, call the super implementation,
3937     * and set additional attributes.
3938     * </p>
3939     * @param info The instance to initialize.
3940     */
3941    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
3942        Rect bounds = mAttachInfo.mTmpInvalRect;
3943        getDrawingRect(bounds);
3944        info.setBoundsInParent(bounds);
3945
3946        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
3947        getLocationOnScreen(locationOnScreen);
3948        bounds.offsetTo(0, 0);
3949        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
3950        info.setBoundsInScreen(bounds);
3951
3952        ViewParent parent = getParent();
3953        if (parent instanceof View) {
3954            View parentView = (View) parent;
3955            info.setParent(parentView);
3956        }
3957
3958        info.setPackageName(mContext.getPackageName());
3959        info.setClassName(getClass().getName());
3960        info.setContentDescription(getContentDescription());
3961
3962        info.setEnabled(isEnabled());
3963        info.setClickable(isClickable());
3964        info.setFocusable(isFocusable());
3965        info.setFocused(isFocused());
3966        info.setSelected(isSelected());
3967        info.setLongClickable(isLongClickable());
3968
3969        // TODO: These make sense only if we are in an AdapterView but all
3970        // views can be selected. Maybe from accessiiblity perspective
3971        // we should report as selectable view in an AdapterView.
3972        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
3973        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
3974
3975        if (isFocusable()) {
3976            if (isFocused()) {
3977                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
3978            } else {
3979                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
3980            }
3981        }
3982    }
3983
3984    /**
3985     * Gets the unique identifier of this view on the screen for accessibility purposes.
3986     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
3987     *
3988     * @return The view accessibility id.
3989     *
3990     * @hide
3991     */
3992    public int getAccessibilityViewId() {
3993        if (mAccessibilityViewId == NO_ID) {
3994            mAccessibilityViewId = sNextAccessibilityViewId++;
3995        }
3996        return mAccessibilityViewId;
3997    }
3998
3999    /**
4000     * Gets the unique identifier of the window in which this View reseides.
4001     *
4002     * @return The window accessibility id.
4003     *
4004     * @hide
4005     */
4006    public int getAccessibilityWindowId() {
4007        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4008    }
4009
4010    /**
4011     * Gets the {@link View} description. It briefly describes the view and is
4012     * primarily used for accessibility support. Set this property to enable
4013     * better accessibility support for your application. This is especially
4014     * true for views that do not have textual representation (For example,
4015     * ImageButton).
4016     *
4017     * @return The content descriptiopn.
4018     *
4019     * @attr ref android.R.styleable#View_contentDescription
4020     */
4021    public CharSequence getContentDescription() {
4022        return mContentDescription;
4023    }
4024
4025    /**
4026     * Sets the {@link View} description. It briefly describes the view and is
4027     * primarily used for accessibility support. Set this property to enable
4028     * better accessibility support for your application. This is especially
4029     * true for views that do not have textual representation (For example,
4030     * ImageButton).
4031     *
4032     * @param contentDescription The content description.
4033     *
4034     * @attr ref android.R.styleable#View_contentDescription
4035     */
4036    public void setContentDescription(CharSequence contentDescription) {
4037        mContentDescription = contentDescription;
4038    }
4039
4040    /**
4041     * Invoked whenever this view loses focus, either by losing window focus or by losing
4042     * focus within its window. This method can be used to clear any state tied to the
4043     * focus. For instance, if a button is held pressed with the trackball and the window
4044     * loses focus, this method can be used to cancel the press.
4045     *
4046     * Subclasses of View overriding this method should always call super.onFocusLost().
4047     *
4048     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4049     * @see #onWindowFocusChanged(boolean)
4050     *
4051     * @hide pending API council approval
4052     */
4053    protected void onFocusLost() {
4054        resetPressedState();
4055    }
4056
4057    private void resetPressedState() {
4058        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4059            return;
4060        }
4061
4062        if (isPressed()) {
4063            setPressed(false);
4064
4065            if (!mHasPerformedLongPress) {
4066                removeLongPressCallback();
4067            }
4068        }
4069    }
4070
4071    /**
4072     * Returns true if this view has focus
4073     *
4074     * @return True if this view has focus, false otherwise.
4075     */
4076    @ViewDebug.ExportedProperty(category = "focus")
4077    public boolean isFocused() {
4078        return (mPrivateFlags & FOCUSED) != 0;
4079    }
4080
4081    /**
4082     * Find the view in the hierarchy rooted at this view that currently has
4083     * focus.
4084     *
4085     * @return The view that currently has focus, or null if no focused view can
4086     *         be found.
4087     */
4088    public View findFocus() {
4089        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4090    }
4091
4092    /**
4093     * Change whether this view is one of the set of scrollable containers in
4094     * its window.  This will be used to determine whether the window can
4095     * resize or must pan when a soft input area is open -- scrollable
4096     * containers allow the window to use resize mode since the container
4097     * will appropriately shrink.
4098     */
4099    public void setScrollContainer(boolean isScrollContainer) {
4100        if (isScrollContainer) {
4101            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4102                mAttachInfo.mScrollContainers.add(this);
4103                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4104            }
4105            mPrivateFlags |= SCROLL_CONTAINER;
4106        } else {
4107            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4108                mAttachInfo.mScrollContainers.remove(this);
4109            }
4110            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4111        }
4112    }
4113
4114    /**
4115     * Returns the quality of the drawing cache.
4116     *
4117     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4118     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4119     *
4120     * @see #setDrawingCacheQuality(int)
4121     * @see #setDrawingCacheEnabled(boolean)
4122     * @see #isDrawingCacheEnabled()
4123     *
4124     * @attr ref android.R.styleable#View_drawingCacheQuality
4125     */
4126    public int getDrawingCacheQuality() {
4127        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4128    }
4129
4130    /**
4131     * Set the drawing cache quality of this view. This value is used only when the
4132     * drawing cache is enabled
4133     *
4134     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4135     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4136     *
4137     * @see #getDrawingCacheQuality()
4138     * @see #setDrawingCacheEnabled(boolean)
4139     * @see #isDrawingCacheEnabled()
4140     *
4141     * @attr ref android.R.styleable#View_drawingCacheQuality
4142     */
4143    public void setDrawingCacheQuality(int quality) {
4144        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4145    }
4146
4147    /**
4148     * Returns whether the screen should remain on, corresponding to the current
4149     * value of {@link #KEEP_SCREEN_ON}.
4150     *
4151     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4152     *
4153     * @see #setKeepScreenOn(boolean)
4154     *
4155     * @attr ref android.R.styleable#View_keepScreenOn
4156     */
4157    public boolean getKeepScreenOn() {
4158        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4159    }
4160
4161    /**
4162     * Controls whether the screen should remain on, modifying the
4163     * value of {@link #KEEP_SCREEN_ON}.
4164     *
4165     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4166     *
4167     * @see #getKeepScreenOn()
4168     *
4169     * @attr ref android.R.styleable#View_keepScreenOn
4170     */
4171    public void setKeepScreenOn(boolean keepScreenOn) {
4172        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4173    }
4174
4175    /**
4176     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4177     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4178     *
4179     * @attr ref android.R.styleable#View_nextFocusLeft
4180     */
4181    public int getNextFocusLeftId() {
4182        return mNextFocusLeftId;
4183    }
4184
4185    /**
4186     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4187     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4188     * decide automatically.
4189     *
4190     * @attr ref android.R.styleable#View_nextFocusLeft
4191     */
4192    public void setNextFocusLeftId(int nextFocusLeftId) {
4193        mNextFocusLeftId = nextFocusLeftId;
4194    }
4195
4196    /**
4197     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4198     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4199     *
4200     * @attr ref android.R.styleable#View_nextFocusRight
4201     */
4202    public int getNextFocusRightId() {
4203        return mNextFocusRightId;
4204    }
4205
4206    /**
4207     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4208     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4209     * decide automatically.
4210     *
4211     * @attr ref android.R.styleable#View_nextFocusRight
4212     */
4213    public void setNextFocusRightId(int nextFocusRightId) {
4214        mNextFocusRightId = nextFocusRightId;
4215    }
4216
4217    /**
4218     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4219     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4220     *
4221     * @attr ref android.R.styleable#View_nextFocusUp
4222     */
4223    public int getNextFocusUpId() {
4224        return mNextFocusUpId;
4225    }
4226
4227    /**
4228     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4229     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4230     * decide automatically.
4231     *
4232     * @attr ref android.R.styleable#View_nextFocusUp
4233     */
4234    public void setNextFocusUpId(int nextFocusUpId) {
4235        mNextFocusUpId = nextFocusUpId;
4236    }
4237
4238    /**
4239     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4240     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4241     *
4242     * @attr ref android.R.styleable#View_nextFocusDown
4243     */
4244    public int getNextFocusDownId() {
4245        return mNextFocusDownId;
4246    }
4247
4248    /**
4249     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4250     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4251     * decide automatically.
4252     *
4253     * @attr ref android.R.styleable#View_nextFocusDown
4254     */
4255    public void setNextFocusDownId(int nextFocusDownId) {
4256        mNextFocusDownId = nextFocusDownId;
4257    }
4258
4259    /**
4260     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4261     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4262     *
4263     * @attr ref android.R.styleable#View_nextFocusForward
4264     */
4265    public int getNextFocusForwardId() {
4266        return mNextFocusForwardId;
4267    }
4268
4269    /**
4270     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4271     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4272     * decide automatically.
4273     *
4274     * @attr ref android.R.styleable#View_nextFocusForward
4275     */
4276    public void setNextFocusForwardId(int nextFocusForwardId) {
4277        mNextFocusForwardId = nextFocusForwardId;
4278    }
4279
4280    /**
4281     * Returns the visibility of this view and all of its ancestors
4282     *
4283     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4284     */
4285    public boolean isShown() {
4286        View current = this;
4287        //noinspection ConstantConditions
4288        do {
4289            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4290                return false;
4291            }
4292            ViewParent parent = current.mParent;
4293            if (parent == null) {
4294                return false; // We are not attached to the view root
4295            }
4296            if (!(parent instanceof View)) {
4297                return true;
4298            }
4299            current = (View) parent;
4300        } while (current != null);
4301
4302        return false;
4303    }
4304
4305    /**
4306     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4307     * is set
4308     *
4309     * @param insets Insets for system windows
4310     *
4311     * @return True if this view applied the insets, false otherwise
4312     */
4313    protected boolean fitSystemWindows(Rect insets) {
4314        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4315            mPaddingLeft = insets.left;
4316            mPaddingTop = insets.top;
4317            mPaddingRight = insets.right;
4318            mPaddingBottom = insets.bottom;
4319            requestLayout();
4320            return true;
4321        }
4322        return false;
4323    }
4324
4325    /**
4326     * Set whether or not this view should account for system screen decorations
4327     * such as the status bar and inset its content. This allows this view to be
4328     * positioned in absolute screen coordinates and remain visible to the user.
4329     *
4330     * <p>This should only be used by top-level window decor views.
4331     *
4332     * @param fitSystemWindows true to inset content for system screen decorations, false for
4333     *                         default behavior.
4334     *
4335     * @attr ref android.R.styleable#View_fitsSystemWindows
4336     */
4337    public void setFitsSystemWindows(boolean fitSystemWindows) {
4338        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4339    }
4340
4341    /**
4342     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4343     * will account for system screen decorations such as the status bar and inset its
4344     * content. This allows the view to be positioned in absolute screen coordinates
4345     * and remain visible to the user.
4346     *
4347     * @return true if this view will adjust its content bounds for system screen decorations.
4348     *
4349     * @attr ref android.R.styleable#View_fitsSystemWindows
4350     */
4351    public boolean fitsSystemWindows() {
4352        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4353    }
4354
4355    /**
4356     * Returns the visibility status for this view.
4357     *
4358     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4359     * @attr ref android.R.styleable#View_visibility
4360     */
4361    @ViewDebug.ExportedProperty(mapping = {
4362        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4363        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4364        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4365    })
4366    public int getVisibility() {
4367        return mViewFlags & VISIBILITY_MASK;
4368    }
4369
4370    /**
4371     * Set the enabled state of this view.
4372     *
4373     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4374     * @attr ref android.R.styleable#View_visibility
4375     */
4376    @RemotableViewMethod
4377    public void setVisibility(int visibility) {
4378        setFlags(visibility, VISIBILITY_MASK);
4379        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4380    }
4381
4382    /**
4383     * Returns the enabled status for this view. The interpretation of the
4384     * enabled state varies by subclass.
4385     *
4386     * @return True if this view is enabled, false otherwise.
4387     */
4388    @ViewDebug.ExportedProperty
4389    public boolean isEnabled() {
4390        return (mViewFlags & ENABLED_MASK) == ENABLED;
4391    }
4392
4393    /**
4394     * Set the enabled state of this view. The interpretation of the enabled
4395     * state varies by subclass.
4396     *
4397     * @param enabled True if this view is enabled, false otherwise.
4398     */
4399    @RemotableViewMethod
4400    public void setEnabled(boolean enabled) {
4401        if (enabled == isEnabled()) return;
4402
4403        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4404
4405        /*
4406         * The View most likely has to change its appearance, so refresh
4407         * the drawable state.
4408         */
4409        refreshDrawableState();
4410
4411        // Invalidate too, since the default behavior for views is to be
4412        // be drawn at 50% alpha rather than to change the drawable.
4413        invalidate(true);
4414    }
4415
4416    /**
4417     * Set whether this view can receive the focus.
4418     *
4419     * Setting this to false will also ensure that this view is not focusable
4420     * in touch mode.
4421     *
4422     * @param focusable If true, this view can receive the focus.
4423     *
4424     * @see #setFocusableInTouchMode(boolean)
4425     * @attr ref android.R.styleable#View_focusable
4426     */
4427    public void setFocusable(boolean focusable) {
4428        if (!focusable) {
4429            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4430        }
4431        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4432    }
4433
4434    /**
4435     * Set whether this view can receive focus while in touch mode.
4436     *
4437     * Setting this to true will also ensure that this view is focusable.
4438     *
4439     * @param focusableInTouchMode If true, this view can receive the focus while
4440     *   in touch mode.
4441     *
4442     * @see #setFocusable(boolean)
4443     * @attr ref android.R.styleable#View_focusableInTouchMode
4444     */
4445    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4446        // Focusable in touch mode should always be set before the focusable flag
4447        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4448        // which, in touch mode, will not successfully request focus on this view
4449        // because the focusable in touch mode flag is not set
4450        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4451        if (focusableInTouchMode) {
4452            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4453        }
4454    }
4455
4456    /**
4457     * Set whether this view should have sound effects enabled for events such as
4458     * clicking and touching.
4459     *
4460     * <p>You may wish to disable sound effects for a view if you already play sounds,
4461     * for instance, a dial key that plays dtmf tones.
4462     *
4463     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4464     * @see #isSoundEffectsEnabled()
4465     * @see #playSoundEffect(int)
4466     * @attr ref android.R.styleable#View_soundEffectsEnabled
4467     */
4468    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4469        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4470    }
4471
4472    /**
4473     * @return whether this view should have sound effects enabled for events such as
4474     *     clicking and touching.
4475     *
4476     * @see #setSoundEffectsEnabled(boolean)
4477     * @see #playSoundEffect(int)
4478     * @attr ref android.R.styleable#View_soundEffectsEnabled
4479     */
4480    @ViewDebug.ExportedProperty
4481    public boolean isSoundEffectsEnabled() {
4482        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4483    }
4484
4485    /**
4486     * Set whether this view should have haptic feedback for events such as
4487     * long presses.
4488     *
4489     * <p>You may wish to disable haptic feedback if your view already controls
4490     * its own haptic feedback.
4491     *
4492     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4493     * @see #isHapticFeedbackEnabled()
4494     * @see #performHapticFeedback(int)
4495     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4496     */
4497    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4498        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4499    }
4500
4501    /**
4502     * @return whether this view should have haptic feedback enabled for events
4503     * long presses.
4504     *
4505     * @see #setHapticFeedbackEnabled(boolean)
4506     * @see #performHapticFeedback(int)
4507     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4508     */
4509    @ViewDebug.ExportedProperty
4510    public boolean isHapticFeedbackEnabled() {
4511        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4512    }
4513
4514    /**
4515     * Returns the layout direction for this view.
4516     *
4517     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4518     *   {@link #LAYOUT_DIRECTION_RTL},
4519     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4520     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4521     * @attr ref android.R.styleable#View_layoutDirection
4522     *
4523     * @hide
4524     */
4525    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4526        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4527        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4528        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4529        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4530    })
4531    public int getLayoutDirection() {
4532        return mViewFlags & LAYOUT_DIRECTION_MASK;
4533    }
4534
4535    /**
4536     * Set the layout direction for this view. This will propagate a reset of layout direction
4537     * resolution to the view's children and resolve layout direction for this view.
4538     *
4539     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4540     *   {@link #LAYOUT_DIRECTION_RTL},
4541     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4542     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4543     *
4544     * @attr ref android.R.styleable#View_layoutDirection
4545     *
4546     * @hide
4547     */
4548    @RemotableViewMethod
4549    public void setLayoutDirection(int layoutDirection) {
4550        if (getLayoutDirection() != layoutDirection) {
4551            resetResolvedLayoutDirection();
4552            // Setting the flag will also request a layout.
4553            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4554        }
4555    }
4556
4557    /**
4558     * Returns the resolved layout direction for this view.
4559     *
4560     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4561     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4562     *
4563     * @hide
4564     */
4565    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4566        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4567        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4568    })
4569    public int getResolvedLayoutDirection() {
4570        resolveLayoutDirectionIfNeeded();
4571        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4572                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4573    }
4574
4575    /**
4576     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4577     * layout attribute and/or the inherited value from the parent.</p>
4578     *
4579     * @return true if the layout is right-to-left.
4580     *
4581     * @hide
4582     */
4583    @ViewDebug.ExportedProperty(category = "layout")
4584    public boolean isLayoutRtl() {
4585        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4586    }
4587
4588    /**
4589     * If this view doesn't do any drawing on its own, set this flag to
4590     * allow further optimizations. By default, this flag is not set on
4591     * View, but could be set on some View subclasses such as ViewGroup.
4592     *
4593     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4594     * you should clear this flag.
4595     *
4596     * @param willNotDraw whether or not this View draw on its own
4597     */
4598    public void setWillNotDraw(boolean willNotDraw) {
4599        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4600    }
4601
4602    /**
4603     * Returns whether or not this View draws on its own.
4604     *
4605     * @return true if this view has nothing to draw, false otherwise
4606     */
4607    @ViewDebug.ExportedProperty(category = "drawing")
4608    public boolean willNotDraw() {
4609        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4610    }
4611
4612    /**
4613     * When a View's drawing cache is enabled, drawing is redirected to an
4614     * offscreen bitmap. Some views, like an ImageView, must be able to
4615     * bypass this mechanism if they already draw a single bitmap, to avoid
4616     * unnecessary usage of the memory.
4617     *
4618     * @param willNotCacheDrawing true if this view does not cache its
4619     *        drawing, false otherwise
4620     */
4621    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4622        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4623    }
4624
4625    /**
4626     * Returns whether or not this View can cache its drawing or not.
4627     *
4628     * @return true if this view does not cache its drawing, false otherwise
4629     */
4630    @ViewDebug.ExportedProperty(category = "drawing")
4631    public boolean willNotCacheDrawing() {
4632        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4633    }
4634
4635    /**
4636     * Indicates whether this view reacts to click events or not.
4637     *
4638     * @return true if the view is clickable, false otherwise
4639     *
4640     * @see #setClickable(boolean)
4641     * @attr ref android.R.styleable#View_clickable
4642     */
4643    @ViewDebug.ExportedProperty
4644    public boolean isClickable() {
4645        return (mViewFlags & CLICKABLE) == CLICKABLE;
4646    }
4647
4648    /**
4649     * Enables or disables click events for this view. When a view
4650     * is clickable it will change its state to "pressed" on every click.
4651     * Subclasses should set the view clickable to visually react to
4652     * user's clicks.
4653     *
4654     * @param clickable true to make the view clickable, false otherwise
4655     *
4656     * @see #isClickable()
4657     * @attr ref android.R.styleable#View_clickable
4658     */
4659    public void setClickable(boolean clickable) {
4660        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4661    }
4662
4663    /**
4664     * Indicates whether this view reacts to long click events or not.
4665     *
4666     * @return true if the view is long clickable, false otherwise
4667     *
4668     * @see #setLongClickable(boolean)
4669     * @attr ref android.R.styleable#View_longClickable
4670     */
4671    public boolean isLongClickable() {
4672        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4673    }
4674
4675    /**
4676     * Enables or disables long click events for this view. When a view is long
4677     * clickable it reacts to the user holding down the button for a longer
4678     * duration than a tap. This event can either launch the listener or a
4679     * context menu.
4680     *
4681     * @param longClickable true to make the view long clickable, false otherwise
4682     * @see #isLongClickable()
4683     * @attr ref android.R.styleable#View_longClickable
4684     */
4685    public void setLongClickable(boolean longClickable) {
4686        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4687    }
4688
4689    /**
4690     * Sets the pressed state for this view.
4691     *
4692     * @see #isClickable()
4693     * @see #setClickable(boolean)
4694     *
4695     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4696     *        the View's internal state from a previously set "pressed" state.
4697     */
4698    public void setPressed(boolean pressed) {
4699        if (pressed) {
4700            mPrivateFlags |= PRESSED;
4701        } else {
4702            mPrivateFlags &= ~PRESSED;
4703        }
4704        refreshDrawableState();
4705        dispatchSetPressed(pressed);
4706    }
4707
4708    /**
4709     * Dispatch setPressed to all of this View's children.
4710     *
4711     * @see #setPressed(boolean)
4712     *
4713     * @param pressed The new pressed state
4714     */
4715    protected void dispatchSetPressed(boolean pressed) {
4716    }
4717
4718    /**
4719     * Indicates whether the view is currently in pressed state. Unless
4720     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4721     * the pressed state.
4722     *
4723     * @see #setPressed(boolean)
4724     * @see #isClickable()
4725     * @see #setClickable(boolean)
4726     *
4727     * @return true if the view is currently pressed, false otherwise
4728     */
4729    public boolean isPressed() {
4730        return (mPrivateFlags & PRESSED) == PRESSED;
4731    }
4732
4733    /**
4734     * Indicates whether this view will save its state (that is,
4735     * whether its {@link #onSaveInstanceState} method will be called).
4736     *
4737     * @return Returns true if the view state saving is enabled, else false.
4738     *
4739     * @see #setSaveEnabled(boolean)
4740     * @attr ref android.R.styleable#View_saveEnabled
4741     */
4742    public boolean isSaveEnabled() {
4743        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4744    }
4745
4746    /**
4747     * Controls whether the saving of this view's state is
4748     * enabled (that is, whether its {@link #onSaveInstanceState} method
4749     * will be called).  Note that even if freezing is enabled, the
4750     * view still must have an id assigned to it (via {@link #setId(int)})
4751     * for its state to be saved.  This flag can only disable the
4752     * saving of this view; any child views may still have their state saved.
4753     *
4754     * @param enabled Set to false to <em>disable</em> state saving, or true
4755     * (the default) to allow it.
4756     *
4757     * @see #isSaveEnabled()
4758     * @see #setId(int)
4759     * @see #onSaveInstanceState()
4760     * @attr ref android.R.styleable#View_saveEnabled
4761     */
4762    public void setSaveEnabled(boolean enabled) {
4763        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4764    }
4765
4766    /**
4767     * Gets whether the framework should discard touches when the view's
4768     * window is obscured by another visible window.
4769     * Refer to the {@link View} security documentation for more details.
4770     *
4771     * @return True if touch filtering is enabled.
4772     *
4773     * @see #setFilterTouchesWhenObscured(boolean)
4774     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4775     */
4776    @ViewDebug.ExportedProperty
4777    public boolean getFilterTouchesWhenObscured() {
4778        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4779    }
4780
4781    /**
4782     * Sets whether the framework should discard touches when the view's
4783     * window is obscured by another visible window.
4784     * Refer to the {@link View} security documentation for more details.
4785     *
4786     * @param enabled True if touch filtering should be enabled.
4787     *
4788     * @see #getFilterTouchesWhenObscured
4789     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4790     */
4791    public void setFilterTouchesWhenObscured(boolean enabled) {
4792        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4793                FILTER_TOUCHES_WHEN_OBSCURED);
4794    }
4795
4796    /**
4797     * Indicates whether the entire hierarchy under this view will save its
4798     * state when a state saving traversal occurs from its parent.  The default
4799     * is true; if false, these views will not be saved unless
4800     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4801     *
4802     * @return Returns true if the view state saving from parent is enabled, else false.
4803     *
4804     * @see #setSaveFromParentEnabled(boolean)
4805     */
4806    public boolean isSaveFromParentEnabled() {
4807        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4808    }
4809
4810    /**
4811     * Controls whether the entire hierarchy under this view will save its
4812     * state when a state saving traversal occurs from its parent.  The default
4813     * is true; if false, these views will not be saved unless
4814     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4815     *
4816     * @param enabled Set to false to <em>disable</em> state saving, or true
4817     * (the default) to allow it.
4818     *
4819     * @see #isSaveFromParentEnabled()
4820     * @see #setId(int)
4821     * @see #onSaveInstanceState()
4822     */
4823    public void setSaveFromParentEnabled(boolean enabled) {
4824        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4825    }
4826
4827
4828    /**
4829     * Returns whether this View is able to take focus.
4830     *
4831     * @return True if this view can take focus, or false otherwise.
4832     * @attr ref android.R.styleable#View_focusable
4833     */
4834    @ViewDebug.ExportedProperty(category = "focus")
4835    public final boolean isFocusable() {
4836        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4837    }
4838
4839    /**
4840     * When a view is focusable, it may not want to take focus when in touch mode.
4841     * For example, a button would like focus when the user is navigating via a D-pad
4842     * so that the user can click on it, but once the user starts touching the screen,
4843     * the button shouldn't take focus
4844     * @return Whether the view is focusable in touch mode.
4845     * @attr ref android.R.styleable#View_focusableInTouchMode
4846     */
4847    @ViewDebug.ExportedProperty
4848    public final boolean isFocusableInTouchMode() {
4849        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4850    }
4851
4852    /**
4853     * Find the nearest view in the specified direction that can take focus.
4854     * This does not actually give focus to that view.
4855     *
4856     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4857     *
4858     * @return The nearest focusable in the specified direction, or null if none
4859     *         can be found.
4860     */
4861    public View focusSearch(int direction) {
4862        if (mParent != null) {
4863            return mParent.focusSearch(this, direction);
4864        } else {
4865            return null;
4866        }
4867    }
4868
4869    /**
4870     * This method is the last chance for the focused view and its ancestors to
4871     * respond to an arrow key. This is called when the focused view did not
4872     * consume the key internally, nor could the view system find a new view in
4873     * the requested direction to give focus to.
4874     *
4875     * @param focused The currently focused view.
4876     * @param direction The direction focus wants to move. One of FOCUS_UP,
4877     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4878     * @return True if the this view consumed this unhandled move.
4879     */
4880    public boolean dispatchUnhandledMove(View focused, int direction) {
4881        return false;
4882    }
4883
4884    /**
4885     * If a user manually specified the next view id for a particular direction,
4886     * use the root to look up the view.
4887     * @param root The root view of the hierarchy containing this view.
4888     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4889     * or FOCUS_BACKWARD.
4890     * @return The user specified next view, or null if there is none.
4891     */
4892    View findUserSetNextFocus(View root, int direction) {
4893        switch (direction) {
4894            case FOCUS_LEFT:
4895                if (mNextFocusLeftId == View.NO_ID) return null;
4896                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
4897            case FOCUS_RIGHT:
4898                if (mNextFocusRightId == View.NO_ID) return null;
4899                return findViewInsideOutShouldExist(root, mNextFocusRightId);
4900            case FOCUS_UP:
4901                if (mNextFocusUpId == View.NO_ID) return null;
4902                return findViewInsideOutShouldExist(root, mNextFocusUpId);
4903            case FOCUS_DOWN:
4904                if (mNextFocusDownId == View.NO_ID) return null;
4905                return findViewInsideOutShouldExist(root, mNextFocusDownId);
4906            case FOCUS_FORWARD:
4907                if (mNextFocusForwardId == View.NO_ID) return null;
4908                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
4909            case FOCUS_BACKWARD: {
4910                final int id = mID;
4911                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
4912                    @Override
4913                    public boolean apply(View t) {
4914                        return t.mNextFocusForwardId == id;
4915                    }
4916                });
4917            }
4918        }
4919        return null;
4920    }
4921
4922    private View findViewInsideOutShouldExist(View root, final int childViewId) {
4923        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
4924            @Override
4925            public boolean apply(View t) {
4926                return t.mID == childViewId;
4927            }
4928        });
4929
4930        if (result == null) {
4931            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4932                    + "by user for id " + childViewId);
4933        }
4934        return result;
4935    }
4936
4937    /**
4938     * Find and return all focusable views that are descendants of this view,
4939     * possibly including this view if it is focusable itself.
4940     *
4941     * @param direction The direction of the focus
4942     * @return A list of focusable views
4943     */
4944    public ArrayList<View> getFocusables(int direction) {
4945        ArrayList<View> result = new ArrayList<View>(24);
4946        addFocusables(result, direction);
4947        return result;
4948    }
4949
4950    /**
4951     * Add any focusable views that are descendants of this view (possibly
4952     * including this view if it is focusable itself) to views.  If we are in touch mode,
4953     * only add views that are also focusable in touch mode.
4954     *
4955     * @param views Focusable views found so far
4956     * @param direction The direction of the focus
4957     */
4958    public void addFocusables(ArrayList<View> views, int direction) {
4959        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4960    }
4961
4962    /**
4963     * Adds any focusable views that are descendants of this view (possibly
4964     * including this view if it is focusable itself) to views. This method
4965     * adds all focusable views regardless if we are in touch mode or
4966     * only views focusable in touch mode if we are in touch mode depending on
4967     * the focusable mode paramater.
4968     *
4969     * @param views Focusable views found so far or null if all we are interested is
4970     *        the number of focusables.
4971     * @param direction The direction of the focus.
4972     * @param focusableMode The type of focusables to be added.
4973     *
4974     * @see #FOCUSABLES_ALL
4975     * @see #FOCUSABLES_TOUCH_MODE
4976     */
4977    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4978        if (!isFocusable()) {
4979            return;
4980        }
4981
4982        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4983                isInTouchMode() && !isFocusableInTouchMode()) {
4984            return;
4985        }
4986
4987        if (views != null) {
4988            views.add(this);
4989        }
4990    }
4991
4992    /**
4993     * Finds the Views that contain given text. The containment is case insensitive.
4994     * As View's text is considered any text content that View renders.
4995     *
4996     * @param outViews The output list of matching Views.
4997     * @param text The text to match against.
4998     */
4999    public void findViewsWithText(ArrayList<View> outViews, CharSequence text) {
5000    }
5001
5002    /**
5003     * Find and return all touchable views that are descendants of this view,
5004     * possibly including this view if it is touchable itself.
5005     *
5006     * @return A list of touchable views
5007     */
5008    public ArrayList<View> getTouchables() {
5009        ArrayList<View> result = new ArrayList<View>();
5010        addTouchables(result);
5011        return result;
5012    }
5013
5014    /**
5015     * Add any touchable views that are descendants of this view (possibly
5016     * including this view if it is touchable itself) to views.
5017     *
5018     * @param views Touchable views found so far
5019     */
5020    public void addTouchables(ArrayList<View> views) {
5021        final int viewFlags = mViewFlags;
5022
5023        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5024                && (viewFlags & ENABLED_MASK) == ENABLED) {
5025            views.add(this);
5026        }
5027    }
5028
5029    /**
5030     * Call this to try to give focus to a specific view or to one of its
5031     * descendants.
5032     *
5033     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5034     * false), or if it is focusable and it is not focusable in touch mode
5035     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5036     *
5037     * See also {@link #focusSearch(int)}, which is what you call to say that you
5038     * have focus, and you want your parent to look for the next one.
5039     *
5040     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5041     * {@link #FOCUS_DOWN} and <code>null</code>.
5042     *
5043     * @return Whether this view or one of its descendants actually took focus.
5044     */
5045    public final boolean requestFocus() {
5046        return requestFocus(View.FOCUS_DOWN);
5047    }
5048
5049
5050    /**
5051     * Call this to try to give focus to a specific view or to one of its
5052     * descendants and give it a hint about what direction focus is heading.
5053     *
5054     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5055     * false), or if it is focusable and it is not focusable in touch mode
5056     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5057     *
5058     * See also {@link #focusSearch(int)}, which is what you call to say that you
5059     * have focus, and you want your parent to look for the next one.
5060     *
5061     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5062     * <code>null</code> set for the previously focused rectangle.
5063     *
5064     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5065     * @return Whether this view or one of its descendants actually took focus.
5066     */
5067    public final boolean requestFocus(int direction) {
5068        return requestFocus(direction, null);
5069    }
5070
5071    /**
5072     * Call this to try to give focus to a specific view or to one of its descendants
5073     * and give it hints about the direction and a specific rectangle that the focus
5074     * is coming from.  The rectangle can help give larger views a finer grained hint
5075     * about where focus is coming from, and therefore, where to show selection, or
5076     * forward focus change internally.
5077     *
5078     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5079     * false), or if it is focusable and it is not focusable in touch mode
5080     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5081     *
5082     * A View will not take focus if it is not visible.
5083     *
5084     * A View will not take focus if one of its parents has
5085     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5086     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5087     *
5088     * See also {@link #focusSearch(int)}, which is what you call to say that you
5089     * have focus, and you want your parent to look for the next one.
5090     *
5091     * You may wish to override this method if your custom {@link View} has an internal
5092     * {@link View} that it wishes to forward the request to.
5093     *
5094     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5095     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5096     *        to give a finer grained hint about where focus is coming from.  May be null
5097     *        if there is no hint.
5098     * @return Whether this view or one of its descendants actually took focus.
5099     */
5100    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5101        // need to be focusable
5102        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5103                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5104            return false;
5105        }
5106
5107        // need to be focusable in touch mode if in touch mode
5108        if (isInTouchMode() &&
5109            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5110               return false;
5111        }
5112
5113        // need to not have any parents blocking us
5114        if (hasAncestorThatBlocksDescendantFocus()) {
5115            return false;
5116        }
5117
5118        handleFocusGainInternal(direction, previouslyFocusedRect);
5119        return true;
5120    }
5121
5122    /** Gets the ViewAncestor, or null if not attached. */
5123    /*package*/ ViewRootImpl getViewRootImpl() {
5124        View root = getRootView();
5125        return root != null ? (ViewRootImpl)root.getParent() : null;
5126    }
5127
5128    /**
5129     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5130     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5131     * touch mode to request focus when they are touched.
5132     *
5133     * @return Whether this view or one of its descendants actually took focus.
5134     *
5135     * @see #isInTouchMode()
5136     *
5137     */
5138    public final boolean requestFocusFromTouch() {
5139        // Leave touch mode if we need to
5140        if (isInTouchMode()) {
5141            ViewRootImpl viewRoot = getViewRootImpl();
5142            if (viewRoot != null) {
5143                viewRoot.ensureTouchMode(false);
5144            }
5145        }
5146        return requestFocus(View.FOCUS_DOWN);
5147    }
5148
5149    /**
5150     * @return Whether any ancestor of this view blocks descendant focus.
5151     */
5152    private boolean hasAncestorThatBlocksDescendantFocus() {
5153        ViewParent ancestor = mParent;
5154        while (ancestor instanceof ViewGroup) {
5155            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5156            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5157                return true;
5158            } else {
5159                ancestor = vgAncestor.getParent();
5160            }
5161        }
5162        return false;
5163    }
5164
5165    /**
5166     * @hide
5167     */
5168    public void dispatchStartTemporaryDetach() {
5169        onStartTemporaryDetach();
5170    }
5171
5172    /**
5173     * This is called when a container is going to temporarily detach a child, with
5174     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5175     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5176     * {@link #onDetachedFromWindow()} when the container is done.
5177     */
5178    public void onStartTemporaryDetach() {
5179        removeUnsetPressCallback();
5180        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5181    }
5182
5183    /**
5184     * @hide
5185     */
5186    public void dispatchFinishTemporaryDetach() {
5187        onFinishTemporaryDetach();
5188    }
5189
5190    /**
5191     * Called after {@link #onStartTemporaryDetach} when the container is done
5192     * changing the view.
5193     */
5194    public void onFinishTemporaryDetach() {
5195    }
5196
5197    /**
5198     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5199     * for this view's window.  Returns null if the view is not currently attached
5200     * to the window.  Normally you will not need to use this directly, but
5201     * just use the standard high-level event callbacks like
5202     * {@link #onKeyDown(int, KeyEvent)}.
5203     */
5204    public KeyEvent.DispatcherState getKeyDispatcherState() {
5205        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5206    }
5207
5208    /**
5209     * Dispatch a key event before it is processed by any input method
5210     * associated with the view hierarchy.  This can be used to intercept
5211     * key events in special situations before the IME consumes them; a
5212     * typical example would be handling the BACK key to update the application's
5213     * UI instead of allowing the IME to see it and close itself.
5214     *
5215     * @param event The key event to be dispatched.
5216     * @return True if the event was handled, false otherwise.
5217     */
5218    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5219        return onKeyPreIme(event.getKeyCode(), event);
5220    }
5221
5222    /**
5223     * Dispatch a key event to the next view on the focus path. This path runs
5224     * from the top of the view tree down to the currently focused view. If this
5225     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5226     * the next node down the focus path. This method also fires any key
5227     * listeners.
5228     *
5229     * @param event The key event to be dispatched.
5230     * @return True if the event was handled, false otherwise.
5231     */
5232    public boolean dispatchKeyEvent(KeyEvent event) {
5233        if (mInputEventConsistencyVerifier != null) {
5234            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5235        }
5236
5237        // Give any attached key listener a first crack at the event.
5238        //noinspection SimplifiableIfStatement
5239        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5240                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5241            return true;
5242        }
5243
5244        if (event.dispatch(this, mAttachInfo != null
5245                ? mAttachInfo.mKeyDispatchState : null, this)) {
5246            return true;
5247        }
5248
5249        if (mInputEventConsistencyVerifier != null) {
5250            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5251        }
5252        return false;
5253    }
5254
5255    /**
5256     * Dispatches a key shortcut event.
5257     *
5258     * @param event The key event to be dispatched.
5259     * @return True if the event was handled by the view, false otherwise.
5260     */
5261    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5262        return onKeyShortcut(event.getKeyCode(), event);
5263    }
5264
5265    /**
5266     * Pass the touch screen motion event down to the target view, or this
5267     * view if it is the target.
5268     *
5269     * @param event The motion event to be dispatched.
5270     * @return True if the event was handled by the view, false otherwise.
5271     */
5272    public boolean dispatchTouchEvent(MotionEvent event) {
5273        if (mInputEventConsistencyVerifier != null) {
5274            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5275        }
5276
5277        if (onFilterTouchEventForSecurity(event)) {
5278            //noinspection SimplifiableIfStatement
5279            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
5280                    mOnTouchListener.onTouch(this, event)) {
5281                return true;
5282            }
5283
5284            if (onTouchEvent(event)) {
5285                return true;
5286            }
5287        }
5288
5289        if (mInputEventConsistencyVerifier != null) {
5290            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5291        }
5292        return false;
5293    }
5294
5295    /**
5296     * Filter the touch event to apply security policies.
5297     *
5298     * @param event The motion event to be filtered.
5299     * @return True if the event should be dispatched, false if the event should be dropped.
5300     *
5301     * @see #getFilterTouchesWhenObscured
5302     */
5303    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5304        //noinspection RedundantIfStatement
5305        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5306                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5307            // Window is obscured, drop this touch.
5308            return false;
5309        }
5310        return true;
5311    }
5312
5313    /**
5314     * Pass a trackball motion event down to the focused view.
5315     *
5316     * @param event The motion event to be dispatched.
5317     * @return True if the event was handled by the view, false otherwise.
5318     */
5319    public boolean dispatchTrackballEvent(MotionEvent event) {
5320        if (mInputEventConsistencyVerifier != null) {
5321            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5322        }
5323
5324        return onTrackballEvent(event);
5325    }
5326
5327    /**
5328     * Dispatch a generic motion event.
5329     * <p>
5330     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5331     * are delivered to the view under the pointer.  All other generic motion events are
5332     * delivered to the focused view.  Hover events are handled specially and are delivered
5333     * to {@link #onHoverEvent(MotionEvent)}.
5334     * </p>
5335     *
5336     * @param event The motion event to be dispatched.
5337     * @return True if the event was handled by the view, false otherwise.
5338     */
5339    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5340        if (mInputEventConsistencyVerifier != null) {
5341            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5342        }
5343
5344        final int source = event.getSource();
5345        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5346            final int action = event.getAction();
5347            if (action == MotionEvent.ACTION_HOVER_ENTER
5348                    || action == MotionEvent.ACTION_HOVER_MOVE
5349                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5350                if (dispatchHoverEvent(event)) {
5351                    return true;
5352                }
5353            } else if (dispatchGenericPointerEvent(event)) {
5354                return true;
5355            }
5356        } else if (dispatchGenericFocusedEvent(event)) {
5357            return true;
5358        }
5359
5360        if (dispatchGenericMotionEventInternal(event)) {
5361            return true;
5362        }
5363
5364        if (mInputEventConsistencyVerifier != null) {
5365            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5366        }
5367        return false;
5368    }
5369
5370    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5371        //noinspection SimplifiableIfStatement
5372        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5373                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5374            return true;
5375        }
5376
5377        if (onGenericMotionEvent(event)) {
5378            return true;
5379        }
5380
5381        if (mInputEventConsistencyVerifier != null) {
5382            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5383        }
5384        return false;
5385    }
5386
5387    /**
5388     * Dispatch a hover event.
5389     * <p>
5390     * Do not call this method directly.
5391     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5392     * </p>
5393     *
5394     * @param event The motion event to be dispatched.
5395     * @return True if the event was handled by the view, false otherwise.
5396     */
5397    protected boolean dispatchHoverEvent(MotionEvent event) {
5398        //noinspection SimplifiableIfStatement
5399        if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5400                && mOnHoverListener.onHover(this, event)) {
5401            return true;
5402        }
5403
5404        return onHoverEvent(event);
5405    }
5406
5407    /**
5408     * Returns true if the view has a child to which it has recently sent
5409     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5410     * it does not have a hovered child, then it must be the innermost hovered view.
5411     * @hide
5412     */
5413    protected boolean hasHoveredChild() {
5414        return false;
5415    }
5416
5417    /**
5418     * Dispatch a generic motion event to the view under the first pointer.
5419     * <p>
5420     * Do not call this method directly.
5421     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5422     * </p>
5423     *
5424     * @param event The motion event to be dispatched.
5425     * @return True if the event was handled by the view, false otherwise.
5426     */
5427    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5428        return false;
5429    }
5430
5431    /**
5432     * Dispatch a generic motion event to the currently focused view.
5433     * <p>
5434     * Do not call this method directly.
5435     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5436     * </p>
5437     *
5438     * @param event The motion event to be dispatched.
5439     * @return True if the event was handled by the view, false otherwise.
5440     */
5441    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5442        return false;
5443    }
5444
5445    /**
5446     * Dispatch a pointer event.
5447     * <p>
5448     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5449     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5450     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5451     * and should not be expected to handle other pointing device features.
5452     * </p>
5453     *
5454     * @param event The motion event to be dispatched.
5455     * @return True if the event was handled by the view, false otherwise.
5456     * @hide
5457     */
5458    public final boolean dispatchPointerEvent(MotionEvent event) {
5459        if (event.isTouchEvent()) {
5460            return dispatchTouchEvent(event);
5461        } else {
5462            return dispatchGenericMotionEvent(event);
5463        }
5464    }
5465
5466    /**
5467     * Called when the window containing this view gains or loses window focus.
5468     * ViewGroups should override to route to their children.
5469     *
5470     * @param hasFocus True if the window containing this view now has focus,
5471     *        false otherwise.
5472     */
5473    public void dispatchWindowFocusChanged(boolean hasFocus) {
5474        onWindowFocusChanged(hasFocus);
5475    }
5476
5477    /**
5478     * Called when the window containing this view gains or loses focus.  Note
5479     * that this is separate from view focus: to receive key events, both
5480     * your view and its window must have focus.  If a window is displayed
5481     * on top of yours that takes input focus, then your own window will lose
5482     * focus but the view focus will remain unchanged.
5483     *
5484     * @param hasWindowFocus True if the window containing this view now has
5485     *        focus, false otherwise.
5486     */
5487    public void onWindowFocusChanged(boolean hasWindowFocus) {
5488        InputMethodManager imm = InputMethodManager.peekInstance();
5489        if (!hasWindowFocus) {
5490            if (isPressed()) {
5491                setPressed(false);
5492            }
5493            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5494                imm.focusOut(this);
5495            }
5496            removeLongPressCallback();
5497            removeTapCallback();
5498            onFocusLost();
5499        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5500            imm.focusIn(this);
5501        }
5502        refreshDrawableState();
5503    }
5504
5505    /**
5506     * Returns true if this view is in a window that currently has window focus.
5507     * Note that this is not the same as the view itself having focus.
5508     *
5509     * @return True if this view is in a window that currently has window focus.
5510     */
5511    public boolean hasWindowFocus() {
5512        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5513    }
5514
5515    /**
5516     * Dispatch a view visibility change down the view hierarchy.
5517     * ViewGroups should override to route to their children.
5518     * @param changedView The view whose visibility changed. Could be 'this' or
5519     * an ancestor view.
5520     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5521     * {@link #INVISIBLE} or {@link #GONE}.
5522     */
5523    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5524        onVisibilityChanged(changedView, visibility);
5525    }
5526
5527    /**
5528     * Called when the visibility of the view or an ancestor of the view is changed.
5529     * @param changedView The view whose visibility changed. Could be 'this' or
5530     * an ancestor view.
5531     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5532     * {@link #INVISIBLE} or {@link #GONE}.
5533     */
5534    protected void onVisibilityChanged(View changedView, int visibility) {
5535        if (visibility == VISIBLE) {
5536            if (mAttachInfo != null) {
5537                initialAwakenScrollBars();
5538            } else {
5539                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5540            }
5541        }
5542    }
5543
5544    /**
5545     * Dispatch a hint about whether this view is displayed. For instance, when
5546     * a View moves out of the screen, it might receives a display hint indicating
5547     * the view is not displayed. Applications should not <em>rely</em> on this hint
5548     * as there is no guarantee that they will receive one.
5549     *
5550     * @param hint A hint about whether or not this view is displayed:
5551     * {@link #VISIBLE} or {@link #INVISIBLE}.
5552     */
5553    public void dispatchDisplayHint(int hint) {
5554        onDisplayHint(hint);
5555    }
5556
5557    /**
5558     * Gives this view a hint about whether is displayed or not. For instance, when
5559     * a View moves out of the screen, it might receives a display hint indicating
5560     * the view is not displayed. Applications should not <em>rely</em> on this hint
5561     * as there is no guarantee that they will receive one.
5562     *
5563     * @param hint A hint about whether or not this view is displayed:
5564     * {@link #VISIBLE} or {@link #INVISIBLE}.
5565     */
5566    protected void onDisplayHint(int hint) {
5567    }
5568
5569    /**
5570     * Dispatch a window visibility change down the view hierarchy.
5571     * ViewGroups should override to route to their children.
5572     *
5573     * @param visibility The new visibility of the window.
5574     *
5575     * @see #onWindowVisibilityChanged(int)
5576     */
5577    public void dispatchWindowVisibilityChanged(int visibility) {
5578        onWindowVisibilityChanged(visibility);
5579    }
5580
5581    /**
5582     * Called when the window containing has change its visibility
5583     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5584     * that this tells you whether or not your window is being made visible
5585     * to the window manager; this does <em>not</em> tell you whether or not
5586     * your window is obscured by other windows on the screen, even if it
5587     * is itself visible.
5588     *
5589     * @param visibility The new visibility of the window.
5590     */
5591    protected void onWindowVisibilityChanged(int visibility) {
5592        if (visibility == VISIBLE) {
5593            initialAwakenScrollBars();
5594        }
5595    }
5596
5597    /**
5598     * Returns the current visibility of the window this view is attached to
5599     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5600     *
5601     * @return Returns the current visibility of the view's window.
5602     */
5603    public int getWindowVisibility() {
5604        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5605    }
5606
5607    /**
5608     * Retrieve the overall visible display size in which the window this view is
5609     * attached to has been positioned in.  This takes into account screen
5610     * decorations above the window, for both cases where the window itself
5611     * is being position inside of them or the window is being placed under
5612     * then and covered insets are used for the window to position its content
5613     * inside.  In effect, this tells you the available area where content can
5614     * be placed and remain visible to users.
5615     *
5616     * <p>This function requires an IPC back to the window manager to retrieve
5617     * the requested information, so should not be used in performance critical
5618     * code like drawing.
5619     *
5620     * @param outRect Filled in with the visible display frame.  If the view
5621     * is not attached to a window, this is simply the raw display size.
5622     */
5623    public void getWindowVisibleDisplayFrame(Rect outRect) {
5624        if (mAttachInfo != null) {
5625            try {
5626                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5627            } catch (RemoteException e) {
5628                return;
5629            }
5630            // XXX This is really broken, and probably all needs to be done
5631            // in the window manager, and we need to know more about whether
5632            // we want the area behind or in front of the IME.
5633            final Rect insets = mAttachInfo.mVisibleInsets;
5634            outRect.left += insets.left;
5635            outRect.top += insets.top;
5636            outRect.right -= insets.right;
5637            outRect.bottom -= insets.bottom;
5638            return;
5639        }
5640        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5641        d.getRectSize(outRect);
5642    }
5643
5644    /**
5645     * Dispatch a notification about a resource configuration change down
5646     * the view hierarchy.
5647     * ViewGroups should override to route to their children.
5648     *
5649     * @param newConfig The new resource configuration.
5650     *
5651     * @see #onConfigurationChanged(android.content.res.Configuration)
5652     */
5653    public void dispatchConfigurationChanged(Configuration newConfig) {
5654        onConfigurationChanged(newConfig);
5655    }
5656
5657    /**
5658     * Called when the current configuration of the resources being used
5659     * by the application have changed.  You can use this to decide when
5660     * to reload resources that can changed based on orientation and other
5661     * configuration characterstics.  You only need to use this if you are
5662     * not relying on the normal {@link android.app.Activity} mechanism of
5663     * recreating the activity instance upon a configuration change.
5664     *
5665     * @param newConfig The new resource configuration.
5666     */
5667    protected void onConfigurationChanged(Configuration newConfig) {
5668    }
5669
5670    /**
5671     * Private function to aggregate all per-view attributes in to the view
5672     * root.
5673     */
5674    void dispatchCollectViewAttributes(int visibility) {
5675        performCollectViewAttributes(visibility);
5676    }
5677
5678    void performCollectViewAttributes(int visibility) {
5679        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5680            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5681                mAttachInfo.mKeepScreenOn = true;
5682            }
5683            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5684            if (mOnSystemUiVisibilityChangeListener != null) {
5685                mAttachInfo.mHasSystemUiListeners = true;
5686            }
5687        }
5688    }
5689
5690    void needGlobalAttributesUpdate(boolean force) {
5691        final AttachInfo ai = mAttachInfo;
5692        if (ai != null) {
5693            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5694                    || ai.mHasSystemUiListeners) {
5695                ai.mRecomputeGlobalAttributes = true;
5696            }
5697        }
5698    }
5699
5700    /**
5701     * Returns whether the device is currently in touch mode.  Touch mode is entered
5702     * once the user begins interacting with the device by touch, and affects various
5703     * things like whether focus is always visible to the user.
5704     *
5705     * @return Whether the device is in touch mode.
5706     */
5707    @ViewDebug.ExportedProperty
5708    public boolean isInTouchMode() {
5709        if (mAttachInfo != null) {
5710            return mAttachInfo.mInTouchMode;
5711        } else {
5712            return ViewRootImpl.isInTouchMode();
5713        }
5714    }
5715
5716    /**
5717     * Returns the context the view is running in, through which it can
5718     * access the current theme, resources, etc.
5719     *
5720     * @return The view's Context.
5721     */
5722    @ViewDebug.CapturedViewProperty
5723    public final Context getContext() {
5724        return mContext;
5725    }
5726
5727    /**
5728     * Handle a key event before it is processed by any input method
5729     * associated with the view hierarchy.  This can be used to intercept
5730     * key events in special situations before the IME consumes them; a
5731     * typical example would be handling the BACK key to update the application's
5732     * UI instead of allowing the IME to see it and close itself.
5733     *
5734     * @param keyCode The value in event.getKeyCode().
5735     * @param event Description of the key event.
5736     * @return If you handled the event, return true. If you want to allow the
5737     *         event to be handled by the next receiver, return false.
5738     */
5739    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5740        return false;
5741    }
5742
5743    /**
5744     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5745     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5746     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5747     * is released, if the view is enabled and clickable.
5748     *
5749     * @param keyCode A key code that represents the button pressed, from
5750     *                {@link android.view.KeyEvent}.
5751     * @param event   The KeyEvent object that defines the button action.
5752     */
5753    public boolean onKeyDown(int keyCode, KeyEvent event) {
5754        boolean result = false;
5755
5756        switch (keyCode) {
5757            case KeyEvent.KEYCODE_DPAD_CENTER:
5758            case KeyEvent.KEYCODE_ENTER: {
5759                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5760                    return true;
5761                }
5762                // Long clickable items don't necessarily have to be clickable
5763                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5764                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5765                        (event.getRepeatCount() == 0)) {
5766                    setPressed(true);
5767                    checkForLongClick(0);
5768                    return true;
5769                }
5770                break;
5771            }
5772        }
5773        return result;
5774    }
5775
5776    /**
5777     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5778     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5779     * the event).
5780     */
5781    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5782        return false;
5783    }
5784
5785    /**
5786     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5787     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5788     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5789     * {@link KeyEvent#KEYCODE_ENTER} is released.
5790     *
5791     * @param keyCode A key code that represents the button pressed, from
5792     *                {@link android.view.KeyEvent}.
5793     * @param event   The KeyEvent object that defines the button action.
5794     */
5795    public boolean onKeyUp(int keyCode, KeyEvent event) {
5796        boolean result = false;
5797
5798        switch (keyCode) {
5799            case KeyEvent.KEYCODE_DPAD_CENTER:
5800            case KeyEvent.KEYCODE_ENTER: {
5801                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5802                    return true;
5803                }
5804                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5805                    setPressed(false);
5806
5807                    if (!mHasPerformedLongPress) {
5808                        // This is a tap, so remove the longpress check
5809                        removeLongPressCallback();
5810
5811                        result = performClick();
5812                    }
5813                }
5814                break;
5815            }
5816        }
5817        return result;
5818    }
5819
5820    /**
5821     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
5822     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
5823     * the event).
5824     *
5825     * @param keyCode     A key code that represents the button pressed, from
5826     *                    {@link android.view.KeyEvent}.
5827     * @param repeatCount The number of times the action was made.
5828     * @param event       The KeyEvent object that defines the button action.
5829     */
5830    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5831        return false;
5832    }
5833
5834    /**
5835     * Called on the focused view when a key shortcut event is not handled.
5836     * Override this method to implement local key shortcuts for the View.
5837     * Key shortcuts can also be implemented by setting the
5838     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
5839     *
5840     * @param keyCode The value in event.getKeyCode().
5841     * @param event Description of the key event.
5842     * @return If you handled the event, return true. If you want to allow the
5843     *         event to be handled by the next receiver, return false.
5844     */
5845    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
5846        return false;
5847    }
5848
5849    /**
5850     * Check whether the called view is a text editor, in which case it
5851     * would make sense to automatically display a soft input window for
5852     * it.  Subclasses should override this if they implement
5853     * {@link #onCreateInputConnection(EditorInfo)} to return true if
5854     * a call on that method would return a non-null InputConnection, and
5855     * they are really a first-class editor that the user would normally
5856     * start typing on when the go into a window containing your view.
5857     *
5858     * <p>The default implementation always returns false.  This does
5859     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
5860     * will not be called or the user can not otherwise perform edits on your
5861     * view; it is just a hint to the system that this is not the primary
5862     * purpose of this view.
5863     *
5864     * @return Returns true if this view is a text editor, else false.
5865     */
5866    public boolean onCheckIsTextEditor() {
5867        return false;
5868    }
5869
5870    /**
5871     * Create a new InputConnection for an InputMethod to interact
5872     * with the view.  The default implementation returns null, since it doesn't
5873     * support input methods.  You can override this to implement such support.
5874     * This is only needed for views that take focus and text input.
5875     *
5876     * <p>When implementing this, you probably also want to implement
5877     * {@link #onCheckIsTextEditor()} to indicate you will return a
5878     * non-null InputConnection.
5879     *
5880     * @param outAttrs Fill in with attribute information about the connection.
5881     */
5882    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5883        return null;
5884    }
5885
5886    /**
5887     * Called by the {@link android.view.inputmethod.InputMethodManager}
5888     * when a view who is not the current
5889     * input connection target is trying to make a call on the manager.  The
5890     * default implementation returns false; you can override this to return
5891     * true for certain views if you are performing InputConnection proxying
5892     * to them.
5893     * @param view The View that is making the InputMethodManager call.
5894     * @return Return true to allow the call, false to reject.
5895     */
5896    public boolean checkInputConnectionProxy(View view) {
5897        return false;
5898    }
5899
5900    /**
5901     * Show the context menu for this view. It is not safe to hold on to the
5902     * menu after returning from this method.
5903     *
5904     * You should normally not overload this method. Overload
5905     * {@link #onCreateContextMenu(ContextMenu)} or define an
5906     * {@link OnCreateContextMenuListener} to add items to the context menu.
5907     *
5908     * @param menu The context menu to populate
5909     */
5910    public void createContextMenu(ContextMenu menu) {
5911        ContextMenuInfo menuInfo = getContextMenuInfo();
5912
5913        // Sets the current menu info so all items added to menu will have
5914        // my extra info set.
5915        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
5916
5917        onCreateContextMenu(menu);
5918        if (mOnCreateContextMenuListener != null) {
5919            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
5920        }
5921
5922        // Clear the extra information so subsequent items that aren't mine don't
5923        // have my extra info.
5924        ((MenuBuilder)menu).setCurrentMenuInfo(null);
5925
5926        if (mParent != null) {
5927            mParent.createContextMenu(menu);
5928        }
5929    }
5930
5931    /**
5932     * Views should implement this if they have extra information to associate
5933     * with the context menu. The return result is supplied as a parameter to
5934     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5935     * callback.
5936     *
5937     * @return Extra information about the item for which the context menu
5938     *         should be shown. This information will vary across different
5939     *         subclasses of View.
5940     */
5941    protected ContextMenuInfo getContextMenuInfo() {
5942        return null;
5943    }
5944
5945    /**
5946     * Views should implement this if the view itself is going to add items to
5947     * the context menu.
5948     *
5949     * @param menu the context menu to populate
5950     */
5951    protected void onCreateContextMenu(ContextMenu menu) {
5952    }
5953
5954    /**
5955     * Implement this method to handle trackball motion events.  The
5956     * <em>relative</em> movement of the trackball since the last event
5957     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5958     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
5959     * that a movement of 1 corresponds to the user pressing one DPAD key (so
5960     * they will often be fractional values, representing the more fine-grained
5961     * movement information available from a trackball).
5962     *
5963     * @param event The motion event.
5964     * @return True if the event was handled, false otherwise.
5965     */
5966    public boolean onTrackballEvent(MotionEvent event) {
5967        return false;
5968    }
5969
5970    /**
5971     * Implement this method to handle generic motion events.
5972     * <p>
5973     * Generic motion events describe joystick movements, mouse hovers, track pad
5974     * touches, scroll wheel movements and other input events.  The
5975     * {@link MotionEvent#getSource() source} of the motion event specifies
5976     * the class of input that was received.  Implementations of this method
5977     * must examine the bits in the source before processing the event.
5978     * The following code example shows how this is done.
5979     * </p><p>
5980     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5981     * are delivered to the view under the pointer.  All other generic motion events are
5982     * delivered to the focused view.
5983     * </p>
5984     * <code>
5985     * public boolean onGenericMotionEvent(MotionEvent event) {
5986     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
5987     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
5988     *             // process the joystick movement...
5989     *             return true;
5990     *         }
5991     *     }
5992     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
5993     *         switch (event.getAction()) {
5994     *             case MotionEvent.ACTION_HOVER_MOVE:
5995     *                 // process the mouse hover movement...
5996     *                 return true;
5997     *             case MotionEvent.ACTION_SCROLL:
5998     *                 // process the scroll wheel movement...
5999     *                 return true;
6000     *         }
6001     *     }
6002     *     return super.onGenericMotionEvent(event);
6003     * }
6004     * </code>
6005     *
6006     * @param event The generic motion event being processed.
6007     * @return True if the event was handled, false otherwise.
6008     */
6009    public boolean onGenericMotionEvent(MotionEvent event) {
6010        return false;
6011    }
6012
6013    /**
6014     * Implement this method to handle hover events.
6015     * <p>
6016     * This method is called whenever a pointer is hovering into, over, or out of the
6017     * bounds of a view and the view is not currently being touched.
6018     * Hover events are represented as pointer events with action
6019     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6020     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6021     * </p>
6022     * <ul>
6023     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6024     * when the pointer enters the bounds of the view.</li>
6025     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6026     * when the pointer has already entered the bounds of the view and has moved.</li>
6027     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6028     * when the pointer has exited the bounds of the view or when the pointer is
6029     * about to go down due to a button click, tap, or similar user action that
6030     * causes the view to be touched.</li>
6031     * </ul>
6032     * <p>
6033     * The view should implement this method to return true to indicate that it is
6034     * handling the hover event, such as by changing its drawable state.
6035     * </p><p>
6036     * The default implementation calls {@link #setHovered} to update the hovered state
6037     * of the view when a hover enter or hover exit event is received, if the view
6038     * is enabled and is clickable.  The default implementation also sends hover
6039     * accessibility events.
6040     * </p>
6041     *
6042     * @param event The motion event that describes the hover.
6043     * @return True if the view handled the hover event.
6044     *
6045     * @see #isHovered
6046     * @see #setHovered
6047     * @see #onHoverChanged
6048     */
6049    public boolean onHoverEvent(MotionEvent event) {
6050        // The root view may receive hover (or touch) events that are outside the bounds of
6051        // the window.  This code ensures that we only send accessibility events for
6052        // hovers that are actually within the bounds of the root view.
6053        final int action = event.getAction();
6054        if (!mSendingHoverAccessibilityEvents) {
6055            if ((action == MotionEvent.ACTION_HOVER_ENTER
6056                    || action == MotionEvent.ACTION_HOVER_MOVE)
6057                    && !hasHoveredChild()
6058                    && pointInView(event.getX(), event.getY())) {
6059                mSendingHoverAccessibilityEvents = true;
6060                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6061            }
6062        } else {
6063            if (action == MotionEvent.ACTION_HOVER_EXIT
6064                    || (action == MotionEvent.ACTION_HOVER_MOVE
6065                            && !pointInView(event.getX(), event.getY()))) {
6066                mSendingHoverAccessibilityEvents = false;
6067                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6068            }
6069        }
6070
6071        if (isHoverable()) {
6072            switch (action) {
6073                case MotionEvent.ACTION_HOVER_ENTER:
6074                    setHovered(true);
6075                    break;
6076                case MotionEvent.ACTION_HOVER_EXIT:
6077                    setHovered(false);
6078                    break;
6079            }
6080
6081            // Dispatch the event to onGenericMotionEvent before returning true.
6082            // This is to provide compatibility with existing applications that
6083            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6084            // break because of the new default handling for hoverable views
6085            // in onHoverEvent.
6086            // Note that onGenericMotionEvent will be called by default when
6087            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6088            dispatchGenericMotionEventInternal(event);
6089            return true;
6090        }
6091        return false;
6092    }
6093
6094    /**
6095     * Returns true if the view should handle {@link #onHoverEvent}
6096     * by calling {@link #setHovered} to change its hovered state.
6097     *
6098     * @return True if the view is hoverable.
6099     */
6100    private boolean isHoverable() {
6101        final int viewFlags = mViewFlags;
6102        //noinspection SimplifiableIfStatement
6103        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6104            return false;
6105        }
6106
6107        return (viewFlags & CLICKABLE) == CLICKABLE
6108                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6109    }
6110
6111    /**
6112     * Returns true if the view is currently hovered.
6113     *
6114     * @return True if the view is currently hovered.
6115     *
6116     * @see #setHovered
6117     * @see #onHoverChanged
6118     */
6119    @ViewDebug.ExportedProperty
6120    public boolean isHovered() {
6121        return (mPrivateFlags & HOVERED) != 0;
6122    }
6123
6124    /**
6125     * Sets whether the view is currently hovered.
6126     * <p>
6127     * Calling this method also changes the drawable state of the view.  This
6128     * enables the view to react to hover by using different drawable resources
6129     * to change its appearance.
6130     * </p><p>
6131     * The {@link #onHoverChanged} method is called when the hovered state changes.
6132     * </p>
6133     *
6134     * @param hovered True if the view is hovered.
6135     *
6136     * @see #isHovered
6137     * @see #onHoverChanged
6138     */
6139    public void setHovered(boolean hovered) {
6140        if (hovered) {
6141            if ((mPrivateFlags & HOVERED) == 0) {
6142                mPrivateFlags |= HOVERED;
6143                refreshDrawableState();
6144                onHoverChanged(true);
6145            }
6146        } else {
6147            if ((mPrivateFlags & HOVERED) != 0) {
6148                mPrivateFlags &= ~HOVERED;
6149                refreshDrawableState();
6150                onHoverChanged(false);
6151            }
6152        }
6153    }
6154
6155    /**
6156     * Implement this method to handle hover state changes.
6157     * <p>
6158     * This method is called whenever the hover state changes as a result of a
6159     * call to {@link #setHovered}.
6160     * </p>
6161     *
6162     * @param hovered The current hover state, as returned by {@link #isHovered}.
6163     *
6164     * @see #isHovered
6165     * @see #setHovered
6166     */
6167    public void onHoverChanged(boolean hovered) {
6168    }
6169
6170    /**
6171     * Implement this method to handle touch screen motion events.
6172     *
6173     * @param event The motion event.
6174     * @return True if the event was handled, false otherwise.
6175     */
6176    public boolean onTouchEvent(MotionEvent event) {
6177        final int viewFlags = mViewFlags;
6178
6179        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6180            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6181                mPrivateFlags &= ~PRESSED;
6182                refreshDrawableState();
6183            }
6184            // A disabled view that is clickable still consumes the touch
6185            // events, it just doesn't respond to them.
6186            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6187                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6188        }
6189
6190        if (mTouchDelegate != null) {
6191            if (mTouchDelegate.onTouchEvent(event)) {
6192                return true;
6193            }
6194        }
6195
6196        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6197                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6198            switch (event.getAction()) {
6199                case MotionEvent.ACTION_UP:
6200                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6201                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6202                        // take focus if we don't have it already and we should in
6203                        // touch mode.
6204                        boolean focusTaken = false;
6205                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6206                            focusTaken = requestFocus();
6207                        }
6208
6209                        if (prepressed) {
6210                            // The button is being released before we actually
6211                            // showed it as pressed.  Make it show the pressed
6212                            // state now (before scheduling the click) to ensure
6213                            // the user sees it.
6214                            mPrivateFlags |= PRESSED;
6215                            refreshDrawableState();
6216                       }
6217
6218                        if (!mHasPerformedLongPress) {
6219                            // This is a tap, so remove the longpress check
6220                            removeLongPressCallback();
6221
6222                            // Only perform take click actions if we were in the pressed state
6223                            if (!focusTaken) {
6224                                // Use a Runnable and post this rather than calling
6225                                // performClick directly. This lets other visual state
6226                                // of the view update before click actions start.
6227                                if (mPerformClick == null) {
6228                                    mPerformClick = new PerformClick();
6229                                }
6230                                if (!post(mPerformClick)) {
6231                                    performClick();
6232                                }
6233                            }
6234                        }
6235
6236                        if (mUnsetPressedState == null) {
6237                            mUnsetPressedState = new UnsetPressedState();
6238                        }
6239
6240                        if (prepressed) {
6241                            postDelayed(mUnsetPressedState,
6242                                    ViewConfiguration.getPressedStateDuration());
6243                        } else if (!post(mUnsetPressedState)) {
6244                            // If the post failed, unpress right now
6245                            mUnsetPressedState.run();
6246                        }
6247                        removeTapCallback();
6248                    }
6249                    break;
6250
6251                case MotionEvent.ACTION_DOWN:
6252                    mHasPerformedLongPress = false;
6253
6254                    if (performButtonActionOnTouchDown(event)) {
6255                        break;
6256                    }
6257
6258                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6259                    boolean isInScrollingContainer = isInScrollingContainer();
6260
6261                    // For views inside a scrolling container, delay the pressed feedback for
6262                    // a short period in case this is a scroll.
6263                    if (isInScrollingContainer) {
6264                        mPrivateFlags |= PREPRESSED;
6265                        if (mPendingCheckForTap == null) {
6266                            mPendingCheckForTap = new CheckForTap();
6267                        }
6268                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6269                    } else {
6270                        // Not inside a scrolling container, so show the feedback right away
6271                        mPrivateFlags |= PRESSED;
6272                        refreshDrawableState();
6273                        checkForLongClick(0);
6274                    }
6275                    break;
6276
6277                case MotionEvent.ACTION_CANCEL:
6278                    mPrivateFlags &= ~PRESSED;
6279                    refreshDrawableState();
6280                    removeTapCallback();
6281                    break;
6282
6283                case MotionEvent.ACTION_MOVE:
6284                    final int x = (int) event.getX();
6285                    final int y = (int) event.getY();
6286
6287                    // Be lenient about moving outside of buttons
6288                    if (!pointInView(x, y, mTouchSlop)) {
6289                        // Outside button
6290                        removeTapCallback();
6291                        if ((mPrivateFlags & PRESSED) != 0) {
6292                            // Remove any future long press/tap checks
6293                            removeLongPressCallback();
6294
6295                            // Need to switch from pressed to not pressed
6296                            mPrivateFlags &= ~PRESSED;
6297                            refreshDrawableState();
6298                        }
6299                    }
6300                    break;
6301            }
6302            return true;
6303        }
6304
6305        return false;
6306    }
6307
6308    /**
6309     * @hide
6310     */
6311    public boolean isInScrollingContainer() {
6312        ViewParent p = getParent();
6313        while (p != null && p instanceof ViewGroup) {
6314            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6315                return true;
6316            }
6317            p = p.getParent();
6318        }
6319        return false;
6320    }
6321
6322    /**
6323     * Remove the longpress detection timer.
6324     */
6325    private void removeLongPressCallback() {
6326        if (mPendingCheckForLongPress != null) {
6327          removeCallbacks(mPendingCheckForLongPress);
6328        }
6329    }
6330
6331    /**
6332     * Remove the pending click action
6333     */
6334    private void removePerformClickCallback() {
6335        if (mPerformClick != null) {
6336            removeCallbacks(mPerformClick);
6337        }
6338    }
6339
6340    /**
6341     * Remove the prepress detection timer.
6342     */
6343    private void removeUnsetPressCallback() {
6344        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6345            setPressed(false);
6346            removeCallbacks(mUnsetPressedState);
6347        }
6348    }
6349
6350    /**
6351     * Remove the tap detection timer.
6352     */
6353    private void removeTapCallback() {
6354        if (mPendingCheckForTap != null) {
6355            mPrivateFlags &= ~PREPRESSED;
6356            removeCallbacks(mPendingCheckForTap);
6357        }
6358    }
6359
6360    /**
6361     * Cancels a pending long press.  Your subclass can use this if you
6362     * want the context menu to come up if the user presses and holds
6363     * at the same place, but you don't want it to come up if they press
6364     * and then move around enough to cause scrolling.
6365     */
6366    public void cancelLongPress() {
6367        removeLongPressCallback();
6368
6369        /*
6370         * The prepressed state handled by the tap callback is a display
6371         * construct, but the tap callback will post a long press callback
6372         * less its own timeout. Remove it here.
6373         */
6374        removeTapCallback();
6375    }
6376
6377    /**
6378     * Remove the pending callback for sending a
6379     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6380     */
6381    private void removeSendViewScrolledAccessibilityEventCallback() {
6382        if (mSendViewScrolledAccessibilityEvent != null) {
6383            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6384        }
6385    }
6386
6387    /**
6388     * Sets the TouchDelegate for this View.
6389     */
6390    public void setTouchDelegate(TouchDelegate delegate) {
6391        mTouchDelegate = delegate;
6392    }
6393
6394    /**
6395     * Gets the TouchDelegate for this View.
6396     */
6397    public TouchDelegate getTouchDelegate() {
6398        return mTouchDelegate;
6399    }
6400
6401    /**
6402     * Set flags controlling behavior of this view.
6403     *
6404     * @param flags Constant indicating the value which should be set
6405     * @param mask Constant indicating the bit range that should be changed
6406     */
6407    void setFlags(int flags, int mask) {
6408        int old = mViewFlags;
6409        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6410
6411        int changed = mViewFlags ^ old;
6412        if (changed == 0) {
6413            return;
6414        }
6415        int privateFlags = mPrivateFlags;
6416
6417        /* Check if the FOCUSABLE bit has changed */
6418        if (((changed & FOCUSABLE_MASK) != 0) &&
6419                ((privateFlags & HAS_BOUNDS) !=0)) {
6420            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6421                    && ((privateFlags & FOCUSED) != 0)) {
6422                /* Give up focus if we are no longer focusable */
6423                clearFocus();
6424            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6425                    && ((privateFlags & FOCUSED) == 0)) {
6426                /*
6427                 * Tell the view system that we are now available to take focus
6428                 * if no one else already has it.
6429                 */
6430                if (mParent != null) mParent.focusableViewAvailable(this);
6431            }
6432        }
6433
6434        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6435            if ((changed & VISIBILITY_MASK) != 0) {
6436                /*
6437                 * If this view is becoming visible, invalidate it in case it changed while
6438                 * it was not visible. Marking it drawn ensures that the invalidation will
6439                 * go through.
6440                 */
6441                mPrivateFlags |= DRAWN;
6442                invalidate(true);
6443
6444                needGlobalAttributesUpdate(true);
6445
6446                // a view becoming visible is worth notifying the parent
6447                // about in case nothing has focus.  even if this specific view
6448                // isn't focusable, it may contain something that is, so let
6449                // the root view try to give this focus if nothing else does.
6450                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6451                    mParent.focusableViewAvailable(this);
6452                }
6453            }
6454        }
6455
6456        /* Check if the GONE bit has changed */
6457        if ((changed & GONE) != 0) {
6458            needGlobalAttributesUpdate(false);
6459            requestLayout();
6460
6461            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6462                if (hasFocus()) clearFocus();
6463                destroyDrawingCache();
6464                if (mParent instanceof View) {
6465                    // GONE views noop invalidation, so invalidate the parent
6466                    ((View) mParent).invalidate(true);
6467                }
6468                // Mark the view drawn to ensure that it gets invalidated properly the next
6469                // time it is visible and gets invalidated
6470                mPrivateFlags |= DRAWN;
6471            }
6472            if (mAttachInfo != null) {
6473                mAttachInfo.mViewVisibilityChanged = true;
6474            }
6475        }
6476
6477        /* Check if the VISIBLE bit has changed */
6478        if ((changed & INVISIBLE) != 0) {
6479            needGlobalAttributesUpdate(false);
6480            /*
6481             * If this view is becoming invisible, set the DRAWN flag so that
6482             * the next invalidate() will not be skipped.
6483             */
6484            mPrivateFlags |= DRAWN;
6485
6486            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6487                // root view becoming invisible shouldn't clear focus
6488                if (getRootView() != this) {
6489                    clearFocus();
6490                }
6491            }
6492            if (mAttachInfo != null) {
6493                mAttachInfo.mViewVisibilityChanged = true;
6494            }
6495        }
6496
6497        if ((changed & VISIBILITY_MASK) != 0) {
6498            if (mParent instanceof ViewGroup) {
6499                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6500                ((View) mParent).invalidate(true);
6501            } else if (mParent != null) {
6502                mParent.invalidateChild(this, null);
6503            }
6504            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6505        }
6506
6507        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6508            destroyDrawingCache();
6509        }
6510
6511        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6512            destroyDrawingCache();
6513            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6514            invalidateParentCaches();
6515        }
6516
6517        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6518            destroyDrawingCache();
6519            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6520        }
6521
6522        if ((changed & DRAW_MASK) != 0) {
6523            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6524                if (mBGDrawable != null) {
6525                    mPrivateFlags &= ~SKIP_DRAW;
6526                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6527                } else {
6528                    mPrivateFlags |= SKIP_DRAW;
6529                }
6530            } else {
6531                mPrivateFlags &= ~SKIP_DRAW;
6532            }
6533            requestLayout();
6534            invalidate(true);
6535        }
6536
6537        if ((changed & KEEP_SCREEN_ON) != 0) {
6538            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6539                mParent.recomputeViewAttributes(this);
6540            }
6541        }
6542
6543        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6544            requestLayout();
6545        }
6546    }
6547
6548    /**
6549     * Change the view's z order in the tree, so it's on top of other sibling
6550     * views
6551     */
6552    public void bringToFront() {
6553        if (mParent != null) {
6554            mParent.bringChildToFront(this);
6555        }
6556    }
6557
6558    /**
6559     * This is called in response to an internal scroll in this view (i.e., the
6560     * view scrolled its own contents). This is typically as a result of
6561     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6562     * called.
6563     *
6564     * @param l Current horizontal scroll origin.
6565     * @param t Current vertical scroll origin.
6566     * @param oldl Previous horizontal scroll origin.
6567     * @param oldt Previous vertical scroll origin.
6568     */
6569    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6570        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6571            postSendViewScrolledAccessibilityEventCallback();
6572        }
6573
6574        mBackgroundSizeChanged = true;
6575
6576        final AttachInfo ai = mAttachInfo;
6577        if (ai != null) {
6578            ai.mViewScrollChanged = true;
6579        }
6580    }
6581
6582    /**
6583     * Interface definition for a callback to be invoked when the layout bounds of a view
6584     * changes due to layout processing.
6585     */
6586    public interface OnLayoutChangeListener {
6587        /**
6588         * Called when the focus state of a view has changed.
6589         *
6590         * @param v The view whose state has changed.
6591         * @param left The new value of the view's left property.
6592         * @param top The new value of the view's top property.
6593         * @param right The new value of the view's right property.
6594         * @param bottom The new value of the view's bottom property.
6595         * @param oldLeft The previous value of the view's left property.
6596         * @param oldTop The previous value of the view's top property.
6597         * @param oldRight The previous value of the view's right property.
6598         * @param oldBottom The previous value of the view's bottom property.
6599         */
6600        void onLayoutChange(View v, int left, int top, int right, int bottom,
6601            int oldLeft, int oldTop, int oldRight, int oldBottom);
6602    }
6603
6604    /**
6605     * This is called during layout when the size of this view has changed. If
6606     * you were just added to the view hierarchy, you're called with the old
6607     * values of 0.
6608     *
6609     * @param w Current width of this view.
6610     * @param h Current height of this view.
6611     * @param oldw Old width of this view.
6612     * @param oldh Old height of this view.
6613     */
6614    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6615    }
6616
6617    /**
6618     * Called by draw to draw the child views. This may be overridden
6619     * by derived classes to gain control just before its children are drawn
6620     * (but after its own view has been drawn).
6621     * @param canvas the canvas on which to draw the view
6622     */
6623    protected void dispatchDraw(Canvas canvas) {
6624    }
6625
6626    /**
6627     * Gets the parent of this view. Note that the parent is a
6628     * ViewParent and not necessarily a View.
6629     *
6630     * @return Parent of this view.
6631     */
6632    public final ViewParent getParent() {
6633        return mParent;
6634    }
6635
6636    /**
6637     * Set the horizontal scrolled position of your view. This will cause a call to
6638     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6639     * invalidated.
6640     * @param value the x position to scroll to
6641     */
6642    public void setScrollX(int value) {
6643        scrollTo(value, mScrollY);
6644    }
6645
6646    /**
6647     * Set the vertical scrolled position of your view. This will cause a call to
6648     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6649     * invalidated.
6650     * @param value the y position to scroll to
6651     */
6652    public void setScrollY(int value) {
6653        scrollTo(mScrollX, value);
6654    }
6655
6656    /**
6657     * Return the scrolled left position of this view. This is the left edge of
6658     * the displayed part of your view. You do not need to draw any pixels
6659     * farther left, since those are outside of the frame of your view on
6660     * screen.
6661     *
6662     * @return The left edge of the displayed part of your view, in pixels.
6663     */
6664    public final int getScrollX() {
6665        return mScrollX;
6666    }
6667
6668    /**
6669     * Return the scrolled top position of this view. This is the top edge of
6670     * the displayed part of your view. You do not need to draw any pixels above
6671     * it, since those are outside of the frame of your view on screen.
6672     *
6673     * @return The top edge of the displayed part of your view, in pixels.
6674     */
6675    public final int getScrollY() {
6676        return mScrollY;
6677    }
6678
6679    /**
6680     * Return the width of the your view.
6681     *
6682     * @return The width of your view, in pixels.
6683     */
6684    @ViewDebug.ExportedProperty(category = "layout")
6685    public final int getWidth() {
6686        return mRight - mLeft;
6687    }
6688
6689    /**
6690     * Return the height of your view.
6691     *
6692     * @return The height of your view, in pixels.
6693     */
6694    @ViewDebug.ExportedProperty(category = "layout")
6695    public final int getHeight() {
6696        return mBottom - mTop;
6697    }
6698
6699    /**
6700     * Return the visible drawing bounds of your view. Fills in the output
6701     * rectangle with the values from getScrollX(), getScrollY(),
6702     * getWidth(), and getHeight().
6703     *
6704     * @param outRect The (scrolled) drawing bounds of the view.
6705     */
6706    public void getDrawingRect(Rect outRect) {
6707        outRect.left = mScrollX;
6708        outRect.top = mScrollY;
6709        outRect.right = mScrollX + (mRight - mLeft);
6710        outRect.bottom = mScrollY + (mBottom - mTop);
6711    }
6712
6713    /**
6714     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6715     * raw width component (that is the result is masked by
6716     * {@link #MEASURED_SIZE_MASK}).
6717     *
6718     * @return The raw measured width of this view.
6719     */
6720    public final int getMeasuredWidth() {
6721        return mMeasuredWidth & MEASURED_SIZE_MASK;
6722    }
6723
6724    /**
6725     * Return the full width measurement information for this view as computed
6726     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6727     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6728     * This should be used during measurement and layout calculations only. Use
6729     * {@link #getWidth()} to see how wide a view is after layout.
6730     *
6731     * @return The measured width of this view as a bit mask.
6732     */
6733    public final int getMeasuredWidthAndState() {
6734        return mMeasuredWidth;
6735    }
6736
6737    /**
6738     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6739     * raw width component (that is the result is masked by
6740     * {@link #MEASURED_SIZE_MASK}).
6741     *
6742     * @return The raw measured height of this view.
6743     */
6744    public final int getMeasuredHeight() {
6745        return mMeasuredHeight & MEASURED_SIZE_MASK;
6746    }
6747
6748    /**
6749     * Return the full height measurement information for this view as computed
6750     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6751     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6752     * This should be used during measurement and layout calculations only. Use
6753     * {@link #getHeight()} to see how wide a view is after layout.
6754     *
6755     * @return The measured width of this view as a bit mask.
6756     */
6757    public final int getMeasuredHeightAndState() {
6758        return mMeasuredHeight;
6759    }
6760
6761    /**
6762     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6763     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6764     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6765     * and the height component is at the shifted bits
6766     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6767     */
6768    public final int getMeasuredState() {
6769        return (mMeasuredWidth&MEASURED_STATE_MASK)
6770                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6771                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6772    }
6773
6774    /**
6775     * The transform matrix of this view, which is calculated based on the current
6776     * roation, scale, and pivot properties.
6777     *
6778     * @see #getRotation()
6779     * @see #getScaleX()
6780     * @see #getScaleY()
6781     * @see #getPivotX()
6782     * @see #getPivotY()
6783     * @return The current transform matrix for the view
6784     */
6785    public Matrix getMatrix() {
6786        updateMatrix();
6787        return mMatrix;
6788    }
6789
6790    /**
6791     * Utility function to determine if the value is far enough away from zero to be
6792     * considered non-zero.
6793     * @param value A floating point value to check for zero-ness
6794     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6795     */
6796    private static boolean nonzero(float value) {
6797        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6798    }
6799
6800    /**
6801     * Returns true if the transform matrix is the identity matrix.
6802     * Recomputes the matrix if necessary.
6803     *
6804     * @return True if the transform matrix is the identity matrix, false otherwise.
6805     */
6806    final boolean hasIdentityMatrix() {
6807        updateMatrix();
6808        return mMatrixIsIdentity;
6809    }
6810
6811    /**
6812     * Recomputes the transform matrix if necessary.
6813     */
6814    private void updateMatrix() {
6815        if (mMatrixDirty) {
6816            // transform-related properties have changed since the last time someone
6817            // asked for the matrix; recalculate it with the current values
6818
6819            // Figure out if we need to update the pivot point
6820            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6821                if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
6822                    mPrevWidth = mRight - mLeft;
6823                    mPrevHeight = mBottom - mTop;
6824                    mPivotX = mPrevWidth / 2f;
6825                    mPivotY = mPrevHeight / 2f;
6826                }
6827            }
6828            mMatrix.reset();
6829            if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
6830                mMatrix.setTranslate(mTranslationX, mTranslationY);
6831                mMatrix.preRotate(mRotation, mPivotX, mPivotY);
6832                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6833            } else {
6834                if (mCamera == null) {
6835                    mCamera = new Camera();
6836                    matrix3D = new Matrix();
6837                }
6838                mCamera.save();
6839                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6840                mCamera.rotate(mRotationX, mRotationY, -mRotation);
6841                mCamera.getMatrix(matrix3D);
6842                matrix3D.preTranslate(-mPivotX, -mPivotY);
6843                matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
6844                mMatrix.postConcat(matrix3D);
6845                mCamera.restore();
6846            }
6847            mMatrixDirty = false;
6848            mMatrixIsIdentity = mMatrix.isIdentity();
6849            mInverseMatrixDirty = true;
6850        }
6851    }
6852
6853    /**
6854     * Utility method to retrieve the inverse of the current mMatrix property.
6855     * We cache the matrix to avoid recalculating it when transform properties
6856     * have not changed.
6857     *
6858     * @return The inverse of the current matrix of this view.
6859     */
6860    final Matrix getInverseMatrix() {
6861        updateMatrix();
6862        if (mInverseMatrixDirty) {
6863            if (mInverseMatrix == null) {
6864                mInverseMatrix = new Matrix();
6865            }
6866            mMatrix.invert(mInverseMatrix);
6867            mInverseMatrixDirty = false;
6868        }
6869        return mInverseMatrix;
6870    }
6871
6872    /**
6873     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
6874     * views are drawn) from the camera to this view. The camera's distance
6875     * affects 3D transformations, for instance rotations around the X and Y
6876     * axis. If the rotationX or rotationY properties are changed and this view is
6877     * large (more than half the size of the screen), it is recommended to always
6878     * use a camera distance that's greater than the height (X axis rotation) or
6879     * the width (Y axis rotation) of this view.</p>
6880     *
6881     * <p>The distance of the camera from the view plane can have an affect on the
6882     * perspective distortion of the view when it is rotated around the x or y axis.
6883     * For example, a large distance will result in a large viewing angle, and there
6884     * will not be much perspective distortion of the view as it rotates. A short
6885     * distance may cause much more perspective distortion upon rotation, and can
6886     * also result in some drawing artifacts if the rotated view ends up partially
6887     * behind the camera (which is why the recommendation is to use a distance at
6888     * least as far as the size of the view, if the view is to be rotated.)</p>
6889     *
6890     * <p>The distance is expressed in "depth pixels." The default distance depends
6891     * on the screen density. For instance, on a medium density display, the
6892     * default distance is 1280. On a high density display, the default distance
6893     * is 1920.</p>
6894     *
6895     * <p>If you want to specify a distance that leads to visually consistent
6896     * results across various densities, use the following formula:</p>
6897     * <pre>
6898     * float scale = context.getResources().getDisplayMetrics().density;
6899     * view.setCameraDistance(distance * scale);
6900     * </pre>
6901     *
6902     * <p>The density scale factor of a high density display is 1.5,
6903     * and 1920 = 1280 * 1.5.</p>
6904     *
6905     * @param distance The distance in "depth pixels", if negative the opposite
6906     *        value is used
6907     *
6908     * @see #setRotationX(float)
6909     * @see #setRotationY(float)
6910     */
6911    public void setCameraDistance(float distance) {
6912        invalidateParentCaches();
6913        invalidate(false);
6914
6915        final float dpi = mResources.getDisplayMetrics().densityDpi;
6916        if (mCamera == null) {
6917            mCamera = new Camera();
6918            matrix3D = new Matrix();
6919        }
6920
6921        mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
6922        mMatrixDirty = true;
6923
6924        invalidate(false);
6925    }
6926
6927    /**
6928     * The degrees that the view is rotated around the pivot point.
6929     *
6930     * @see #setRotation(float)
6931     * @see #getPivotX()
6932     * @see #getPivotY()
6933     *
6934     * @return The degrees of rotation.
6935     */
6936    public float getRotation() {
6937        return mRotation;
6938    }
6939
6940    /**
6941     * Sets the degrees that the view is rotated around the pivot point. Increasing values
6942     * result in clockwise rotation.
6943     *
6944     * @param rotation The degrees of rotation.
6945     *
6946     * @see #getRotation()
6947     * @see #getPivotX()
6948     * @see #getPivotY()
6949     * @see #setRotationX(float)
6950     * @see #setRotationY(float)
6951     *
6952     * @attr ref android.R.styleable#View_rotation
6953     */
6954    public void setRotation(float rotation) {
6955        if (mRotation != rotation) {
6956            invalidateParentCaches();
6957            // Double-invalidation is necessary to capture view's old and new areas
6958            invalidate(false);
6959            mRotation = rotation;
6960            mMatrixDirty = true;
6961            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6962            invalidate(false);
6963        }
6964    }
6965
6966    /**
6967     * The degrees that the view is rotated around the vertical axis through the pivot point.
6968     *
6969     * @see #getPivotX()
6970     * @see #getPivotY()
6971     * @see #setRotationY(float)
6972     *
6973     * @return The degrees of Y rotation.
6974     */
6975    public float getRotationY() {
6976        return mRotationY;
6977    }
6978
6979    /**
6980     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
6981     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
6982     * down the y axis.
6983     *
6984     * When rotating large views, it is recommended to adjust the camera distance
6985     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
6986     *
6987     * @param rotationY The degrees of Y rotation.
6988     *
6989     * @see #getRotationY()
6990     * @see #getPivotX()
6991     * @see #getPivotY()
6992     * @see #setRotation(float)
6993     * @see #setRotationX(float)
6994     * @see #setCameraDistance(float)
6995     *
6996     * @attr ref android.R.styleable#View_rotationY
6997     */
6998    public void setRotationY(float rotationY) {
6999        if (mRotationY != rotationY) {
7000            invalidateParentCaches();
7001            // Double-invalidation is necessary to capture view's old and new areas
7002            invalidate(false);
7003            mRotationY = rotationY;
7004            mMatrixDirty = true;
7005            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7006            invalidate(false);
7007        }
7008    }
7009
7010    /**
7011     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7012     *
7013     * @see #getPivotX()
7014     * @see #getPivotY()
7015     * @see #setRotationX(float)
7016     *
7017     * @return The degrees of X rotation.
7018     */
7019    public float getRotationX() {
7020        return mRotationX;
7021    }
7022
7023    /**
7024     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7025     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7026     * x axis.
7027     *
7028     * When rotating large views, it is recommended to adjust the camera distance
7029     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7030     *
7031     * @param rotationX The degrees of X rotation.
7032     *
7033     * @see #getRotationX()
7034     * @see #getPivotX()
7035     * @see #getPivotY()
7036     * @see #setRotation(float)
7037     * @see #setRotationY(float)
7038     * @see #setCameraDistance(float)
7039     *
7040     * @attr ref android.R.styleable#View_rotationX
7041     */
7042    public void setRotationX(float rotationX) {
7043        if (mRotationX != rotationX) {
7044            invalidateParentCaches();
7045            // Double-invalidation is necessary to capture view's old and new areas
7046            invalidate(false);
7047            mRotationX = rotationX;
7048            mMatrixDirty = true;
7049            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7050            invalidate(false);
7051        }
7052    }
7053
7054    /**
7055     * The amount that the view is scaled in x around the pivot point, as a proportion of
7056     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7057     *
7058     * <p>By default, this is 1.0f.
7059     *
7060     * @see #getPivotX()
7061     * @see #getPivotY()
7062     * @return The scaling factor.
7063     */
7064    public float getScaleX() {
7065        return mScaleX;
7066    }
7067
7068    /**
7069     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7070     * the view's unscaled width. A value of 1 means that no scaling is applied.
7071     *
7072     * @param scaleX The scaling factor.
7073     * @see #getPivotX()
7074     * @see #getPivotY()
7075     *
7076     * @attr ref android.R.styleable#View_scaleX
7077     */
7078    public void setScaleX(float scaleX) {
7079        if (mScaleX != scaleX) {
7080            invalidateParentCaches();
7081            // Double-invalidation is necessary to capture view's old and new areas
7082            invalidate(false);
7083            mScaleX = scaleX;
7084            mMatrixDirty = true;
7085            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7086            invalidate(false);
7087        }
7088    }
7089
7090    /**
7091     * The amount that the view is scaled in y around the pivot point, as a proportion of
7092     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7093     *
7094     * <p>By default, this is 1.0f.
7095     *
7096     * @see #getPivotX()
7097     * @see #getPivotY()
7098     * @return The scaling factor.
7099     */
7100    public float getScaleY() {
7101        return mScaleY;
7102    }
7103
7104    /**
7105     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7106     * the view's unscaled width. A value of 1 means that no scaling is applied.
7107     *
7108     * @param scaleY The scaling factor.
7109     * @see #getPivotX()
7110     * @see #getPivotY()
7111     *
7112     * @attr ref android.R.styleable#View_scaleY
7113     */
7114    public void setScaleY(float scaleY) {
7115        if (mScaleY != scaleY) {
7116            invalidateParentCaches();
7117            // Double-invalidation is necessary to capture view's old and new areas
7118            invalidate(false);
7119            mScaleY = scaleY;
7120            mMatrixDirty = true;
7121            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7122            invalidate(false);
7123        }
7124    }
7125
7126    /**
7127     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7128     * and {@link #setScaleX(float) scaled}.
7129     *
7130     * @see #getRotation()
7131     * @see #getScaleX()
7132     * @see #getScaleY()
7133     * @see #getPivotY()
7134     * @return The x location of the pivot point.
7135     */
7136    public float getPivotX() {
7137        return mPivotX;
7138    }
7139
7140    /**
7141     * Sets the x location of the point around which the view is
7142     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7143     * By default, the pivot point is centered on the object.
7144     * Setting this property disables this behavior and causes the view to use only the
7145     * explicitly set pivotX and pivotY values.
7146     *
7147     * @param pivotX The x location of the pivot point.
7148     * @see #getRotation()
7149     * @see #getScaleX()
7150     * @see #getScaleY()
7151     * @see #getPivotY()
7152     *
7153     * @attr ref android.R.styleable#View_transformPivotX
7154     */
7155    public void setPivotX(float pivotX) {
7156        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7157        if (mPivotX != pivotX) {
7158            invalidateParentCaches();
7159            // Double-invalidation is necessary to capture view's old and new areas
7160            invalidate(false);
7161            mPivotX = pivotX;
7162            mMatrixDirty = true;
7163            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7164            invalidate(false);
7165        }
7166    }
7167
7168    /**
7169     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7170     * and {@link #setScaleY(float) scaled}.
7171     *
7172     * @see #getRotation()
7173     * @see #getScaleX()
7174     * @see #getScaleY()
7175     * @see #getPivotY()
7176     * @return The y location of the pivot point.
7177     */
7178    public float getPivotY() {
7179        return mPivotY;
7180    }
7181
7182    /**
7183     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7184     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7185     * Setting this property disables this behavior and causes the view to use only the
7186     * explicitly set pivotX and pivotY values.
7187     *
7188     * @param pivotY The y location of the pivot point.
7189     * @see #getRotation()
7190     * @see #getScaleX()
7191     * @see #getScaleY()
7192     * @see #getPivotY()
7193     *
7194     * @attr ref android.R.styleable#View_transformPivotY
7195     */
7196    public void setPivotY(float pivotY) {
7197        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7198        if (mPivotY != pivotY) {
7199            invalidateParentCaches();
7200            // Double-invalidation is necessary to capture view's old and new areas
7201            invalidate(false);
7202            mPivotY = pivotY;
7203            mMatrixDirty = true;
7204            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7205            invalidate(false);
7206        }
7207    }
7208
7209    /**
7210     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7211     * completely transparent and 1 means the view is completely opaque.
7212     *
7213     * <p>By default this is 1.0f.
7214     * @return The opacity of the view.
7215     */
7216    public float getAlpha() {
7217        return mAlpha;
7218    }
7219
7220    /**
7221     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7222     * completely transparent and 1 means the view is completely opaque.</p>
7223     *
7224     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7225     * responsible for applying the opacity itself. Otherwise, calling this method is
7226     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7227     * setting a hardware layer.</p>
7228     *
7229     * @param alpha The opacity of the view.
7230     *
7231     * @see #setLayerType(int, android.graphics.Paint)
7232     *
7233     * @attr ref android.R.styleable#View_alpha
7234     */
7235    public void setAlpha(float alpha) {
7236        mAlpha = alpha;
7237        invalidateParentCaches();
7238        if (onSetAlpha((int) (alpha * 255))) {
7239            mPrivateFlags |= ALPHA_SET;
7240            // subclass is handling alpha - don't optimize rendering cache invalidation
7241            invalidate(true);
7242        } else {
7243            mPrivateFlags &= ~ALPHA_SET;
7244            invalidate(false);
7245        }
7246    }
7247
7248    /**
7249     * Faster version of setAlpha() which performs the same steps except there are
7250     * no calls to invalidate(). The caller of this function should perform proper invalidation
7251     * on the parent and this object. The return value indicates whether the subclass handles
7252     * alpha (the return value for onSetAlpha()).
7253     *
7254     * @param alpha The new value for the alpha property
7255     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
7256     */
7257    boolean setAlphaNoInvalidation(float alpha) {
7258        mAlpha = alpha;
7259        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7260        if (subclassHandlesAlpha) {
7261            mPrivateFlags |= ALPHA_SET;
7262        } else {
7263            mPrivateFlags &= ~ALPHA_SET;
7264        }
7265        return subclassHandlesAlpha;
7266    }
7267
7268    /**
7269     * Top position of this view relative to its parent.
7270     *
7271     * @return The top of this view, in pixels.
7272     */
7273    @ViewDebug.CapturedViewProperty
7274    public final int getTop() {
7275        return mTop;
7276    }
7277
7278    /**
7279     * Sets the top position of this view relative to its parent. This method is meant to be called
7280     * by the layout system and should not generally be called otherwise, because the property
7281     * may be changed at any time by the layout.
7282     *
7283     * @param top The top of this view, in pixels.
7284     */
7285    public final void setTop(int top) {
7286        if (top != mTop) {
7287            updateMatrix();
7288            if (mMatrixIsIdentity) {
7289                if (mAttachInfo != null) {
7290                    int minTop;
7291                    int yLoc;
7292                    if (top < mTop) {
7293                        minTop = top;
7294                        yLoc = top - mTop;
7295                    } else {
7296                        minTop = mTop;
7297                        yLoc = 0;
7298                    }
7299                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7300                }
7301            } else {
7302                // Double-invalidation is necessary to capture view's old and new areas
7303                invalidate(true);
7304            }
7305
7306            int width = mRight - mLeft;
7307            int oldHeight = mBottom - mTop;
7308
7309            mTop = top;
7310
7311            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7312
7313            if (!mMatrixIsIdentity) {
7314                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7315                    // A change in dimension means an auto-centered pivot point changes, too
7316                    mMatrixDirty = true;
7317                }
7318                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7319                invalidate(true);
7320            }
7321            mBackgroundSizeChanged = true;
7322            invalidateParentIfNeeded();
7323        }
7324    }
7325
7326    /**
7327     * Bottom position of this view relative to its parent.
7328     *
7329     * @return The bottom of this view, in pixels.
7330     */
7331    @ViewDebug.CapturedViewProperty
7332    public final int getBottom() {
7333        return mBottom;
7334    }
7335
7336    /**
7337     * True if this view has changed since the last time being drawn.
7338     *
7339     * @return The dirty state of this view.
7340     */
7341    public boolean isDirty() {
7342        return (mPrivateFlags & DIRTY_MASK) != 0;
7343    }
7344
7345    /**
7346     * Sets the bottom position of this view relative to its parent. This method is meant to be
7347     * called by the layout system and should not generally be called otherwise, because the
7348     * property may be changed at any time by the layout.
7349     *
7350     * @param bottom The bottom of this view, in pixels.
7351     */
7352    public final void setBottom(int bottom) {
7353        if (bottom != mBottom) {
7354            updateMatrix();
7355            if (mMatrixIsIdentity) {
7356                if (mAttachInfo != null) {
7357                    int maxBottom;
7358                    if (bottom < mBottom) {
7359                        maxBottom = mBottom;
7360                    } else {
7361                        maxBottom = bottom;
7362                    }
7363                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7364                }
7365            } else {
7366                // Double-invalidation is necessary to capture view's old and new areas
7367                invalidate(true);
7368            }
7369
7370            int width = mRight - mLeft;
7371            int oldHeight = mBottom - mTop;
7372
7373            mBottom = bottom;
7374
7375            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7376
7377            if (!mMatrixIsIdentity) {
7378                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7379                    // A change in dimension means an auto-centered pivot point changes, too
7380                    mMatrixDirty = true;
7381                }
7382                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7383                invalidate(true);
7384            }
7385            mBackgroundSizeChanged = true;
7386            invalidateParentIfNeeded();
7387        }
7388    }
7389
7390    /**
7391     * Left position of this view relative to its parent.
7392     *
7393     * @return The left edge of this view, in pixels.
7394     */
7395    @ViewDebug.CapturedViewProperty
7396    public final int getLeft() {
7397        return mLeft;
7398    }
7399
7400    /**
7401     * Sets the left position of this view relative to its parent. This method is meant to be called
7402     * by the layout system and should not generally be called otherwise, because the property
7403     * may be changed at any time by the layout.
7404     *
7405     * @param left The bottom of this view, in pixels.
7406     */
7407    public final void setLeft(int left) {
7408        if (left != mLeft) {
7409            updateMatrix();
7410            if (mMatrixIsIdentity) {
7411                if (mAttachInfo != null) {
7412                    int minLeft;
7413                    int xLoc;
7414                    if (left < mLeft) {
7415                        minLeft = left;
7416                        xLoc = left - mLeft;
7417                    } else {
7418                        minLeft = mLeft;
7419                        xLoc = 0;
7420                    }
7421                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7422                }
7423            } else {
7424                // Double-invalidation is necessary to capture view's old and new areas
7425                invalidate(true);
7426            }
7427
7428            int oldWidth = mRight - mLeft;
7429            int height = mBottom - mTop;
7430
7431            mLeft = left;
7432
7433            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7434
7435            if (!mMatrixIsIdentity) {
7436                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7437                    // A change in dimension means an auto-centered pivot point changes, too
7438                    mMatrixDirty = true;
7439                }
7440                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7441                invalidate(true);
7442            }
7443            mBackgroundSizeChanged = true;
7444            invalidateParentIfNeeded();
7445        }
7446    }
7447
7448    /**
7449     * Right position of this view relative to its parent.
7450     *
7451     * @return The right edge of this view, in pixels.
7452     */
7453    @ViewDebug.CapturedViewProperty
7454    public final int getRight() {
7455        return mRight;
7456    }
7457
7458    /**
7459     * Sets the right position of this view relative to its parent. This method is meant to be called
7460     * by the layout system and should not generally be called otherwise, because the property
7461     * may be changed at any time by the layout.
7462     *
7463     * @param right The bottom of this view, in pixels.
7464     */
7465    public final void setRight(int right) {
7466        if (right != mRight) {
7467            updateMatrix();
7468            if (mMatrixIsIdentity) {
7469                if (mAttachInfo != null) {
7470                    int maxRight;
7471                    if (right < mRight) {
7472                        maxRight = mRight;
7473                    } else {
7474                        maxRight = right;
7475                    }
7476                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7477                }
7478            } else {
7479                // Double-invalidation is necessary to capture view's old and new areas
7480                invalidate(true);
7481            }
7482
7483            int oldWidth = mRight - mLeft;
7484            int height = mBottom - mTop;
7485
7486            mRight = right;
7487
7488            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7489
7490            if (!mMatrixIsIdentity) {
7491                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7492                    // A change in dimension means an auto-centered pivot point changes, too
7493                    mMatrixDirty = true;
7494                }
7495                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7496                invalidate(true);
7497            }
7498            mBackgroundSizeChanged = true;
7499            invalidateParentIfNeeded();
7500        }
7501    }
7502
7503    /**
7504     * The visual x position of this view, in pixels. This is equivalent to the
7505     * {@link #setTranslationX(float) translationX} property plus the current
7506     * {@link #getLeft() left} property.
7507     *
7508     * @return The visual x position of this view, in pixels.
7509     */
7510    public float getX() {
7511        return mLeft + mTranslationX;
7512    }
7513
7514    /**
7515     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7516     * {@link #setTranslationX(float) translationX} property to be the difference between
7517     * the x value passed in and the current {@link #getLeft() left} property.
7518     *
7519     * @param x The visual x position of this view, in pixels.
7520     */
7521    public void setX(float x) {
7522        setTranslationX(x - mLeft);
7523    }
7524
7525    /**
7526     * The visual y position of this view, in pixels. This is equivalent to the
7527     * {@link #setTranslationY(float) translationY} property plus the current
7528     * {@link #getTop() top} property.
7529     *
7530     * @return The visual y position of this view, in pixels.
7531     */
7532    public float getY() {
7533        return mTop + mTranslationY;
7534    }
7535
7536    /**
7537     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7538     * {@link #setTranslationY(float) translationY} property to be the difference between
7539     * the y value passed in and the current {@link #getTop() top} property.
7540     *
7541     * @param y The visual y position of this view, in pixels.
7542     */
7543    public void setY(float y) {
7544        setTranslationY(y - mTop);
7545    }
7546
7547
7548    /**
7549     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7550     * This position is post-layout, in addition to wherever the object's
7551     * layout placed it.
7552     *
7553     * @return The horizontal position of this view relative to its left position, in pixels.
7554     */
7555    public float getTranslationX() {
7556        return mTranslationX;
7557    }
7558
7559    /**
7560     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7561     * This effectively positions the object post-layout, in addition to wherever the object's
7562     * layout placed it.
7563     *
7564     * @param translationX The horizontal position of this view relative to its left position,
7565     * in pixels.
7566     *
7567     * @attr ref android.R.styleable#View_translationX
7568     */
7569    public void setTranslationX(float translationX) {
7570        if (mTranslationX != translationX) {
7571            invalidateParentCaches();
7572            // Double-invalidation is necessary to capture view's old and new areas
7573            invalidate(false);
7574            mTranslationX = translationX;
7575            mMatrixDirty = true;
7576            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7577            invalidate(false);
7578        }
7579    }
7580
7581    /**
7582     * The horizontal location of this view relative to its {@link #getTop() top} position.
7583     * This position is post-layout, in addition to wherever the object's
7584     * layout placed it.
7585     *
7586     * @return The vertical position of this view relative to its top position,
7587     * in pixels.
7588     */
7589    public float getTranslationY() {
7590        return mTranslationY;
7591    }
7592
7593    /**
7594     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7595     * This effectively positions the object post-layout, in addition to wherever the object's
7596     * layout placed it.
7597     *
7598     * @param translationY The vertical position of this view relative to its top position,
7599     * in pixels.
7600     *
7601     * @attr ref android.R.styleable#View_translationY
7602     */
7603    public void setTranslationY(float translationY) {
7604        if (mTranslationY != translationY) {
7605            invalidateParentCaches();
7606            // Double-invalidation is necessary to capture view's old and new areas
7607            invalidate(false);
7608            mTranslationY = translationY;
7609            mMatrixDirty = true;
7610            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7611            invalidate(false);
7612        }
7613    }
7614
7615    /**
7616     * @hide
7617     */
7618    public void setFastTranslationX(float x) {
7619        mTranslationX = x;
7620        mMatrixDirty = true;
7621    }
7622
7623    /**
7624     * @hide
7625     */
7626    public void setFastTranslationY(float y) {
7627        mTranslationY = y;
7628        mMatrixDirty = true;
7629    }
7630
7631    /**
7632     * @hide
7633     */
7634    public void setFastX(float x) {
7635        mTranslationX = x - mLeft;
7636        mMatrixDirty = true;
7637    }
7638
7639    /**
7640     * @hide
7641     */
7642    public void setFastY(float y) {
7643        mTranslationY = y - mTop;
7644        mMatrixDirty = true;
7645    }
7646
7647    /**
7648     * @hide
7649     */
7650    public void setFastScaleX(float x) {
7651        mScaleX = x;
7652        mMatrixDirty = true;
7653    }
7654
7655    /**
7656     * @hide
7657     */
7658    public void setFastScaleY(float y) {
7659        mScaleY = y;
7660        mMatrixDirty = true;
7661    }
7662
7663    /**
7664     * @hide
7665     */
7666    public void setFastAlpha(float alpha) {
7667        mAlpha = alpha;
7668    }
7669
7670    /**
7671     * @hide
7672     */
7673    public void setFastRotationY(float y) {
7674        mRotationY = y;
7675        mMatrixDirty = true;
7676    }
7677
7678    /**
7679     * Hit rectangle in parent's coordinates
7680     *
7681     * @param outRect The hit rectangle of the view.
7682     */
7683    public void getHitRect(Rect outRect) {
7684        updateMatrix();
7685        if (mMatrixIsIdentity || mAttachInfo == null) {
7686            outRect.set(mLeft, mTop, mRight, mBottom);
7687        } else {
7688            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7689            tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
7690            mMatrix.mapRect(tmpRect);
7691            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7692                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7693        }
7694    }
7695
7696    /**
7697     * Determines whether the given point, in local coordinates is inside the view.
7698     */
7699    /*package*/ final boolean pointInView(float localX, float localY) {
7700        return localX >= 0 && localX < (mRight - mLeft)
7701                && localY >= 0 && localY < (mBottom - mTop);
7702    }
7703
7704    /**
7705     * Utility method to determine whether the given point, in local coordinates,
7706     * is inside the view, where the area of the view is expanded by the slop factor.
7707     * This method is called while processing touch-move events to determine if the event
7708     * is still within the view.
7709     */
7710    private boolean pointInView(float localX, float localY, float slop) {
7711        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7712                localY < ((mBottom - mTop) + slop);
7713    }
7714
7715    /**
7716     * When a view has focus and the user navigates away from it, the next view is searched for
7717     * starting from the rectangle filled in by this method.
7718     *
7719     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7720     * of the view.  However, if your view maintains some idea of internal selection,
7721     * such as a cursor, or a selected row or column, you should override this method and
7722     * fill in a more specific rectangle.
7723     *
7724     * @param r The rectangle to fill in, in this view's coordinates.
7725     */
7726    public void getFocusedRect(Rect r) {
7727        getDrawingRect(r);
7728    }
7729
7730    /**
7731     * If some part of this view is not clipped by any of its parents, then
7732     * return that area in r in global (root) coordinates. To convert r to local
7733     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7734     * -globalOffset.y)) If the view is completely clipped or translated out,
7735     * return false.
7736     *
7737     * @param r If true is returned, r holds the global coordinates of the
7738     *        visible portion of this view.
7739     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7740     *        between this view and its root. globalOffet may be null.
7741     * @return true if r is non-empty (i.e. part of the view is visible at the
7742     *         root level.
7743     */
7744    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7745        int width = mRight - mLeft;
7746        int height = mBottom - mTop;
7747        if (width > 0 && height > 0) {
7748            r.set(0, 0, width, height);
7749            if (globalOffset != null) {
7750                globalOffset.set(-mScrollX, -mScrollY);
7751            }
7752            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
7753        }
7754        return false;
7755    }
7756
7757    public final boolean getGlobalVisibleRect(Rect r) {
7758        return getGlobalVisibleRect(r, null);
7759    }
7760
7761    public final boolean getLocalVisibleRect(Rect r) {
7762        Point offset = new Point();
7763        if (getGlobalVisibleRect(r, offset)) {
7764            r.offset(-offset.x, -offset.y); // make r local
7765            return true;
7766        }
7767        return false;
7768    }
7769
7770    /**
7771     * Offset this view's vertical location by the specified number of pixels.
7772     *
7773     * @param offset the number of pixels to offset the view by
7774     */
7775    public void offsetTopAndBottom(int offset) {
7776        if (offset != 0) {
7777            updateMatrix();
7778            if (mMatrixIsIdentity) {
7779                final ViewParent p = mParent;
7780                if (p != null && mAttachInfo != null) {
7781                    final Rect r = mAttachInfo.mTmpInvalRect;
7782                    int minTop;
7783                    int maxBottom;
7784                    int yLoc;
7785                    if (offset < 0) {
7786                        minTop = mTop + offset;
7787                        maxBottom = mBottom;
7788                        yLoc = offset;
7789                    } else {
7790                        minTop = mTop;
7791                        maxBottom = mBottom + offset;
7792                        yLoc = 0;
7793                    }
7794                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
7795                    p.invalidateChild(this, r);
7796                }
7797            } else {
7798                invalidate(false);
7799            }
7800
7801            mTop += offset;
7802            mBottom += offset;
7803
7804            if (!mMatrixIsIdentity) {
7805                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7806                invalidate(false);
7807            }
7808            invalidateParentIfNeeded();
7809        }
7810    }
7811
7812    /**
7813     * Offset this view's horizontal location by the specified amount of pixels.
7814     *
7815     * @param offset the numer of pixels to offset the view by
7816     */
7817    public void offsetLeftAndRight(int offset) {
7818        if (offset != 0) {
7819            updateMatrix();
7820            if (mMatrixIsIdentity) {
7821                final ViewParent p = mParent;
7822                if (p != null && mAttachInfo != null) {
7823                    final Rect r = mAttachInfo.mTmpInvalRect;
7824                    int minLeft;
7825                    int maxRight;
7826                    if (offset < 0) {
7827                        minLeft = mLeft + offset;
7828                        maxRight = mRight;
7829                    } else {
7830                        minLeft = mLeft;
7831                        maxRight = mRight + offset;
7832                    }
7833                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
7834                    p.invalidateChild(this, r);
7835                }
7836            } else {
7837                invalidate(false);
7838            }
7839
7840            mLeft += offset;
7841            mRight += offset;
7842
7843            if (!mMatrixIsIdentity) {
7844                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7845                invalidate(false);
7846            }
7847            invalidateParentIfNeeded();
7848        }
7849    }
7850
7851    /**
7852     * Get the LayoutParams associated with this view. All views should have
7853     * layout parameters. These supply parameters to the <i>parent</i> of this
7854     * view specifying how it should be arranged. There are many subclasses of
7855     * ViewGroup.LayoutParams, and these correspond to the different subclasses
7856     * of ViewGroup that are responsible for arranging their children.
7857     *
7858     * This method may return null if this View is not attached to a parent
7859     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
7860     * was not invoked successfully. When a View is attached to a parent
7861     * ViewGroup, this method must not return null.
7862     *
7863     * @return The LayoutParams associated with this view, or null if no
7864     *         parameters have been set yet
7865     */
7866    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
7867    public ViewGroup.LayoutParams getLayoutParams() {
7868        return mLayoutParams;
7869    }
7870
7871    /**
7872     * Set the layout parameters associated with this view. These supply
7873     * parameters to the <i>parent</i> of this view specifying how it should be
7874     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
7875     * correspond to the different subclasses of ViewGroup that are responsible
7876     * for arranging their children.
7877     *
7878     * @param params The layout parameters for this view, cannot be null
7879     */
7880    public void setLayoutParams(ViewGroup.LayoutParams params) {
7881        if (params == null) {
7882            throw new NullPointerException("Layout parameters cannot be null");
7883        }
7884        mLayoutParams = params;
7885        requestLayout();
7886    }
7887
7888    /**
7889     * Set the scrolled position of your view. This will cause a call to
7890     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7891     * invalidated.
7892     * @param x the x position to scroll to
7893     * @param y the y position to scroll to
7894     */
7895    public void scrollTo(int x, int y) {
7896        if (mScrollX != x || mScrollY != y) {
7897            int oldX = mScrollX;
7898            int oldY = mScrollY;
7899            mScrollX = x;
7900            mScrollY = y;
7901            invalidateParentCaches();
7902            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
7903            if (!awakenScrollBars()) {
7904                invalidate(true);
7905            }
7906        }
7907    }
7908
7909    /**
7910     * Move the scrolled position of your view. This will cause a call to
7911     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7912     * invalidated.
7913     * @param x the amount of pixels to scroll by horizontally
7914     * @param y the amount of pixels to scroll by vertically
7915     */
7916    public void scrollBy(int x, int y) {
7917        scrollTo(mScrollX + x, mScrollY + y);
7918    }
7919
7920    /**
7921     * <p>Trigger the scrollbars to draw. When invoked this method starts an
7922     * animation to fade the scrollbars out after a default delay. If a subclass
7923     * provides animated scrolling, the start delay should equal the duration
7924     * of the scrolling animation.</p>
7925     *
7926     * <p>The animation starts only if at least one of the scrollbars is
7927     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
7928     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7929     * this method returns true, and false otherwise. If the animation is
7930     * started, this method calls {@link #invalidate()}; in that case the
7931     * caller should not call {@link #invalidate()}.</p>
7932     *
7933     * <p>This method should be invoked every time a subclass directly updates
7934     * the scroll parameters.</p>
7935     *
7936     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
7937     * and {@link #scrollTo(int, int)}.</p>
7938     *
7939     * @return true if the animation is played, false otherwise
7940     *
7941     * @see #awakenScrollBars(int)
7942     * @see #scrollBy(int, int)
7943     * @see #scrollTo(int, int)
7944     * @see #isHorizontalScrollBarEnabled()
7945     * @see #isVerticalScrollBarEnabled()
7946     * @see #setHorizontalScrollBarEnabled(boolean)
7947     * @see #setVerticalScrollBarEnabled(boolean)
7948     */
7949    protected boolean awakenScrollBars() {
7950        return mScrollCache != null &&
7951                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
7952    }
7953
7954    /**
7955     * Trigger the scrollbars to draw.
7956     * This method differs from awakenScrollBars() only in its default duration.
7957     * initialAwakenScrollBars() will show the scroll bars for longer than
7958     * usual to give the user more of a chance to notice them.
7959     *
7960     * @return true if the animation is played, false otherwise.
7961     */
7962    private boolean initialAwakenScrollBars() {
7963        return mScrollCache != null &&
7964                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
7965    }
7966
7967    /**
7968     * <p>
7969     * Trigger the scrollbars to draw. When invoked this method starts an
7970     * animation to fade the scrollbars out after a fixed delay. If a subclass
7971     * provides animated scrolling, the start delay should equal the duration of
7972     * the scrolling animation.
7973     * </p>
7974     *
7975     * <p>
7976     * The animation starts only if at least one of the scrollbars is enabled,
7977     * as specified by {@link #isHorizontalScrollBarEnabled()} and
7978     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7979     * this method returns true, and false otherwise. If the animation is
7980     * started, this method calls {@link #invalidate()}; in that case the caller
7981     * should not call {@link #invalidate()}.
7982     * </p>
7983     *
7984     * <p>
7985     * This method should be invoked everytime a subclass directly updates the
7986     * scroll parameters.
7987     * </p>
7988     *
7989     * @param startDelay the delay, in milliseconds, after which the animation
7990     *        should start; when the delay is 0, the animation starts
7991     *        immediately
7992     * @return true if the animation is played, false otherwise
7993     *
7994     * @see #scrollBy(int, int)
7995     * @see #scrollTo(int, int)
7996     * @see #isHorizontalScrollBarEnabled()
7997     * @see #isVerticalScrollBarEnabled()
7998     * @see #setHorizontalScrollBarEnabled(boolean)
7999     * @see #setVerticalScrollBarEnabled(boolean)
8000     */
8001    protected boolean awakenScrollBars(int startDelay) {
8002        return awakenScrollBars(startDelay, true);
8003    }
8004
8005    /**
8006     * <p>
8007     * Trigger the scrollbars to draw. When invoked this method starts an
8008     * animation to fade the scrollbars out after a fixed delay. If a subclass
8009     * provides animated scrolling, the start delay should equal the duration of
8010     * the scrolling animation.
8011     * </p>
8012     *
8013     * <p>
8014     * The animation starts only if at least one of the scrollbars is enabled,
8015     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8016     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8017     * this method returns true, and false otherwise. If the animation is
8018     * started, this method calls {@link #invalidate()} if the invalidate parameter
8019     * is set to true; in that case the caller
8020     * should not call {@link #invalidate()}.
8021     * </p>
8022     *
8023     * <p>
8024     * This method should be invoked everytime a subclass directly updates the
8025     * scroll parameters.
8026     * </p>
8027     *
8028     * @param startDelay the delay, in milliseconds, after which the animation
8029     *        should start; when the delay is 0, the animation starts
8030     *        immediately
8031     *
8032     * @param invalidate Wheter this method should call invalidate
8033     *
8034     * @return true if the animation is played, false otherwise
8035     *
8036     * @see #scrollBy(int, int)
8037     * @see #scrollTo(int, int)
8038     * @see #isHorizontalScrollBarEnabled()
8039     * @see #isVerticalScrollBarEnabled()
8040     * @see #setHorizontalScrollBarEnabled(boolean)
8041     * @see #setVerticalScrollBarEnabled(boolean)
8042     */
8043    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8044        final ScrollabilityCache scrollCache = mScrollCache;
8045
8046        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8047            return false;
8048        }
8049
8050        if (scrollCache.scrollBar == null) {
8051            scrollCache.scrollBar = new ScrollBarDrawable();
8052        }
8053
8054        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8055
8056            if (invalidate) {
8057                // Invalidate to show the scrollbars
8058                invalidate(true);
8059            }
8060
8061            if (scrollCache.state == ScrollabilityCache.OFF) {
8062                // FIXME: this is copied from WindowManagerService.
8063                // We should get this value from the system when it
8064                // is possible to do so.
8065                final int KEY_REPEAT_FIRST_DELAY = 750;
8066                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8067            }
8068
8069            // Tell mScrollCache when we should start fading. This may
8070            // extend the fade start time if one was already scheduled
8071            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8072            scrollCache.fadeStartTime = fadeStartTime;
8073            scrollCache.state = ScrollabilityCache.ON;
8074
8075            // Schedule our fader to run, unscheduling any old ones first
8076            if (mAttachInfo != null) {
8077                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8078                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8079            }
8080
8081            return true;
8082        }
8083
8084        return false;
8085    }
8086
8087    /**
8088     * Do not invalidate views which are not visible and which are not running an animation. They
8089     * will not get drawn and they should not set dirty flags as if they will be drawn
8090     */
8091    private boolean skipInvalidate() {
8092        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8093                (!(mParent instanceof ViewGroup) ||
8094                        !((ViewGroup) mParent).isViewTransitioning(this));
8095    }
8096    /**
8097     * Mark the the area defined by dirty as needing to be drawn. If the view is
8098     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8099     * in the future. This must be called from a UI thread. To call from a non-UI
8100     * thread, call {@link #postInvalidate()}.
8101     *
8102     * WARNING: This method is destructive to dirty.
8103     * @param dirty the rectangle representing the bounds of the dirty region
8104     */
8105    public void invalidate(Rect dirty) {
8106        if (ViewDebug.TRACE_HIERARCHY) {
8107            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8108        }
8109
8110        if (skipInvalidate()) {
8111            return;
8112        }
8113        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8114                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8115                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8116            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8117            mPrivateFlags |= INVALIDATED;
8118            final ViewParent p = mParent;
8119            final AttachInfo ai = mAttachInfo;
8120            //noinspection PointlessBooleanExpression,ConstantConditions
8121            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8122                if (p != null && ai != null && ai.mHardwareAccelerated) {
8123                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8124                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8125                    p.invalidateChild(this, null);
8126                    return;
8127                }
8128            }
8129            if (p != null && ai != null) {
8130                final int scrollX = mScrollX;
8131                final int scrollY = mScrollY;
8132                final Rect r = ai.mTmpInvalRect;
8133                r.set(dirty.left - scrollX, dirty.top - scrollY,
8134                        dirty.right - scrollX, dirty.bottom - scrollY);
8135                mParent.invalidateChild(this, r);
8136            }
8137        }
8138    }
8139
8140    /**
8141     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
8142     * The coordinates of the dirty rect are relative to the view.
8143     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8144     * will be called at some point in the future. This must be called from
8145     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8146     * @param l the left position of the dirty region
8147     * @param t the top position of the dirty region
8148     * @param r the right position of the dirty region
8149     * @param b the bottom position of the dirty region
8150     */
8151    public void invalidate(int l, int t, int r, int b) {
8152        if (ViewDebug.TRACE_HIERARCHY) {
8153            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8154        }
8155
8156        if (skipInvalidate()) {
8157            return;
8158        }
8159        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8160                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8161                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8162            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8163            mPrivateFlags |= INVALIDATED;
8164            final ViewParent p = mParent;
8165            final AttachInfo ai = mAttachInfo;
8166            //noinspection PointlessBooleanExpression,ConstantConditions
8167            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8168                if (p != null && ai != null && ai.mHardwareAccelerated) {
8169                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8170                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8171                    p.invalidateChild(this, null);
8172                    return;
8173                }
8174            }
8175            if (p != null && ai != null && l < r && t < b) {
8176                final int scrollX = mScrollX;
8177                final int scrollY = mScrollY;
8178                final Rect tmpr = ai.mTmpInvalRect;
8179                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8180                p.invalidateChild(this, tmpr);
8181            }
8182        }
8183    }
8184
8185    /**
8186     * Invalidate the whole view. If the view is visible,
8187     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8188     * the future. This must be called from a UI thread. To call from a non-UI thread,
8189     * call {@link #postInvalidate()}.
8190     */
8191    public void invalidate() {
8192        invalidate(true);
8193    }
8194
8195    /**
8196     * This is where the invalidate() work actually happens. A full invalidate()
8197     * causes the drawing cache to be invalidated, but this function can be called with
8198     * invalidateCache set to false to skip that invalidation step for cases that do not
8199     * need it (for example, a component that remains at the same dimensions with the same
8200     * content).
8201     *
8202     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8203     * well. This is usually true for a full invalidate, but may be set to false if the
8204     * View's contents or dimensions have not changed.
8205     */
8206    void invalidate(boolean invalidateCache) {
8207        if (ViewDebug.TRACE_HIERARCHY) {
8208            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8209        }
8210
8211        if (skipInvalidate()) {
8212            return;
8213        }
8214        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8215                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8216                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8217            mLastIsOpaque = isOpaque();
8218            mPrivateFlags &= ~DRAWN;
8219            if (invalidateCache) {
8220                mPrivateFlags |= INVALIDATED;
8221                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8222            }
8223            final AttachInfo ai = mAttachInfo;
8224            final ViewParent p = mParent;
8225            //noinspection PointlessBooleanExpression,ConstantConditions
8226            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8227                if (p != null && ai != null && ai.mHardwareAccelerated) {
8228                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8229                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8230                    p.invalidateChild(this, null);
8231                    return;
8232                }
8233            }
8234
8235            if (p != null && ai != null) {
8236                final Rect r = ai.mTmpInvalRect;
8237                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8238                // Don't call invalidate -- we don't want to internally scroll
8239                // our own bounds
8240                p.invalidateChild(this, r);
8241            }
8242        }
8243    }
8244
8245    /**
8246     * @hide
8247     */
8248    public void fastInvalidate() {
8249        if (skipInvalidate()) {
8250            return;
8251        }
8252        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8253            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8254            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8255            if (mParent instanceof View) {
8256                ((View) mParent).mPrivateFlags |= INVALIDATED;
8257            }
8258            mPrivateFlags &= ~DRAWN;
8259            mPrivateFlags |= INVALIDATED;
8260            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8261            if (mParent != null && mAttachInfo != null) {
8262                if (mAttachInfo.mHardwareAccelerated) {
8263                    mParent.invalidateChild(this, null);
8264                } else {
8265                    final Rect r = mAttachInfo.mTmpInvalRect;
8266                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
8267                    // Don't call invalidate -- we don't want to internally scroll
8268                    // our own bounds
8269                    mParent.invalidateChild(this, r);
8270                }
8271            }
8272        }
8273    }
8274
8275    /**
8276     * Used to indicate that the parent of this view should clear its caches. This functionality
8277     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8278     * which is necessary when various parent-managed properties of the view change, such as
8279     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8280     * clears the parent caches and does not causes an invalidate event.
8281     *
8282     * @hide
8283     */
8284    protected void invalidateParentCaches() {
8285        if (mParent instanceof View) {
8286            ((View) mParent).mPrivateFlags |= INVALIDATED;
8287        }
8288    }
8289
8290    /**
8291     * Used to indicate that the parent of this view should be invalidated. This functionality
8292     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8293     * which is necessary when various parent-managed properties of the view change, such as
8294     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8295     * an invalidation event to the parent.
8296     *
8297     * @hide
8298     */
8299    protected void invalidateParentIfNeeded() {
8300        if (isHardwareAccelerated() && mParent instanceof View) {
8301            ((View) mParent).invalidate(true);
8302        }
8303    }
8304
8305    /**
8306     * Indicates whether this View is opaque. An opaque View guarantees that it will
8307     * draw all the pixels overlapping its bounds using a fully opaque color.
8308     *
8309     * Subclasses of View should override this method whenever possible to indicate
8310     * whether an instance is opaque. Opaque Views are treated in a special way by
8311     * the View hierarchy, possibly allowing it to perform optimizations during
8312     * invalidate/draw passes.
8313     *
8314     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8315     */
8316    @ViewDebug.ExportedProperty(category = "drawing")
8317    public boolean isOpaque() {
8318        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8319                (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8320    }
8321
8322    /**
8323     * @hide
8324     */
8325    protected void computeOpaqueFlags() {
8326        // Opaque if:
8327        //   - Has a background
8328        //   - Background is opaque
8329        //   - Doesn't have scrollbars or scrollbars are inside overlay
8330
8331        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8332            mPrivateFlags |= OPAQUE_BACKGROUND;
8333        } else {
8334            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8335        }
8336
8337        final int flags = mViewFlags;
8338        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8339                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8340            mPrivateFlags |= OPAQUE_SCROLLBARS;
8341        } else {
8342            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8343        }
8344    }
8345
8346    /**
8347     * @hide
8348     */
8349    protected boolean hasOpaqueScrollbars() {
8350        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8351    }
8352
8353    /**
8354     * @return A handler associated with the thread running the View. This
8355     * handler can be used to pump events in the UI events queue.
8356     */
8357    public Handler getHandler() {
8358        if (mAttachInfo != null) {
8359            return mAttachInfo.mHandler;
8360        }
8361        return null;
8362    }
8363
8364    /**
8365     * <p>Causes the Runnable to be added to the message queue.
8366     * The runnable will be run on the user interface thread.</p>
8367     *
8368     * <p>This method can be invoked from outside of the UI thread
8369     * only when this View is attached to a window.</p>
8370     *
8371     * @param action The Runnable that will be executed.
8372     *
8373     * @return Returns true if the Runnable was successfully placed in to the
8374     *         message queue.  Returns false on failure, usually because the
8375     *         looper processing the message queue is exiting.
8376     */
8377    public boolean post(Runnable action) {
8378        Handler handler;
8379        AttachInfo attachInfo = mAttachInfo;
8380        if (attachInfo != null) {
8381            handler = attachInfo.mHandler;
8382        } else {
8383            // Assume that post will succeed later
8384            ViewRootImpl.getRunQueue().post(action);
8385            return true;
8386        }
8387
8388        return handler.post(action);
8389    }
8390
8391    /**
8392     * <p>Causes the Runnable to be added to the message queue, to be run
8393     * after the specified amount of time elapses.
8394     * The runnable will be run on the user interface thread.</p>
8395     *
8396     * <p>This method can be invoked from outside of the UI thread
8397     * only when this View is attached to a window.</p>
8398     *
8399     * @param action The Runnable that will be executed.
8400     * @param delayMillis The delay (in milliseconds) until the Runnable
8401     *        will be executed.
8402     *
8403     * @return true if the Runnable was successfully placed in to the
8404     *         message queue.  Returns false on failure, usually because the
8405     *         looper processing the message queue is exiting.  Note that a
8406     *         result of true does not mean the Runnable will be processed --
8407     *         if the looper is quit before the delivery time of the message
8408     *         occurs then the message will be dropped.
8409     */
8410    public boolean postDelayed(Runnable action, long delayMillis) {
8411        Handler handler;
8412        AttachInfo attachInfo = mAttachInfo;
8413        if (attachInfo != null) {
8414            handler = attachInfo.mHandler;
8415        } else {
8416            // Assume that post will succeed later
8417            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8418            return true;
8419        }
8420
8421        return handler.postDelayed(action, delayMillis);
8422    }
8423
8424    /**
8425     * <p>Removes the specified Runnable from the message queue.</p>
8426     *
8427     * <p>This method can be invoked from outside of the UI thread
8428     * only when this View is attached to a window.</p>
8429     *
8430     * @param action The Runnable to remove from the message handling queue
8431     *
8432     * @return true if this view could ask the Handler to remove the Runnable,
8433     *         false otherwise. When the returned value is true, the Runnable
8434     *         may or may not have been actually removed from the message queue
8435     *         (for instance, if the Runnable was not in the queue already.)
8436     */
8437    public boolean removeCallbacks(Runnable action) {
8438        Handler handler;
8439        AttachInfo attachInfo = mAttachInfo;
8440        if (attachInfo != null) {
8441            handler = attachInfo.mHandler;
8442        } else {
8443            // Assume that post will succeed later
8444            ViewRootImpl.getRunQueue().removeCallbacks(action);
8445            return true;
8446        }
8447
8448        handler.removeCallbacks(action);
8449        return true;
8450    }
8451
8452    /**
8453     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8454     * Use this to invalidate the View from a non-UI thread.</p>
8455     *
8456     * <p>This method can be invoked from outside of the UI thread
8457     * only when this View is attached to a window.</p>
8458     *
8459     * @see #invalidate()
8460     */
8461    public void postInvalidate() {
8462        postInvalidateDelayed(0);
8463    }
8464
8465    /**
8466     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8467     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8468     *
8469     * <p>This method can be invoked from outside of the UI thread
8470     * only when this View is attached to a window.</p>
8471     *
8472     * @param left The left coordinate of the rectangle to invalidate.
8473     * @param top The top coordinate of the rectangle to invalidate.
8474     * @param right The right coordinate of the rectangle to invalidate.
8475     * @param bottom The bottom coordinate of the rectangle to invalidate.
8476     *
8477     * @see #invalidate(int, int, int, int)
8478     * @see #invalidate(Rect)
8479     */
8480    public void postInvalidate(int left, int top, int right, int bottom) {
8481        postInvalidateDelayed(0, left, top, right, bottom);
8482    }
8483
8484    /**
8485     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8486     * loop. Waits for the specified amount of time.</p>
8487     *
8488     * <p>This method can be invoked from outside of the UI thread
8489     * only when this View is attached to a window.</p>
8490     *
8491     * @param delayMilliseconds the duration in milliseconds to delay the
8492     *         invalidation by
8493     */
8494    public void postInvalidateDelayed(long delayMilliseconds) {
8495        // We try only with the AttachInfo because there's no point in invalidating
8496        // if we are not attached to our window
8497        AttachInfo attachInfo = mAttachInfo;
8498        if (attachInfo != null) {
8499            Message msg = Message.obtain();
8500            msg.what = AttachInfo.INVALIDATE_MSG;
8501            msg.obj = this;
8502            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8503        }
8504    }
8505
8506    /**
8507     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8508     * through the event loop. Waits for the specified amount of time.</p>
8509     *
8510     * <p>This method can be invoked from outside of the UI thread
8511     * only when this View is attached to a window.</p>
8512     *
8513     * @param delayMilliseconds the duration in milliseconds to delay the
8514     *         invalidation by
8515     * @param left The left coordinate of the rectangle to invalidate.
8516     * @param top The top coordinate of the rectangle to invalidate.
8517     * @param right The right coordinate of the rectangle to invalidate.
8518     * @param bottom The bottom coordinate of the rectangle to invalidate.
8519     */
8520    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8521            int right, int bottom) {
8522
8523        // We try only with the AttachInfo because there's no point in invalidating
8524        // if we are not attached to our window
8525        AttachInfo attachInfo = mAttachInfo;
8526        if (attachInfo != null) {
8527            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8528            info.target = this;
8529            info.left = left;
8530            info.top = top;
8531            info.right = right;
8532            info.bottom = bottom;
8533
8534            final Message msg = Message.obtain();
8535            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8536            msg.obj = info;
8537            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8538        }
8539    }
8540
8541    /**
8542     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8543     * This event is sent at most once every
8544     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8545     */
8546    private void postSendViewScrolledAccessibilityEventCallback() {
8547        if (mSendViewScrolledAccessibilityEvent == null) {
8548            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8549        }
8550        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8551            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8552            postDelayed(mSendViewScrolledAccessibilityEvent,
8553                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8554        }
8555    }
8556
8557    /**
8558     * Called by a parent to request that a child update its values for mScrollX
8559     * and mScrollY if necessary. This will typically be done if the child is
8560     * animating a scroll using a {@link android.widget.Scroller Scroller}
8561     * object.
8562     */
8563    public void computeScroll() {
8564    }
8565
8566    /**
8567     * <p>Indicate whether the horizontal edges are faded when the view is
8568     * scrolled horizontally.</p>
8569     *
8570     * @return true if the horizontal edges should are faded on scroll, false
8571     *         otherwise
8572     *
8573     * @see #setHorizontalFadingEdgeEnabled(boolean)
8574     * @attr ref android.R.styleable#View_fadingEdge
8575     */
8576    public boolean isHorizontalFadingEdgeEnabled() {
8577        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8578    }
8579
8580    /**
8581     * <p>Define whether the horizontal edges should be faded when this view
8582     * is scrolled horizontally.</p>
8583     *
8584     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8585     *                                    be faded when the view is scrolled
8586     *                                    horizontally
8587     *
8588     * @see #isHorizontalFadingEdgeEnabled()
8589     * @attr ref android.R.styleable#View_fadingEdge
8590     */
8591    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8592        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8593            if (horizontalFadingEdgeEnabled) {
8594                initScrollCache();
8595            }
8596
8597            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8598        }
8599    }
8600
8601    /**
8602     * <p>Indicate whether the vertical edges are faded when the view is
8603     * scrolled horizontally.</p>
8604     *
8605     * @return true if the vertical edges should are faded on scroll, false
8606     *         otherwise
8607     *
8608     * @see #setVerticalFadingEdgeEnabled(boolean)
8609     * @attr ref android.R.styleable#View_fadingEdge
8610     */
8611    public boolean isVerticalFadingEdgeEnabled() {
8612        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8613    }
8614
8615    /**
8616     * <p>Define whether the vertical edges should be faded when this view
8617     * is scrolled vertically.</p>
8618     *
8619     * @param verticalFadingEdgeEnabled true if the vertical edges should
8620     *                                  be faded when the view is scrolled
8621     *                                  vertically
8622     *
8623     * @see #isVerticalFadingEdgeEnabled()
8624     * @attr ref android.R.styleable#View_fadingEdge
8625     */
8626    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8627        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8628            if (verticalFadingEdgeEnabled) {
8629                initScrollCache();
8630            }
8631
8632            mViewFlags ^= FADING_EDGE_VERTICAL;
8633        }
8634    }
8635
8636    /**
8637     * Returns the strength, or intensity, of the top faded edge. The strength is
8638     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8639     * returns 0.0 or 1.0 but no value in between.
8640     *
8641     * Subclasses should override this method to provide a smoother fade transition
8642     * when scrolling occurs.
8643     *
8644     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8645     */
8646    protected float getTopFadingEdgeStrength() {
8647        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8648    }
8649
8650    /**
8651     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8652     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8653     * returns 0.0 or 1.0 but no value in between.
8654     *
8655     * Subclasses should override this method to provide a smoother fade transition
8656     * when scrolling occurs.
8657     *
8658     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8659     */
8660    protected float getBottomFadingEdgeStrength() {
8661        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8662                computeVerticalScrollRange() ? 1.0f : 0.0f;
8663    }
8664
8665    /**
8666     * Returns the strength, or intensity, of the left faded edge. The strength is
8667     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8668     * returns 0.0 or 1.0 but no value in between.
8669     *
8670     * Subclasses should override this method to provide a smoother fade transition
8671     * when scrolling occurs.
8672     *
8673     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8674     */
8675    protected float getLeftFadingEdgeStrength() {
8676        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8677    }
8678
8679    /**
8680     * Returns the strength, or intensity, of the right faded edge. The strength is
8681     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8682     * returns 0.0 or 1.0 but no value in between.
8683     *
8684     * Subclasses should override this method to provide a smoother fade transition
8685     * when scrolling occurs.
8686     *
8687     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8688     */
8689    protected float getRightFadingEdgeStrength() {
8690        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8691                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8692    }
8693
8694    /**
8695     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8696     * scrollbar is not drawn by default.</p>
8697     *
8698     * @return true if the horizontal scrollbar should be painted, false
8699     *         otherwise
8700     *
8701     * @see #setHorizontalScrollBarEnabled(boolean)
8702     */
8703    public boolean isHorizontalScrollBarEnabled() {
8704        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8705    }
8706
8707    /**
8708     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8709     * scrollbar is not drawn by default.</p>
8710     *
8711     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8712     *                                   be painted
8713     *
8714     * @see #isHorizontalScrollBarEnabled()
8715     */
8716    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8717        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8718            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8719            computeOpaqueFlags();
8720            resolvePadding();
8721        }
8722    }
8723
8724    /**
8725     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8726     * scrollbar is not drawn by default.</p>
8727     *
8728     * @return true if the vertical scrollbar should be painted, false
8729     *         otherwise
8730     *
8731     * @see #setVerticalScrollBarEnabled(boolean)
8732     */
8733    public boolean isVerticalScrollBarEnabled() {
8734        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8735    }
8736
8737    /**
8738     * <p>Define whether the vertical scrollbar should be drawn or not. The
8739     * scrollbar is not drawn by default.</p>
8740     *
8741     * @param verticalScrollBarEnabled true if the vertical scrollbar should
8742     *                                 be painted
8743     *
8744     * @see #isVerticalScrollBarEnabled()
8745     */
8746    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
8747        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
8748            mViewFlags ^= SCROLLBARS_VERTICAL;
8749            computeOpaqueFlags();
8750            resolvePadding();
8751        }
8752    }
8753
8754    /**
8755     * @hide
8756     */
8757    protected void recomputePadding() {
8758        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
8759    }
8760
8761    /**
8762     * Define whether scrollbars will fade when the view is not scrolling.
8763     *
8764     * @param fadeScrollbars wheter to enable fading
8765     *
8766     */
8767    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
8768        initScrollCache();
8769        final ScrollabilityCache scrollabilityCache = mScrollCache;
8770        scrollabilityCache.fadeScrollBars = fadeScrollbars;
8771        if (fadeScrollbars) {
8772            scrollabilityCache.state = ScrollabilityCache.OFF;
8773        } else {
8774            scrollabilityCache.state = ScrollabilityCache.ON;
8775        }
8776    }
8777
8778    /**
8779     *
8780     * Returns true if scrollbars will fade when this view is not scrolling
8781     *
8782     * @return true if scrollbar fading is enabled
8783     */
8784    public boolean isScrollbarFadingEnabled() {
8785        return mScrollCache != null && mScrollCache.fadeScrollBars;
8786    }
8787
8788    /**
8789     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
8790     * inset. When inset, they add to the padding of the view. And the scrollbars
8791     * can be drawn inside the padding area or on the edge of the view. For example,
8792     * if a view has a background drawable and you want to draw the scrollbars
8793     * inside the padding specified by the drawable, you can use
8794     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
8795     * appear at the edge of the view, ignoring the padding, then you can use
8796     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
8797     * @param style the style of the scrollbars. Should be one of
8798     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
8799     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
8800     * @see #SCROLLBARS_INSIDE_OVERLAY
8801     * @see #SCROLLBARS_INSIDE_INSET
8802     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8803     * @see #SCROLLBARS_OUTSIDE_INSET
8804     */
8805    public void setScrollBarStyle(int style) {
8806        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
8807            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
8808            computeOpaqueFlags();
8809            resolvePadding();
8810        }
8811    }
8812
8813    /**
8814     * <p>Returns the current scrollbar style.</p>
8815     * @return the current scrollbar style
8816     * @see #SCROLLBARS_INSIDE_OVERLAY
8817     * @see #SCROLLBARS_INSIDE_INSET
8818     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8819     * @see #SCROLLBARS_OUTSIDE_INSET
8820     */
8821    @ViewDebug.ExportedProperty(mapping = {
8822            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
8823            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
8824            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
8825            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
8826    })
8827    public int getScrollBarStyle() {
8828        return mViewFlags & SCROLLBARS_STYLE_MASK;
8829    }
8830
8831    /**
8832     * <p>Compute the horizontal range that the horizontal scrollbar
8833     * represents.</p>
8834     *
8835     * <p>The range is expressed in arbitrary units that must be the same as the
8836     * units used by {@link #computeHorizontalScrollExtent()} and
8837     * {@link #computeHorizontalScrollOffset()}.</p>
8838     *
8839     * <p>The default range is the drawing width of this view.</p>
8840     *
8841     * @return the total horizontal range represented by the horizontal
8842     *         scrollbar
8843     *
8844     * @see #computeHorizontalScrollExtent()
8845     * @see #computeHorizontalScrollOffset()
8846     * @see android.widget.ScrollBarDrawable
8847     */
8848    protected int computeHorizontalScrollRange() {
8849        return getWidth();
8850    }
8851
8852    /**
8853     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
8854     * within the horizontal range. This value is used to compute the position
8855     * of the thumb within the scrollbar's track.</p>
8856     *
8857     * <p>The range is expressed in arbitrary units that must be the same as the
8858     * units used by {@link #computeHorizontalScrollRange()} and
8859     * {@link #computeHorizontalScrollExtent()}.</p>
8860     *
8861     * <p>The default offset is the scroll offset of this view.</p>
8862     *
8863     * @return the horizontal offset of the scrollbar's thumb
8864     *
8865     * @see #computeHorizontalScrollRange()
8866     * @see #computeHorizontalScrollExtent()
8867     * @see android.widget.ScrollBarDrawable
8868     */
8869    protected int computeHorizontalScrollOffset() {
8870        return mScrollX;
8871    }
8872
8873    /**
8874     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
8875     * within the horizontal range. This value is used to compute the length
8876     * of the thumb within the scrollbar's track.</p>
8877     *
8878     * <p>The range is expressed in arbitrary units that must be the same as the
8879     * units used by {@link #computeHorizontalScrollRange()} and
8880     * {@link #computeHorizontalScrollOffset()}.</p>
8881     *
8882     * <p>The default extent is the drawing width of this view.</p>
8883     *
8884     * @return the horizontal extent of the scrollbar's thumb
8885     *
8886     * @see #computeHorizontalScrollRange()
8887     * @see #computeHorizontalScrollOffset()
8888     * @see android.widget.ScrollBarDrawable
8889     */
8890    protected int computeHorizontalScrollExtent() {
8891        return getWidth();
8892    }
8893
8894    /**
8895     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
8896     *
8897     * <p>The range is expressed in arbitrary units that must be the same as the
8898     * units used by {@link #computeVerticalScrollExtent()} and
8899     * {@link #computeVerticalScrollOffset()}.</p>
8900     *
8901     * @return the total vertical range represented by the vertical scrollbar
8902     *
8903     * <p>The default range is the drawing height of this view.</p>
8904     *
8905     * @see #computeVerticalScrollExtent()
8906     * @see #computeVerticalScrollOffset()
8907     * @see android.widget.ScrollBarDrawable
8908     */
8909    protected int computeVerticalScrollRange() {
8910        return getHeight();
8911    }
8912
8913    /**
8914     * <p>Compute the vertical offset of the vertical scrollbar's thumb
8915     * within the horizontal range. This value is used to compute the position
8916     * of the thumb within the scrollbar's track.</p>
8917     *
8918     * <p>The range is expressed in arbitrary units that must be the same as the
8919     * units used by {@link #computeVerticalScrollRange()} and
8920     * {@link #computeVerticalScrollExtent()}.</p>
8921     *
8922     * <p>The default offset is the scroll offset of this view.</p>
8923     *
8924     * @return the vertical offset of the scrollbar's thumb
8925     *
8926     * @see #computeVerticalScrollRange()
8927     * @see #computeVerticalScrollExtent()
8928     * @see android.widget.ScrollBarDrawable
8929     */
8930    protected int computeVerticalScrollOffset() {
8931        return mScrollY;
8932    }
8933
8934    /**
8935     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
8936     * within the vertical range. This value is used to compute the length
8937     * of the thumb within the scrollbar's track.</p>
8938     *
8939     * <p>The range is expressed in arbitrary units that must be the same as the
8940     * units used by {@link #computeVerticalScrollRange()} and
8941     * {@link #computeVerticalScrollOffset()}.</p>
8942     *
8943     * <p>The default extent is the drawing height of this view.</p>
8944     *
8945     * @return the vertical extent of the scrollbar's thumb
8946     *
8947     * @see #computeVerticalScrollRange()
8948     * @see #computeVerticalScrollOffset()
8949     * @see android.widget.ScrollBarDrawable
8950     */
8951    protected int computeVerticalScrollExtent() {
8952        return getHeight();
8953    }
8954
8955    /**
8956     * Check if this view can be scrolled horizontally in a certain direction.
8957     *
8958     * @param direction Negative to check scrolling left, positive to check scrolling right.
8959     * @return true if this view can be scrolled in the specified direction, false otherwise.
8960     */
8961    public boolean canScrollHorizontally(int direction) {
8962        final int offset = computeHorizontalScrollOffset();
8963        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
8964        if (range == 0) return false;
8965        if (direction < 0) {
8966            return offset > 0;
8967        } else {
8968            return offset < range - 1;
8969        }
8970    }
8971
8972    /**
8973     * Check if this view can be scrolled vertically in a certain direction.
8974     *
8975     * @param direction Negative to check scrolling up, positive to check scrolling down.
8976     * @return true if this view can be scrolled in the specified direction, false otherwise.
8977     */
8978    public boolean canScrollVertically(int direction) {
8979        final int offset = computeVerticalScrollOffset();
8980        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
8981        if (range == 0) return false;
8982        if (direction < 0) {
8983            return offset > 0;
8984        } else {
8985            return offset < range - 1;
8986        }
8987    }
8988
8989    /**
8990     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
8991     * scrollbars are painted only if they have been awakened first.</p>
8992     *
8993     * @param canvas the canvas on which to draw the scrollbars
8994     *
8995     * @see #awakenScrollBars(int)
8996     */
8997    protected final void onDrawScrollBars(Canvas canvas) {
8998        // scrollbars are drawn only when the animation is running
8999        final ScrollabilityCache cache = mScrollCache;
9000        if (cache != null) {
9001
9002            int state = cache.state;
9003
9004            if (state == ScrollabilityCache.OFF) {
9005                return;
9006            }
9007
9008            boolean invalidate = false;
9009
9010            if (state == ScrollabilityCache.FADING) {
9011                // We're fading -- get our fade interpolation
9012                if (cache.interpolatorValues == null) {
9013                    cache.interpolatorValues = new float[1];
9014                }
9015
9016                float[] values = cache.interpolatorValues;
9017
9018                // Stops the animation if we're done
9019                if (cache.scrollBarInterpolator.timeToValues(values) ==
9020                        Interpolator.Result.FREEZE_END) {
9021                    cache.state = ScrollabilityCache.OFF;
9022                } else {
9023                    cache.scrollBar.setAlpha(Math.round(values[0]));
9024                }
9025
9026                // This will make the scroll bars inval themselves after
9027                // drawing. We only want this when we're fading so that
9028                // we prevent excessive redraws
9029                invalidate = true;
9030            } else {
9031                // We're just on -- but we may have been fading before so
9032                // reset alpha
9033                cache.scrollBar.setAlpha(255);
9034            }
9035
9036
9037            final int viewFlags = mViewFlags;
9038
9039            final boolean drawHorizontalScrollBar =
9040                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9041            final boolean drawVerticalScrollBar =
9042                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9043                && !isVerticalScrollBarHidden();
9044
9045            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9046                final int width = mRight - mLeft;
9047                final int height = mBottom - mTop;
9048
9049                final ScrollBarDrawable scrollBar = cache.scrollBar;
9050
9051                final int scrollX = mScrollX;
9052                final int scrollY = mScrollY;
9053                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9054
9055                int left, top, right, bottom;
9056
9057                if (drawHorizontalScrollBar) {
9058                    int size = scrollBar.getSize(false);
9059                    if (size <= 0) {
9060                        size = cache.scrollBarSize;
9061                    }
9062
9063                    scrollBar.setParameters(computeHorizontalScrollRange(),
9064                                            computeHorizontalScrollOffset(),
9065                                            computeHorizontalScrollExtent(), false);
9066                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9067                            getVerticalScrollbarWidth() : 0;
9068                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9069                    left = scrollX + (mPaddingLeft & inside);
9070                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9071                    bottom = top + size;
9072                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9073                    if (invalidate) {
9074                        invalidate(left, top, right, bottom);
9075                    }
9076                }
9077
9078                if (drawVerticalScrollBar) {
9079                    int size = scrollBar.getSize(true);
9080                    if (size <= 0) {
9081                        size = cache.scrollBarSize;
9082                    }
9083
9084                    scrollBar.setParameters(computeVerticalScrollRange(),
9085                                            computeVerticalScrollOffset(),
9086                                            computeVerticalScrollExtent(), true);
9087                    switch (mVerticalScrollbarPosition) {
9088                        default:
9089                        case SCROLLBAR_POSITION_DEFAULT:
9090                        case SCROLLBAR_POSITION_RIGHT:
9091                            left = scrollX + width - size - (mUserPaddingRight & inside);
9092                            break;
9093                        case SCROLLBAR_POSITION_LEFT:
9094                            left = scrollX + (mUserPaddingLeft & inside);
9095                            break;
9096                    }
9097                    top = scrollY + (mPaddingTop & inside);
9098                    right = left + size;
9099                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9100                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9101                    if (invalidate) {
9102                        invalidate(left, top, right, bottom);
9103                    }
9104                }
9105            }
9106        }
9107    }
9108
9109    /**
9110     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9111     * FastScroller is visible.
9112     * @return whether to temporarily hide the vertical scrollbar
9113     * @hide
9114     */
9115    protected boolean isVerticalScrollBarHidden() {
9116        return false;
9117    }
9118
9119    /**
9120     * <p>Draw the horizontal scrollbar if
9121     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9122     *
9123     * @param canvas the canvas on which to draw the scrollbar
9124     * @param scrollBar the scrollbar's drawable
9125     *
9126     * @see #isHorizontalScrollBarEnabled()
9127     * @see #computeHorizontalScrollRange()
9128     * @see #computeHorizontalScrollExtent()
9129     * @see #computeHorizontalScrollOffset()
9130     * @see android.widget.ScrollBarDrawable
9131     * @hide
9132     */
9133    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9134            int l, int t, int r, int b) {
9135        scrollBar.setBounds(l, t, r, b);
9136        scrollBar.draw(canvas);
9137    }
9138
9139    /**
9140     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9141     * returns true.</p>
9142     *
9143     * @param canvas the canvas on which to draw the scrollbar
9144     * @param scrollBar the scrollbar's drawable
9145     *
9146     * @see #isVerticalScrollBarEnabled()
9147     * @see #computeVerticalScrollRange()
9148     * @see #computeVerticalScrollExtent()
9149     * @see #computeVerticalScrollOffset()
9150     * @see android.widget.ScrollBarDrawable
9151     * @hide
9152     */
9153    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9154            int l, int t, int r, int b) {
9155        scrollBar.setBounds(l, t, r, b);
9156        scrollBar.draw(canvas);
9157    }
9158
9159    /**
9160     * Implement this to do your drawing.
9161     *
9162     * @param canvas the canvas on which the background will be drawn
9163     */
9164    protected void onDraw(Canvas canvas) {
9165    }
9166
9167    /*
9168     * Caller is responsible for calling requestLayout if necessary.
9169     * (This allows addViewInLayout to not request a new layout.)
9170     */
9171    void assignParent(ViewParent parent) {
9172        if (mParent == null) {
9173            mParent = parent;
9174        } else if (parent == null) {
9175            mParent = null;
9176        } else {
9177            throw new RuntimeException("view " + this + " being added, but"
9178                    + " it already has a parent");
9179        }
9180    }
9181
9182    /**
9183     * This is called when the view is attached to a window.  At this point it
9184     * has a Surface and will start drawing.  Note that this function is
9185     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9186     * however it may be called any time before the first onDraw -- including
9187     * before or after {@link #onMeasure(int, int)}.
9188     *
9189     * @see #onDetachedFromWindow()
9190     */
9191    protected void onAttachedToWindow() {
9192        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9193            mParent.requestTransparentRegion(this);
9194        }
9195        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9196            initialAwakenScrollBars();
9197            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9198        }
9199        jumpDrawablesToCurrentState();
9200        // Order is important here: LayoutDirection MUST be resolved before Padding
9201        // and TextDirection
9202        resolveLayoutDirectionIfNeeded();
9203        resolvePadding();
9204        resolveTextDirection();
9205        if (isFocused()) {
9206            InputMethodManager imm = InputMethodManager.peekInstance();
9207            imm.focusIn(this);
9208        }
9209    }
9210
9211    /**
9212     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9213     * that the parent directionality can and will be resolved before its children.
9214     */
9215    private void resolveLayoutDirectionIfNeeded() {
9216        // Do not resolve if it is not needed
9217        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9218
9219        // Clear any previous layout direction resolution
9220        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9221
9222        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9223        // TextDirectionHeuristic
9224        resetResolvedTextDirection();
9225
9226        // Set resolved depending on layout direction
9227        switch (getLayoutDirection()) {
9228            case LAYOUT_DIRECTION_INHERIT:
9229                // We cannot do the resolution if there is no parent
9230                if (mParent == null) return;
9231
9232                // If this is root view, no need to look at parent's layout dir.
9233                if (mParent instanceof ViewGroup) {
9234                    ViewGroup viewGroup = ((ViewGroup) mParent);
9235
9236                    // Check if the parent view group can resolve
9237                    if (! viewGroup.canResolveLayoutDirection()) {
9238                        return;
9239                    }
9240                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9241                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9242                    }
9243                }
9244                break;
9245            case LAYOUT_DIRECTION_RTL:
9246                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9247                break;
9248            case LAYOUT_DIRECTION_LOCALE:
9249                if(isLayoutDirectionRtl(Locale.getDefault())) {
9250                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9251                }
9252                break;
9253            default:
9254                // Nothing to do, LTR by default
9255        }
9256
9257        // Set to resolved
9258        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9259    }
9260
9261    /**
9262     * @hide
9263     */
9264    protected void resolvePadding() {
9265        // If the user specified the absolute padding (either with android:padding or
9266        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9267        // use the default padding or the padding from the background drawable
9268        // (stored at this point in mPadding*)
9269        switch (getResolvedLayoutDirection()) {
9270            case LAYOUT_DIRECTION_RTL:
9271                // Start user padding override Right user padding. Otherwise, if Right user
9272                // padding is not defined, use the default Right padding. If Right user padding
9273                // is defined, just use it.
9274                if (mUserPaddingStart >= 0) {
9275                    mUserPaddingRight = mUserPaddingStart;
9276                } else if (mUserPaddingRight < 0) {
9277                    mUserPaddingRight = mPaddingRight;
9278                }
9279                if (mUserPaddingEnd >= 0) {
9280                    mUserPaddingLeft = mUserPaddingEnd;
9281                } else if (mUserPaddingLeft < 0) {
9282                    mUserPaddingLeft = mPaddingLeft;
9283                }
9284                break;
9285            case LAYOUT_DIRECTION_LTR:
9286            default:
9287                // Start user padding override Left user padding. Otherwise, if Left user
9288                // padding is not defined, use the default left padding. If Left user padding
9289                // is defined, just use it.
9290                if (mUserPaddingStart >= 0) {
9291                    mUserPaddingLeft = mUserPaddingStart;
9292                } else if (mUserPaddingLeft < 0) {
9293                    mUserPaddingLeft = mPaddingLeft;
9294                }
9295                if (mUserPaddingEnd >= 0) {
9296                    mUserPaddingRight = mUserPaddingEnd;
9297                } else if (mUserPaddingRight < 0) {
9298                    mUserPaddingRight = mPaddingRight;
9299                }
9300        }
9301
9302        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9303
9304        recomputePadding();
9305    }
9306
9307    protected boolean canResolveLayoutDirection() {
9308        switch (getLayoutDirection()) {
9309            case LAYOUT_DIRECTION_INHERIT:
9310                return (mParent != null);
9311            default:
9312                return true;
9313        }
9314    }
9315
9316    /**
9317     * Reset the resolved layout direction.
9318     *
9319     * Subclasses need to override this method to clear cached information that depends on the
9320     * resolved layout direction, or to inform child views that inherit their layout direction.
9321     * Overrides must also call the superclass implementation at the start of their implementation.
9322     *
9323     * @hide
9324     */
9325    protected void resetResolvedLayoutDirection() {
9326        // Reset the current View resolution
9327        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9328    }
9329
9330    /**
9331     * Check if a Locale is corresponding to a RTL script.
9332     *
9333     * @param locale Locale to check
9334     * @return true if a Locale is corresponding to a RTL script.
9335     */
9336    protected static boolean isLayoutDirectionRtl(Locale locale) {
9337        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9338                LocaleUtil.getLayoutDirectionFromLocale(locale));
9339    }
9340
9341    /**
9342     * This is called when the view is detached from a window.  At this point it
9343     * no longer has a surface for drawing.
9344     *
9345     * @see #onAttachedToWindow()
9346     */
9347    protected void onDetachedFromWindow() {
9348        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9349
9350        removeUnsetPressCallback();
9351        removeLongPressCallback();
9352        removePerformClickCallback();
9353        removeSendViewScrolledAccessibilityEventCallback();
9354
9355        destroyDrawingCache();
9356
9357        destroyLayer();
9358
9359        if (mDisplayList != null) {
9360            mDisplayList.invalidate();
9361        }
9362
9363        if (mAttachInfo != null) {
9364            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9365        }
9366
9367        mCurrentAnimation = null;
9368
9369        resetResolvedLayoutDirection();
9370        resetResolvedTextDirection();
9371    }
9372
9373    /**
9374     * @return The number of times this view has been attached to a window
9375     */
9376    protected int getWindowAttachCount() {
9377        return mWindowAttachCount;
9378    }
9379
9380    /**
9381     * Retrieve a unique token identifying the window this view is attached to.
9382     * @return Return the window's token for use in
9383     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9384     */
9385    public IBinder getWindowToken() {
9386        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9387    }
9388
9389    /**
9390     * Retrieve a unique token identifying the top-level "real" window of
9391     * the window that this view is attached to.  That is, this is like
9392     * {@link #getWindowToken}, except if the window this view in is a panel
9393     * window (attached to another containing window), then the token of
9394     * the containing window is returned instead.
9395     *
9396     * @return Returns the associated window token, either
9397     * {@link #getWindowToken()} or the containing window's token.
9398     */
9399    public IBinder getApplicationWindowToken() {
9400        AttachInfo ai = mAttachInfo;
9401        if (ai != null) {
9402            IBinder appWindowToken = ai.mPanelParentWindowToken;
9403            if (appWindowToken == null) {
9404                appWindowToken = ai.mWindowToken;
9405            }
9406            return appWindowToken;
9407        }
9408        return null;
9409    }
9410
9411    /**
9412     * Retrieve private session object this view hierarchy is using to
9413     * communicate with the window manager.
9414     * @return the session object to communicate with the window manager
9415     */
9416    /*package*/ IWindowSession getWindowSession() {
9417        return mAttachInfo != null ? mAttachInfo.mSession : null;
9418    }
9419
9420    /**
9421     * @param info the {@link android.view.View.AttachInfo} to associated with
9422     *        this view
9423     */
9424    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9425        //System.out.println("Attached! " + this);
9426        mAttachInfo = info;
9427        mWindowAttachCount++;
9428        // We will need to evaluate the drawable state at least once.
9429        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9430        if (mFloatingTreeObserver != null) {
9431            info.mTreeObserver.merge(mFloatingTreeObserver);
9432            mFloatingTreeObserver = null;
9433        }
9434        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9435            mAttachInfo.mScrollContainers.add(this);
9436            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9437        }
9438        performCollectViewAttributes(visibility);
9439        onAttachedToWindow();
9440
9441        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9442                mOnAttachStateChangeListeners;
9443        if (listeners != null && listeners.size() > 0) {
9444            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9445            // perform the dispatching. The iterator is a safe guard against listeners that
9446            // could mutate the list by calling the various add/remove methods. This prevents
9447            // the array from being modified while we iterate it.
9448            for (OnAttachStateChangeListener listener : listeners) {
9449                listener.onViewAttachedToWindow(this);
9450            }
9451        }
9452
9453        int vis = info.mWindowVisibility;
9454        if (vis != GONE) {
9455            onWindowVisibilityChanged(vis);
9456        }
9457        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9458            // If nobody has evaluated the drawable state yet, then do it now.
9459            refreshDrawableState();
9460        }
9461    }
9462
9463    void dispatchDetachedFromWindow() {
9464        AttachInfo info = mAttachInfo;
9465        if (info != null) {
9466            int vis = info.mWindowVisibility;
9467            if (vis != GONE) {
9468                onWindowVisibilityChanged(GONE);
9469            }
9470        }
9471
9472        onDetachedFromWindow();
9473
9474        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9475                mOnAttachStateChangeListeners;
9476        if (listeners != null && listeners.size() > 0) {
9477            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9478            // perform the dispatching. The iterator is a safe guard against listeners that
9479            // could mutate the list by calling the various add/remove methods. This prevents
9480            // the array from being modified while we iterate it.
9481            for (OnAttachStateChangeListener listener : listeners) {
9482                listener.onViewDetachedFromWindow(this);
9483            }
9484        }
9485
9486        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9487            mAttachInfo.mScrollContainers.remove(this);
9488            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9489        }
9490
9491        mAttachInfo = null;
9492    }
9493
9494    /**
9495     * Store this view hierarchy's frozen state into the given container.
9496     *
9497     * @param container The SparseArray in which to save the view's state.
9498     *
9499     * @see #restoreHierarchyState(android.util.SparseArray)
9500     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9501     * @see #onSaveInstanceState()
9502     */
9503    public void saveHierarchyState(SparseArray<Parcelable> container) {
9504        dispatchSaveInstanceState(container);
9505    }
9506
9507    /**
9508     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9509     * this view and its children. May be overridden to modify how freezing happens to a
9510     * view's children; for example, some views may want to not store state for their children.
9511     *
9512     * @param container The SparseArray in which to save the view's state.
9513     *
9514     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9515     * @see #saveHierarchyState(android.util.SparseArray)
9516     * @see #onSaveInstanceState()
9517     */
9518    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9519        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9520            mPrivateFlags &= ~SAVE_STATE_CALLED;
9521            Parcelable state = onSaveInstanceState();
9522            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9523                throw new IllegalStateException(
9524                        "Derived class did not call super.onSaveInstanceState()");
9525            }
9526            if (state != null) {
9527                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9528                // + ": " + state);
9529                container.put(mID, state);
9530            }
9531        }
9532    }
9533
9534    /**
9535     * Hook allowing a view to generate a representation of its internal state
9536     * that can later be used to create a new instance with that same state.
9537     * This state should only contain information that is not persistent or can
9538     * not be reconstructed later. For example, you will never store your
9539     * current position on screen because that will be computed again when a
9540     * new instance of the view is placed in its view hierarchy.
9541     * <p>
9542     * Some examples of things you may store here: the current cursor position
9543     * in a text view (but usually not the text itself since that is stored in a
9544     * content provider or other persistent storage), the currently selected
9545     * item in a list view.
9546     *
9547     * @return Returns a Parcelable object containing the view's current dynamic
9548     *         state, or null if there is nothing interesting to save. The
9549     *         default implementation returns null.
9550     * @see #onRestoreInstanceState(android.os.Parcelable)
9551     * @see #saveHierarchyState(android.util.SparseArray)
9552     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9553     * @see #setSaveEnabled(boolean)
9554     */
9555    protected Parcelable onSaveInstanceState() {
9556        mPrivateFlags |= SAVE_STATE_CALLED;
9557        return BaseSavedState.EMPTY_STATE;
9558    }
9559
9560    /**
9561     * Restore this view hierarchy's frozen state from the given container.
9562     *
9563     * @param container The SparseArray which holds previously frozen states.
9564     *
9565     * @see #saveHierarchyState(android.util.SparseArray)
9566     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9567     * @see #onRestoreInstanceState(android.os.Parcelable)
9568     */
9569    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9570        dispatchRestoreInstanceState(container);
9571    }
9572
9573    /**
9574     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9575     * state for this view and its children. May be overridden to modify how restoring
9576     * happens to a view's children; for example, some views may want to not store state
9577     * for their children.
9578     *
9579     * @param container The SparseArray which holds previously saved state.
9580     *
9581     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9582     * @see #restoreHierarchyState(android.util.SparseArray)
9583     * @see #onRestoreInstanceState(android.os.Parcelable)
9584     */
9585    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9586        if (mID != NO_ID) {
9587            Parcelable state = container.get(mID);
9588            if (state != null) {
9589                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9590                // + ": " + state);
9591                mPrivateFlags &= ~SAVE_STATE_CALLED;
9592                onRestoreInstanceState(state);
9593                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9594                    throw new IllegalStateException(
9595                            "Derived class did not call super.onRestoreInstanceState()");
9596                }
9597            }
9598        }
9599    }
9600
9601    /**
9602     * Hook allowing a view to re-apply a representation of its internal state that had previously
9603     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9604     * null state.
9605     *
9606     * @param state The frozen state that had previously been returned by
9607     *        {@link #onSaveInstanceState}.
9608     *
9609     * @see #onSaveInstanceState()
9610     * @see #restoreHierarchyState(android.util.SparseArray)
9611     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9612     */
9613    protected void onRestoreInstanceState(Parcelable state) {
9614        mPrivateFlags |= SAVE_STATE_CALLED;
9615        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9616            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9617                    + "received " + state.getClass().toString() + " instead. This usually happens "
9618                    + "when two views of different type have the same id in the same hierarchy. "
9619                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9620                    + "other views do not use the same id.");
9621        }
9622    }
9623
9624    /**
9625     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9626     *
9627     * @return the drawing start time in milliseconds
9628     */
9629    public long getDrawingTime() {
9630        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9631    }
9632
9633    /**
9634     * <p>Enables or disables the duplication of the parent's state into this view. When
9635     * duplication is enabled, this view gets its drawable state from its parent rather
9636     * than from its own internal properties.</p>
9637     *
9638     * <p>Note: in the current implementation, setting this property to true after the
9639     * view was added to a ViewGroup might have no effect at all. This property should
9640     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9641     *
9642     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9643     * property is enabled, an exception will be thrown.</p>
9644     *
9645     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9646     * parent, these states should not be affected by this method.</p>
9647     *
9648     * @param enabled True to enable duplication of the parent's drawable state, false
9649     *                to disable it.
9650     *
9651     * @see #getDrawableState()
9652     * @see #isDuplicateParentStateEnabled()
9653     */
9654    public void setDuplicateParentStateEnabled(boolean enabled) {
9655        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9656    }
9657
9658    /**
9659     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9660     *
9661     * @return True if this view's drawable state is duplicated from the parent,
9662     *         false otherwise
9663     *
9664     * @see #getDrawableState()
9665     * @see #setDuplicateParentStateEnabled(boolean)
9666     */
9667    public boolean isDuplicateParentStateEnabled() {
9668        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9669    }
9670
9671    /**
9672     * <p>Specifies the type of layer backing this view. The layer can be
9673     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9674     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9675     *
9676     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9677     * instance that controls how the layer is composed on screen. The following
9678     * properties of the paint are taken into account when composing the layer:</p>
9679     * <ul>
9680     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9681     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9682     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9683     * </ul>
9684     *
9685     * <p>If this view has an alpha value set to < 1.0 by calling
9686     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9687     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9688     * equivalent to setting a hardware layer on this view and providing a paint with
9689     * the desired alpha value.<p>
9690     *
9691     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9692     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9693     * for more information on when and how to use layers.</p>
9694     *
9695     * @param layerType The ype of layer to use with this view, must be one of
9696     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9697     *        {@link #LAYER_TYPE_HARDWARE}
9698     * @param paint The paint used to compose the layer. This argument is optional
9699     *        and can be null. It is ignored when the layer type is
9700     *        {@link #LAYER_TYPE_NONE}
9701     *
9702     * @see #getLayerType()
9703     * @see #LAYER_TYPE_NONE
9704     * @see #LAYER_TYPE_SOFTWARE
9705     * @see #LAYER_TYPE_HARDWARE
9706     * @see #setAlpha(float)
9707     *
9708     * @attr ref android.R.styleable#View_layerType
9709     */
9710    public void setLayerType(int layerType, Paint paint) {
9711        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9712            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9713                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9714        }
9715
9716        if (layerType == mLayerType) {
9717            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9718                mLayerPaint = paint == null ? new Paint() : paint;
9719                invalidateParentCaches();
9720                invalidate(true);
9721            }
9722            return;
9723        }
9724
9725        // Destroy any previous software drawing cache if needed
9726        switch (mLayerType) {
9727            case LAYER_TYPE_HARDWARE:
9728                destroyLayer();
9729                // fall through - unaccelerated views may use software layer mechanism instead
9730            case LAYER_TYPE_SOFTWARE:
9731                destroyDrawingCache();
9732                break;
9733            default:
9734                break;
9735        }
9736
9737        mLayerType = layerType;
9738        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
9739        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
9740        mLocalDirtyRect = layerDisabled ? null : new Rect();
9741
9742        invalidateParentCaches();
9743        invalidate(true);
9744    }
9745
9746    /**
9747     * Indicates what type of layer is currently associated with this view. By default
9748     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
9749     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
9750     * for more information on the different types of layers.
9751     *
9752     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9753     *         {@link #LAYER_TYPE_HARDWARE}
9754     *
9755     * @see #setLayerType(int, android.graphics.Paint)
9756     * @see #buildLayer()
9757     * @see #LAYER_TYPE_NONE
9758     * @see #LAYER_TYPE_SOFTWARE
9759     * @see #LAYER_TYPE_HARDWARE
9760     */
9761    public int getLayerType() {
9762        return mLayerType;
9763    }
9764
9765    /**
9766     * Forces this view's layer to be created and this view to be rendered
9767     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
9768     * invoking this method will have no effect.
9769     *
9770     * This method can for instance be used to render a view into its layer before
9771     * starting an animation. If this view is complex, rendering into the layer
9772     * before starting the animation will avoid skipping frames.
9773     *
9774     * @throws IllegalStateException If this view is not attached to a window
9775     *
9776     * @see #setLayerType(int, android.graphics.Paint)
9777     */
9778    public void buildLayer() {
9779        if (mLayerType == LAYER_TYPE_NONE) return;
9780
9781        if (mAttachInfo == null) {
9782            throw new IllegalStateException("This view must be attached to a window first");
9783        }
9784
9785        switch (mLayerType) {
9786            case LAYER_TYPE_HARDWARE:
9787                getHardwareLayer();
9788                break;
9789            case LAYER_TYPE_SOFTWARE:
9790                buildDrawingCache(true);
9791                break;
9792        }
9793    }
9794
9795    /**
9796     * <p>Returns a hardware layer that can be used to draw this view again
9797     * without executing its draw method.</p>
9798     *
9799     * @return A HardwareLayer ready to render, or null if an error occurred.
9800     */
9801    HardwareLayer getHardwareLayer() {
9802        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
9803                !mAttachInfo.mHardwareRenderer.isEnabled()) {
9804            return null;
9805        }
9806
9807        final int width = mRight - mLeft;
9808        final int height = mBottom - mTop;
9809
9810        if (width == 0 || height == 0) {
9811            return null;
9812        }
9813
9814        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
9815            if (mHardwareLayer == null) {
9816                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
9817                        width, height, isOpaque());
9818                mLocalDirtyRect.setEmpty();
9819            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
9820                mHardwareLayer.resize(width, height);
9821                mLocalDirtyRect.setEmpty();
9822            }
9823
9824            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
9825            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
9826            mAttachInfo.mHardwareCanvas = canvas;
9827            try {
9828                canvas.setViewport(width, height);
9829                canvas.onPreDraw(mLocalDirtyRect);
9830                mLocalDirtyRect.setEmpty();
9831
9832                final int restoreCount = canvas.save();
9833
9834                computeScroll();
9835                canvas.translate(-mScrollX, -mScrollY);
9836
9837                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9838
9839                // Fast path for layouts with no backgrounds
9840                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9841                    mPrivateFlags &= ~DIRTY_MASK;
9842                    dispatchDraw(canvas);
9843                } else {
9844                    draw(canvas);
9845                }
9846
9847                canvas.restoreToCount(restoreCount);
9848            } finally {
9849                canvas.onPostDraw();
9850                mHardwareLayer.end(currentCanvas);
9851                mAttachInfo.mHardwareCanvas = currentCanvas;
9852            }
9853        }
9854
9855        return mHardwareLayer;
9856    }
9857
9858    boolean destroyLayer() {
9859        if (mHardwareLayer != null) {
9860            mHardwareLayer.destroy();
9861            mHardwareLayer = null;
9862            return true;
9863        }
9864        return false;
9865    }
9866
9867    /**
9868     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
9869     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
9870     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
9871     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
9872     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
9873     * null.</p>
9874     *
9875     * <p>Enabling the drawing cache is similar to
9876     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
9877     * acceleration is turned off. When hardware acceleration is turned on, enabling the
9878     * drawing cache has no effect on rendering because the system uses a different mechanism
9879     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
9880     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
9881     * for information on how to enable software and hardware layers.</p>
9882     *
9883     * <p>This API can be used to manually generate
9884     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
9885     * {@link #getDrawingCache()}.</p>
9886     *
9887     * @param enabled true to enable the drawing cache, false otherwise
9888     *
9889     * @see #isDrawingCacheEnabled()
9890     * @see #getDrawingCache()
9891     * @see #buildDrawingCache()
9892     * @see #setLayerType(int, android.graphics.Paint)
9893     */
9894    public void setDrawingCacheEnabled(boolean enabled) {
9895        mCachingFailed = false;
9896        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
9897    }
9898
9899    /**
9900     * <p>Indicates whether the drawing cache is enabled for this view.</p>
9901     *
9902     * @return true if the drawing cache is enabled
9903     *
9904     * @see #setDrawingCacheEnabled(boolean)
9905     * @see #getDrawingCache()
9906     */
9907    @ViewDebug.ExportedProperty(category = "drawing")
9908    public boolean isDrawingCacheEnabled() {
9909        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
9910    }
9911
9912    /**
9913     * Debugging utility which recursively outputs the dirty state of a view and its
9914     * descendants.
9915     *
9916     * @hide
9917     */
9918    @SuppressWarnings({"UnusedDeclaration"})
9919    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
9920        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
9921                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
9922                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
9923                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
9924        if (clear) {
9925            mPrivateFlags &= clearMask;
9926        }
9927        if (this instanceof ViewGroup) {
9928            ViewGroup parent = (ViewGroup) this;
9929            final int count = parent.getChildCount();
9930            for (int i = 0; i < count; i++) {
9931                final View child = parent.getChildAt(i);
9932                child.outputDirtyFlags(indent + "  ", clear, clearMask);
9933            }
9934        }
9935    }
9936
9937    /**
9938     * This method is used by ViewGroup to cause its children to restore or recreate their
9939     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
9940     * to recreate its own display list, which would happen if it went through the normal
9941     * draw/dispatchDraw mechanisms.
9942     *
9943     * @hide
9944     */
9945    protected void dispatchGetDisplayList() {}
9946
9947    /**
9948     * A view that is not attached or hardware accelerated cannot create a display list.
9949     * This method checks these conditions and returns the appropriate result.
9950     *
9951     * @return true if view has the ability to create a display list, false otherwise.
9952     *
9953     * @hide
9954     */
9955    public boolean canHaveDisplayList() {
9956        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
9957    }
9958
9959    /**
9960     * <p>Returns a display list that can be used to draw this view again
9961     * without executing its draw method.</p>
9962     *
9963     * @return A DisplayList ready to replay, or null if caching is not enabled.
9964     *
9965     * @hide
9966     */
9967    public DisplayList getDisplayList() {
9968        if (!canHaveDisplayList()) {
9969            return null;
9970        }
9971
9972        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
9973                mDisplayList == null || !mDisplayList.isValid() ||
9974                mRecreateDisplayList)) {
9975            // Don't need to recreate the display list, just need to tell our
9976            // children to restore/recreate theirs
9977            if (mDisplayList != null && mDisplayList.isValid() &&
9978                    !mRecreateDisplayList) {
9979                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9980                mPrivateFlags &= ~DIRTY_MASK;
9981                dispatchGetDisplayList();
9982
9983                return mDisplayList;
9984            }
9985
9986            // If we got here, we're recreating it. Mark it as such to ensure that
9987            // we copy in child display lists into ours in drawChild()
9988            mRecreateDisplayList = true;
9989            if (mDisplayList == null) {
9990                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
9991                // If we're creating a new display list, make sure our parent gets invalidated
9992                // since they will need to recreate their display list to account for this
9993                // new child display list.
9994                invalidateParentCaches();
9995            }
9996
9997            final HardwareCanvas canvas = mDisplayList.start();
9998            try {
9999                int width = mRight - mLeft;
10000                int height = mBottom - mTop;
10001
10002                canvas.setViewport(width, height);
10003                // The dirty rect should always be null for a display list
10004                canvas.onPreDraw(null);
10005
10006                computeScroll();
10007                canvas.translate(-mScrollX, -mScrollY);
10008                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10009                mPrivateFlags &= ~DIRTY_MASK;
10010
10011                // Fast path for layouts with no backgrounds
10012                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10013                    dispatchDraw(canvas);
10014                } else {
10015                    draw(canvas);
10016                }
10017            } finally {
10018                canvas.onPostDraw();
10019
10020                mDisplayList.end();
10021            }
10022        } else {
10023            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10024            mPrivateFlags &= ~DIRTY_MASK;
10025        }
10026
10027        return mDisplayList;
10028    }
10029
10030    /**
10031     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10032     *
10033     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10034     *
10035     * @see #getDrawingCache(boolean)
10036     */
10037    public Bitmap getDrawingCache() {
10038        return getDrawingCache(false);
10039    }
10040
10041    /**
10042     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10043     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10044     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10045     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10046     * request the drawing cache by calling this method and draw it on screen if the
10047     * returned bitmap is not null.</p>
10048     *
10049     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10050     * this method will create a bitmap of the same size as this view. Because this bitmap
10051     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10052     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10053     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10054     * size than the view. This implies that your application must be able to handle this
10055     * size.</p>
10056     *
10057     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10058     *        the current density of the screen when the application is in compatibility
10059     *        mode.
10060     *
10061     * @return A bitmap representing this view or null if cache is disabled.
10062     *
10063     * @see #setDrawingCacheEnabled(boolean)
10064     * @see #isDrawingCacheEnabled()
10065     * @see #buildDrawingCache(boolean)
10066     * @see #destroyDrawingCache()
10067     */
10068    public Bitmap getDrawingCache(boolean autoScale) {
10069        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10070            return null;
10071        }
10072        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10073            buildDrawingCache(autoScale);
10074        }
10075        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10076    }
10077
10078    /**
10079     * <p>Frees the resources used by the drawing cache. If you call
10080     * {@link #buildDrawingCache()} manually without calling
10081     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10082     * should cleanup the cache with this method afterwards.</p>
10083     *
10084     * @see #setDrawingCacheEnabled(boolean)
10085     * @see #buildDrawingCache()
10086     * @see #getDrawingCache()
10087     */
10088    public void destroyDrawingCache() {
10089        if (mDrawingCache != null) {
10090            mDrawingCache.recycle();
10091            mDrawingCache = null;
10092        }
10093        if (mUnscaledDrawingCache != null) {
10094            mUnscaledDrawingCache.recycle();
10095            mUnscaledDrawingCache = null;
10096        }
10097    }
10098
10099    /**
10100     * Setting a solid background color for the drawing cache's bitmaps will improve
10101     * perfromance and memory usage. Note, though that this should only be used if this
10102     * view will always be drawn on top of a solid color.
10103     *
10104     * @param color The background color to use for the drawing cache's bitmap
10105     *
10106     * @see #setDrawingCacheEnabled(boolean)
10107     * @see #buildDrawingCache()
10108     * @see #getDrawingCache()
10109     */
10110    public void setDrawingCacheBackgroundColor(int color) {
10111        if (color != mDrawingCacheBackgroundColor) {
10112            mDrawingCacheBackgroundColor = color;
10113            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10114        }
10115    }
10116
10117    /**
10118     * @see #setDrawingCacheBackgroundColor(int)
10119     *
10120     * @return The background color to used for the drawing cache's bitmap
10121     */
10122    public int getDrawingCacheBackgroundColor() {
10123        return mDrawingCacheBackgroundColor;
10124    }
10125
10126    /**
10127     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10128     *
10129     * @see #buildDrawingCache(boolean)
10130     */
10131    public void buildDrawingCache() {
10132        buildDrawingCache(false);
10133    }
10134
10135    /**
10136     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10137     *
10138     * <p>If you call {@link #buildDrawingCache()} manually without calling
10139     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10140     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10141     *
10142     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10143     * this method will create a bitmap of the same size as this view. Because this bitmap
10144     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10145     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10146     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10147     * size than the view. This implies that your application must be able to handle this
10148     * size.</p>
10149     *
10150     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10151     * you do not need the drawing cache bitmap, calling this method will increase memory
10152     * usage and cause the view to be rendered in software once, thus negatively impacting
10153     * performance.</p>
10154     *
10155     * @see #getDrawingCache()
10156     * @see #destroyDrawingCache()
10157     */
10158    public void buildDrawingCache(boolean autoScale) {
10159        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10160                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10161            mCachingFailed = false;
10162
10163            if (ViewDebug.TRACE_HIERARCHY) {
10164                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10165            }
10166
10167            int width = mRight - mLeft;
10168            int height = mBottom - mTop;
10169
10170            final AttachInfo attachInfo = mAttachInfo;
10171            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10172
10173            if (autoScale && scalingRequired) {
10174                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10175                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10176            }
10177
10178            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10179            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10180            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10181
10182            if (width <= 0 || height <= 0 ||
10183                     // Projected bitmap size in bytes
10184                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10185                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10186                destroyDrawingCache();
10187                mCachingFailed = true;
10188                return;
10189            }
10190
10191            boolean clear = true;
10192            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10193
10194            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10195                Bitmap.Config quality;
10196                if (!opaque) {
10197                    // Never pick ARGB_4444 because it looks awful
10198                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10199                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10200                        case DRAWING_CACHE_QUALITY_AUTO:
10201                            quality = Bitmap.Config.ARGB_8888;
10202                            break;
10203                        case DRAWING_CACHE_QUALITY_LOW:
10204                            quality = Bitmap.Config.ARGB_8888;
10205                            break;
10206                        case DRAWING_CACHE_QUALITY_HIGH:
10207                            quality = Bitmap.Config.ARGB_8888;
10208                            break;
10209                        default:
10210                            quality = Bitmap.Config.ARGB_8888;
10211                            break;
10212                    }
10213                } else {
10214                    // Optimization for translucent windows
10215                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10216                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10217                }
10218
10219                // Try to cleanup memory
10220                if (bitmap != null) bitmap.recycle();
10221
10222                try {
10223                    bitmap = Bitmap.createBitmap(width, height, quality);
10224                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10225                    if (autoScale) {
10226                        mDrawingCache = bitmap;
10227                    } else {
10228                        mUnscaledDrawingCache = bitmap;
10229                    }
10230                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10231                } catch (OutOfMemoryError e) {
10232                    // If there is not enough memory to create the bitmap cache, just
10233                    // ignore the issue as bitmap caches are not required to draw the
10234                    // view hierarchy
10235                    if (autoScale) {
10236                        mDrawingCache = null;
10237                    } else {
10238                        mUnscaledDrawingCache = null;
10239                    }
10240                    mCachingFailed = true;
10241                    return;
10242                }
10243
10244                clear = drawingCacheBackgroundColor != 0;
10245            }
10246
10247            Canvas canvas;
10248            if (attachInfo != null) {
10249                canvas = attachInfo.mCanvas;
10250                if (canvas == null) {
10251                    canvas = new Canvas();
10252                }
10253                canvas.setBitmap(bitmap);
10254                // Temporarily clobber the cached Canvas in case one of our children
10255                // is also using a drawing cache. Without this, the children would
10256                // steal the canvas by attaching their own bitmap to it and bad, bad
10257                // thing would happen (invisible views, corrupted drawings, etc.)
10258                attachInfo.mCanvas = null;
10259            } else {
10260                // This case should hopefully never or seldom happen
10261                canvas = new Canvas(bitmap);
10262            }
10263
10264            if (clear) {
10265                bitmap.eraseColor(drawingCacheBackgroundColor);
10266            }
10267
10268            computeScroll();
10269            final int restoreCount = canvas.save();
10270
10271            if (autoScale && scalingRequired) {
10272                final float scale = attachInfo.mApplicationScale;
10273                canvas.scale(scale, scale);
10274            }
10275
10276            canvas.translate(-mScrollX, -mScrollY);
10277
10278            mPrivateFlags |= DRAWN;
10279            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10280                    mLayerType != LAYER_TYPE_NONE) {
10281                mPrivateFlags |= DRAWING_CACHE_VALID;
10282            }
10283
10284            // Fast path for layouts with no backgrounds
10285            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10286                if (ViewDebug.TRACE_HIERARCHY) {
10287                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10288                }
10289                mPrivateFlags &= ~DIRTY_MASK;
10290                dispatchDraw(canvas);
10291            } else {
10292                draw(canvas);
10293            }
10294
10295            canvas.restoreToCount(restoreCount);
10296            canvas.setBitmap(null);
10297
10298            if (attachInfo != null) {
10299                // Restore the cached Canvas for our siblings
10300                attachInfo.mCanvas = canvas;
10301            }
10302        }
10303    }
10304
10305    /**
10306     * Create a snapshot of the view into a bitmap.  We should probably make
10307     * some form of this public, but should think about the API.
10308     */
10309    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10310        int width = mRight - mLeft;
10311        int height = mBottom - mTop;
10312
10313        final AttachInfo attachInfo = mAttachInfo;
10314        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10315        width = (int) ((width * scale) + 0.5f);
10316        height = (int) ((height * scale) + 0.5f);
10317
10318        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10319        if (bitmap == null) {
10320            throw new OutOfMemoryError();
10321        }
10322
10323        Resources resources = getResources();
10324        if (resources != null) {
10325            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10326        }
10327
10328        Canvas canvas;
10329        if (attachInfo != null) {
10330            canvas = attachInfo.mCanvas;
10331            if (canvas == null) {
10332                canvas = new Canvas();
10333            }
10334            canvas.setBitmap(bitmap);
10335            // Temporarily clobber the cached Canvas in case one of our children
10336            // is also using a drawing cache. Without this, the children would
10337            // steal the canvas by attaching their own bitmap to it and bad, bad
10338            // things would happen (invisible views, corrupted drawings, etc.)
10339            attachInfo.mCanvas = null;
10340        } else {
10341            // This case should hopefully never or seldom happen
10342            canvas = new Canvas(bitmap);
10343        }
10344
10345        if ((backgroundColor & 0xff000000) != 0) {
10346            bitmap.eraseColor(backgroundColor);
10347        }
10348
10349        computeScroll();
10350        final int restoreCount = canvas.save();
10351        canvas.scale(scale, scale);
10352        canvas.translate(-mScrollX, -mScrollY);
10353
10354        // Temporarily remove the dirty mask
10355        int flags = mPrivateFlags;
10356        mPrivateFlags &= ~DIRTY_MASK;
10357
10358        // Fast path for layouts with no backgrounds
10359        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10360            dispatchDraw(canvas);
10361        } else {
10362            draw(canvas);
10363        }
10364
10365        mPrivateFlags = flags;
10366
10367        canvas.restoreToCount(restoreCount);
10368        canvas.setBitmap(null);
10369
10370        if (attachInfo != null) {
10371            // Restore the cached Canvas for our siblings
10372            attachInfo.mCanvas = canvas;
10373        }
10374
10375        return bitmap;
10376    }
10377
10378    /**
10379     * Indicates whether this View is currently in edit mode. A View is usually
10380     * in edit mode when displayed within a developer tool. For instance, if
10381     * this View is being drawn by a visual user interface builder, this method
10382     * should return true.
10383     *
10384     * Subclasses should check the return value of this method to provide
10385     * different behaviors if their normal behavior might interfere with the
10386     * host environment. For instance: the class spawns a thread in its
10387     * constructor, the drawing code relies on device-specific features, etc.
10388     *
10389     * This method is usually checked in the drawing code of custom widgets.
10390     *
10391     * @return True if this View is in edit mode, false otherwise.
10392     */
10393    public boolean isInEditMode() {
10394        return false;
10395    }
10396
10397    /**
10398     * If the View draws content inside its padding and enables fading edges,
10399     * it needs to support padding offsets. Padding offsets are added to the
10400     * fading edges to extend the length of the fade so that it covers pixels
10401     * drawn inside the padding.
10402     *
10403     * Subclasses of this class should override this method if they need
10404     * to draw content inside the padding.
10405     *
10406     * @return True if padding offset must be applied, false otherwise.
10407     *
10408     * @see #getLeftPaddingOffset()
10409     * @see #getRightPaddingOffset()
10410     * @see #getTopPaddingOffset()
10411     * @see #getBottomPaddingOffset()
10412     *
10413     * @since CURRENT
10414     */
10415    protected boolean isPaddingOffsetRequired() {
10416        return false;
10417    }
10418
10419    /**
10420     * Amount by which to extend the left fading region. Called only when
10421     * {@link #isPaddingOffsetRequired()} returns true.
10422     *
10423     * @return The left padding offset in pixels.
10424     *
10425     * @see #isPaddingOffsetRequired()
10426     *
10427     * @since CURRENT
10428     */
10429    protected int getLeftPaddingOffset() {
10430        return 0;
10431    }
10432
10433    /**
10434     * Amount by which to extend the right fading region. Called only when
10435     * {@link #isPaddingOffsetRequired()} returns true.
10436     *
10437     * @return The right padding offset in pixels.
10438     *
10439     * @see #isPaddingOffsetRequired()
10440     *
10441     * @since CURRENT
10442     */
10443    protected int getRightPaddingOffset() {
10444        return 0;
10445    }
10446
10447    /**
10448     * Amount by which to extend the top fading region. Called only when
10449     * {@link #isPaddingOffsetRequired()} returns true.
10450     *
10451     * @return The top padding offset in pixels.
10452     *
10453     * @see #isPaddingOffsetRequired()
10454     *
10455     * @since CURRENT
10456     */
10457    protected int getTopPaddingOffset() {
10458        return 0;
10459    }
10460
10461    /**
10462     * Amount by which to extend the bottom fading region. Called only when
10463     * {@link #isPaddingOffsetRequired()} returns true.
10464     *
10465     * @return The bottom padding offset in pixels.
10466     *
10467     * @see #isPaddingOffsetRequired()
10468     *
10469     * @since CURRENT
10470     */
10471    protected int getBottomPaddingOffset() {
10472        return 0;
10473    }
10474
10475    /**
10476     * @hide
10477     * @param offsetRequired
10478     */
10479    protected int getFadeTop(boolean offsetRequired) {
10480        int top = mPaddingTop;
10481        if (offsetRequired) top += getTopPaddingOffset();
10482        return top;
10483    }
10484
10485    /**
10486     * @hide
10487     * @param offsetRequired
10488     */
10489    protected int getFadeHeight(boolean offsetRequired) {
10490        int padding = mPaddingTop;
10491        if (offsetRequired) padding += getTopPaddingOffset();
10492        return mBottom - mTop - mPaddingBottom - padding;
10493    }
10494
10495    /**
10496     * <p>Indicates whether this view is attached to an hardware accelerated
10497     * window or not.</p>
10498     *
10499     * <p>Even if this method returns true, it does not mean that every call
10500     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10501     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10502     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10503     * window is hardware accelerated,
10504     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10505     * return false, and this method will return true.</p>
10506     *
10507     * @return True if the view is attached to a window and the window is
10508     *         hardware accelerated; false in any other case.
10509     */
10510    public boolean isHardwareAccelerated() {
10511        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10512    }
10513
10514    /**
10515     * Manually render this view (and all of its children) to the given Canvas.
10516     * The view must have already done a full layout before this function is
10517     * called.  When implementing a view, implement
10518     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10519     * If you do need to override this method, call the superclass version.
10520     *
10521     * @param canvas The Canvas to which the View is rendered.
10522     */
10523    public void draw(Canvas canvas) {
10524        if (ViewDebug.TRACE_HIERARCHY) {
10525            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10526        }
10527
10528        final int privateFlags = mPrivateFlags;
10529        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10530                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10531        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10532
10533        /*
10534         * Draw traversal performs several drawing steps which must be executed
10535         * in the appropriate order:
10536         *
10537         *      1. Draw the background
10538         *      2. If necessary, save the canvas' layers to prepare for fading
10539         *      3. Draw view's content
10540         *      4. Draw children
10541         *      5. If necessary, draw the fading edges and restore layers
10542         *      6. Draw decorations (scrollbars for instance)
10543         */
10544
10545        // Step 1, draw the background, if needed
10546        int saveCount;
10547
10548        if (!dirtyOpaque) {
10549            final Drawable background = mBGDrawable;
10550            if (background != null) {
10551                final int scrollX = mScrollX;
10552                final int scrollY = mScrollY;
10553
10554                if (mBackgroundSizeChanged) {
10555                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10556                    mBackgroundSizeChanged = false;
10557                }
10558
10559                if ((scrollX | scrollY) == 0) {
10560                    background.draw(canvas);
10561                } else {
10562                    canvas.translate(scrollX, scrollY);
10563                    background.draw(canvas);
10564                    canvas.translate(-scrollX, -scrollY);
10565                }
10566            }
10567        }
10568
10569        // skip step 2 & 5 if possible (common case)
10570        final int viewFlags = mViewFlags;
10571        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10572        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10573        if (!verticalEdges && !horizontalEdges) {
10574            // Step 3, draw the content
10575            if (!dirtyOpaque) onDraw(canvas);
10576
10577            // Step 4, draw the children
10578            dispatchDraw(canvas);
10579
10580            // Step 6, draw decorations (scrollbars)
10581            onDrawScrollBars(canvas);
10582
10583            // we're done...
10584            return;
10585        }
10586
10587        /*
10588         * Here we do the full fledged routine...
10589         * (this is an uncommon case where speed matters less,
10590         * this is why we repeat some of the tests that have been
10591         * done above)
10592         */
10593
10594        boolean drawTop = false;
10595        boolean drawBottom = false;
10596        boolean drawLeft = false;
10597        boolean drawRight = false;
10598
10599        float topFadeStrength = 0.0f;
10600        float bottomFadeStrength = 0.0f;
10601        float leftFadeStrength = 0.0f;
10602        float rightFadeStrength = 0.0f;
10603
10604        // Step 2, save the canvas' layers
10605        int paddingLeft = mPaddingLeft;
10606
10607        final boolean offsetRequired = isPaddingOffsetRequired();
10608        if (offsetRequired) {
10609            paddingLeft += getLeftPaddingOffset();
10610        }
10611
10612        int left = mScrollX + paddingLeft;
10613        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
10614        int top = mScrollY + getFadeTop(offsetRequired);
10615        int bottom = top + getFadeHeight(offsetRequired);
10616
10617        if (offsetRequired) {
10618            right += getRightPaddingOffset();
10619            bottom += getBottomPaddingOffset();
10620        }
10621
10622        final ScrollabilityCache scrollabilityCache = mScrollCache;
10623        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
10624        int length = (int) fadeHeight;
10625
10626        // clip the fade length if top and bottom fades overlap
10627        // overlapping fades produce odd-looking artifacts
10628        if (verticalEdges && (top + length > bottom - length)) {
10629            length = (bottom - top) / 2;
10630        }
10631
10632        // also clip horizontal fades if necessary
10633        if (horizontalEdges && (left + length > right - length)) {
10634            length = (right - left) / 2;
10635        }
10636
10637        if (verticalEdges) {
10638            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
10639            drawTop = topFadeStrength * fadeHeight > 1.0f;
10640            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
10641            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
10642        }
10643
10644        if (horizontalEdges) {
10645            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
10646            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
10647            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
10648            drawRight = rightFadeStrength * fadeHeight > 1.0f;
10649        }
10650
10651        saveCount = canvas.getSaveCount();
10652
10653        int solidColor = getSolidColor();
10654        if (solidColor == 0) {
10655            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
10656
10657            if (drawTop) {
10658                canvas.saveLayer(left, top, right, top + length, null, flags);
10659            }
10660
10661            if (drawBottom) {
10662                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
10663            }
10664
10665            if (drawLeft) {
10666                canvas.saveLayer(left, top, left + length, bottom, null, flags);
10667            }
10668
10669            if (drawRight) {
10670                canvas.saveLayer(right - length, top, right, bottom, null, flags);
10671            }
10672        } else {
10673            scrollabilityCache.setFadeColor(solidColor);
10674        }
10675
10676        // Step 3, draw the content
10677        if (!dirtyOpaque) onDraw(canvas);
10678
10679        // Step 4, draw the children
10680        dispatchDraw(canvas);
10681
10682        // Step 5, draw the fade effect and restore layers
10683        final Paint p = scrollabilityCache.paint;
10684        final Matrix matrix = scrollabilityCache.matrix;
10685        final Shader fade = scrollabilityCache.shader;
10686
10687        if (drawTop) {
10688            matrix.setScale(1, fadeHeight * topFadeStrength);
10689            matrix.postTranslate(left, top);
10690            fade.setLocalMatrix(matrix);
10691            canvas.drawRect(left, top, right, top + length, p);
10692        }
10693
10694        if (drawBottom) {
10695            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10696            matrix.postRotate(180);
10697            matrix.postTranslate(left, bottom);
10698            fade.setLocalMatrix(matrix);
10699            canvas.drawRect(left, bottom - length, right, bottom, p);
10700        }
10701
10702        if (drawLeft) {
10703            matrix.setScale(1, fadeHeight * leftFadeStrength);
10704            matrix.postRotate(-90);
10705            matrix.postTranslate(left, top);
10706            fade.setLocalMatrix(matrix);
10707            canvas.drawRect(left, top, left + length, bottom, p);
10708        }
10709
10710        if (drawRight) {
10711            matrix.setScale(1, fadeHeight * rightFadeStrength);
10712            matrix.postRotate(90);
10713            matrix.postTranslate(right, top);
10714            fade.setLocalMatrix(matrix);
10715            canvas.drawRect(right - length, top, right, bottom, p);
10716        }
10717
10718        canvas.restoreToCount(saveCount);
10719
10720        // Step 6, draw decorations (scrollbars)
10721        onDrawScrollBars(canvas);
10722    }
10723
10724    /**
10725     * Override this if your view is known to always be drawn on top of a solid color background,
10726     * and needs to draw fading edges. Returning a non-zero color enables the view system to
10727     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
10728     * should be set to 0xFF.
10729     *
10730     * @see #setVerticalFadingEdgeEnabled(boolean)
10731     * @see #setHorizontalFadingEdgeEnabled(boolean)
10732     *
10733     * @return The known solid color background for this view, or 0 if the color may vary
10734     */
10735    @ViewDebug.ExportedProperty(category = "drawing")
10736    public int getSolidColor() {
10737        return 0;
10738    }
10739
10740    /**
10741     * Build a human readable string representation of the specified view flags.
10742     *
10743     * @param flags the view flags to convert to a string
10744     * @return a String representing the supplied flags
10745     */
10746    private static String printFlags(int flags) {
10747        String output = "";
10748        int numFlags = 0;
10749        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
10750            output += "TAKES_FOCUS";
10751            numFlags++;
10752        }
10753
10754        switch (flags & VISIBILITY_MASK) {
10755        case INVISIBLE:
10756            if (numFlags > 0) {
10757                output += " ";
10758            }
10759            output += "INVISIBLE";
10760            // USELESS HERE numFlags++;
10761            break;
10762        case GONE:
10763            if (numFlags > 0) {
10764                output += " ";
10765            }
10766            output += "GONE";
10767            // USELESS HERE numFlags++;
10768            break;
10769        default:
10770            break;
10771        }
10772        return output;
10773    }
10774
10775    /**
10776     * Build a human readable string representation of the specified private
10777     * view flags.
10778     *
10779     * @param privateFlags the private view flags to convert to a string
10780     * @return a String representing the supplied flags
10781     */
10782    private static String printPrivateFlags(int privateFlags) {
10783        String output = "";
10784        int numFlags = 0;
10785
10786        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
10787            output += "WANTS_FOCUS";
10788            numFlags++;
10789        }
10790
10791        if ((privateFlags & FOCUSED) == FOCUSED) {
10792            if (numFlags > 0) {
10793                output += " ";
10794            }
10795            output += "FOCUSED";
10796            numFlags++;
10797        }
10798
10799        if ((privateFlags & SELECTED) == SELECTED) {
10800            if (numFlags > 0) {
10801                output += " ";
10802            }
10803            output += "SELECTED";
10804            numFlags++;
10805        }
10806
10807        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
10808            if (numFlags > 0) {
10809                output += " ";
10810            }
10811            output += "IS_ROOT_NAMESPACE";
10812            numFlags++;
10813        }
10814
10815        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
10816            if (numFlags > 0) {
10817                output += " ";
10818            }
10819            output += "HAS_BOUNDS";
10820            numFlags++;
10821        }
10822
10823        if ((privateFlags & DRAWN) == DRAWN) {
10824            if (numFlags > 0) {
10825                output += " ";
10826            }
10827            output += "DRAWN";
10828            // USELESS HERE numFlags++;
10829        }
10830        return output;
10831    }
10832
10833    /**
10834     * <p>Indicates whether or not this view's layout will be requested during
10835     * the next hierarchy layout pass.</p>
10836     *
10837     * @return true if the layout will be forced during next layout pass
10838     */
10839    public boolean isLayoutRequested() {
10840        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
10841    }
10842
10843    /**
10844     * Assign a size and position to a view and all of its
10845     * descendants
10846     *
10847     * <p>This is the second phase of the layout mechanism.
10848     * (The first is measuring). In this phase, each parent calls
10849     * layout on all of its children to position them.
10850     * This is typically done using the child measurements
10851     * that were stored in the measure pass().</p>
10852     *
10853     * <p>Derived classes should not override this method.
10854     * Derived classes with children should override
10855     * onLayout. In that method, they should
10856     * call layout on each of their children.</p>
10857     *
10858     * @param l Left position, relative to parent
10859     * @param t Top position, relative to parent
10860     * @param r Right position, relative to parent
10861     * @param b Bottom position, relative to parent
10862     */
10863    @SuppressWarnings({"unchecked"})
10864    public void layout(int l, int t, int r, int b) {
10865        int oldL = mLeft;
10866        int oldT = mTop;
10867        int oldB = mBottom;
10868        int oldR = mRight;
10869        boolean changed = setFrame(l, t, r, b);
10870        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
10871            if (ViewDebug.TRACE_HIERARCHY) {
10872                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
10873            }
10874
10875            onLayout(changed, l, t, r, b);
10876            mPrivateFlags &= ~LAYOUT_REQUIRED;
10877
10878            if (mOnLayoutChangeListeners != null) {
10879                ArrayList<OnLayoutChangeListener> listenersCopy =
10880                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
10881                int numListeners = listenersCopy.size();
10882                for (int i = 0; i < numListeners; ++i) {
10883                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
10884                }
10885            }
10886        }
10887        mPrivateFlags &= ~FORCE_LAYOUT;
10888    }
10889
10890    /**
10891     * Called from layout when this view should
10892     * assign a size and position to each of its children.
10893     *
10894     * Derived classes with children should override
10895     * this method and call layout on each of
10896     * their children.
10897     * @param changed This is a new size or position for this view
10898     * @param left Left position, relative to parent
10899     * @param top Top position, relative to parent
10900     * @param right Right position, relative to parent
10901     * @param bottom Bottom position, relative to parent
10902     */
10903    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
10904    }
10905
10906    /**
10907     * Assign a size and position to this view.
10908     *
10909     * This is called from layout.
10910     *
10911     * @param left Left position, relative to parent
10912     * @param top Top position, relative to parent
10913     * @param right Right position, relative to parent
10914     * @param bottom Bottom position, relative to parent
10915     * @return true if the new size and position are different than the
10916     *         previous ones
10917     * {@hide}
10918     */
10919    protected boolean setFrame(int left, int top, int right, int bottom) {
10920        boolean changed = false;
10921
10922        if (DBG) {
10923            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
10924                    + right + "," + bottom + ")");
10925        }
10926
10927        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
10928            changed = true;
10929
10930            // Remember our drawn bit
10931            int drawn = mPrivateFlags & DRAWN;
10932
10933            int oldWidth = mRight - mLeft;
10934            int oldHeight = mBottom - mTop;
10935            int newWidth = right - left;
10936            int newHeight = bottom - top;
10937            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
10938
10939            // Invalidate our old position
10940            invalidate(sizeChanged);
10941
10942            mLeft = left;
10943            mTop = top;
10944            mRight = right;
10945            mBottom = bottom;
10946
10947            mPrivateFlags |= HAS_BOUNDS;
10948
10949
10950            if (sizeChanged) {
10951                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
10952                    // A change in dimension means an auto-centered pivot point changes, too
10953                    mMatrixDirty = true;
10954                }
10955                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
10956            }
10957
10958            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
10959                // If we are visible, force the DRAWN bit to on so that
10960                // this invalidate will go through (at least to our parent).
10961                // This is because someone may have invalidated this view
10962                // before this call to setFrame came in, thereby clearing
10963                // the DRAWN bit.
10964                mPrivateFlags |= DRAWN;
10965                invalidate(sizeChanged);
10966                // parent display list may need to be recreated based on a change in the bounds
10967                // of any child
10968                invalidateParentCaches();
10969            }
10970
10971            // Reset drawn bit to original value (invalidate turns it off)
10972            mPrivateFlags |= drawn;
10973
10974            mBackgroundSizeChanged = true;
10975        }
10976        return changed;
10977    }
10978
10979    /**
10980     * Finalize inflating a view from XML.  This is called as the last phase
10981     * of inflation, after all child views have been added.
10982     *
10983     * <p>Even if the subclass overrides onFinishInflate, they should always be
10984     * sure to call the super method, so that we get called.
10985     */
10986    protected void onFinishInflate() {
10987    }
10988
10989    /**
10990     * Returns the resources associated with this view.
10991     *
10992     * @return Resources object.
10993     */
10994    public Resources getResources() {
10995        return mResources;
10996    }
10997
10998    /**
10999     * Invalidates the specified Drawable.
11000     *
11001     * @param drawable the drawable to invalidate
11002     */
11003    public void invalidateDrawable(Drawable drawable) {
11004        if (verifyDrawable(drawable)) {
11005            final Rect dirty = drawable.getBounds();
11006            final int scrollX = mScrollX;
11007            final int scrollY = mScrollY;
11008
11009            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11010                    dirty.right + scrollX, dirty.bottom + scrollY);
11011        }
11012    }
11013
11014    /**
11015     * Schedules an action on a drawable to occur at a specified time.
11016     *
11017     * @param who the recipient of the action
11018     * @param what the action to run on the drawable
11019     * @param when the time at which the action must occur. Uses the
11020     *        {@link SystemClock#uptimeMillis} timebase.
11021     */
11022    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11023        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11024            mAttachInfo.mHandler.postAtTime(what, who, when);
11025        }
11026    }
11027
11028    /**
11029     * Cancels a scheduled action on a drawable.
11030     *
11031     * @param who the recipient of the action
11032     * @param what the action to cancel
11033     */
11034    public void unscheduleDrawable(Drawable who, Runnable what) {
11035        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11036            mAttachInfo.mHandler.removeCallbacks(what, who);
11037        }
11038    }
11039
11040    /**
11041     * Unschedule any events associated with the given Drawable.  This can be
11042     * used when selecting a new Drawable into a view, so that the previous
11043     * one is completely unscheduled.
11044     *
11045     * @param who The Drawable to unschedule.
11046     *
11047     * @see #drawableStateChanged
11048     */
11049    public void unscheduleDrawable(Drawable who) {
11050        if (mAttachInfo != null) {
11051            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11052        }
11053    }
11054
11055    /**
11056    * Return the layout direction of a given Drawable.
11057    *
11058    * @param who the Drawable to query
11059    *
11060    * @hide
11061    */
11062    public int getResolvedLayoutDirection(Drawable who) {
11063        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11064    }
11065
11066    /**
11067     * If your view subclass is displaying its own Drawable objects, it should
11068     * override this function and return true for any Drawable it is
11069     * displaying.  This allows animations for those drawables to be
11070     * scheduled.
11071     *
11072     * <p>Be sure to call through to the super class when overriding this
11073     * function.
11074     *
11075     * @param who The Drawable to verify.  Return true if it is one you are
11076     *            displaying, else return the result of calling through to the
11077     *            super class.
11078     *
11079     * @return boolean If true than the Drawable is being displayed in the
11080     *         view; else false and it is not allowed to animate.
11081     *
11082     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11083     * @see #drawableStateChanged()
11084     */
11085    protected boolean verifyDrawable(Drawable who) {
11086        return who == mBGDrawable;
11087    }
11088
11089    /**
11090     * This function is called whenever the state of the view changes in such
11091     * a way that it impacts the state of drawables being shown.
11092     *
11093     * <p>Be sure to call through to the superclass when overriding this
11094     * function.
11095     *
11096     * @see Drawable#setState(int[])
11097     */
11098    protected void drawableStateChanged() {
11099        Drawable d = mBGDrawable;
11100        if (d != null && d.isStateful()) {
11101            d.setState(getDrawableState());
11102        }
11103    }
11104
11105    /**
11106     * Call this to force a view to update its drawable state. This will cause
11107     * drawableStateChanged to be called on this view. Views that are interested
11108     * in the new state should call getDrawableState.
11109     *
11110     * @see #drawableStateChanged
11111     * @see #getDrawableState
11112     */
11113    public void refreshDrawableState() {
11114        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11115        drawableStateChanged();
11116
11117        ViewParent parent = mParent;
11118        if (parent != null) {
11119            parent.childDrawableStateChanged(this);
11120        }
11121    }
11122
11123    /**
11124     * Return an array of resource IDs of the drawable states representing the
11125     * current state of the view.
11126     *
11127     * @return The current drawable state
11128     *
11129     * @see Drawable#setState(int[])
11130     * @see #drawableStateChanged()
11131     * @see #onCreateDrawableState(int)
11132     */
11133    public final int[] getDrawableState() {
11134        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11135            return mDrawableState;
11136        } else {
11137            mDrawableState = onCreateDrawableState(0);
11138            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11139            return mDrawableState;
11140        }
11141    }
11142
11143    /**
11144     * Generate the new {@link android.graphics.drawable.Drawable} state for
11145     * this view. This is called by the view
11146     * system when the cached Drawable state is determined to be invalid.  To
11147     * retrieve the current state, you should use {@link #getDrawableState}.
11148     *
11149     * @param extraSpace if non-zero, this is the number of extra entries you
11150     * would like in the returned array in which you can place your own
11151     * states.
11152     *
11153     * @return Returns an array holding the current {@link Drawable} state of
11154     * the view.
11155     *
11156     * @see #mergeDrawableStates(int[], int[])
11157     */
11158    protected int[] onCreateDrawableState(int extraSpace) {
11159        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11160                mParent instanceof View) {
11161            return ((View) mParent).onCreateDrawableState(extraSpace);
11162        }
11163
11164        int[] drawableState;
11165
11166        int privateFlags = mPrivateFlags;
11167
11168        int viewStateIndex = 0;
11169        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11170        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11171        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11172        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11173        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11174        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11175        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11176                HardwareRenderer.isAvailable()) {
11177            // This is set if HW acceleration is requested, even if the current
11178            // process doesn't allow it.  This is just to allow app preview
11179            // windows to better match their app.
11180            viewStateIndex |= VIEW_STATE_ACCELERATED;
11181        }
11182        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11183
11184        final int privateFlags2 = mPrivateFlags2;
11185        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11186        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11187
11188        drawableState = VIEW_STATE_SETS[viewStateIndex];
11189
11190        //noinspection ConstantIfStatement
11191        if (false) {
11192            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11193            Log.i("View", toString()
11194                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11195                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11196                    + " fo=" + hasFocus()
11197                    + " sl=" + ((privateFlags & SELECTED) != 0)
11198                    + " wf=" + hasWindowFocus()
11199                    + ": " + Arrays.toString(drawableState));
11200        }
11201
11202        if (extraSpace == 0) {
11203            return drawableState;
11204        }
11205
11206        final int[] fullState;
11207        if (drawableState != null) {
11208            fullState = new int[drawableState.length + extraSpace];
11209            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11210        } else {
11211            fullState = new int[extraSpace];
11212        }
11213
11214        return fullState;
11215    }
11216
11217    /**
11218     * Merge your own state values in <var>additionalState</var> into the base
11219     * state values <var>baseState</var> that were returned by
11220     * {@link #onCreateDrawableState(int)}.
11221     *
11222     * @param baseState The base state values returned by
11223     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11224     * own additional state values.
11225     *
11226     * @param additionalState The additional state values you would like
11227     * added to <var>baseState</var>; this array is not modified.
11228     *
11229     * @return As a convenience, the <var>baseState</var> array you originally
11230     * passed into the function is returned.
11231     *
11232     * @see #onCreateDrawableState(int)
11233     */
11234    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11235        final int N = baseState.length;
11236        int i = N - 1;
11237        while (i >= 0 && baseState[i] == 0) {
11238            i--;
11239        }
11240        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11241        return baseState;
11242    }
11243
11244    /**
11245     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11246     * on all Drawable objects associated with this view.
11247     */
11248    public void jumpDrawablesToCurrentState() {
11249        if (mBGDrawable != null) {
11250            mBGDrawable.jumpToCurrentState();
11251        }
11252    }
11253
11254    /**
11255     * Sets the background color for this view.
11256     * @param color the color of the background
11257     */
11258    @RemotableViewMethod
11259    public void setBackgroundColor(int color) {
11260        if (mBGDrawable instanceof ColorDrawable) {
11261            ((ColorDrawable) mBGDrawable).setColor(color);
11262        } else {
11263            setBackgroundDrawable(new ColorDrawable(color));
11264        }
11265    }
11266
11267    /**
11268     * Set the background to a given resource. The resource should refer to
11269     * a Drawable object or 0 to remove the background.
11270     * @param resid The identifier of the resource.
11271     * @attr ref android.R.styleable#View_background
11272     */
11273    @RemotableViewMethod
11274    public void setBackgroundResource(int resid) {
11275        if (resid != 0 && resid == mBackgroundResource) {
11276            return;
11277        }
11278
11279        Drawable d= null;
11280        if (resid != 0) {
11281            d = mResources.getDrawable(resid);
11282        }
11283        setBackgroundDrawable(d);
11284
11285        mBackgroundResource = resid;
11286    }
11287
11288    /**
11289     * Set the background to a given Drawable, or remove the background. If the
11290     * background has padding, this View's padding is set to the background's
11291     * padding. However, when a background is removed, this View's padding isn't
11292     * touched. If setting the padding is desired, please use
11293     * {@link #setPadding(int, int, int, int)}.
11294     *
11295     * @param d The Drawable to use as the background, or null to remove the
11296     *        background
11297     */
11298    public void setBackgroundDrawable(Drawable d) {
11299        if (d == mBGDrawable) {
11300            return;
11301        }
11302
11303        boolean requestLayout = false;
11304
11305        mBackgroundResource = 0;
11306
11307        /*
11308         * Regardless of whether we're setting a new background or not, we want
11309         * to clear the previous drawable.
11310         */
11311        if (mBGDrawable != null) {
11312            mBGDrawable.setCallback(null);
11313            unscheduleDrawable(mBGDrawable);
11314        }
11315
11316        if (d != null) {
11317            Rect padding = sThreadLocal.get();
11318            if (padding == null) {
11319                padding = new Rect();
11320                sThreadLocal.set(padding);
11321            }
11322            if (d.getPadding(padding)) {
11323                switch (d.getResolvedLayoutDirectionSelf()) {
11324                    case LAYOUT_DIRECTION_RTL:
11325                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11326                        break;
11327                    case LAYOUT_DIRECTION_LTR:
11328                    default:
11329                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11330                }
11331            }
11332
11333            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11334            // if it has a different minimum size, we should layout again
11335            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11336                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11337                requestLayout = true;
11338            }
11339
11340            d.setCallback(this);
11341            if (d.isStateful()) {
11342                d.setState(getDrawableState());
11343            }
11344            d.setVisible(getVisibility() == VISIBLE, false);
11345            mBGDrawable = d;
11346
11347            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11348                mPrivateFlags &= ~SKIP_DRAW;
11349                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11350                requestLayout = true;
11351            }
11352        } else {
11353            /* Remove the background */
11354            mBGDrawable = null;
11355
11356            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11357                /*
11358                 * This view ONLY drew the background before and we're removing
11359                 * the background, so now it won't draw anything
11360                 * (hence we SKIP_DRAW)
11361                 */
11362                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11363                mPrivateFlags |= SKIP_DRAW;
11364            }
11365
11366            /*
11367             * When the background is set, we try to apply its padding to this
11368             * View. When the background is removed, we don't touch this View's
11369             * padding. This is noted in the Javadocs. Hence, we don't need to
11370             * requestLayout(), the invalidate() below is sufficient.
11371             */
11372
11373            // The old background's minimum size could have affected this
11374            // View's layout, so let's requestLayout
11375            requestLayout = true;
11376        }
11377
11378        computeOpaqueFlags();
11379
11380        if (requestLayout) {
11381            requestLayout();
11382        }
11383
11384        mBackgroundSizeChanged = true;
11385        invalidate(true);
11386    }
11387
11388    /**
11389     * Gets the background drawable
11390     * @return The drawable used as the background for this view, if any.
11391     */
11392    public Drawable getBackground() {
11393        return mBGDrawable;
11394    }
11395
11396    /**
11397     * Sets the padding. The view may add on the space required to display
11398     * the scrollbars, depending on the style and visibility of the scrollbars.
11399     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11400     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11401     * from the values set in this call.
11402     *
11403     * @attr ref android.R.styleable#View_padding
11404     * @attr ref android.R.styleable#View_paddingBottom
11405     * @attr ref android.R.styleable#View_paddingLeft
11406     * @attr ref android.R.styleable#View_paddingRight
11407     * @attr ref android.R.styleable#View_paddingTop
11408     * @param left the left padding in pixels
11409     * @param top the top padding in pixels
11410     * @param right the right padding in pixels
11411     * @param bottom the bottom padding in pixels
11412     */
11413    public void setPadding(int left, int top, int right, int bottom) {
11414        boolean changed = false;
11415
11416        mUserPaddingRelative = false;
11417
11418        mUserPaddingLeft = left;
11419        mUserPaddingRight = right;
11420        mUserPaddingBottom = bottom;
11421
11422        final int viewFlags = mViewFlags;
11423
11424        // Common case is there are no scroll bars.
11425        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11426            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11427                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11428                        ? 0 : getVerticalScrollbarWidth();
11429                switch (mVerticalScrollbarPosition) {
11430                    case SCROLLBAR_POSITION_DEFAULT:
11431                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11432                            left += offset;
11433                        } else {
11434                            right += offset;
11435                        }
11436                        break;
11437                    case SCROLLBAR_POSITION_RIGHT:
11438                        right += offset;
11439                        break;
11440                    case SCROLLBAR_POSITION_LEFT:
11441                        left += offset;
11442                        break;
11443                }
11444            }
11445            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11446                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11447                        ? 0 : getHorizontalScrollbarHeight();
11448            }
11449        }
11450
11451        if (mPaddingLeft != left) {
11452            changed = true;
11453            mPaddingLeft = left;
11454        }
11455        if (mPaddingTop != top) {
11456            changed = true;
11457            mPaddingTop = top;
11458        }
11459        if (mPaddingRight != right) {
11460            changed = true;
11461            mPaddingRight = right;
11462        }
11463        if (mPaddingBottom != bottom) {
11464            changed = true;
11465            mPaddingBottom = bottom;
11466        }
11467
11468        if (changed) {
11469            requestLayout();
11470        }
11471    }
11472
11473    /**
11474     * Sets the relative padding. The view may add on the space required to display
11475     * the scrollbars, depending on the style and visibility of the scrollbars.
11476     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11477     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11478     * from the values set in this call.
11479     *
11480     * @attr ref android.R.styleable#View_padding
11481     * @attr ref android.R.styleable#View_paddingBottom
11482     * @attr ref android.R.styleable#View_paddingStart
11483     * @attr ref android.R.styleable#View_paddingEnd
11484     * @attr ref android.R.styleable#View_paddingTop
11485     * @param start the start padding in pixels
11486     * @param top the top padding in pixels
11487     * @param end the end padding in pixels
11488     * @param bottom the bottom padding in pixels
11489     *
11490     * @hide
11491     */
11492    public void setPaddingRelative(int start, int top, int end, int bottom) {
11493        mUserPaddingRelative = true;
11494
11495        mUserPaddingStart = start;
11496        mUserPaddingEnd = end;
11497
11498        switch(getResolvedLayoutDirection()) {
11499            case LAYOUT_DIRECTION_RTL:
11500                setPadding(end, top, start, bottom);
11501                break;
11502            case LAYOUT_DIRECTION_LTR:
11503            default:
11504                setPadding(start, top, end, bottom);
11505        }
11506    }
11507
11508    /**
11509     * Returns the top padding of this view.
11510     *
11511     * @return the top padding in pixels
11512     */
11513    public int getPaddingTop() {
11514        return mPaddingTop;
11515    }
11516
11517    /**
11518     * Returns the bottom padding of this view. If there are inset and enabled
11519     * scrollbars, this value may include the space required to display the
11520     * scrollbars as well.
11521     *
11522     * @return the bottom padding in pixels
11523     */
11524    public int getPaddingBottom() {
11525        return mPaddingBottom;
11526    }
11527
11528    /**
11529     * Returns the left padding of this view. If there are inset and enabled
11530     * scrollbars, this value may include the space required to display the
11531     * scrollbars as well.
11532     *
11533     * @return the left padding in pixels
11534     */
11535    public int getPaddingLeft() {
11536        return mPaddingLeft;
11537    }
11538
11539    /**
11540     * Returns the start padding of this view. If there are inset and enabled
11541     * scrollbars, this value may include the space required to display the
11542     * scrollbars as well.
11543     *
11544     * @return the start padding in pixels
11545     *
11546     * @hide
11547     */
11548    public int getPaddingStart() {
11549        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11550                mPaddingRight : mPaddingLeft;
11551    }
11552
11553    /**
11554     * Returns the right padding of this view. If there are inset and enabled
11555     * scrollbars, this value may include the space required to display the
11556     * scrollbars as well.
11557     *
11558     * @return the right padding in pixels
11559     */
11560    public int getPaddingRight() {
11561        return mPaddingRight;
11562    }
11563
11564    /**
11565     * Returns the end padding of this view. If there are inset and enabled
11566     * scrollbars, this value may include the space required to display the
11567     * scrollbars as well.
11568     *
11569     * @return the end padding in pixels
11570     *
11571     * @hide
11572     */
11573    public int getPaddingEnd() {
11574        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11575                mPaddingLeft : mPaddingRight;
11576    }
11577
11578    /**
11579     * Return if the padding as been set thru relative values
11580     * {@link #setPaddingRelative(int, int, int, int)} or thru
11581     * @attr ref android.R.styleable#View_paddingStart or
11582     * @attr ref android.R.styleable#View_paddingEnd
11583     *
11584     * @return true if the padding is relative or false if it is not.
11585     *
11586     * @hide
11587     */
11588    public boolean isPaddingRelative() {
11589        return mUserPaddingRelative;
11590    }
11591
11592    /**
11593     * Changes the selection state of this view. A view can be selected or not.
11594     * Note that selection is not the same as focus. Views are typically
11595     * selected in the context of an AdapterView like ListView or GridView;
11596     * the selected view is the view that is highlighted.
11597     *
11598     * @param selected true if the view must be selected, false otherwise
11599     */
11600    public void setSelected(boolean selected) {
11601        if (((mPrivateFlags & SELECTED) != 0) != selected) {
11602            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
11603            if (!selected) resetPressedState();
11604            invalidate(true);
11605            refreshDrawableState();
11606            dispatchSetSelected(selected);
11607        }
11608    }
11609
11610    /**
11611     * Dispatch setSelected to all of this View's children.
11612     *
11613     * @see #setSelected(boolean)
11614     *
11615     * @param selected The new selected state
11616     */
11617    protected void dispatchSetSelected(boolean selected) {
11618    }
11619
11620    /**
11621     * Indicates the selection state of this view.
11622     *
11623     * @return true if the view is selected, false otherwise
11624     */
11625    @ViewDebug.ExportedProperty
11626    public boolean isSelected() {
11627        return (mPrivateFlags & SELECTED) != 0;
11628    }
11629
11630    /**
11631     * Changes the activated state of this view. A view can be activated or not.
11632     * Note that activation is not the same as selection.  Selection is
11633     * a transient property, representing the view (hierarchy) the user is
11634     * currently interacting with.  Activation is a longer-term state that the
11635     * user can move views in and out of.  For example, in a list view with
11636     * single or multiple selection enabled, the views in the current selection
11637     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
11638     * here.)  The activated state is propagated down to children of the view it
11639     * is set on.
11640     *
11641     * @param activated true if the view must be activated, false otherwise
11642     */
11643    public void setActivated(boolean activated) {
11644        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
11645            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
11646            invalidate(true);
11647            refreshDrawableState();
11648            dispatchSetActivated(activated);
11649        }
11650    }
11651
11652    /**
11653     * Dispatch setActivated to all of this View's children.
11654     *
11655     * @see #setActivated(boolean)
11656     *
11657     * @param activated The new activated state
11658     */
11659    protected void dispatchSetActivated(boolean activated) {
11660    }
11661
11662    /**
11663     * Indicates the activation state of this view.
11664     *
11665     * @return true if the view is activated, false otherwise
11666     */
11667    @ViewDebug.ExportedProperty
11668    public boolean isActivated() {
11669        return (mPrivateFlags & ACTIVATED) != 0;
11670    }
11671
11672    /**
11673     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
11674     * observer can be used to get notifications when global events, like
11675     * layout, happen.
11676     *
11677     * The returned ViewTreeObserver observer is not guaranteed to remain
11678     * valid for the lifetime of this View. If the caller of this method keeps
11679     * a long-lived reference to ViewTreeObserver, it should always check for
11680     * the return value of {@link ViewTreeObserver#isAlive()}.
11681     *
11682     * @return The ViewTreeObserver for this view's hierarchy.
11683     */
11684    public ViewTreeObserver getViewTreeObserver() {
11685        if (mAttachInfo != null) {
11686            return mAttachInfo.mTreeObserver;
11687        }
11688        if (mFloatingTreeObserver == null) {
11689            mFloatingTreeObserver = new ViewTreeObserver();
11690        }
11691        return mFloatingTreeObserver;
11692    }
11693
11694    /**
11695     * <p>Finds the topmost view in the current view hierarchy.</p>
11696     *
11697     * @return the topmost view containing this view
11698     */
11699    public View getRootView() {
11700        if (mAttachInfo != null) {
11701            final View v = mAttachInfo.mRootView;
11702            if (v != null) {
11703                return v;
11704            }
11705        }
11706
11707        View parent = this;
11708
11709        while (parent.mParent != null && parent.mParent instanceof View) {
11710            parent = (View) parent.mParent;
11711        }
11712
11713        return parent;
11714    }
11715
11716    /**
11717     * <p>Computes the coordinates of this view on the screen. The argument
11718     * must be an array of two integers. After the method returns, the array
11719     * contains the x and y location in that order.</p>
11720     *
11721     * @param location an array of two integers in which to hold the coordinates
11722     */
11723    public void getLocationOnScreen(int[] location) {
11724        getLocationInWindow(location);
11725
11726        final AttachInfo info = mAttachInfo;
11727        if (info != null) {
11728            location[0] += info.mWindowLeft;
11729            location[1] += info.mWindowTop;
11730        }
11731    }
11732
11733    /**
11734     * <p>Computes the coordinates of this view in its window. The argument
11735     * must be an array of two integers. After the method returns, the array
11736     * contains the x and y location in that order.</p>
11737     *
11738     * @param location an array of two integers in which to hold the coordinates
11739     */
11740    public void getLocationInWindow(int[] location) {
11741        if (location == null || location.length < 2) {
11742            throw new IllegalArgumentException("location must be an array of "
11743                    + "two integers");
11744        }
11745
11746        location[0] = mLeft + (int) (mTranslationX + 0.5f);
11747        location[1] = mTop + (int) (mTranslationY + 0.5f);
11748
11749        ViewParent viewParent = mParent;
11750        while (viewParent instanceof View) {
11751            final View view = (View)viewParent;
11752            location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
11753            location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
11754            viewParent = view.mParent;
11755        }
11756
11757        if (viewParent instanceof ViewRootImpl) {
11758            // *cough*
11759            final ViewRootImpl vr = (ViewRootImpl)viewParent;
11760            location[1] -= vr.mCurScrollY;
11761        }
11762    }
11763
11764    /**
11765     * {@hide}
11766     * @param id the id of the view to be found
11767     * @return the view of the specified id, null if cannot be found
11768     */
11769    protected View findViewTraversal(int id) {
11770        if (id == mID) {
11771            return this;
11772        }
11773        return null;
11774    }
11775
11776    /**
11777     * {@hide}
11778     * @param tag the tag of the view to be found
11779     * @return the view of specified tag, null if cannot be found
11780     */
11781    protected View findViewWithTagTraversal(Object tag) {
11782        if (tag != null && tag.equals(mTag)) {
11783            return this;
11784        }
11785        return null;
11786    }
11787
11788    /**
11789     * {@hide}
11790     * @param predicate The predicate to evaluate.
11791     * @param childToSkip If not null, ignores this child during the recursive traversal.
11792     * @return The first view that matches the predicate or null.
11793     */
11794    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
11795        if (predicate.apply(this)) {
11796            return this;
11797        }
11798        return null;
11799    }
11800
11801    /**
11802     * Look for a child view with the given id.  If this view has the given
11803     * id, return this view.
11804     *
11805     * @param id The id to search for.
11806     * @return The view that has the given id in the hierarchy or null
11807     */
11808    public final View findViewById(int id) {
11809        if (id < 0) {
11810            return null;
11811        }
11812        return findViewTraversal(id);
11813    }
11814
11815    /**
11816     * Look for a child view with the given tag.  If this view has the given
11817     * tag, return this view.
11818     *
11819     * @param tag The tag to search for, using "tag.equals(getTag())".
11820     * @return The View that has the given tag in the hierarchy or null
11821     */
11822    public final View findViewWithTag(Object tag) {
11823        if (tag == null) {
11824            return null;
11825        }
11826        return findViewWithTagTraversal(tag);
11827    }
11828
11829    /**
11830     * {@hide}
11831     * Look for a child view that matches the specified predicate.
11832     * If this view matches the predicate, return this view.
11833     *
11834     * @param predicate The predicate to evaluate.
11835     * @return The first view that matches the predicate or null.
11836     */
11837    public final View findViewByPredicate(Predicate<View> predicate) {
11838        return findViewByPredicateTraversal(predicate, null);
11839    }
11840
11841    /**
11842     * {@hide}
11843     * Look for a child view that matches the specified predicate,
11844     * starting with the specified view and its descendents and then
11845     * recusively searching the ancestors and siblings of that view
11846     * until this view is reached.
11847     *
11848     * This method is useful in cases where the predicate does not match
11849     * a single unique view (perhaps multiple views use the same id)
11850     * and we are trying to find the view that is "closest" in scope to the
11851     * starting view.
11852     *
11853     * @param start The view to start from.
11854     * @param predicate The predicate to evaluate.
11855     * @return The first view that matches the predicate or null.
11856     */
11857    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
11858        View childToSkip = null;
11859        for (;;) {
11860            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
11861            if (view != null || start == this) {
11862                return view;
11863            }
11864
11865            ViewParent parent = start.getParent();
11866            if (parent == null || !(parent instanceof View)) {
11867                return null;
11868            }
11869
11870            childToSkip = start;
11871            start = (View) parent;
11872        }
11873    }
11874
11875    /**
11876     * Sets the identifier for this view. The identifier does not have to be
11877     * unique in this view's hierarchy. The identifier should be a positive
11878     * number.
11879     *
11880     * @see #NO_ID
11881     * @see #getId()
11882     * @see #findViewById(int)
11883     *
11884     * @param id a number used to identify the view
11885     *
11886     * @attr ref android.R.styleable#View_id
11887     */
11888    public void setId(int id) {
11889        mID = id;
11890    }
11891
11892    /**
11893     * {@hide}
11894     *
11895     * @param isRoot true if the view belongs to the root namespace, false
11896     *        otherwise
11897     */
11898    public void setIsRootNamespace(boolean isRoot) {
11899        if (isRoot) {
11900            mPrivateFlags |= IS_ROOT_NAMESPACE;
11901        } else {
11902            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
11903        }
11904    }
11905
11906    /**
11907     * {@hide}
11908     *
11909     * @return true if the view belongs to the root namespace, false otherwise
11910     */
11911    public boolean isRootNamespace() {
11912        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
11913    }
11914
11915    /**
11916     * Returns this view's identifier.
11917     *
11918     * @return a positive integer used to identify the view or {@link #NO_ID}
11919     *         if the view has no ID
11920     *
11921     * @see #setId(int)
11922     * @see #findViewById(int)
11923     * @attr ref android.R.styleable#View_id
11924     */
11925    @ViewDebug.CapturedViewProperty
11926    public int getId() {
11927        return mID;
11928    }
11929
11930    /**
11931     * Returns this view's tag.
11932     *
11933     * @return the Object stored in this view as a tag
11934     *
11935     * @see #setTag(Object)
11936     * @see #getTag(int)
11937     */
11938    @ViewDebug.ExportedProperty
11939    public Object getTag() {
11940        return mTag;
11941    }
11942
11943    /**
11944     * Sets the tag associated with this view. A tag can be used to mark
11945     * a view in its hierarchy and does not have to be unique within the
11946     * hierarchy. Tags can also be used to store data within a view without
11947     * resorting to another data structure.
11948     *
11949     * @param tag an Object to tag the view with
11950     *
11951     * @see #getTag()
11952     * @see #setTag(int, Object)
11953     */
11954    public void setTag(final Object tag) {
11955        mTag = tag;
11956    }
11957
11958    /**
11959     * Returns the tag associated with this view and the specified key.
11960     *
11961     * @param key The key identifying the tag
11962     *
11963     * @return the Object stored in this view as a tag
11964     *
11965     * @see #setTag(int, Object)
11966     * @see #getTag()
11967     */
11968    public Object getTag(int key) {
11969        SparseArray<Object> tags = null;
11970        synchronized (sTagsLock) {
11971            if (sTags != null) {
11972                tags = sTags.get(this);
11973            }
11974        }
11975
11976        if (tags != null) return tags.get(key);
11977        return null;
11978    }
11979
11980    /**
11981     * Sets a tag associated with this view and a key. A tag can be used
11982     * to mark a view in its hierarchy and does not have to be unique within
11983     * the hierarchy. Tags can also be used to store data within a view
11984     * without resorting to another data structure.
11985     *
11986     * The specified key should be an id declared in the resources of the
11987     * application to ensure it is unique (see the <a
11988     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
11989     * Keys identified as belonging to
11990     * the Android framework or not associated with any package will cause
11991     * an {@link IllegalArgumentException} to be thrown.
11992     *
11993     * @param key The key identifying the tag
11994     * @param tag An Object to tag the view with
11995     *
11996     * @throws IllegalArgumentException If they specified key is not valid
11997     *
11998     * @see #setTag(Object)
11999     * @see #getTag(int)
12000     */
12001    public void setTag(int key, final Object tag) {
12002        // If the package id is 0x00 or 0x01, it's either an undefined package
12003        // or a framework id
12004        if ((key >>> 24) < 2) {
12005            throw new IllegalArgumentException("The key must be an application-specific "
12006                    + "resource id.");
12007        }
12008
12009        setTagInternal(this, key, tag);
12010    }
12011
12012    /**
12013     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12014     * framework id.
12015     *
12016     * @hide
12017     */
12018    public void setTagInternal(int key, Object tag) {
12019        if ((key >>> 24) != 0x1) {
12020            throw new IllegalArgumentException("The key must be a framework-specific "
12021                    + "resource id.");
12022        }
12023
12024        setTagInternal(this, key, tag);
12025    }
12026
12027    private static void setTagInternal(View view, int key, Object tag) {
12028        SparseArray<Object> tags = null;
12029        synchronized (sTagsLock) {
12030            if (sTags == null) {
12031                sTags = new WeakHashMap<View, SparseArray<Object>>();
12032            } else {
12033                tags = sTags.get(view);
12034            }
12035        }
12036
12037        if (tags == null) {
12038            tags = new SparseArray<Object>(2);
12039            synchronized (sTagsLock) {
12040                sTags.put(view, tags);
12041            }
12042        }
12043
12044        tags.put(key, tag);
12045    }
12046
12047    /**
12048     * @param consistency The type of consistency. See ViewDebug for more information.
12049     *
12050     * @hide
12051     */
12052    protected boolean dispatchConsistencyCheck(int consistency) {
12053        return onConsistencyCheck(consistency);
12054    }
12055
12056    /**
12057     * Method that subclasses should implement to check their consistency. The type of
12058     * consistency check is indicated by the bit field passed as a parameter.
12059     *
12060     * @param consistency The type of consistency. See ViewDebug for more information.
12061     *
12062     * @throws IllegalStateException if the view is in an inconsistent state.
12063     *
12064     * @hide
12065     */
12066    protected boolean onConsistencyCheck(int consistency) {
12067        boolean result = true;
12068
12069        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12070        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12071
12072        if (checkLayout) {
12073            if (getParent() == null) {
12074                result = false;
12075                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12076                        "View " + this + " does not have a parent.");
12077            }
12078
12079            if (mAttachInfo == null) {
12080                result = false;
12081                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12082                        "View " + this + " is not attached to a window.");
12083            }
12084        }
12085
12086        if (checkDrawing) {
12087            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12088            // from their draw() method
12089
12090            if ((mPrivateFlags & DRAWN) != DRAWN &&
12091                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12092                result = false;
12093                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12094                        "View " + this + " was invalidated but its drawing cache is valid.");
12095            }
12096        }
12097
12098        return result;
12099    }
12100
12101    /**
12102     * Prints information about this view in the log output, with the tag
12103     * {@link #VIEW_LOG_TAG}.
12104     *
12105     * @hide
12106     */
12107    public void debug() {
12108        debug(0);
12109    }
12110
12111    /**
12112     * Prints information about this view in the log output, with the tag
12113     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12114     * indentation defined by the <code>depth</code>.
12115     *
12116     * @param depth the indentation level
12117     *
12118     * @hide
12119     */
12120    protected void debug(int depth) {
12121        String output = debugIndent(depth - 1);
12122
12123        output += "+ " + this;
12124        int id = getId();
12125        if (id != -1) {
12126            output += " (id=" + id + ")";
12127        }
12128        Object tag = getTag();
12129        if (tag != null) {
12130            output += " (tag=" + tag + ")";
12131        }
12132        Log.d(VIEW_LOG_TAG, output);
12133
12134        if ((mPrivateFlags & FOCUSED) != 0) {
12135            output = debugIndent(depth) + " FOCUSED";
12136            Log.d(VIEW_LOG_TAG, output);
12137        }
12138
12139        output = debugIndent(depth);
12140        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12141                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12142                + "} ";
12143        Log.d(VIEW_LOG_TAG, output);
12144
12145        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12146                || mPaddingBottom != 0) {
12147            output = debugIndent(depth);
12148            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12149                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12150            Log.d(VIEW_LOG_TAG, output);
12151        }
12152
12153        output = debugIndent(depth);
12154        output += "mMeasureWidth=" + mMeasuredWidth +
12155                " mMeasureHeight=" + mMeasuredHeight;
12156        Log.d(VIEW_LOG_TAG, output);
12157
12158        output = debugIndent(depth);
12159        if (mLayoutParams == null) {
12160            output += "BAD! no layout params";
12161        } else {
12162            output = mLayoutParams.debug(output);
12163        }
12164        Log.d(VIEW_LOG_TAG, output);
12165
12166        output = debugIndent(depth);
12167        output += "flags={";
12168        output += View.printFlags(mViewFlags);
12169        output += "}";
12170        Log.d(VIEW_LOG_TAG, output);
12171
12172        output = debugIndent(depth);
12173        output += "privateFlags={";
12174        output += View.printPrivateFlags(mPrivateFlags);
12175        output += "}";
12176        Log.d(VIEW_LOG_TAG, output);
12177    }
12178
12179    /**
12180     * Creates an string of whitespaces used for indentation.
12181     *
12182     * @param depth the indentation level
12183     * @return a String containing (depth * 2 + 3) * 2 white spaces
12184     *
12185     * @hide
12186     */
12187    protected static String debugIndent(int depth) {
12188        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12189        for (int i = 0; i < (depth * 2) + 3; i++) {
12190            spaces.append(' ').append(' ');
12191        }
12192        return spaces.toString();
12193    }
12194
12195    /**
12196     * <p>Return the offset of the widget's text baseline from the widget's top
12197     * boundary. If this widget does not support baseline alignment, this
12198     * method returns -1. </p>
12199     *
12200     * @return the offset of the baseline within the widget's bounds or -1
12201     *         if baseline alignment is not supported
12202     */
12203    @ViewDebug.ExportedProperty(category = "layout")
12204    public int getBaseline() {
12205        return -1;
12206    }
12207
12208    /**
12209     * Call this when something has changed which has invalidated the
12210     * layout of this view. This will schedule a layout pass of the view
12211     * tree.
12212     */
12213    public void requestLayout() {
12214        if (ViewDebug.TRACE_HIERARCHY) {
12215            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12216        }
12217
12218        mPrivateFlags |= FORCE_LAYOUT;
12219        mPrivateFlags |= INVALIDATED;
12220
12221        if (mParent != null) {
12222            if (mLayoutParams != null) {
12223                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12224            }
12225            if (!mParent.isLayoutRequested()) {
12226                mParent.requestLayout();
12227            }
12228        }
12229    }
12230
12231    /**
12232     * Forces this view to be laid out during the next layout pass.
12233     * This method does not call requestLayout() or forceLayout()
12234     * on the parent.
12235     */
12236    public void forceLayout() {
12237        mPrivateFlags |= FORCE_LAYOUT;
12238        mPrivateFlags |= INVALIDATED;
12239    }
12240
12241    /**
12242     * <p>
12243     * This is called to find out how big a view should be. The parent
12244     * supplies constraint information in the width and height parameters.
12245     * </p>
12246     *
12247     * <p>
12248     * The actual mesurement work of a view is performed in
12249     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12250     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12251     * </p>
12252     *
12253     *
12254     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12255     *        parent
12256     * @param heightMeasureSpec Vertical space requirements as imposed by the
12257     *        parent
12258     *
12259     * @see #onMeasure(int, int)
12260     */
12261    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12262        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12263                widthMeasureSpec != mOldWidthMeasureSpec ||
12264                heightMeasureSpec != mOldHeightMeasureSpec) {
12265
12266            // first clears the measured dimension flag
12267            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12268
12269            if (ViewDebug.TRACE_HIERARCHY) {
12270                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12271            }
12272
12273            // measure ourselves, this should set the measured dimension flag back
12274            onMeasure(widthMeasureSpec, heightMeasureSpec);
12275
12276            // flag not set, setMeasuredDimension() was not invoked, we raise
12277            // an exception to warn the developer
12278            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12279                throw new IllegalStateException("onMeasure() did not set the"
12280                        + " measured dimension by calling"
12281                        + " setMeasuredDimension()");
12282            }
12283
12284            mPrivateFlags |= LAYOUT_REQUIRED;
12285        }
12286
12287        mOldWidthMeasureSpec = widthMeasureSpec;
12288        mOldHeightMeasureSpec = heightMeasureSpec;
12289    }
12290
12291    /**
12292     * <p>
12293     * Measure the view and its content to determine the measured width and the
12294     * measured height. This method is invoked by {@link #measure(int, int)} and
12295     * should be overriden by subclasses to provide accurate and efficient
12296     * measurement of their contents.
12297     * </p>
12298     *
12299     * <p>
12300     * <strong>CONTRACT:</strong> When overriding this method, you
12301     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12302     * measured width and height of this view. Failure to do so will trigger an
12303     * <code>IllegalStateException</code>, thrown by
12304     * {@link #measure(int, int)}. Calling the superclass'
12305     * {@link #onMeasure(int, int)} is a valid use.
12306     * </p>
12307     *
12308     * <p>
12309     * The base class implementation of measure defaults to the background size,
12310     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12311     * override {@link #onMeasure(int, int)} to provide better measurements of
12312     * their content.
12313     * </p>
12314     *
12315     * <p>
12316     * If this method is overridden, it is the subclass's responsibility to make
12317     * sure the measured height and width are at least the view's minimum height
12318     * and width ({@link #getSuggestedMinimumHeight()} and
12319     * {@link #getSuggestedMinimumWidth()}).
12320     * </p>
12321     *
12322     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12323     *                         The requirements are encoded with
12324     *                         {@link android.view.View.MeasureSpec}.
12325     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12326     *                         The requirements are encoded with
12327     *                         {@link android.view.View.MeasureSpec}.
12328     *
12329     * @see #getMeasuredWidth()
12330     * @see #getMeasuredHeight()
12331     * @see #setMeasuredDimension(int, int)
12332     * @see #getSuggestedMinimumHeight()
12333     * @see #getSuggestedMinimumWidth()
12334     * @see android.view.View.MeasureSpec#getMode(int)
12335     * @see android.view.View.MeasureSpec#getSize(int)
12336     */
12337    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12338        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12339                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12340    }
12341
12342    /**
12343     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12344     * measured width and measured height. Failing to do so will trigger an
12345     * exception at measurement time.</p>
12346     *
12347     * @param measuredWidth The measured width of this view.  May be a complex
12348     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12349     * {@link #MEASURED_STATE_TOO_SMALL}.
12350     * @param measuredHeight The measured height of this view.  May be a complex
12351     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12352     * {@link #MEASURED_STATE_TOO_SMALL}.
12353     */
12354    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12355        mMeasuredWidth = measuredWidth;
12356        mMeasuredHeight = measuredHeight;
12357
12358        mPrivateFlags |= MEASURED_DIMENSION_SET;
12359    }
12360
12361    /**
12362     * Merge two states as returned by {@link #getMeasuredState()}.
12363     * @param curState The current state as returned from a view or the result
12364     * of combining multiple views.
12365     * @param newState The new view state to combine.
12366     * @return Returns a new integer reflecting the combination of the two
12367     * states.
12368     */
12369    public static int combineMeasuredStates(int curState, int newState) {
12370        return curState | newState;
12371    }
12372
12373    /**
12374     * Version of {@link #resolveSizeAndState(int, int, int)}
12375     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12376     */
12377    public static int resolveSize(int size, int measureSpec) {
12378        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12379    }
12380
12381    /**
12382     * Utility to reconcile a desired size and state, with constraints imposed
12383     * by a MeasureSpec.  Will take the desired size, unless a different size
12384     * is imposed by the constraints.  The returned value is a compound integer,
12385     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12386     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12387     * size is smaller than the size the view wants to be.
12388     *
12389     * @param size How big the view wants to be
12390     * @param measureSpec Constraints imposed by the parent
12391     * @return Size information bit mask as defined by
12392     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12393     */
12394    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12395        int result = size;
12396        int specMode = MeasureSpec.getMode(measureSpec);
12397        int specSize =  MeasureSpec.getSize(measureSpec);
12398        switch (specMode) {
12399        case MeasureSpec.UNSPECIFIED:
12400            result = size;
12401            break;
12402        case MeasureSpec.AT_MOST:
12403            if (specSize < size) {
12404                result = specSize | MEASURED_STATE_TOO_SMALL;
12405            } else {
12406                result = size;
12407            }
12408            break;
12409        case MeasureSpec.EXACTLY:
12410            result = specSize;
12411            break;
12412        }
12413        return result | (childMeasuredState&MEASURED_STATE_MASK);
12414    }
12415
12416    /**
12417     * Utility to return a default size. Uses the supplied size if the
12418     * MeasureSpec imposed no constraints. Will get larger if allowed
12419     * by the MeasureSpec.
12420     *
12421     * @param size Default size for this view
12422     * @param measureSpec Constraints imposed by the parent
12423     * @return The size this view should be.
12424     */
12425    public static int getDefaultSize(int size, int measureSpec) {
12426        int result = size;
12427        int specMode = MeasureSpec.getMode(measureSpec);
12428        int specSize = MeasureSpec.getSize(measureSpec);
12429
12430        switch (specMode) {
12431        case MeasureSpec.UNSPECIFIED:
12432            result = size;
12433            break;
12434        case MeasureSpec.AT_MOST:
12435        case MeasureSpec.EXACTLY:
12436            result = specSize;
12437            break;
12438        }
12439        return result;
12440    }
12441
12442    /**
12443     * Returns the suggested minimum height that the view should use. This
12444     * returns the maximum of the view's minimum height
12445     * and the background's minimum height
12446     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12447     * <p>
12448     * When being used in {@link #onMeasure(int, int)}, the caller should still
12449     * ensure the returned height is within the requirements of the parent.
12450     *
12451     * @return The suggested minimum height of the view.
12452     */
12453    protected int getSuggestedMinimumHeight() {
12454        int suggestedMinHeight = mMinHeight;
12455
12456        if (mBGDrawable != null) {
12457            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12458            if (suggestedMinHeight < bgMinHeight) {
12459                suggestedMinHeight = bgMinHeight;
12460            }
12461        }
12462
12463        return suggestedMinHeight;
12464    }
12465
12466    /**
12467     * Returns the suggested minimum width that the view should use. This
12468     * returns the maximum of the view's minimum width)
12469     * and the background's minimum width
12470     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12471     * <p>
12472     * When being used in {@link #onMeasure(int, int)}, the caller should still
12473     * ensure the returned width is within the requirements of the parent.
12474     *
12475     * @return The suggested minimum width of the view.
12476     */
12477    protected int getSuggestedMinimumWidth() {
12478        int suggestedMinWidth = mMinWidth;
12479
12480        if (mBGDrawable != null) {
12481            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12482            if (suggestedMinWidth < bgMinWidth) {
12483                suggestedMinWidth = bgMinWidth;
12484            }
12485        }
12486
12487        return suggestedMinWidth;
12488    }
12489
12490    /**
12491     * Sets the minimum height of the view. It is not guaranteed the view will
12492     * be able to achieve this minimum height (for example, if its parent layout
12493     * constrains it with less available height).
12494     *
12495     * @param minHeight The minimum height the view will try to be.
12496     */
12497    public void setMinimumHeight(int minHeight) {
12498        mMinHeight = minHeight;
12499    }
12500
12501    /**
12502     * Sets the minimum width of the view. It is not guaranteed the view will
12503     * be able to achieve this minimum width (for example, if its parent layout
12504     * constrains it with less available width).
12505     *
12506     * @param minWidth The minimum width the view will try to be.
12507     */
12508    public void setMinimumWidth(int minWidth) {
12509        mMinWidth = minWidth;
12510    }
12511
12512    /**
12513     * Get the animation currently associated with this view.
12514     *
12515     * @return The animation that is currently playing or
12516     *         scheduled to play for this view.
12517     */
12518    public Animation getAnimation() {
12519        return mCurrentAnimation;
12520    }
12521
12522    /**
12523     * Start the specified animation now.
12524     *
12525     * @param animation the animation to start now
12526     */
12527    public void startAnimation(Animation animation) {
12528        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12529        setAnimation(animation);
12530        invalidateParentCaches();
12531        invalidate(true);
12532    }
12533
12534    /**
12535     * Cancels any animations for this view.
12536     */
12537    public void clearAnimation() {
12538        if (mCurrentAnimation != null) {
12539            mCurrentAnimation.detach();
12540        }
12541        mCurrentAnimation = null;
12542        invalidateParentIfNeeded();
12543    }
12544
12545    /**
12546     * Sets the next animation to play for this view.
12547     * If you want the animation to play immediately, use
12548     * startAnimation. This method provides allows fine-grained
12549     * control over the start time and invalidation, but you
12550     * must make sure that 1) the animation has a start time set, and
12551     * 2) the view will be invalidated when the animation is supposed to
12552     * start.
12553     *
12554     * @param animation The next animation, or null.
12555     */
12556    public void setAnimation(Animation animation) {
12557        mCurrentAnimation = animation;
12558        if (animation != null) {
12559            animation.reset();
12560        }
12561    }
12562
12563    /**
12564     * Invoked by a parent ViewGroup to notify the start of the animation
12565     * currently associated with this view. If you override this method,
12566     * always call super.onAnimationStart();
12567     *
12568     * @see #setAnimation(android.view.animation.Animation)
12569     * @see #getAnimation()
12570     */
12571    protected void onAnimationStart() {
12572        mPrivateFlags |= ANIMATION_STARTED;
12573    }
12574
12575    /**
12576     * Invoked by a parent ViewGroup to notify the end of the animation
12577     * currently associated with this view. If you override this method,
12578     * always call super.onAnimationEnd();
12579     *
12580     * @see #setAnimation(android.view.animation.Animation)
12581     * @see #getAnimation()
12582     */
12583    protected void onAnimationEnd() {
12584        mPrivateFlags &= ~ANIMATION_STARTED;
12585    }
12586
12587    /**
12588     * Invoked if there is a Transform that involves alpha. Subclass that can
12589     * draw themselves with the specified alpha should return true, and then
12590     * respect that alpha when their onDraw() is called. If this returns false
12591     * then the view may be redirected to draw into an offscreen buffer to
12592     * fulfill the request, which will look fine, but may be slower than if the
12593     * subclass handles it internally. The default implementation returns false.
12594     *
12595     * @param alpha The alpha (0..255) to apply to the view's drawing
12596     * @return true if the view can draw with the specified alpha.
12597     */
12598    protected boolean onSetAlpha(int alpha) {
12599        return false;
12600    }
12601
12602    /**
12603     * This is used by the RootView to perform an optimization when
12604     * the view hierarchy contains one or several SurfaceView.
12605     * SurfaceView is always considered transparent, but its children are not,
12606     * therefore all View objects remove themselves from the global transparent
12607     * region (passed as a parameter to this function).
12608     *
12609     * @param region The transparent region for this ViewAncestor (window).
12610     *
12611     * @return Returns true if the effective visibility of the view at this
12612     * point is opaque, regardless of the transparent region; returns false
12613     * if it is possible for underlying windows to be seen behind the view.
12614     *
12615     * {@hide}
12616     */
12617    public boolean gatherTransparentRegion(Region region) {
12618        final AttachInfo attachInfo = mAttachInfo;
12619        if (region != null && attachInfo != null) {
12620            final int pflags = mPrivateFlags;
12621            if ((pflags & SKIP_DRAW) == 0) {
12622                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
12623                // remove it from the transparent region.
12624                final int[] location = attachInfo.mTransparentLocation;
12625                getLocationInWindow(location);
12626                region.op(location[0], location[1], location[0] + mRight - mLeft,
12627                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
12628            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
12629                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
12630                // exists, so we remove the background drawable's non-transparent
12631                // parts from this transparent region.
12632                applyDrawableToTransparentRegion(mBGDrawable, region);
12633            }
12634        }
12635        return true;
12636    }
12637
12638    /**
12639     * Play a sound effect for this view.
12640     *
12641     * <p>The framework will play sound effects for some built in actions, such as
12642     * clicking, but you may wish to play these effects in your widget,
12643     * for instance, for internal navigation.
12644     *
12645     * <p>The sound effect will only be played if sound effects are enabled by the user, and
12646     * {@link #isSoundEffectsEnabled()} is true.
12647     *
12648     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
12649     */
12650    public void playSoundEffect(int soundConstant) {
12651        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
12652            return;
12653        }
12654        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
12655    }
12656
12657    /**
12658     * BZZZTT!!1!
12659     *
12660     * <p>Provide haptic feedback to the user for this view.
12661     *
12662     * <p>The framework will provide haptic feedback for some built in actions,
12663     * such as long presses, but you may wish to provide feedback for your
12664     * own widget.
12665     *
12666     * <p>The feedback will only be performed if
12667     * {@link #isHapticFeedbackEnabled()} is true.
12668     *
12669     * @param feedbackConstant One of the constants defined in
12670     * {@link HapticFeedbackConstants}
12671     */
12672    public boolean performHapticFeedback(int feedbackConstant) {
12673        return performHapticFeedback(feedbackConstant, 0);
12674    }
12675
12676    /**
12677     * BZZZTT!!1!
12678     *
12679     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
12680     *
12681     * @param feedbackConstant One of the constants defined in
12682     * {@link HapticFeedbackConstants}
12683     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
12684     */
12685    public boolean performHapticFeedback(int feedbackConstant, int flags) {
12686        if (mAttachInfo == null) {
12687            return false;
12688        }
12689        //noinspection SimplifiableIfStatement
12690        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
12691                && !isHapticFeedbackEnabled()) {
12692            return false;
12693        }
12694        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
12695                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
12696    }
12697
12698    /**
12699     * Request that the visibility of the status bar be changed.
12700     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12701     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12702     *
12703     * This value will be re-applied immediately, even if the flags have not changed, so a view may
12704     * easily reassert a particular SystemUiVisibility condition even if the system UI itself has
12705     * since countermanded the original request.
12706     */
12707    public void setSystemUiVisibility(int visibility) {
12708        mSystemUiVisibility = visibility;
12709        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12710            mParent.recomputeViewAttributes(this);
12711        }
12712    }
12713
12714    /**
12715     * Returns the status bar visibility that this view has requested.
12716     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12717     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12718     */
12719    public int getSystemUiVisibility() {
12720        return mSystemUiVisibility;
12721    }
12722
12723    /**
12724     * Set a listener to receive callbacks when the visibility of the system bar changes.
12725     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
12726     */
12727    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
12728        mOnSystemUiVisibilityChangeListener = l;
12729        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12730            mParent.recomputeViewAttributes(this);
12731        }
12732    }
12733
12734    /**
12735     */
12736    public void dispatchSystemUiVisibilityChanged(int visibility) {
12737        if (mOnSystemUiVisibilityChangeListener != null) {
12738            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
12739                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
12740        }
12741    }
12742
12743    /**
12744     * Creates an image that the system displays during the drag and drop
12745     * operation. This is called a &quot;drag shadow&quot;. The default implementation
12746     * for a DragShadowBuilder based on a View returns an image that has exactly the same
12747     * appearance as the given View. The default also positions the center of the drag shadow
12748     * directly under the touch point. If no View is provided (the constructor with no parameters
12749     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
12750     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
12751     * default is an invisible drag shadow.
12752     * <p>
12753     * You are not required to use the View you provide to the constructor as the basis of the
12754     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
12755     * anything you want as the drag shadow.
12756     * </p>
12757     * <p>
12758     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
12759     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
12760     *  size and position of the drag shadow. It uses this data to construct a
12761     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
12762     *  so that your application can draw the shadow image in the Canvas.
12763     * </p>
12764     */
12765    public static class DragShadowBuilder {
12766        private final WeakReference<View> mView;
12767
12768        /**
12769         * Constructs a shadow image builder based on a View. By default, the resulting drag
12770         * shadow will have the same appearance and dimensions as the View, with the touch point
12771         * over the center of the View.
12772         * @param view A View. Any View in scope can be used.
12773         */
12774        public DragShadowBuilder(View view) {
12775            mView = new WeakReference<View>(view);
12776        }
12777
12778        /**
12779         * Construct a shadow builder object with no associated View.  This
12780         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
12781         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
12782         * to supply the drag shadow's dimensions and appearance without
12783         * reference to any View object. If they are not overridden, then the result is an
12784         * invisible drag shadow.
12785         */
12786        public DragShadowBuilder() {
12787            mView = new WeakReference<View>(null);
12788        }
12789
12790        /**
12791         * Returns the View object that had been passed to the
12792         * {@link #View.DragShadowBuilder(View)}
12793         * constructor.  If that View parameter was {@code null} or if the
12794         * {@link #View.DragShadowBuilder()}
12795         * constructor was used to instantiate the builder object, this method will return
12796         * null.
12797         *
12798         * @return The View object associate with this builder object.
12799         */
12800        @SuppressWarnings({"JavadocReference"})
12801        final public View getView() {
12802            return mView.get();
12803        }
12804
12805        /**
12806         * Provides the metrics for the shadow image. These include the dimensions of
12807         * the shadow image, and the point within that shadow that should
12808         * be centered under the touch location while dragging.
12809         * <p>
12810         * The default implementation sets the dimensions of the shadow to be the
12811         * same as the dimensions of the View itself and centers the shadow under
12812         * the touch point.
12813         * </p>
12814         *
12815         * @param shadowSize A {@link android.graphics.Point} containing the width and height
12816         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
12817         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
12818         * image.
12819         *
12820         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
12821         * shadow image that should be underneath the touch point during the drag and drop
12822         * operation. Your application must set {@link android.graphics.Point#x} to the
12823         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
12824         */
12825        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
12826            final View view = mView.get();
12827            if (view != null) {
12828                shadowSize.set(view.getWidth(), view.getHeight());
12829                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
12830            } else {
12831                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
12832            }
12833        }
12834
12835        /**
12836         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
12837         * based on the dimensions it received from the
12838         * {@link #onProvideShadowMetrics(Point, Point)} callback.
12839         *
12840         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
12841         */
12842        public void onDrawShadow(Canvas canvas) {
12843            final View view = mView.get();
12844            if (view != null) {
12845                view.draw(canvas);
12846            } else {
12847                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
12848            }
12849        }
12850    }
12851
12852    /**
12853     * Starts a drag and drop operation. When your application calls this method, it passes a
12854     * {@link android.view.View.DragShadowBuilder} object to the system. The
12855     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
12856     * to get metrics for the drag shadow, and then calls the object's
12857     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
12858     * <p>
12859     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
12860     *  drag events to all the View objects in your application that are currently visible. It does
12861     *  this either by calling the View object's drag listener (an implementation of
12862     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
12863     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
12864     *  Both are passed a {@link android.view.DragEvent} object that has a
12865     *  {@link android.view.DragEvent#getAction()} value of
12866     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
12867     * </p>
12868     * <p>
12869     * Your application can invoke startDrag() on any attached View object. The View object does not
12870     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
12871     * be related to the View the user selected for dragging.
12872     * </p>
12873     * @param data A {@link android.content.ClipData} object pointing to the data to be
12874     * transferred by the drag and drop operation.
12875     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
12876     * drag shadow.
12877     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
12878     * drop operation. This Object is put into every DragEvent object sent by the system during the
12879     * current drag.
12880     * <p>
12881     * myLocalState is a lightweight mechanism for the sending information from the dragged View
12882     * to the target Views. For example, it can contain flags that differentiate between a
12883     * a copy operation and a move operation.
12884     * </p>
12885     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
12886     * so the parameter should be set to 0.
12887     * @return {@code true} if the method completes successfully, or
12888     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
12889     * do a drag, and so no drag operation is in progress.
12890     */
12891    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
12892            Object myLocalState, int flags) {
12893        if (ViewDebug.DEBUG_DRAG) {
12894            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
12895        }
12896        boolean okay = false;
12897
12898        Point shadowSize = new Point();
12899        Point shadowTouchPoint = new Point();
12900        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
12901
12902        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
12903                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
12904            throw new IllegalStateException("Drag shadow dimensions must not be negative");
12905        }
12906
12907        if (ViewDebug.DEBUG_DRAG) {
12908            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
12909                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
12910        }
12911        Surface surface = new Surface();
12912        try {
12913            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
12914                    flags, shadowSize.x, shadowSize.y, surface);
12915            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
12916                    + " surface=" + surface);
12917            if (token != null) {
12918                Canvas canvas = surface.lockCanvas(null);
12919                try {
12920                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
12921                    shadowBuilder.onDrawShadow(canvas);
12922                } finally {
12923                    surface.unlockCanvasAndPost(canvas);
12924                }
12925
12926                final ViewRootImpl root = getViewRootImpl();
12927
12928                // Cache the local state object for delivery with DragEvents
12929                root.setLocalDragState(myLocalState);
12930
12931                // repurpose 'shadowSize' for the last touch point
12932                root.getLastTouchPoint(shadowSize);
12933
12934                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
12935                        shadowSize.x, shadowSize.y,
12936                        shadowTouchPoint.x, shadowTouchPoint.y, data);
12937                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
12938            }
12939        } catch (Exception e) {
12940            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
12941            surface.destroy();
12942        }
12943
12944        return okay;
12945    }
12946
12947    /**
12948     * Handles drag events sent by the system following a call to
12949     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
12950     *<p>
12951     * When the system calls this method, it passes a
12952     * {@link android.view.DragEvent} object. A call to
12953     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
12954     * in DragEvent. The method uses these to determine what is happening in the drag and drop
12955     * operation.
12956     * @param event The {@link android.view.DragEvent} sent by the system.
12957     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
12958     * in DragEvent, indicating the type of drag event represented by this object.
12959     * @return {@code true} if the method was successful, otherwise {@code false}.
12960     * <p>
12961     *  The method should return {@code true} in response to an action type of
12962     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
12963     *  operation.
12964     * </p>
12965     * <p>
12966     *  The method should also return {@code true} in response to an action type of
12967     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
12968     *  {@code false} if it didn't.
12969     * </p>
12970     */
12971    public boolean onDragEvent(DragEvent event) {
12972        return false;
12973    }
12974
12975    /**
12976     * Detects if this View is enabled and has a drag event listener.
12977     * If both are true, then it calls the drag event listener with the
12978     * {@link android.view.DragEvent} it received. If the drag event listener returns
12979     * {@code true}, then dispatchDragEvent() returns {@code true}.
12980     * <p>
12981     * For all other cases, the method calls the
12982     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
12983     * method and returns its result.
12984     * </p>
12985     * <p>
12986     * This ensures that a drag event is always consumed, even if the View does not have a drag
12987     * event listener. However, if the View has a listener and the listener returns true, then
12988     * onDragEvent() is not called.
12989     * </p>
12990     */
12991    public boolean dispatchDragEvent(DragEvent event) {
12992        //noinspection SimplifiableIfStatement
12993        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
12994                && mOnDragListener.onDrag(this, event)) {
12995            return true;
12996        }
12997        return onDragEvent(event);
12998    }
12999
13000    boolean canAcceptDrag() {
13001        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13002    }
13003
13004    /**
13005     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13006     * it is ever exposed at all.
13007     * @hide
13008     */
13009    public void onCloseSystemDialogs(String reason) {
13010    }
13011
13012    /**
13013     * Given a Drawable whose bounds have been set to draw into this view,
13014     * update a Region being computed for
13015     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13016     * that any non-transparent parts of the Drawable are removed from the
13017     * given transparent region.
13018     *
13019     * @param dr The Drawable whose transparency is to be applied to the region.
13020     * @param region A Region holding the current transparency information,
13021     * where any parts of the region that are set are considered to be
13022     * transparent.  On return, this region will be modified to have the
13023     * transparency information reduced by the corresponding parts of the
13024     * Drawable that are not transparent.
13025     * {@hide}
13026     */
13027    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13028        if (DBG) {
13029            Log.i("View", "Getting transparent region for: " + this);
13030        }
13031        final Region r = dr.getTransparentRegion();
13032        final Rect db = dr.getBounds();
13033        final AttachInfo attachInfo = mAttachInfo;
13034        if (r != null && attachInfo != null) {
13035            final int w = getRight()-getLeft();
13036            final int h = getBottom()-getTop();
13037            if (db.left > 0) {
13038                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13039                r.op(0, 0, db.left, h, Region.Op.UNION);
13040            }
13041            if (db.right < w) {
13042                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13043                r.op(db.right, 0, w, h, Region.Op.UNION);
13044            }
13045            if (db.top > 0) {
13046                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13047                r.op(0, 0, w, db.top, Region.Op.UNION);
13048            }
13049            if (db.bottom < h) {
13050                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13051                r.op(0, db.bottom, w, h, Region.Op.UNION);
13052            }
13053            final int[] location = attachInfo.mTransparentLocation;
13054            getLocationInWindow(location);
13055            r.translate(location[0], location[1]);
13056            region.op(r, Region.Op.INTERSECT);
13057        } else {
13058            region.op(db, Region.Op.DIFFERENCE);
13059        }
13060    }
13061
13062    private void checkForLongClick(int delayOffset) {
13063        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13064            mHasPerformedLongPress = false;
13065
13066            if (mPendingCheckForLongPress == null) {
13067                mPendingCheckForLongPress = new CheckForLongPress();
13068            }
13069            mPendingCheckForLongPress.rememberWindowAttachCount();
13070            postDelayed(mPendingCheckForLongPress,
13071                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13072        }
13073    }
13074
13075    /**
13076     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13077     * LayoutInflater} class, which provides a full range of options for view inflation.
13078     *
13079     * @param context The Context object for your activity or application.
13080     * @param resource The resource ID to inflate
13081     * @param root A view group that will be the parent.  Used to properly inflate the
13082     * layout_* parameters.
13083     * @see LayoutInflater
13084     */
13085    public static View inflate(Context context, int resource, ViewGroup root) {
13086        LayoutInflater factory = LayoutInflater.from(context);
13087        return factory.inflate(resource, root);
13088    }
13089
13090    /**
13091     * Scroll the view with standard behavior for scrolling beyond the normal
13092     * content boundaries. Views that call this method should override
13093     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13094     * results of an over-scroll operation.
13095     *
13096     * Views can use this method to handle any touch or fling-based scrolling.
13097     *
13098     * @param deltaX Change in X in pixels
13099     * @param deltaY Change in Y in pixels
13100     * @param scrollX Current X scroll value in pixels before applying deltaX
13101     * @param scrollY Current Y scroll value in pixels before applying deltaY
13102     * @param scrollRangeX Maximum content scroll range along the X axis
13103     * @param scrollRangeY Maximum content scroll range along the Y axis
13104     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13105     *          along the X axis.
13106     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13107     *          along the Y axis.
13108     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13109     * @return true if scrolling was clamped to an over-scroll boundary along either
13110     *          axis, false otherwise.
13111     */
13112    @SuppressWarnings({"UnusedParameters"})
13113    protected boolean overScrollBy(int deltaX, int deltaY,
13114            int scrollX, int scrollY,
13115            int scrollRangeX, int scrollRangeY,
13116            int maxOverScrollX, int maxOverScrollY,
13117            boolean isTouchEvent) {
13118        final int overScrollMode = mOverScrollMode;
13119        final boolean canScrollHorizontal =
13120                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13121        final boolean canScrollVertical =
13122                computeVerticalScrollRange() > computeVerticalScrollExtent();
13123        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13124                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13125        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13126                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13127
13128        int newScrollX = scrollX + deltaX;
13129        if (!overScrollHorizontal) {
13130            maxOverScrollX = 0;
13131        }
13132
13133        int newScrollY = scrollY + deltaY;
13134        if (!overScrollVertical) {
13135            maxOverScrollY = 0;
13136        }
13137
13138        // Clamp values if at the limits and record
13139        final int left = -maxOverScrollX;
13140        final int right = maxOverScrollX + scrollRangeX;
13141        final int top = -maxOverScrollY;
13142        final int bottom = maxOverScrollY + scrollRangeY;
13143
13144        boolean clampedX = false;
13145        if (newScrollX > right) {
13146            newScrollX = right;
13147            clampedX = true;
13148        } else if (newScrollX < left) {
13149            newScrollX = left;
13150            clampedX = true;
13151        }
13152
13153        boolean clampedY = false;
13154        if (newScrollY > bottom) {
13155            newScrollY = bottom;
13156            clampedY = true;
13157        } else if (newScrollY < top) {
13158            newScrollY = top;
13159            clampedY = true;
13160        }
13161
13162        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13163
13164        return clampedX || clampedY;
13165    }
13166
13167    /**
13168     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13169     * respond to the results of an over-scroll operation.
13170     *
13171     * @param scrollX New X scroll value in pixels
13172     * @param scrollY New Y scroll value in pixels
13173     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13174     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13175     */
13176    protected void onOverScrolled(int scrollX, int scrollY,
13177            boolean clampedX, boolean clampedY) {
13178        // Intentionally empty.
13179    }
13180
13181    /**
13182     * Returns the over-scroll mode for this view. The result will be
13183     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13184     * (allow over-scrolling only if the view content is larger than the container),
13185     * or {@link #OVER_SCROLL_NEVER}.
13186     *
13187     * @return This view's over-scroll mode.
13188     */
13189    public int getOverScrollMode() {
13190        return mOverScrollMode;
13191    }
13192
13193    /**
13194     * Set the over-scroll mode for this view. Valid over-scroll modes are
13195     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13196     * (allow over-scrolling only if the view content is larger than the container),
13197     * or {@link #OVER_SCROLL_NEVER}.
13198     *
13199     * Setting the over-scroll mode of a view will have an effect only if the
13200     * view is capable of scrolling.
13201     *
13202     * @param overScrollMode The new over-scroll mode for this view.
13203     */
13204    public void setOverScrollMode(int overScrollMode) {
13205        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13206                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13207                overScrollMode != OVER_SCROLL_NEVER) {
13208            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13209        }
13210        mOverScrollMode = overScrollMode;
13211    }
13212
13213    /**
13214     * Gets a scale factor that determines the distance the view should scroll
13215     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13216     * @return The vertical scroll scale factor.
13217     * @hide
13218     */
13219    protected float getVerticalScrollFactor() {
13220        if (mVerticalScrollFactor == 0) {
13221            TypedValue outValue = new TypedValue();
13222            if (!mContext.getTheme().resolveAttribute(
13223                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13224                throw new IllegalStateException(
13225                        "Expected theme to define listPreferredItemHeight.");
13226            }
13227            mVerticalScrollFactor = outValue.getDimension(
13228                    mContext.getResources().getDisplayMetrics());
13229        }
13230        return mVerticalScrollFactor;
13231    }
13232
13233    /**
13234     * Gets a scale factor that determines the distance the view should scroll
13235     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13236     * @return The horizontal scroll scale factor.
13237     * @hide
13238     */
13239    protected float getHorizontalScrollFactor() {
13240        // TODO: Should use something else.
13241        return getVerticalScrollFactor();
13242    }
13243
13244    /**
13245     * Return the value specifying the text direction or policy that was set with
13246     * {@link #setTextDirection(int)}.
13247     *
13248     * @return the defined text direction. It can be one of:
13249     *
13250     * {@link #TEXT_DIRECTION_INHERIT},
13251     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13252     * {@link #TEXT_DIRECTION_ANY_RTL},
13253     * {@link #TEXT_DIRECTION_CHAR_COUNT},
13254     * {@link #TEXT_DIRECTION_LTR},
13255     * {@link #TEXT_DIRECTION_RTL},
13256     *
13257     * @hide
13258     */
13259    public int getTextDirection() {
13260        return mTextDirection;
13261    }
13262
13263    /**
13264     * Set the text direction.
13265     *
13266     * @param textDirection the direction to set. Should be one of:
13267     *
13268     * {@link #TEXT_DIRECTION_INHERIT},
13269     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13270     * {@link #TEXT_DIRECTION_ANY_RTL},
13271     * {@link #TEXT_DIRECTION_CHAR_COUNT},
13272     * {@link #TEXT_DIRECTION_LTR},
13273     * {@link #TEXT_DIRECTION_RTL},
13274     *
13275     * @hide
13276     */
13277    public void setTextDirection(int textDirection) {
13278        if (textDirection != mTextDirection) {
13279            mTextDirection = textDirection;
13280            resetResolvedTextDirection();
13281            requestLayout();
13282        }
13283    }
13284
13285    /**
13286     * Return the resolved text direction.
13287     *
13288     * @return the resolved text direction. Return one of:
13289     *
13290     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13291     * {@link #TEXT_DIRECTION_ANY_RTL},
13292     * {@link #TEXT_DIRECTION_CHAR_COUNT},
13293     * {@link #TEXT_DIRECTION_LTR},
13294     * {@link #TEXT_DIRECTION_RTL},
13295     *
13296     * @hide
13297     */
13298    public int getResolvedTextDirection() {
13299        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13300            resolveTextDirection();
13301        }
13302        return mResolvedTextDirection;
13303    }
13304
13305    /**
13306     * Resolve the text direction.
13307     */
13308    protected void resolveTextDirection() {
13309        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13310            mResolvedTextDirection = mTextDirection;
13311            return;
13312        }
13313        if (mParent != null && mParent instanceof ViewGroup) {
13314            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13315            return;
13316        }
13317        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13318    }
13319
13320    /**
13321     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13322     */
13323    protected void resetResolvedTextDirection() {
13324        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13325    }
13326
13327    //
13328    // Properties
13329    //
13330    /**
13331     * A Property wrapper around the <code>alpha</code> functionality handled by the
13332     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13333     */
13334    public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13335        @Override
13336        public void setValue(View object, float value) {
13337            object.setAlpha(value);
13338        }
13339
13340        @Override
13341        public Float get(View object) {
13342            return object.getAlpha();
13343        }
13344    };
13345
13346    /**
13347     * A Property wrapper around the <code>translationX</code> functionality handled by the
13348     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13349     */
13350    public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13351        @Override
13352        public void setValue(View object, float value) {
13353            object.setTranslationX(value);
13354        }
13355
13356                @Override
13357        public Float get(View object) {
13358            return object.getTranslationX();
13359        }
13360    };
13361
13362    /**
13363     * A Property wrapper around the <code>translationY</code> functionality handled by the
13364     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13365     */
13366    public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13367        @Override
13368        public void setValue(View object, float value) {
13369            object.setTranslationY(value);
13370        }
13371
13372        @Override
13373        public Float get(View object) {
13374            return object.getTranslationY();
13375        }
13376    };
13377
13378    /**
13379     * A Property wrapper around the <code>x</code> functionality handled by the
13380     * {@link View#setX(float)} and {@link View#getX()} methods.
13381     */
13382    public static Property<View, Float> X = new FloatProperty<View>("x") {
13383        @Override
13384        public void setValue(View object, float value) {
13385            object.setX(value);
13386        }
13387
13388        @Override
13389        public Float get(View object) {
13390            return object.getX();
13391        }
13392    };
13393
13394    /**
13395     * A Property wrapper around the <code>y</code> functionality handled by the
13396     * {@link View#setY(float)} and {@link View#getY()} methods.
13397     */
13398    public static Property<View, Float> Y = new FloatProperty<View>("y") {
13399        @Override
13400        public void setValue(View object, float value) {
13401            object.setY(value);
13402        }
13403
13404        @Override
13405        public Float get(View object) {
13406            return object.getY();
13407        }
13408    };
13409
13410    /**
13411     * A Property wrapper around the <code>rotation</code> functionality handled by the
13412     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13413     */
13414    public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13415        @Override
13416        public void setValue(View object, float value) {
13417            object.setRotation(value);
13418        }
13419
13420        @Override
13421        public Float get(View object) {
13422            return object.getRotation();
13423        }
13424    };
13425
13426    /**
13427     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13428     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13429     */
13430    public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13431        @Override
13432        public void setValue(View object, float value) {
13433            object.setRotationX(value);
13434        }
13435
13436        @Override
13437        public Float get(View object) {
13438            return object.getRotationX();
13439        }
13440    };
13441
13442    /**
13443     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13444     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13445     */
13446    public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13447        @Override
13448        public void setValue(View object, float value) {
13449            object.setRotationY(value);
13450        }
13451
13452        @Override
13453        public Float get(View object) {
13454            return object.getRotationY();
13455        }
13456    };
13457
13458    /**
13459     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13460     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13461     */
13462    public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13463        @Override
13464        public void setValue(View object, float value) {
13465            object.setScaleX(value);
13466        }
13467
13468        @Override
13469        public Float get(View object) {
13470            return object.getScaleX();
13471        }
13472    };
13473
13474    /**
13475     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13476     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13477     */
13478    public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13479        @Override
13480        public void setValue(View object, float value) {
13481            object.setScaleY(value);
13482        }
13483
13484        @Override
13485        public Float get(View object) {
13486            return object.getScaleY();
13487        }
13488    };
13489
13490    /**
13491     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13492     * Each MeasureSpec represents a requirement for either the width or the height.
13493     * A MeasureSpec is comprised of a size and a mode. There are three possible
13494     * modes:
13495     * <dl>
13496     * <dt>UNSPECIFIED</dt>
13497     * <dd>
13498     * The parent has not imposed any constraint on the child. It can be whatever size
13499     * it wants.
13500     * </dd>
13501     *
13502     * <dt>EXACTLY</dt>
13503     * <dd>
13504     * The parent has determined an exact size for the child. The child is going to be
13505     * given those bounds regardless of how big it wants to be.
13506     * </dd>
13507     *
13508     * <dt>AT_MOST</dt>
13509     * <dd>
13510     * The child can be as large as it wants up to the specified size.
13511     * </dd>
13512     * </dl>
13513     *
13514     * MeasureSpecs are implemented as ints to reduce object allocation. This class
13515     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
13516     */
13517    public static class MeasureSpec {
13518        private static final int MODE_SHIFT = 30;
13519        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
13520
13521        /**
13522         * Measure specification mode: The parent has not imposed any constraint
13523         * on the child. It can be whatever size it wants.
13524         */
13525        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
13526
13527        /**
13528         * Measure specification mode: The parent has determined an exact size
13529         * for the child. The child is going to be given those bounds regardless
13530         * of how big it wants to be.
13531         */
13532        public static final int EXACTLY     = 1 << MODE_SHIFT;
13533
13534        /**
13535         * Measure specification mode: The child can be as large as it wants up
13536         * to the specified size.
13537         */
13538        public static final int AT_MOST     = 2 << MODE_SHIFT;
13539
13540        /**
13541         * Creates a measure specification based on the supplied size and mode.
13542         *
13543         * The mode must always be one of the following:
13544         * <ul>
13545         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
13546         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
13547         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
13548         * </ul>
13549         *
13550         * @param size the size of the measure specification
13551         * @param mode the mode of the measure specification
13552         * @return the measure specification based on size and mode
13553         */
13554        public static int makeMeasureSpec(int size, int mode) {
13555            return size + mode;
13556        }
13557
13558        /**
13559         * Extracts the mode from the supplied measure specification.
13560         *
13561         * @param measureSpec the measure specification to extract the mode from
13562         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
13563         *         {@link android.view.View.MeasureSpec#AT_MOST} or
13564         *         {@link android.view.View.MeasureSpec#EXACTLY}
13565         */
13566        public static int getMode(int measureSpec) {
13567            return (measureSpec & MODE_MASK);
13568        }
13569
13570        /**
13571         * Extracts the size from the supplied measure specification.
13572         *
13573         * @param measureSpec the measure specification to extract the size from
13574         * @return the size in pixels defined in the supplied measure specification
13575         */
13576        public static int getSize(int measureSpec) {
13577            return (measureSpec & ~MODE_MASK);
13578        }
13579
13580        /**
13581         * Returns a String representation of the specified measure
13582         * specification.
13583         *
13584         * @param measureSpec the measure specification to convert to a String
13585         * @return a String with the following format: "MeasureSpec: MODE SIZE"
13586         */
13587        public static String toString(int measureSpec) {
13588            int mode = getMode(measureSpec);
13589            int size = getSize(measureSpec);
13590
13591            StringBuilder sb = new StringBuilder("MeasureSpec: ");
13592
13593            if (mode == UNSPECIFIED)
13594                sb.append("UNSPECIFIED ");
13595            else if (mode == EXACTLY)
13596                sb.append("EXACTLY ");
13597            else if (mode == AT_MOST)
13598                sb.append("AT_MOST ");
13599            else
13600                sb.append(mode).append(" ");
13601
13602            sb.append(size);
13603            return sb.toString();
13604        }
13605    }
13606
13607    class CheckForLongPress implements Runnable {
13608
13609        private int mOriginalWindowAttachCount;
13610
13611        public void run() {
13612            if (isPressed() && (mParent != null)
13613                    && mOriginalWindowAttachCount == mWindowAttachCount) {
13614                if (performLongClick()) {
13615                    mHasPerformedLongPress = true;
13616                }
13617            }
13618        }
13619
13620        public void rememberWindowAttachCount() {
13621            mOriginalWindowAttachCount = mWindowAttachCount;
13622        }
13623    }
13624
13625    private final class CheckForTap implements Runnable {
13626        public void run() {
13627            mPrivateFlags &= ~PREPRESSED;
13628            mPrivateFlags |= PRESSED;
13629            refreshDrawableState();
13630            checkForLongClick(ViewConfiguration.getTapTimeout());
13631        }
13632    }
13633
13634    private final class PerformClick implements Runnable {
13635        public void run() {
13636            performClick();
13637        }
13638    }
13639
13640    /** @hide */
13641    public void hackTurnOffWindowResizeAnim(boolean off) {
13642        mAttachInfo.mTurnOffWindowResizeAnim = off;
13643    }
13644
13645    /**
13646     * This method returns a ViewPropertyAnimator object, which can be used to animate
13647     * specific properties on this View.
13648     *
13649     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
13650     */
13651    public ViewPropertyAnimator animate() {
13652        if (mAnimator == null) {
13653            mAnimator = new ViewPropertyAnimator(this);
13654        }
13655        return mAnimator;
13656    }
13657
13658    /**
13659     * Interface definition for a callback to be invoked when a key event is
13660     * dispatched to this view. The callback will be invoked before the key
13661     * event is given to the view.
13662     */
13663    public interface OnKeyListener {
13664        /**
13665         * Called when a key is dispatched to a view. This allows listeners to
13666         * get a chance to respond before the target view.
13667         *
13668         * @param v The view the key has been dispatched to.
13669         * @param keyCode The code for the physical key that was pressed
13670         * @param event The KeyEvent object containing full information about
13671         *        the event.
13672         * @return True if the listener has consumed the event, false otherwise.
13673         */
13674        boolean onKey(View v, int keyCode, KeyEvent event);
13675    }
13676
13677    /**
13678     * Interface definition for a callback to be invoked when a touch event is
13679     * dispatched to this view. The callback will be invoked before the touch
13680     * event is given to the view.
13681     */
13682    public interface OnTouchListener {
13683        /**
13684         * Called when a touch event is dispatched to a view. This allows listeners to
13685         * get a chance to respond before the target view.
13686         *
13687         * @param v The view the touch event has been dispatched to.
13688         * @param event The MotionEvent object containing full information about
13689         *        the event.
13690         * @return True if the listener has consumed the event, false otherwise.
13691         */
13692        boolean onTouch(View v, MotionEvent event);
13693    }
13694
13695    /**
13696     * Interface definition for a callback to be invoked when a hover event is
13697     * dispatched to this view. The callback will be invoked before the hover
13698     * event is given to the view.
13699     */
13700    public interface OnHoverListener {
13701        /**
13702         * Called when a hover event is dispatched to a view. This allows listeners to
13703         * get a chance to respond before the target view.
13704         *
13705         * @param v The view the hover event has been dispatched to.
13706         * @param event The MotionEvent object containing full information about
13707         *        the event.
13708         * @return True if the listener has consumed the event, false otherwise.
13709         */
13710        boolean onHover(View v, MotionEvent event);
13711    }
13712
13713    /**
13714     * Interface definition for a callback to be invoked when a generic motion event is
13715     * dispatched to this view. The callback will be invoked before the generic motion
13716     * event is given to the view.
13717     */
13718    public interface OnGenericMotionListener {
13719        /**
13720         * Called when a generic motion event is dispatched to a view. This allows listeners to
13721         * get a chance to respond before the target view.
13722         *
13723         * @param v The view the generic motion event has been dispatched to.
13724         * @param event The MotionEvent object containing full information about
13725         *        the event.
13726         * @return True if the listener has consumed the event, false otherwise.
13727         */
13728        boolean onGenericMotion(View v, MotionEvent event);
13729    }
13730
13731    /**
13732     * Interface definition for a callback to be invoked when a view has been clicked and held.
13733     */
13734    public interface OnLongClickListener {
13735        /**
13736         * Called when a view has been clicked and held.
13737         *
13738         * @param v The view that was clicked and held.
13739         *
13740         * @return true if the callback consumed the long click, false otherwise.
13741         */
13742        boolean onLongClick(View v);
13743    }
13744
13745    /**
13746     * Interface definition for a callback to be invoked when a drag is being dispatched
13747     * to this view.  The callback will be invoked before the hosting view's own
13748     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
13749     * onDrag(event) behavior, it should return 'false' from this callback.
13750     */
13751    public interface OnDragListener {
13752        /**
13753         * Called when a drag event is dispatched to a view. This allows listeners
13754         * to get a chance to override base View behavior.
13755         *
13756         * @param v The View that received the drag event.
13757         * @param event The {@link android.view.DragEvent} object for the drag event.
13758         * @return {@code true} if the drag event was handled successfully, or {@code false}
13759         * if the drag event was not handled. Note that {@code false} will trigger the View
13760         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
13761         */
13762        boolean onDrag(View v, DragEvent event);
13763    }
13764
13765    /**
13766     * Interface definition for a callback to be invoked when the focus state of
13767     * a view changed.
13768     */
13769    public interface OnFocusChangeListener {
13770        /**
13771         * Called when the focus state of a view has changed.
13772         *
13773         * @param v The view whose state has changed.
13774         * @param hasFocus The new focus state of v.
13775         */
13776        void onFocusChange(View v, boolean hasFocus);
13777    }
13778
13779    /**
13780     * Interface definition for a callback to be invoked when a view is clicked.
13781     */
13782    public interface OnClickListener {
13783        /**
13784         * Called when a view has been clicked.
13785         *
13786         * @param v The view that was clicked.
13787         */
13788        void onClick(View v);
13789    }
13790
13791    /**
13792     * Interface definition for a callback to be invoked when the context menu
13793     * for this view is being built.
13794     */
13795    public interface OnCreateContextMenuListener {
13796        /**
13797         * Called when the context menu for this view is being built. It is not
13798         * safe to hold onto the menu after this method returns.
13799         *
13800         * @param menu The context menu that is being built
13801         * @param v The view for which the context menu is being built
13802         * @param menuInfo Extra information about the item for which the
13803         *            context menu should be shown. This information will vary
13804         *            depending on the class of v.
13805         */
13806        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
13807    }
13808
13809    /**
13810     * Interface definition for a callback to be invoked when the status bar changes
13811     * visibility.
13812     *
13813     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
13814     */
13815    public interface OnSystemUiVisibilityChangeListener {
13816        /**
13817         * Called when the status bar changes visibility because of a call to
13818         * {@link View#setSystemUiVisibility(int)}.
13819         *
13820         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13821         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13822         */
13823        public void onSystemUiVisibilityChange(int visibility);
13824    }
13825
13826    /**
13827     * Interface definition for a callback to be invoked when this view is attached
13828     * or detached from its window.
13829     */
13830    public interface OnAttachStateChangeListener {
13831        /**
13832         * Called when the view is attached to a window.
13833         * @param v The view that was attached
13834         */
13835        public void onViewAttachedToWindow(View v);
13836        /**
13837         * Called when the view is detached from a window.
13838         * @param v The view that was detached
13839         */
13840        public void onViewDetachedFromWindow(View v);
13841    }
13842
13843    private final class UnsetPressedState implements Runnable {
13844        public void run() {
13845            setPressed(false);
13846        }
13847    }
13848
13849    /**
13850     * Base class for derived classes that want to save and restore their own
13851     * state in {@link android.view.View#onSaveInstanceState()}.
13852     */
13853    public static class BaseSavedState extends AbsSavedState {
13854        /**
13855         * Constructor used when reading from a parcel. Reads the state of the superclass.
13856         *
13857         * @param source
13858         */
13859        public BaseSavedState(Parcel source) {
13860            super(source);
13861        }
13862
13863        /**
13864         * Constructor called by derived classes when creating their SavedState objects
13865         *
13866         * @param superState The state of the superclass of this view
13867         */
13868        public BaseSavedState(Parcelable superState) {
13869            super(superState);
13870        }
13871
13872        public static final Parcelable.Creator<BaseSavedState> CREATOR =
13873                new Parcelable.Creator<BaseSavedState>() {
13874            public BaseSavedState createFromParcel(Parcel in) {
13875                return new BaseSavedState(in);
13876            }
13877
13878            public BaseSavedState[] newArray(int size) {
13879                return new BaseSavedState[size];
13880            }
13881        };
13882    }
13883
13884    /**
13885     * A set of information given to a view when it is attached to its parent
13886     * window.
13887     */
13888    static class AttachInfo {
13889        interface Callbacks {
13890            void playSoundEffect(int effectId);
13891            boolean performHapticFeedback(int effectId, boolean always);
13892        }
13893
13894        /**
13895         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
13896         * to a Handler. This class contains the target (View) to invalidate and
13897         * the coordinates of the dirty rectangle.
13898         *
13899         * For performance purposes, this class also implements a pool of up to
13900         * POOL_LIMIT objects that get reused. This reduces memory allocations
13901         * whenever possible.
13902         */
13903        static class InvalidateInfo implements Poolable<InvalidateInfo> {
13904            private static final int POOL_LIMIT = 10;
13905            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
13906                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
13907                        public InvalidateInfo newInstance() {
13908                            return new InvalidateInfo();
13909                        }
13910
13911                        public void onAcquired(InvalidateInfo element) {
13912                        }
13913
13914                        public void onReleased(InvalidateInfo element) {
13915                            element.target = null;
13916                        }
13917                    }, POOL_LIMIT)
13918            );
13919
13920            private InvalidateInfo mNext;
13921            private boolean mIsPooled;
13922
13923            View target;
13924
13925            int left;
13926            int top;
13927            int right;
13928            int bottom;
13929
13930            public void setNextPoolable(InvalidateInfo element) {
13931                mNext = element;
13932            }
13933
13934            public InvalidateInfo getNextPoolable() {
13935                return mNext;
13936            }
13937
13938            static InvalidateInfo acquire() {
13939                return sPool.acquire();
13940            }
13941
13942            void release() {
13943                sPool.release(this);
13944            }
13945
13946            public boolean isPooled() {
13947                return mIsPooled;
13948            }
13949
13950            public void setPooled(boolean isPooled) {
13951                mIsPooled = isPooled;
13952            }
13953        }
13954
13955        final IWindowSession mSession;
13956
13957        final IWindow mWindow;
13958
13959        final IBinder mWindowToken;
13960
13961        final Callbacks mRootCallbacks;
13962
13963        HardwareCanvas mHardwareCanvas;
13964
13965        /**
13966         * The top view of the hierarchy.
13967         */
13968        View mRootView;
13969
13970        IBinder mPanelParentWindowToken;
13971        Surface mSurface;
13972
13973        boolean mHardwareAccelerated;
13974        boolean mHardwareAccelerationRequested;
13975        HardwareRenderer mHardwareRenderer;
13976
13977        /**
13978         * Scale factor used by the compatibility mode
13979         */
13980        float mApplicationScale;
13981
13982        /**
13983         * Indicates whether the application is in compatibility mode
13984         */
13985        boolean mScalingRequired;
13986
13987        /**
13988         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
13989         */
13990        boolean mTurnOffWindowResizeAnim;
13991
13992        /**
13993         * Left position of this view's window
13994         */
13995        int mWindowLeft;
13996
13997        /**
13998         * Top position of this view's window
13999         */
14000        int mWindowTop;
14001
14002        /**
14003         * Indicates whether views need to use 32-bit drawing caches
14004         */
14005        boolean mUse32BitDrawingCache;
14006
14007        /**
14008         * For windows that are full-screen but using insets to layout inside
14009         * of the screen decorations, these are the current insets for the
14010         * content of the window.
14011         */
14012        final Rect mContentInsets = new Rect();
14013
14014        /**
14015         * For windows that are full-screen but using insets to layout inside
14016         * of the screen decorations, these are the current insets for the
14017         * actual visible parts of the window.
14018         */
14019        final Rect mVisibleInsets = new Rect();
14020
14021        /**
14022         * The internal insets given by this window.  This value is
14023         * supplied by the client (through
14024         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14025         * be given to the window manager when changed to be used in laying
14026         * out windows behind it.
14027         */
14028        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14029                = new ViewTreeObserver.InternalInsetsInfo();
14030
14031        /**
14032         * All views in the window's hierarchy that serve as scroll containers,
14033         * used to determine if the window can be resized or must be panned
14034         * to adjust for a soft input area.
14035         */
14036        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14037
14038        final KeyEvent.DispatcherState mKeyDispatchState
14039                = new KeyEvent.DispatcherState();
14040
14041        /**
14042         * Indicates whether the view's window currently has the focus.
14043         */
14044        boolean mHasWindowFocus;
14045
14046        /**
14047         * The current visibility of the window.
14048         */
14049        int mWindowVisibility;
14050
14051        /**
14052         * Indicates the time at which drawing started to occur.
14053         */
14054        long mDrawingTime;
14055
14056        /**
14057         * Indicates whether or not ignoring the DIRTY_MASK flags.
14058         */
14059        boolean mIgnoreDirtyState;
14060
14061        /**
14062         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14063         * to avoid clearing that flag prematurely.
14064         */
14065        boolean mSetIgnoreDirtyState = false;
14066
14067        /**
14068         * Indicates whether the view's window is currently in touch mode.
14069         */
14070        boolean mInTouchMode;
14071
14072        /**
14073         * Indicates that ViewAncestor should trigger a global layout change
14074         * the next time it performs a traversal
14075         */
14076        boolean mRecomputeGlobalAttributes;
14077
14078        /**
14079         * Set during a traveral if any views want to keep the screen on.
14080         */
14081        boolean mKeepScreenOn;
14082
14083        /**
14084         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14085         */
14086        int mSystemUiVisibility;
14087
14088        /**
14089         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14090         * attached.
14091         */
14092        boolean mHasSystemUiListeners;
14093
14094        /**
14095         * Set if the visibility of any views has changed.
14096         */
14097        boolean mViewVisibilityChanged;
14098
14099        /**
14100         * Set to true if a view has been scrolled.
14101         */
14102        boolean mViewScrollChanged;
14103
14104        /**
14105         * Global to the view hierarchy used as a temporary for dealing with
14106         * x/y points in the transparent region computations.
14107         */
14108        final int[] mTransparentLocation = new int[2];
14109
14110        /**
14111         * Global to the view hierarchy used as a temporary for dealing with
14112         * x/y points in the ViewGroup.invalidateChild implementation.
14113         */
14114        final int[] mInvalidateChildLocation = new int[2];
14115
14116
14117        /**
14118         * Global to the view hierarchy used as a temporary for dealing with
14119         * x/y location when view is transformed.
14120         */
14121        final float[] mTmpTransformLocation = new float[2];
14122
14123        /**
14124         * The view tree observer used to dispatch global events like
14125         * layout, pre-draw, touch mode change, etc.
14126         */
14127        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14128
14129        /**
14130         * A Canvas used by the view hierarchy to perform bitmap caching.
14131         */
14132        Canvas mCanvas;
14133
14134        /**
14135         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14136         * handler can be used to pump events in the UI events queue.
14137         */
14138        final Handler mHandler;
14139
14140        /**
14141         * Identifier for messages requesting the view to be invalidated.
14142         * Such messages should be sent to {@link #mHandler}.
14143         */
14144        static final int INVALIDATE_MSG = 0x1;
14145
14146        /**
14147         * Identifier for messages requesting the view to invalidate a region.
14148         * Such messages should be sent to {@link #mHandler}.
14149         */
14150        static final int INVALIDATE_RECT_MSG = 0x2;
14151
14152        /**
14153         * Temporary for use in computing invalidate rectangles while
14154         * calling up the hierarchy.
14155         */
14156        final Rect mTmpInvalRect = new Rect();
14157
14158        /**
14159         * Temporary for use in computing hit areas with transformed views
14160         */
14161        final RectF mTmpTransformRect = new RectF();
14162
14163        /**
14164         * Temporary list for use in collecting focusable descendents of a view.
14165         */
14166        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14167
14168        /**
14169         * The id of the window for accessibility purposes.
14170         */
14171        int mAccessibilityWindowId = View.NO_ID;
14172
14173        /**
14174         * Creates a new set of attachment information with the specified
14175         * events handler and thread.
14176         *
14177         * @param handler the events handler the view must use
14178         */
14179        AttachInfo(IWindowSession session, IWindow window,
14180                Handler handler, Callbacks effectPlayer) {
14181            mSession = session;
14182            mWindow = window;
14183            mWindowToken = window.asBinder();
14184            mHandler = handler;
14185            mRootCallbacks = effectPlayer;
14186        }
14187    }
14188
14189    /**
14190     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14191     * is supported. This avoids keeping too many unused fields in most
14192     * instances of View.</p>
14193     */
14194    private static class ScrollabilityCache implements Runnable {
14195
14196        /**
14197         * Scrollbars are not visible
14198         */
14199        public static final int OFF = 0;
14200
14201        /**
14202         * Scrollbars are visible
14203         */
14204        public static final int ON = 1;
14205
14206        /**
14207         * Scrollbars are fading away
14208         */
14209        public static final int FADING = 2;
14210
14211        public boolean fadeScrollBars;
14212
14213        public int fadingEdgeLength;
14214        public int scrollBarDefaultDelayBeforeFade;
14215        public int scrollBarFadeDuration;
14216
14217        public int scrollBarSize;
14218        public ScrollBarDrawable scrollBar;
14219        public float[] interpolatorValues;
14220        public View host;
14221
14222        public final Paint paint;
14223        public final Matrix matrix;
14224        public Shader shader;
14225
14226        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14227
14228        private static final float[] OPAQUE = { 255 };
14229        private static final float[] TRANSPARENT = { 0.0f };
14230
14231        /**
14232         * When fading should start. This time moves into the future every time
14233         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14234         */
14235        public long fadeStartTime;
14236
14237
14238        /**
14239         * The current state of the scrollbars: ON, OFF, or FADING
14240         */
14241        public int state = OFF;
14242
14243        private int mLastColor;
14244
14245        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14246            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14247            scrollBarSize = configuration.getScaledScrollBarSize();
14248            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14249            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14250
14251            paint = new Paint();
14252            matrix = new Matrix();
14253            // use use a height of 1, and then wack the matrix each time we
14254            // actually use it.
14255            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14256
14257            paint.setShader(shader);
14258            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14259            this.host = host;
14260        }
14261
14262        public void setFadeColor(int color) {
14263            if (color != 0 && color != mLastColor) {
14264                mLastColor = color;
14265                color |= 0xFF000000;
14266
14267                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14268                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14269
14270                paint.setShader(shader);
14271                // Restore the default transfer mode (src_over)
14272                paint.setXfermode(null);
14273            }
14274        }
14275
14276        public void run() {
14277            long now = AnimationUtils.currentAnimationTimeMillis();
14278            if (now >= fadeStartTime) {
14279
14280                // the animation fades the scrollbars out by changing
14281                // the opacity (alpha) from fully opaque to fully
14282                // transparent
14283                int nextFrame = (int) now;
14284                int framesCount = 0;
14285
14286                Interpolator interpolator = scrollBarInterpolator;
14287
14288                // Start opaque
14289                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14290
14291                // End transparent
14292                nextFrame += scrollBarFadeDuration;
14293                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14294
14295                state = FADING;
14296
14297                // Kick off the fade animation
14298                host.invalidate(true);
14299            }
14300        }
14301    }
14302
14303    /**
14304     * Resuable callback for sending
14305     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14306     */
14307    private class SendViewScrolledAccessibilityEvent implements Runnable {
14308        public volatile boolean mIsPending;
14309
14310        public void run() {
14311            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14312            mIsPending = false;
14313        }
14314    }
14315}
14316