View.java revision f186f30a7cbbf84e9b7ef52403d77f252b5229ed
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.Callback, Drawable.Callback2, KeyEvent.Callback,
640        AccessibilityEventSource {
641    private static final boolean DBG = false;
642
643    /**
644     * The logging tag used by this class with android.util.Log.
645     */
646    protected static final String VIEW_LOG_TAG = "View";
647
648    /**
649     * Used to mark a View that has no ID.
650     */
651    public static final int NO_ID = -1;
652
653    /**
654     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
655     * calling setFlags.
656     */
657    private static final int NOT_FOCUSABLE = 0x00000000;
658
659    /**
660     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
661     * setFlags.
662     */
663    private static final int FOCUSABLE = 0x00000001;
664
665    /**
666     * Mask for use with setFlags indicating bits used for focus.
667     */
668    private static final int FOCUSABLE_MASK = 0x00000001;
669
670    /**
671     * This view will adjust its padding to fit sytem windows (e.g. status bar)
672     */
673    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
674
675    /**
676     * This view is visible.
677     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
678     * android:visibility}.
679     */
680    public static final int VISIBLE = 0x00000000;
681
682    /**
683     * This view is invisible, but it still takes up space for layout purposes.
684     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
685     * android:visibility}.
686     */
687    public static final int INVISIBLE = 0x00000004;
688
689    /**
690     * This view is invisible, and it doesn't take any space for layout
691     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
692     * android:visibility}.
693     */
694    public static final int GONE = 0x00000008;
695
696    /**
697     * Mask for use with setFlags indicating bits used for visibility.
698     * {@hide}
699     */
700    static final int VISIBILITY_MASK = 0x0000000C;
701
702    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
703
704    /**
705     * This view is enabled. Intrepretation varies by subclass.
706     * Use with ENABLED_MASK when calling setFlags.
707     * {@hide}
708     */
709    static final int ENABLED = 0x00000000;
710
711    /**
712     * This view is disabled. Intrepretation varies by subclass.
713     * Use with ENABLED_MASK when calling setFlags.
714     * {@hide}
715     */
716    static final int DISABLED = 0x00000020;
717
718   /**
719    * Mask for use with setFlags indicating bits used for indicating whether
720    * this view is enabled
721    * {@hide}
722    */
723    static final int ENABLED_MASK = 0x00000020;
724
725    /**
726     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
727     * called and further optimizations will be performed. It is okay to have
728     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
729     * {@hide}
730     */
731    static final int WILL_NOT_DRAW = 0x00000080;
732
733    /**
734     * Mask for use with setFlags indicating bits used for indicating whether
735     * this view is will draw
736     * {@hide}
737     */
738    static final int DRAW_MASK = 0x00000080;
739
740    /**
741     * <p>This view doesn't show scrollbars.</p>
742     * {@hide}
743     */
744    static final int SCROLLBARS_NONE = 0x00000000;
745
746    /**
747     * <p>This view shows horizontal scrollbars.</p>
748     * {@hide}
749     */
750    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
751
752    /**
753     * <p>This view shows vertical scrollbars.</p>
754     * {@hide}
755     */
756    static final int SCROLLBARS_VERTICAL = 0x00000200;
757
758    /**
759     * <p>Mask for use with setFlags indicating bits used for indicating which
760     * scrollbars are enabled.</p>
761     * {@hide}
762     */
763    static final int SCROLLBARS_MASK = 0x00000300;
764
765    /**
766     * Indicates that the view should filter touches when its window is obscured.
767     * Refer to the class comments for more information about this security feature.
768     * {@hide}
769     */
770    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
771
772    // note flag value 0x00000800 is now available for next flags...
773
774    /**
775     * <p>This view doesn't show fading edges.</p>
776     * {@hide}
777     */
778    static final int FADING_EDGE_NONE = 0x00000000;
779
780    /**
781     * <p>This view shows horizontal fading edges.</p>
782     * {@hide}
783     */
784    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
785
786    /**
787     * <p>This view shows vertical fading edges.</p>
788     * {@hide}
789     */
790    static final int FADING_EDGE_VERTICAL = 0x00002000;
791
792    /**
793     * <p>Mask for use with setFlags indicating bits used for indicating which
794     * fading edges are enabled.</p>
795     * {@hide}
796     */
797    static final int FADING_EDGE_MASK = 0x00003000;
798
799    /**
800     * <p>Indicates this view can be clicked. When clickable, a View reacts
801     * to clicks by notifying the OnClickListener.<p>
802     * {@hide}
803     */
804    static final int CLICKABLE = 0x00004000;
805
806    /**
807     * <p>Indicates this view is caching its drawing into a bitmap.</p>
808     * {@hide}
809     */
810    static final int DRAWING_CACHE_ENABLED = 0x00008000;
811
812    /**
813     * <p>Indicates that no icicle should be saved for this view.<p>
814     * {@hide}
815     */
816    static final int SAVE_DISABLED = 0x000010000;
817
818    /**
819     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
820     * property.</p>
821     * {@hide}
822     */
823    static final int SAVE_DISABLED_MASK = 0x000010000;
824
825    /**
826     * <p>Indicates that no drawing cache should ever be created for this view.<p>
827     * {@hide}
828     */
829    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
830
831    /**
832     * <p>Indicates this view can take / keep focus when int touch mode.</p>
833     * {@hide}
834     */
835    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
836
837    /**
838     * <p>Enables low quality mode for the drawing cache.</p>
839     */
840    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
841
842    /**
843     * <p>Enables high quality mode for the drawing cache.</p>
844     */
845    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
846
847    /**
848     * <p>Enables automatic quality mode for the drawing cache.</p>
849     */
850    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
851
852    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
853            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
854    };
855
856    /**
857     * <p>Mask for use with setFlags indicating bits used for the cache
858     * quality property.</p>
859     * {@hide}
860     */
861    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
862
863    /**
864     * <p>
865     * Indicates this view can be long clicked. When long clickable, a View
866     * reacts to long clicks by notifying the OnLongClickListener or showing a
867     * context menu.
868     * </p>
869     * {@hide}
870     */
871    static final int LONG_CLICKABLE = 0x00200000;
872
873    /**
874     * <p>Indicates that this view gets its drawable states from its direct parent
875     * and ignores its original internal states.</p>
876     *
877     * @hide
878     */
879    static final int DUPLICATE_PARENT_STATE = 0x00400000;
880
881    /**
882     * The scrollbar style to display the scrollbars inside the content area,
883     * without increasing the padding. The scrollbars will be overlaid with
884     * translucency on the view's content.
885     */
886    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
887
888    /**
889     * The scrollbar style to display the scrollbars inside the padded area,
890     * increasing the padding of the view. The scrollbars will not overlap the
891     * content area of the view.
892     */
893    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
894
895    /**
896     * The scrollbar style to display the scrollbars at the edge of the view,
897     * without increasing the padding. The scrollbars will be overlaid with
898     * translucency.
899     */
900    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
901
902    /**
903     * The scrollbar style to display the scrollbars at the edge of the view,
904     * increasing the padding of the view. The scrollbars will only overlap the
905     * background, if any.
906     */
907    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
908
909    /**
910     * Mask to check if the scrollbar style is overlay or inset.
911     * {@hide}
912     */
913    static final int SCROLLBARS_INSET_MASK = 0x01000000;
914
915    /**
916     * Mask to check if the scrollbar style is inside or outside.
917     * {@hide}
918     */
919    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
920
921    /**
922     * Mask for scrollbar style.
923     * {@hide}
924     */
925    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
926
927    /**
928     * View flag indicating that the screen should remain on while the
929     * window containing this view is visible to the user.  This effectively
930     * takes care of automatically setting the WindowManager's
931     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
932     */
933    public static final int KEEP_SCREEN_ON = 0x04000000;
934
935    /**
936     * View flag indicating whether this view should have sound effects enabled
937     * for events such as clicking and touching.
938     */
939    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
940
941    /**
942     * View flag indicating whether this view should have haptic feedback
943     * enabled for events such as long presses.
944     */
945    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
946
947    /**
948     * <p>Indicates that the view hierarchy should stop saving state when
949     * it reaches this view.  If state saving is initiated immediately at
950     * the view, it will be allowed.
951     * {@hide}
952     */
953    static final int PARENT_SAVE_DISABLED = 0x20000000;
954
955    /**
956     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
957     * {@hide}
958     */
959    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
960
961    /**
962     * Horizontal direction of this view is from Left to Right.
963     * Use with {@link #setLayoutDirection}.
964     * {@hide}
965     */
966    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
967
968    /**
969     * Horizontal direction of this view is from Right to Left.
970     * Use with {@link #setLayoutDirection}.
971     * {@hide}
972     */
973    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
974
975    /**
976     * Horizontal direction of this view is inherited from its parent.
977     * Use with {@link #setLayoutDirection}.
978     * {@hide}
979     */
980    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
981
982    /**
983     * Horizontal direction of this view is from deduced from the default language
984     * script for the locale. Use with {@link #setLayoutDirection}.
985     * {@hide}
986     */
987    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
988
989    /**
990     * Mask for use with setFlags indicating bits used for horizontalDirection.
991     * {@hide}
992     */
993    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
994
995    /*
996     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
997     * flag value.
998     * {@hide}
999     */
1000    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
1001        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
1002
1003    /**
1004     * Default horizontalDirection.
1005     * {@hide}
1006     */
1007    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add all focusable Views regardless if they are focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_ALL = 0x00000000;
1014
1015    /**
1016     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1017     * should add only Views focusable in touch mode.
1018     */
1019    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1023     * item.
1024     */
1025    public static final int FOCUS_BACKWARD = 0x00000001;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1029     * item.
1030     */
1031    public static final int FOCUS_FORWARD = 0x00000002;
1032
1033    /**
1034     * Use with {@link #focusSearch(int)}. Move focus to the left.
1035     */
1036    public static final int FOCUS_LEFT = 0x00000011;
1037
1038    /**
1039     * Use with {@link #focusSearch(int)}. Move focus up.
1040     */
1041    public static final int FOCUS_UP = 0x00000021;
1042
1043    /**
1044     * Use with {@link #focusSearch(int)}. Move focus to the right.
1045     */
1046    public static final int FOCUS_RIGHT = 0x00000042;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move focus down.
1050     */
1051    public static final int FOCUS_DOWN = 0x00000082;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1056     */
1057    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1058
1059    /**
1060     * Bits of {@link #getMeasuredWidthAndState()} and
1061     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1062     */
1063    public static final int MEASURED_STATE_MASK = 0xff000000;
1064
1065    /**
1066     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1067     * for functions that combine both width and height into a single int,
1068     * such as {@link #getMeasuredState()} and the childState argument of
1069     * {@link #resolveSizeAndState(int, int, int)}.
1070     */
1071    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1072
1073    /**
1074     * Bit of {@link #getMeasuredWidthAndState()} and
1075     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1076     * is smaller that the space the view would like to have.
1077     */
1078    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1079
1080    /**
1081     * Base View state sets
1082     */
1083    // Singles
1084    /**
1085     * Indicates the view has no states set. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] EMPTY_STATE_SET;
1093    /**
1094     * Indicates the view is enabled. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] ENABLED_STATE_SET;
1102    /**
1103     * Indicates the view is focused. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] FOCUSED_STATE_SET;
1111    /**
1112     * Indicates the view is selected. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     */
1119    protected static final int[] SELECTED_STATE_SET;
1120    /**
1121     * Indicates the view is pressed. States are used with
1122     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1123     * view depending on its state.
1124     *
1125     * @see android.graphics.drawable.Drawable
1126     * @see #getDrawableState()
1127     * @hide
1128     */
1129    protected static final int[] PRESSED_STATE_SET;
1130    /**
1131     * Indicates the view's window has focus. States are used with
1132     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1133     * view depending on its state.
1134     *
1135     * @see android.graphics.drawable.Drawable
1136     * @see #getDrawableState()
1137     */
1138    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1139    // Doubles
1140    /**
1141     * Indicates the view is enabled and has the focus.
1142     *
1143     * @see #ENABLED_STATE_SET
1144     * @see #FOCUSED_STATE_SET
1145     */
1146    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1147    /**
1148     * Indicates the view is enabled and selected.
1149     *
1150     * @see #ENABLED_STATE_SET
1151     * @see #SELECTED_STATE_SET
1152     */
1153    protected static final int[] ENABLED_SELECTED_STATE_SET;
1154    /**
1155     * Indicates the view is enabled and that its window has focus.
1156     *
1157     * @see #ENABLED_STATE_SET
1158     * @see #WINDOW_FOCUSED_STATE_SET
1159     */
1160    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1161    /**
1162     * Indicates the view is focused and selected.
1163     *
1164     * @see #FOCUSED_STATE_SET
1165     * @see #SELECTED_STATE_SET
1166     */
1167    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1168    /**
1169     * Indicates the view has the focus and that its window has the focus.
1170     *
1171     * @see #FOCUSED_STATE_SET
1172     * @see #WINDOW_FOCUSED_STATE_SET
1173     */
1174    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1175    /**
1176     * Indicates the view is selected and that its window has the focus.
1177     *
1178     * @see #SELECTED_STATE_SET
1179     * @see #WINDOW_FOCUSED_STATE_SET
1180     */
1181    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1182    // Triples
1183    /**
1184     * Indicates the view is enabled, focused and selected.
1185     *
1186     * @see #ENABLED_STATE_SET
1187     * @see #FOCUSED_STATE_SET
1188     * @see #SELECTED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1191    /**
1192     * Indicates the view is enabled, focused and its window has the focus.
1193     *
1194     * @see #ENABLED_STATE_SET
1195     * @see #FOCUSED_STATE_SET
1196     * @see #WINDOW_FOCUSED_STATE_SET
1197     */
1198    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1199    /**
1200     * Indicates the view is enabled, selected and its window has the focus.
1201     *
1202     * @see #ENABLED_STATE_SET
1203     * @see #SELECTED_STATE_SET
1204     * @see #WINDOW_FOCUSED_STATE_SET
1205     */
1206    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1207    /**
1208     * Indicates the view is focused, selected and its window has the focus.
1209     *
1210     * @see #FOCUSED_STATE_SET
1211     * @see #SELECTED_STATE_SET
1212     * @see #WINDOW_FOCUSED_STATE_SET
1213     */
1214    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1215    /**
1216     * Indicates the view is enabled, focused, selected and its window
1217     * has the focus.
1218     *
1219     * @see #ENABLED_STATE_SET
1220     * @see #FOCUSED_STATE_SET
1221     * @see #SELECTED_STATE_SET
1222     * @see #WINDOW_FOCUSED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1225    /**
1226     * Indicates the view is pressed and its window has the focus.
1227     *
1228     * @see #PRESSED_STATE_SET
1229     * @see #WINDOW_FOCUSED_STATE_SET
1230     */
1231    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1232    /**
1233     * Indicates the view is pressed and selected.
1234     *
1235     * @see #PRESSED_STATE_SET
1236     * @see #SELECTED_STATE_SET
1237     */
1238    protected static final int[] PRESSED_SELECTED_STATE_SET;
1239    /**
1240     * Indicates the view is pressed, selected and its window has the focus.
1241     *
1242     * @see #PRESSED_STATE_SET
1243     * @see #SELECTED_STATE_SET
1244     * @see #WINDOW_FOCUSED_STATE_SET
1245     */
1246    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1247    /**
1248     * Indicates the view is pressed and focused.
1249     *
1250     * @see #PRESSED_STATE_SET
1251     * @see #FOCUSED_STATE_SET
1252     */
1253    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1254    /**
1255     * Indicates the view is pressed, focused and its window has the focus.
1256     *
1257     * @see #PRESSED_STATE_SET
1258     * @see #FOCUSED_STATE_SET
1259     * @see #WINDOW_FOCUSED_STATE_SET
1260     */
1261    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1262    /**
1263     * Indicates the view is pressed, focused and selected.
1264     *
1265     * @see #PRESSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     * @see #FOCUSED_STATE_SET
1268     */
1269    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1270    /**
1271     * Indicates the view is pressed, focused, selected and its window has the focus.
1272     *
1273     * @see #PRESSED_STATE_SET
1274     * @see #FOCUSED_STATE_SET
1275     * @see #SELECTED_STATE_SET
1276     * @see #WINDOW_FOCUSED_STATE_SET
1277     */
1278    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1279    /**
1280     * Indicates the view is pressed and enabled.
1281     *
1282     * @see #PRESSED_STATE_SET
1283     * @see #ENABLED_STATE_SET
1284     */
1285    protected static final int[] PRESSED_ENABLED_STATE_SET;
1286    /**
1287     * Indicates the view is pressed, enabled and its window has the focus.
1288     *
1289     * @see #PRESSED_STATE_SET
1290     * @see #ENABLED_STATE_SET
1291     * @see #WINDOW_FOCUSED_STATE_SET
1292     */
1293    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1294    /**
1295     * Indicates the view is pressed, enabled and selected.
1296     *
1297     * @see #PRESSED_STATE_SET
1298     * @see #ENABLED_STATE_SET
1299     * @see #SELECTED_STATE_SET
1300     */
1301    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1302    /**
1303     * Indicates the view is pressed, enabled, selected and its window has the
1304     * focus.
1305     *
1306     * @see #PRESSED_STATE_SET
1307     * @see #ENABLED_STATE_SET
1308     * @see #SELECTED_STATE_SET
1309     * @see #WINDOW_FOCUSED_STATE_SET
1310     */
1311    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1312    /**
1313     * Indicates the view is pressed, enabled and focused.
1314     *
1315     * @see #PRESSED_STATE_SET
1316     * @see #ENABLED_STATE_SET
1317     * @see #FOCUSED_STATE_SET
1318     */
1319    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1320    /**
1321     * Indicates the view is pressed, enabled, focused and its window has the
1322     * focus.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #ENABLED_STATE_SET
1326     * @see #FOCUSED_STATE_SET
1327     * @see #WINDOW_FOCUSED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed, enabled, focused and selected.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #ENABLED_STATE_SET
1335     * @see #SELECTED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed, enabled, focused, selected and its window
1341     * has the focus.
1342     *
1343     * @see #PRESSED_STATE_SET
1344     * @see #ENABLED_STATE_SET
1345     * @see #SELECTED_STATE_SET
1346     * @see #FOCUSED_STATE_SET
1347     * @see #WINDOW_FOCUSED_STATE_SET
1348     */
1349    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1350
1351    /**
1352     * The order here is very important to {@link #getDrawableState()}
1353     */
1354    private static final int[][] VIEW_STATE_SETS;
1355
1356    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1357    static final int VIEW_STATE_SELECTED = 1 << 1;
1358    static final int VIEW_STATE_FOCUSED = 1 << 2;
1359    static final int VIEW_STATE_ENABLED = 1 << 3;
1360    static final int VIEW_STATE_PRESSED = 1 << 4;
1361    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1362    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1363    static final int VIEW_STATE_HOVERED = 1 << 7;
1364    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1365    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1366
1367    static final int[] VIEW_STATE_IDS = new int[] {
1368        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1369        R.attr.state_selected,          VIEW_STATE_SELECTED,
1370        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1371        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1372        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1373        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1374        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1375        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1376        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1377        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1378    };
1379
1380    static {
1381        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1382            throw new IllegalStateException(
1383                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1384        }
1385        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1386        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1387            int viewState = R.styleable.ViewDrawableStates[i];
1388            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1389                if (VIEW_STATE_IDS[j] == viewState) {
1390                    orderedIds[i * 2] = viewState;
1391                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1392                }
1393            }
1394        }
1395        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1396        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1397        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1398            int numBits = Integer.bitCount(i);
1399            int[] set = new int[numBits];
1400            int pos = 0;
1401            for (int j = 0; j < orderedIds.length; j += 2) {
1402                if ((i & orderedIds[j+1]) != 0) {
1403                    set[pos++] = orderedIds[j];
1404                }
1405            }
1406            VIEW_STATE_SETS[i] = set;
1407        }
1408
1409        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1410        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1411        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1412        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1414        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1415        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1417        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1419        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421                | VIEW_STATE_FOCUSED];
1422        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1423        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1425        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1427        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1429                | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1432        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1434                | VIEW_STATE_ENABLED];
1435        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1436                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1437                | VIEW_STATE_ENABLED];
1438        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1439                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1440                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1441
1442        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1443        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1445        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1447        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1449                | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1452        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1454                | VIEW_STATE_PRESSED];
1455        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1457                | VIEW_STATE_PRESSED];
1458        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1459                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1460                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1465                | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1468                | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1471                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1472        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1474                | VIEW_STATE_PRESSED];
1475        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1477                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1478        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1479                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1480                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1481        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1483                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1484                | VIEW_STATE_PRESSED];
1485    }
1486
1487    /**
1488     * Temporary Rect currently for use in setBackground().  This will probably
1489     * be extended in the future to hold our own class with more than just
1490     * a Rect. :)
1491     */
1492    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1493
1494    /**
1495     * Map used to store views' tags.
1496     */
1497    private static WeakHashMap<View, SparseArray<Object>> sTags;
1498
1499    /**
1500     * Lock used to access sTags.
1501     */
1502    private static final Object sTagsLock = new Object();
1503
1504    /**
1505     * The next available accessiiblity id.
1506     */
1507    private static int sNextAccessibilityViewId;
1508
1509    /**
1510     * The animation currently associated with this view.
1511     * @hide
1512     */
1513    protected Animation mCurrentAnimation = null;
1514
1515    /**
1516     * Width as measured during measure pass.
1517     * {@hide}
1518     */
1519    @ViewDebug.ExportedProperty(category = "measurement")
1520    int mMeasuredWidth;
1521
1522    /**
1523     * Height as measured during measure pass.
1524     * {@hide}
1525     */
1526    @ViewDebug.ExportedProperty(category = "measurement")
1527    int mMeasuredHeight;
1528
1529    /**
1530     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1531     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1532     * its display list. This flag, used only when hw accelerated, allows us to clear the
1533     * flag while retaining this information until it's needed (at getDisplayList() time and
1534     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1535     *
1536     * {@hide}
1537     */
1538    boolean mRecreateDisplayList = false;
1539
1540    /**
1541     * The view's identifier.
1542     * {@hide}
1543     *
1544     * @see #setId(int)
1545     * @see #getId()
1546     */
1547    @ViewDebug.ExportedProperty(resolveId = true)
1548    int mID = NO_ID;
1549
1550    /**
1551     * The stable ID of this view for accessibility porposes.
1552     */
1553    int mAccessibilityViewId = NO_ID;
1554
1555    /**
1556     * The view's tag.
1557     * {@hide}
1558     *
1559     * @see #setTag(Object)
1560     * @see #getTag()
1561     */
1562    protected Object mTag;
1563
1564    // for mPrivateFlags:
1565    /** {@hide} */
1566    static final int WANTS_FOCUS                    = 0x00000001;
1567    /** {@hide} */
1568    static final int FOCUSED                        = 0x00000002;
1569    /** {@hide} */
1570    static final int SELECTED                       = 0x00000004;
1571    /** {@hide} */
1572    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1573    /** {@hide} */
1574    static final int HAS_BOUNDS                     = 0x00000010;
1575    /** {@hide} */
1576    static final int DRAWN                          = 0x00000020;
1577    /**
1578     * When this flag is set, this view is running an animation on behalf of its
1579     * children and should therefore not cancel invalidate requests, even if they
1580     * lie outside of this view's bounds.
1581     *
1582     * {@hide}
1583     */
1584    static final int DRAW_ANIMATION                 = 0x00000040;
1585    /** {@hide} */
1586    static final int SKIP_DRAW                      = 0x00000080;
1587    /** {@hide} */
1588    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1589    /** {@hide} */
1590    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1591    /** {@hide} */
1592    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1593    /** {@hide} */
1594    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1595    /** {@hide} */
1596    static final int FORCE_LAYOUT                   = 0x00001000;
1597    /** {@hide} */
1598    static final int LAYOUT_REQUIRED                = 0x00002000;
1599
1600    private static final int PRESSED                = 0x00004000;
1601
1602    /** {@hide} */
1603    static final int DRAWING_CACHE_VALID            = 0x00008000;
1604    /**
1605     * Flag used to indicate that this view should be drawn once more (and only once
1606     * more) after its animation has completed.
1607     * {@hide}
1608     */
1609    static final int ANIMATION_STARTED              = 0x00010000;
1610
1611    private static final int SAVE_STATE_CALLED      = 0x00020000;
1612
1613    /**
1614     * Indicates that the View returned true when onSetAlpha() was called and that
1615     * the alpha must be restored.
1616     * {@hide}
1617     */
1618    static final int ALPHA_SET                      = 0x00040000;
1619
1620    /**
1621     * Set by {@link #setScrollContainer(boolean)}.
1622     */
1623    static final int SCROLL_CONTAINER               = 0x00080000;
1624
1625    /**
1626     * Set by {@link #setScrollContainer(boolean)}.
1627     */
1628    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1629
1630    /**
1631     * View flag indicating whether this view was invalidated (fully or partially.)
1632     *
1633     * @hide
1634     */
1635    static final int DIRTY                          = 0x00200000;
1636
1637    /**
1638     * View flag indicating whether this view was invalidated by an opaque
1639     * invalidate request.
1640     *
1641     * @hide
1642     */
1643    static final int DIRTY_OPAQUE                   = 0x00400000;
1644
1645    /**
1646     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1647     *
1648     * @hide
1649     */
1650    static final int DIRTY_MASK                     = 0x00600000;
1651
1652    /**
1653     * Indicates whether the background is opaque.
1654     *
1655     * @hide
1656     */
1657    static final int OPAQUE_BACKGROUND              = 0x00800000;
1658
1659    /**
1660     * Indicates whether the scrollbars are opaque.
1661     *
1662     * @hide
1663     */
1664    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1665
1666    /**
1667     * Indicates whether the view is opaque.
1668     *
1669     * @hide
1670     */
1671    static final int OPAQUE_MASK                    = 0x01800000;
1672
1673    /**
1674     * Indicates a prepressed state;
1675     * the short time between ACTION_DOWN and recognizing
1676     * a 'real' press. Prepressed is used to recognize quick taps
1677     * even when they are shorter than ViewConfiguration.getTapTimeout().
1678     *
1679     * @hide
1680     */
1681    private static final int PREPRESSED             = 0x02000000;
1682
1683    /**
1684     * Indicates whether the view is temporarily detached.
1685     *
1686     * @hide
1687     */
1688    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1689
1690    /**
1691     * Indicates that we should awaken scroll bars once attached
1692     *
1693     * @hide
1694     */
1695    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1696
1697    /**
1698     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1699     * @hide
1700     */
1701    private static final int HOVERED              = 0x10000000;
1702
1703    /**
1704     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1705     * for transform operations
1706     *
1707     * @hide
1708     */
1709    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1710
1711    /** {@hide} */
1712    static final int ACTIVATED                    = 0x40000000;
1713
1714    /**
1715     * Indicates that this view was specifically invalidated, not just dirtied because some
1716     * child view was invalidated. The flag is used to determine when we need to recreate
1717     * a view's display list (as opposed to just returning a reference to its existing
1718     * display list).
1719     *
1720     * @hide
1721     */
1722    static final int INVALIDATED                  = 0x80000000;
1723
1724    /* Masks for mPrivateFlags2 */
1725
1726    /**
1727     * Indicates that this view has reported that it can accept the current drag's content.
1728     * Cleared when the drag operation concludes.
1729     * @hide
1730     */
1731    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1732
1733    /**
1734     * Indicates that this view is currently directly under the drag location in a
1735     * drag-and-drop operation involving content that it can accept.  Cleared when
1736     * the drag exits the view, or when the drag operation concludes.
1737     * @hide
1738     */
1739    static final int DRAG_HOVERED                 = 0x00000002;
1740
1741    /**
1742     * Indicates whether the view layout direction has been resolved and drawn to the
1743     * right-to-left direction.
1744     *
1745     * @hide
1746     */
1747    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1748
1749    /**
1750     * Indicates whether the view layout direction has been resolved.
1751     *
1752     * @hide
1753     */
1754    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1755
1756
1757    /* End of masks for mPrivateFlags2 */
1758
1759    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1760
1761    /**
1762     * Always allow a user to over-scroll this view, provided it is a
1763     * view that can scroll.
1764     *
1765     * @see #getOverScrollMode()
1766     * @see #setOverScrollMode(int)
1767     */
1768    public static final int OVER_SCROLL_ALWAYS = 0;
1769
1770    /**
1771     * Allow a user to over-scroll this view only if the content is large
1772     * enough to meaningfully scroll, provided it is a view that can scroll.
1773     *
1774     * @see #getOverScrollMode()
1775     * @see #setOverScrollMode(int)
1776     */
1777    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1778
1779    /**
1780     * Never allow a user to over-scroll this view.
1781     *
1782     * @see #getOverScrollMode()
1783     * @see #setOverScrollMode(int)
1784     */
1785    public static final int OVER_SCROLL_NEVER = 2;
1786
1787    /**
1788     * View has requested the system UI (status bar) to be visible (the default).
1789     *
1790     * @see #setSystemUiVisibility(int)
1791     */
1792    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1793
1794    /**
1795     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1796     *
1797     * This is for use in games, book readers, video players, or any other "immersive" application
1798     * where the usual system chrome is deemed too distracting.
1799     *
1800     * In low profile mode, the status bar and/or navigation icons may dim.
1801     *
1802     * @see #setSystemUiVisibility(int)
1803     */
1804    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1805
1806    /**
1807     * View has requested that the system navigation be temporarily hidden.
1808     *
1809     * This is an even less obtrusive state than that called for by
1810     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1811     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1812     * those to disappear. This is useful (in conjunction with the
1813     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1814     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1815     * window flags) for displaying content using every last pixel on the display.
1816     *
1817     * There is a limitation: because navigation controls are so important, the least user
1818     * interaction will cause them to reappear immediately.
1819     *
1820     * @see #setSystemUiVisibility(int)
1821     */
1822    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1823
1824    /**
1825     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1826     */
1827    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1828
1829    /**
1830     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1831     */
1832    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1833
1834    /**
1835     * @hide
1836     *
1837     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1838     * out of the public fields to keep the undefined bits out of the developer's way.
1839     *
1840     * Flag to make the status bar not expandable.  Unless you also
1841     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1842     */
1843    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1844
1845    /**
1846     * @hide
1847     *
1848     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1849     * out of the public fields to keep the undefined bits out of the developer's way.
1850     *
1851     * Flag to hide notification icons and scrolling ticker text.
1852     */
1853    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1854
1855    /**
1856     * @hide
1857     *
1858     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1859     * out of the public fields to keep the undefined bits out of the developer's way.
1860     *
1861     * Flag to disable incoming notification alerts.  This will not block
1862     * icons, but it will block sound, vibrating and other visual or aural notifications.
1863     */
1864    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1865
1866    /**
1867     * @hide
1868     *
1869     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1870     * out of the public fields to keep the undefined bits out of the developer's way.
1871     *
1872     * Flag to hide only the scrolling ticker.  Note that
1873     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1874     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1875     */
1876    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1877
1878    /**
1879     * @hide
1880     *
1881     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1882     * out of the public fields to keep the undefined bits out of the developer's way.
1883     *
1884     * Flag to hide the center system info area.
1885     */
1886    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1887
1888    /**
1889     * @hide
1890     *
1891     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1892     * out of the public fields to keep the undefined bits out of the developer's way.
1893     *
1894     * Flag to hide only the navigation buttons.  Don't use this
1895     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1896     *
1897     * THIS DOES NOT DISABLE THE BACK BUTTON
1898     */
1899    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1900
1901    /**
1902     * @hide
1903     *
1904     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1905     * out of the public fields to keep the undefined bits out of the developer's way.
1906     *
1907     * Flag to hide only the back button.  Don't use this
1908     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1909     */
1910    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1911
1912    /**
1913     * @hide
1914     *
1915     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1916     * out of the public fields to keep the undefined bits out of the developer's way.
1917     *
1918     * Flag to hide only the clock.  You might use this if your activity has
1919     * its own clock making the status bar's clock redundant.
1920     */
1921    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1922
1923    /**
1924     * @hide
1925     */
1926    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1927
1928    /**
1929     * Controls the over-scroll mode for this view.
1930     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1931     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1932     * and {@link #OVER_SCROLL_NEVER}.
1933     */
1934    private int mOverScrollMode;
1935
1936    /**
1937     * The parent this view is attached to.
1938     * {@hide}
1939     *
1940     * @see #getParent()
1941     */
1942    protected ViewParent mParent;
1943
1944    /**
1945     * {@hide}
1946     */
1947    AttachInfo mAttachInfo;
1948
1949    /**
1950     * {@hide}
1951     */
1952    @ViewDebug.ExportedProperty(flagMapping = {
1953        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1954                name = "FORCE_LAYOUT"),
1955        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1956                name = "LAYOUT_REQUIRED"),
1957        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1958            name = "DRAWING_CACHE_INVALID", outputIf = false),
1959        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1960        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1961        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1962        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1963    })
1964    int mPrivateFlags;
1965    int mPrivateFlags2;
1966
1967    /**
1968     * This view's request for the visibility of the status bar.
1969     * @hide
1970     */
1971    @ViewDebug.ExportedProperty(flagMapping = {
1972        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
1973                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
1974                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
1975        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1976                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1977                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
1978        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
1979                                equals = SYSTEM_UI_FLAG_VISIBLE,
1980                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
1981    })
1982    int mSystemUiVisibility;
1983
1984    /**
1985     * Count of how many windows this view has been attached to.
1986     */
1987    int mWindowAttachCount;
1988
1989    /**
1990     * The layout parameters associated with this view and used by the parent
1991     * {@link android.view.ViewGroup} to determine how this view should be
1992     * laid out.
1993     * {@hide}
1994     */
1995    protected ViewGroup.LayoutParams mLayoutParams;
1996
1997    /**
1998     * The view flags hold various views states.
1999     * {@hide}
2000     */
2001    @ViewDebug.ExportedProperty
2002    int mViewFlags;
2003
2004    /**
2005     * The transform matrix for the View. This transform is calculated internally
2006     * based on the rotation, scaleX, and scaleY properties. The identity matrix
2007     * is used by default. Do *not* use this variable directly; instead call
2008     * getMatrix(), which will automatically recalculate the matrix if necessary
2009     * to get the correct matrix based on the latest rotation and scale properties.
2010     */
2011    private final Matrix mMatrix = new Matrix();
2012
2013    /**
2014     * The transform matrix for the View. This transform is calculated internally
2015     * based on the rotation, scaleX, and scaleY properties. The identity matrix
2016     * is used by default. Do *not* use this variable directly; instead call
2017     * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2018     * to get the correct matrix based on the latest rotation and scale properties.
2019     */
2020    private Matrix mInverseMatrix;
2021
2022    /**
2023     * An internal variable that tracks whether we need to recalculate the
2024     * transform matrix, based on whether the rotation or scaleX/Y properties
2025     * have changed since the matrix was last calculated.
2026     */
2027    boolean mMatrixDirty = false;
2028
2029    /**
2030     * An internal variable that tracks whether we need to recalculate the
2031     * transform matrix, based on whether the rotation or scaleX/Y properties
2032     * have changed since the matrix was last calculated.
2033     */
2034    private boolean mInverseMatrixDirty = true;
2035
2036    /**
2037     * A variable that tracks whether we need to recalculate the
2038     * transform matrix, based on whether the rotation or scaleX/Y properties
2039     * have changed since the matrix was last calculated. This variable
2040     * is only valid after a call to updateMatrix() or to a function that
2041     * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2042     */
2043    private boolean mMatrixIsIdentity = true;
2044
2045    /**
2046     * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2047     */
2048    private Camera mCamera = null;
2049
2050    /**
2051     * This matrix is used when computing the matrix for 3D rotations.
2052     */
2053    private Matrix matrix3D = null;
2054
2055    /**
2056     * These prev values are used to recalculate a centered pivot point when necessary. The
2057     * pivot point is only used in matrix operations (when rotation, scale, or translation are
2058     * set), so thes values are only used then as well.
2059     */
2060    private int mPrevWidth = -1;
2061    private int mPrevHeight = -1;
2062
2063    private boolean mLastIsOpaque;
2064
2065    /**
2066     * Convenience value to check for float values that are close enough to zero to be considered
2067     * zero.
2068     */
2069    private static final float NONZERO_EPSILON = .001f;
2070
2071    /**
2072     * The degrees rotation around the vertical axis through the pivot point.
2073     */
2074    @ViewDebug.ExportedProperty
2075    float mRotationY = 0f;
2076
2077    /**
2078     * The degrees rotation around the horizontal axis through the pivot point.
2079     */
2080    @ViewDebug.ExportedProperty
2081    float mRotationX = 0f;
2082
2083    /**
2084     * The degrees rotation around the pivot point.
2085     */
2086    @ViewDebug.ExportedProperty
2087    float mRotation = 0f;
2088
2089    /**
2090     * The amount of translation of the object away from its left property (post-layout).
2091     */
2092    @ViewDebug.ExportedProperty
2093    float mTranslationX = 0f;
2094
2095    /**
2096     * The amount of translation of the object away from its top property (post-layout).
2097     */
2098    @ViewDebug.ExportedProperty
2099    float mTranslationY = 0f;
2100
2101    /**
2102     * The amount of scale in the x direction around the pivot point. A
2103     * value of 1 means no scaling is applied.
2104     */
2105    @ViewDebug.ExportedProperty
2106    float mScaleX = 1f;
2107
2108    /**
2109     * The amount of scale in the y direction around the pivot point. A
2110     * value of 1 means no scaling is applied.
2111     */
2112    @ViewDebug.ExportedProperty
2113    float mScaleY = 1f;
2114
2115    /**
2116     * The amount of scale in the x direction around the pivot point. A
2117     * value of 1 means no scaling is applied.
2118     */
2119    @ViewDebug.ExportedProperty
2120    float mPivotX = 0f;
2121
2122    /**
2123     * The amount of scale in the y direction around the pivot point. A
2124     * value of 1 means no scaling is applied.
2125     */
2126    @ViewDebug.ExportedProperty
2127    float mPivotY = 0f;
2128
2129    /**
2130     * The opacity of the View. This is a value from 0 to 1, where 0 means
2131     * completely transparent and 1 means completely opaque.
2132     */
2133    @ViewDebug.ExportedProperty
2134    float mAlpha = 1f;
2135
2136    /**
2137     * The distance in pixels from the left edge of this view's parent
2138     * to the left edge of this view.
2139     * {@hide}
2140     */
2141    @ViewDebug.ExportedProperty(category = "layout")
2142    protected int mLeft;
2143    /**
2144     * The distance in pixels from the left edge of this view's parent
2145     * to the right edge of this view.
2146     * {@hide}
2147     */
2148    @ViewDebug.ExportedProperty(category = "layout")
2149    protected int mRight;
2150    /**
2151     * The distance in pixels from the top edge of this view's parent
2152     * to the top edge of this view.
2153     * {@hide}
2154     */
2155    @ViewDebug.ExportedProperty(category = "layout")
2156    protected int mTop;
2157    /**
2158     * The distance in pixels from the top edge of this view's parent
2159     * to the bottom edge of this view.
2160     * {@hide}
2161     */
2162    @ViewDebug.ExportedProperty(category = "layout")
2163    protected int mBottom;
2164
2165    /**
2166     * The offset, in pixels, by which the content of this view is scrolled
2167     * horizontally.
2168     * {@hide}
2169     */
2170    @ViewDebug.ExportedProperty(category = "scrolling")
2171    protected int mScrollX;
2172    /**
2173     * The offset, in pixels, by which the content of this view is scrolled
2174     * vertically.
2175     * {@hide}
2176     */
2177    @ViewDebug.ExportedProperty(category = "scrolling")
2178    protected int mScrollY;
2179
2180    /**
2181     * The left padding in pixels, that is the distance in pixels between the
2182     * left edge of this view and the left edge of its content.
2183     * {@hide}
2184     */
2185    @ViewDebug.ExportedProperty(category = "padding")
2186    protected int mPaddingLeft;
2187    /**
2188     * The right padding in pixels, that is the distance in pixels between the
2189     * right edge of this view and the right edge of its content.
2190     * {@hide}
2191     */
2192    @ViewDebug.ExportedProperty(category = "padding")
2193    protected int mPaddingRight;
2194    /**
2195     * The top padding in pixels, that is the distance in pixels between the
2196     * top edge of this view and the top edge of its content.
2197     * {@hide}
2198     */
2199    @ViewDebug.ExportedProperty(category = "padding")
2200    protected int mPaddingTop;
2201    /**
2202     * The bottom padding in pixels, that is the distance in pixels between the
2203     * bottom edge of this view and the bottom edge of its content.
2204     * {@hide}
2205     */
2206    @ViewDebug.ExportedProperty(category = "padding")
2207    protected int mPaddingBottom;
2208
2209    /**
2210     * Briefly describes the view and is primarily used for accessibility support.
2211     */
2212    private CharSequence mContentDescription;
2213
2214    /**
2215     * Cache the paddingRight set by the user to append to the scrollbar's size.
2216     *
2217     * @hide
2218     */
2219    @ViewDebug.ExportedProperty(category = "padding")
2220    protected int mUserPaddingRight;
2221
2222    /**
2223     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2224     *
2225     * @hide
2226     */
2227    @ViewDebug.ExportedProperty(category = "padding")
2228    protected int mUserPaddingBottom;
2229
2230    /**
2231     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2232     *
2233     * @hide
2234     */
2235    @ViewDebug.ExportedProperty(category = "padding")
2236    protected int mUserPaddingLeft;
2237
2238    /**
2239     * Cache if the user padding is relative.
2240     *
2241     */
2242    @ViewDebug.ExportedProperty(category = "padding")
2243    boolean mUserPaddingRelative;
2244
2245    /**
2246     * Cache the paddingStart set by the user to append to the scrollbar's size.
2247     *
2248     */
2249    @ViewDebug.ExportedProperty(category = "padding")
2250    int mUserPaddingStart;
2251
2252    /**
2253     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2254     *
2255     */
2256    @ViewDebug.ExportedProperty(category = "padding")
2257    int mUserPaddingEnd;
2258
2259    /**
2260     * @hide
2261     */
2262    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2263    /**
2264     * @hide
2265     */
2266    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2267
2268    private Resources mResources = null;
2269
2270    private Drawable mBGDrawable;
2271
2272    private int mBackgroundResource;
2273    private boolean mBackgroundSizeChanged;
2274
2275    /**
2276     * Listener used to dispatch focus change events.
2277     * This field should be made private, so it is hidden from the SDK.
2278     * {@hide}
2279     */
2280    protected OnFocusChangeListener mOnFocusChangeListener;
2281
2282    /**
2283     * Listeners for layout change events.
2284     */
2285    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2286
2287    /**
2288     * Listeners for attach events.
2289     */
2290    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2291
2292    /**
2293     * Listener used to dispatch click events.
2294     * This field should be made private, so it is hidden from the SDK.
2295     * {@hide}
2296     */
2297    protected OnClickListener mOnClickListener;
2298
2299    /**
2300     * Listener used to dispatch long click events.
2301     * This field should be made private, so it is hidden from the SDK.
2302     * {@hide}
2303     */
2304    protected OnLongClickListener mOnLongClickListener;
2305
2306    /**
2307     * Listener used to build the context menu.
2308     * This field should be made private, so it is hidden from the SDK.
2309     * {@hide}
2310     */
2311    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2312
2313    private OnKeyListener mOnKeyListener;
2314
2315    private OnTouchListener mOnTouchListener;
2316
2317    private OnHoverListener mOnHoverListener;
2318
2319    private OnGenericMotionListener mOnGenericMotionListener;
2320
2321    private OnDragListener mOnDragListener;
2322
2323    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2324
2325    /**
2326     * The application environment this view lives in.
2327     * This field should be made private, so it is hidden from the SDK.
2328     * {@hide}
2329     */
2330    protected Context mContext;
2331
2332    private ScrollabilityCache mScrollCache;
2333
2334    private int[] mDrawableState = null;
2335
2336    /**
2337     * Set to true when drawing cache is enabled and cannot be created.
2338     *
2339     * @hide
2340     */
2341    public boolean mCachingFailed;
2342
2343    private Bitmap mDrawingCache;
2344    private Bitmap mUnscaledDrawingCache;
2345    private HardwareLayer mHardwareLayer;
2346    DisplayList mDisplayList;
2347
2348    /**
2349     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2350     * the user may specify which view to go to next.
2351     */
2352    private int mNextFocusLeftId = View.NO_ID;
2353
2354    /**
2355     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2356     * the user may specify which view to go to next.
2357     */
2358    private int mNextFocusRightId = View.NO_ID;
2359
2360    /**
2361     * When this view has focus and the next focus is {@link #FOCUS_UP},
2362     * the user may specify which view to go to next.
2363     */
2364    private int mNextFocusUpId = View.NO_ID;
2365
2366    /**
2367     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2368     * the user may specify which view to go to next.
2369     */
2370    private int mNextFocusDownId = View.NO_ID;
2371
2372    /**
2373     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2374     * the user may specify which view to go to next.
2375     */
2376    int mNextFocusForwardId = View.NO_ID;
2377
2378    private CheckForLongPress mPendingCheckForLongPress;
2379    private CheckForTap mPendingCheckForTap = null;
2380    private PerformClick mPerformClick;
2381    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2382
2383    private UnsetPressedState mUnsetPressedState;
2384
2385    /**
2386     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2387     * up event while a long press is invoked as soon as the long press duration is reached, so
2388     * a long press could be performed before the tap is checked, in which case the tap's action
2389     * should not be invoked.
2390     */
2391    private boolean mHasPerformedLongPress;
2392
2393    /**
2394     * The minimum height of the view. We'll try our best to have the height
2395     * of this view to at least this amount.
2396     */
2397    @ViewDebug.ExportedProperty(category = "measurement")
2398    private int mMinHeight;
2399
2400    /**
2401     * The minimum width of the view. We'll try our best to have the width
2402     * of this view to at least this amount.
2403     */
2404    @ViewDebug.ExportedProperty(category = "measurement")
2405    private int mMinWidth;
2406
2407    /**
2408     * The delegate to handle touch events that are physically in this view
2409     * but should be handled by another view.
2410     */
2411    private TouchDelegate mTouchDelegate = null;
2412
2413    /**
2414     * Solid color to use as a background when creating the drawing cache. Enables
2415     * the cache to use 16 bit bitmaps instead of 32 bit.
2416     */
2417    private int mDrawingCacheBackgroundColor = 0;
2418
2419    /**
2420     * Special tree observer used when mAttachInfo is null.
2421     */
2422    private ViewTreeObserver mFloatingTreeObserver;
2423
2424    /**
2425     * Cache the touch slop from the context that created the view.
2426     */
2427    private int mTouchSlop;
2428
2429    /**
2430     * Object that handles automatic animation of view properties.
2431     */
2432    private ViewPropertyAnimator mAnimator = null;
2433
2434    /**
2435     * Flag indicating that a drag can cross window boundaries.  When
2436     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2437     * with this flag set, all visible applications will be able to participate
2438     * in the drag operation and receive the dragged content.
2439     *
2440     * @hide
2441     */
2442    public static final int DRAG_FLAG_GLOBAL = 1;
2443
2444    /**
2445     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2446     */
2447    private float mVerticalScrollFactor;
2448
2449    /**
2450     * Position of the vertical scroll bar.
2451     */
2452    private int mVerticalScrollbarPosition;
2453
2454    /**
2455     * Position the scroll bar at the default position as determined by the system.
2456     */
2457    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2458
2459    /**
2460     * Position the scroll bar along the left edge.
2461     */
2462    public static final int SCROLLBAR_POSITION_LEFT = 1;
2463
2464    /**
2465     * Position the scroll bar along the right edge.
2466     */
2467    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2468
2469    /**
2470     * Indicates that the view does not have a layer.
2471     *
2472     * @see #getLayerType()
2473     * @see #setLayerType(int, android.graphics.Paint)
2474     * @see #LAYER_TYPE_SOFTWARE
2475     * @see #LAYER_TYPE_HARDWARE
2476     */
2477    public static final int LAYER_TYPE_NONE = 0;
2478
2479    /**
2480     * <p>Indicates that the view has a software layer. A software layer is backed
2481     * by a bitmap and causes the view to be rendered using Android's software
2482     * rendering pipeline, even if hardware acceleration is enabled.</p>
2483     *
2484     * <p>Software layers have various usages:</p>
2485     * <p>When the application is not using hardware acceleration, a software layer
2486     * is useful to apply a specific color filter and/or blending mode and/or
2487     * translucency to a view and all its children.</p>
2488     * <p>When the application is using hardware acceleration, a software layer
2489     * is useful to render drawing primitives not supported by the hardware
2490     * accelerated pipeline. It can also be used to cache a complex view tree
2491     * into a texture and reduce the complexity of drawing operations. For instance,
2492     * when animating a complex view tree with a translation, a software layer can
2493     * be used to render the view tree only once.</p>
2494     * <p>Software layers should be avoided when the affected view tree updates
2495     * often. Every update will require to re-render the software layer, which can
2496     * potentially be slow (particularly when hardware acceleration is turned on
2497     * since the layer will have to be uploaded into a hardware texture after every
2498     * update.)</p>
2499     *
2500     * @see #getLayerType()
2501     * @see #setLayerType(int, android.graphics.Paint)
2502     * @see #LAYER_TYPE_NONE
2503     * @see #LAYER_TYPE_HARDWARE
2504     */
2505    public static final int LAYER_TYPE_SOFTWARE = 1;
2506
2507    /**
2508     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2509     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2510     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2511     * rendering pipeline, but only if hardware acceleration is turned on for the
2512     * view hierarchy. When hardware acceleration is turned off, hardware layers
2513     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2514     *
2515     * <p>A hardware layer is useful to apply a specific color filter and/or
2516     * blending mode and/or translucency to a view and all its children.</p>
2517     * <p>A hardware layer can be used to cache a complex view tree into a
2518     * texture and reduce the complexity of drawing operations. For instance,
2519     * when animating a complex view tree with a translation, a hardware layer can
2520     * be used to render the view tree only once.</p>
2521     * <p>A hardware layer can also be used to increase the rendering quality when
2522     * rotation transformations are applied on a view. It can also be used to
2523     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2524     *
2525     * @see #getLayerType()
2526     * @see #setLayerType(int, android.graphics.Paint)
2527     * @see #LAYER_TYPE_NONE
2528     * @see #LAYER_TYPE_SOFTWARE
2529     */
2530    public static final int LAYER_TYPE_HARDWARE = 2;
2531
2532    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2533            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2534            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2535            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2536    })
2537    int mLayerType = LAYER_TYPE_NONE;
2538    Paint mLayerPaint;
2539    Rect mLocalDirtyRect;
2540
2541    /**
2542     * Set to true when the view is sending hover accessibility events because it
2543     * is the innermost hovered view.
2544     */
2545    private boolean mSendingHoverAccessibilityEvents;
2546
2547    /**
2548     * Text direction is inherited thru {@link ViewGroup}
2549     * @hide
2550     */
2551    public static final int TEXT_DIRECTION_INHERIT = 0;
2552
2553    /**
2554     * Text direction is using "first strong algorithm". The first strong directional character
2555     * determines the paragraph direction. If there is no strong directional character, the
2556     * paragraph direction is the view's resolved ayout direction.
2557     *
2558     * @hide
2559     */
2560    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2561
2562    /**
2563     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2564     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2565     * If there are neither, the paragraph direction is the view's resolved layout direction.
2566     *
2567     * @hide
2568     */
2569    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2570
2571    /**
2572     * Text direction is forced to LTR.
2573     *
2574     * @hide
2575     */
2576    public static final int TEXT_DIRECTION_LTR = 3;
2577
2578    /**
2579     * Text direction is forced to RTL.
2580     *
2581     * @hide
2582     */
2583    public static final int TEXT_DIRECTION_RTL = 4;
2584
2585    /**
2586     * Default text direction is inherited
2587     *
2588     * @hide
2589     */
2590    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2591
2592    /**
2593     * The text direction that has been defined by {@link #setTextDirection(int)}.
2594     *
2595     * {@hide}
2596     */
2597    @ViewDebug.ExportedProperty(category = "text", mapping = {
2598            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2599            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2600            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2601            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2602            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2603    })
2604    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2605
2606    /**
2607     * The resolved text direction.  This needs resolution if the value is
2608     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if that is
2609     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2610     * chain of the view.
2611     *
2612     * {@hide}
2613     */
2614    @ViewDebug.ExportedProperty(category = "text", mapping = {
2615            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2616            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2617            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2618            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2619            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2620    })
2621    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2622
2623    /**
2624     * Consistency verifier for debugging purposes.
2625     * @hide
2626     */
2627    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2628            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2629                    new InputEventConsistencyVerifier(this, 0) : null;
2630
2631    /**
2632     * Simple constructor to use when creating a view from code.
2633     *
2634     * @param context The Context the view is running in, through which it can
2635     *        access the current theme, resources, etc.
2636     */
2637    public View(Context context) {
2638        mContext = context;
2639        mResources = context != null ? context.getResources() : null;
2640        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2641        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2642        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2643        mUserPaddingStart = -1;
2644        mUserPaddingEnd = -1;
2645        mUserPaddingRelative = false;
2646    }
2647
2648    /**
2649     * Constructor that is called when inflating a view from XML. This is called
2650     * when a view is being constructed from an XML file, supplying attributes
2651     * that were specified in the XML file. This version uses a default style of
2652     * 0, so the only attribute values applied are those in the Context's Theme
2653     * and the given AttributeSet.
2654     *
2655     * <p>
2656     * The method onFinishInflate() will be called after all children have been
2657     * added.
2658     *
2659     * @param context The Context the view is running in, through which it can
2660     *        access the current theme, resources, etc.
2661     * @param attrs The attributes of the XML tag that is inflating the view.
2662     * @see #View(Context, AttributeSet, int)
2663     */
2664    public View(Context context, AttributeSet attrs) {
2665        this(context, attrs, 0);
2666    }
2667
2668    /**
2669     * Perform inflation from XML and apply a class-specific base style. This
2670     * constructor of View allows subclasses to use their own base style when
2671     * they are inflating. For example, a Button class's constructor would call
2672     * this version of the super class constructor and supply
2673     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2674     * the theme's button style to modify all of the base view attributes (in
2675     * particular its background) as well as the Button class's attributes.
2676     *
2677     * @param context The Context the view is running in, through which it can
2678     *        access the current theme, resources, etc.
2679     * @param attrs The attributes of the XML tag that is inflating the view.
2680     * @param defStyle The default style to apply to this view. If 0, no style
2681     *        will be applied (beyond what is included in the theme). This may
2682     *        either be an attribute resource, whose value will be retrieved
2683     *        from the current theme, or an explicit style resource.
2684     * @see #View(Context, AttributeSet)
2685     */
2686    public View(Context context, AttributeSet attrs, int defStyle) {
2687        this(context);
2688
2689        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2690                defStyle, 0);
2691
2692        Drawable background = null;
2693
2694        int leftPadding = -1;
2695        int topPadding = -1;
2696        int rightPadding = -1;
2697        int bottomPadding = -1;
2698        int startPadding = -1;
2699        int endPadding = -1;
2700
2701        int padding = -1;
2702
2703        int viewFlagValues = 0;
2704        int viewFlagMasks = 0;
2705
2706        boolean setScrollContainer = false;
2707
2708        int x = 0;
2709        int y = 0;
2710
2711        float tx = 0;
2712        float ty = 0;
2713        float rotation = 0;
2714        float rotationX = 0;
2715        float rotationY = 0;
2716        float sx = 1f;
2717        float sy = 1f;
2718        boolean transformSet = false;
2719
2720        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2721
2722        int overScrollMode = mOverScrollMode;
2723        final int N = a.getIndexCount();
2724        for (int i = 0; i < N; i++) {
2725            int attr = a.getIndex(i);
2726            switch (attr) {
2727                case com.android.internal.R.styleable.View_background:
2728                    background = a.getDrawable(attr);
2729                    break;
2730                case com.android.internal.R.styleable.View_padding:
2731                    padding = a.getDimensionPixelSize(attr, -1);
2732                    break;
2733                 case com.android.internal.R.styleable.View_paddingLeft:
2734                    leftPadding = a.getDimensionPixelSize(attr, -1);
2735                    break;
2736                case com.android.internal.R.styleable.View_paddingTop:
2737                    topPadding = a.getDimensionPixelSize(attr, -1);
2738                    break;
2739                case com.android.internal.R.styleable.View_paddingRight:
2740                    rightPadding = a.getDimensionPixelSize(attr, -1);
2741                    break;
2742                case com.android.internal.R.styleable.View_paddingBottom:
2743                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2744                    break;
2745                case com.android.internal.R.styleable.View_paddingStart:
2746                    startPadding = a.getDimensionPixelSize(attr, -1);
2747                    break;
2748                case com.android.internal.R.styleable.View_paddingEnd:
2749                    endPadding = a.getDimensionPixelSize(attr, -1);
2750                    break;
2751                case com.android.internal.R.styleable.View_scrollX:
2752                    x = a.getDimensionPixelOffset(attr, 0);
2753                    break;
2754                case com.android.internal.R.styleable.View_scrollY:
2755                    y = a.getDimensionPixelOffset(attr, 0);
2756                    break;
2757                case com.android.internal.R.styleable.View_alpha:
2758                    setAlpha(a.getFloat(attr, 1f));
2759                    break;
2760                case com.android.internal.R.styleable.View_transformPivotX:
2761                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2762                    break;
2763                case com.android.internal.R.styleable.View_transformPivotY:
2764                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2765                    break;
2766                case com.android.internal.R.styleable.View_translationX:
2767                    tx = a.getDimensionPixelOffset(attr, 0);
2768                    transformSet = true;
2769                    break;
2770                case com.android.internal.R.styleable.View_translationY:
2771                    ty = a.getDimensionPixelOffset(attr, 0);
2772                    transformSet = true;
2773                    break;
2774                case com.android.internal.R.styleable.View_rotation:
2775                    rotation = a.getFloat(attr, 0);
2776                    transformSet = true;
2777                    break;
2778                case com.android.internal.R.styleable.View_rotationX:
2779                    rotationX = a.getFloat(attr, 0);
2780                    transformSet = true;
2781                    break;
2782                case com.android.internal.R.styleable.View_rotationY:
2783                    rotationY = a.getFloat(attr, 0);
2784                    transformSet = true;
2785                    break;
2786                case com.android.internal.R.styleable.View_scaleX:
2787                    sx = a.getFloat(attr, 1f);
2788                    transformSet = true;
2789                    break;
2790                case com.android.internal.R.styleable.View_scaleY:
2791                    sy = a.getFloat(attr, 1f);
2792                    transformSet = true;
2793                    break;
2794                case com.android.internal.R.styleable.View_id:
2795                    mID = a.getResourceId(attr, NO_ID);
2796                    break;
2797                case com.android.internal.R.styleable.View_tag:
2798                    mTag = a.getText(attr);
2799                    break;
2800                case com.android.internal.R.styleable.View_fitsSystemWindows:
2801                    if (a.getBoolean(attr, false)) {
2802                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2803                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2804                    }
2805                    break;
2806                case com.android.internal.R.styleable.View_focusable:
2807                    if (a.getBoolean(attr, false)) {
2808                        viewFlagValues |= FOCUSABLE;
2809                        viewFlagMasks |= FOCUSABLE_MASK;
2810                    }
2811                    break;
2812                case com.android.internal.R.styleable.View_focusableInTouchMode:
2813                    if (a.getBoolean(attr, false)) {
2814                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2815                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2816                    }
2817                    break;
2818                case com.android.internal.R.styleable.View_clickable:
2819                    if (a.getBoolean(attr, false)) {
2820                        viewFlagValues |= CLICKABLE;
2821                        viewFlagMasks |= CLICKABLE;
2822                    }
2823                    break;
2824                case com.android.internal.R.styleable.View_longClickable:
2825                    if (a.getBoolean(attr, false)) {
2826                        viewFlagValues |= LONG_CLICKABLE;
2827                        viewFlagMasks |= LONG_CLICKABLE;
2828                    }
2829                    break;
2830                case com.android.internal.R.styleable.View_saveEnabled:
2831                    if (!a.getBoolean(attr, true)) {
2832                        viewFlagValues |= SAVE_DISABLED;
2833                        viewFlagMasks |= SAVE_DISABLED_MASK;
2834                    }
2835                    break;
2836                case com.android.internal.R.styleable.View_duplicateParentState:
2837                    if (a.getBoolean(attr, false)) {
2838                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2839                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2840                    }
2841                    break;
2842                case com.android.internal.R.styleable.View_visibility:
2843                    final int visibility = a.getInt(attr, 0);
2844                    if (visibility != 0) {
2845                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2846                        viewFlagMasks |= VISIBILITY_MASK;
2847                    }
2848                    break;
2849                case com.android.internal.R.styleable.View_layoutDirection:
2850                    // Clear any HORIZONTAL_DIRECTION flag already set
2851                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2852                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2853                    final int layoutDirection = a.getInt(attr, -1);
2854                    if (layoutDirection != -1) {
2855                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2856                    } else {
2857                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2858                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2859                    }
2860                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2861                    break;
2862                case com.android.internal.R.styleable.View_drawingCacheQuality:
2863                    final int cacheQuality = a.getInt(attr, 0);
2864                    if (cacheQuality != 0) {
2865                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2866                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2867                    }
2868                    break;
2869                case com.android.internal.R.styleable.View_contentDescription:
2870                    mContentDescription = a.getString(attr);
2871                    break;
2872                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2873                    if (!a.getBoolean(attr, true)) {
2874                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2875                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2876                    }
2877                    break;
2878                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2879                    if (!a.getBoolean(attr, true)) {
2880                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2881                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2882                    }
2883                    break;
2884                case R.styleable.View_scrollbars:
2885                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2886                    if (scrollbars != SCROLLBARS_NONE) {
2887                        viewFlagValues |= scrollbars;
2888                        viewFlagMasks |= SCROLLBARS_MASK;
2889                        initializeScrollbars(a);
2890                    }
2891                    break;
2892                case R.styleable.View_fadingEdge:
2893                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2894                    if (fadingEdge != FADING_EDGE_NONE) {
2895                        viewFlagValues |= fadingEdge;
2896                        viewFlagMasks |= FADING_EDGE_MASK;
2897                        initializeFadingEdge(a);
2898                    }
2899                    break;
2900                case R.styleable.View_scrollbarStyle:
2901                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2902                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2903                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2904                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2905                    }
2906                    break;
2907                case R.styleable.View_isScrollContainer:
2908                    setScrollContainer = true;
2909                    if (a.getBoolean(attr, false)) {
2910                        setScrollContainer(true);
2911                    }
2912                    break;
2913                case com.android.internal.R.styleable.View_keepScreenOn:
2914                    if (a.getBoolean(attr, false)) {
2915                        viewFlagValues |= KEEP_SCREEN_ON;
2916                        viewFlagMasks |= KEEP_SCREEN_ON;
2917                    }
2918                    break;
2919                case R.styleable.View_filterTouchesWhenObscured:
2920                    if (a.getBoolean(attr, false)) {
2921                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2922                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2923                    }
2924                    break;
2925                case R.styleable.View_nextFocusLeft:
2926                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2927                    break;
2928                case R.styleable.View_nextFocusRight:
2929                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2930                    break;
2931                case R.styleable.View_nextFocusUp:
2932                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2933                    break;
2934                case R.styleable.View_nextFocusDown:
2935                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2936                    break;
2937                case R.styleable.View_nextFocusForward:
2938                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2939                    break;
2940                case R.styleable.View_minWidth:
2941                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2942                    break;
2943                case R.styleable.View_minHeight:
2944                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2945                    break;
2946                case R.styleable.View_onClick:
2947                    if (context.isRestricted()) {
2948                        throw new IllegalStateException("The android:onClick attribute cannot "
2949                                + "be used within a restricted context");
2950                    }
2951
2952                    final String handlerName = a.getString(attr);
2953                    if (handlerName != null) {
2954                        setOnClickListener(new OnClickListener() {
2955                            private Method mHandler;
2956
2957                            public void onClick(View v) {
2958                                if (mHandler == null) {
2959                                    try {
2960                                        mHandler = getContext().getClass().getMethod(handlerName,
2961                                                View.class);
2962                                    } catch (NoSuchMethodException e) {
2963                                        int id = getId();
2964                                        String idText = id == NO_ID ? "" : " with id '"
2965                                                + getContext().getResources().getResourceEntryName(
2966                                                    id) + "'";
2967                                        throw new IllegalStateException("Could not find a method " +
2968                                                handlerName + "(View) in the activity "
2969                                                + getContext().getClass() + " for onClick handler"
2970                                                + " on view " + View.this.getClass() + idText, e);
2971                                    }
2972                                }
2973
2974                                try {
2975                                    mHandler.invoke(getContext(), View.this);
2976                                } catch (IllegalAccessException e) {
2977                                    throw new IllegalStateException("Could not execute non "
2978                                            + "public method of the activity", e);
2979                                } catch (InvocationTargetException e) {
2980                                    throw new IllegalStateException("Could not execute "
2981                                            + "method of the activity", e);
2982                                }
2983                            }
2984                        });
2985                    }
2986                    break;
2987                case R.styleable.View_overScrollMode:
2988                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2989                    break;
2990                case R.styleable.View_verticalScrollbarPosition:
2991                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2992                    break;
2993                case R.styleable.View_layerType:
2994                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2995                    break;
2996                case R.styleable.View_textDirection:
2997                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
2998                    break;
2999            }
3000        }
3001
3002        setOverScrollMode(overScrollMode);
3003
3004        if (background != null) {
3005            setBackgroundDrawable(background);
3006        }
3007
3008        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3009
3010        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3011        // layout direction). Those cached values will be used later during padding resolution.
3012        mUserPaddingStart = startPadding;
3013        mUserPaddingEnd = endPadding;
3014
3015        if (padding >= 0) {
3016            leftPadding = padding;
3017            topPadding = padding;
3018            rightPadding = padding;
3019            bottomPadding = padding;
3020        }
3021
3022        // If the user specified the padding (either with android:padding or
3023        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3024        // use the default padding or the padding from the background drawable
3025        // (stored at this point in mPadding*)
3026        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3027                topPadding >= 0 ? topPadding : mPaddingTop,
3028                rightPadding >= 0 ? rightPadding : mPaddingRight,
3029                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3030
3031        if (viewFlagMasks != 0) {
3032            setFlags(viewFlagValues, viewFlagMasks);
3033        }
3034
3035        // Needs to be called after mViewFlags is set
3036        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3037            recomputePadding();
3038        }
3039
3040        if (x != 0 || y != 0) {
3041            scrollTo(x, y);
3042        }
3043
3044        if (transformSet) {
3045            setTranslationX(tx);
3046            setTranslationY(ty);
3047            setRotation(rotation);
3048            setRotationX(rotationX);
3049            setRotationY(rotationY);
3050            setScaleX(sx);
3051            setScaleY(sy);
3052        }
3053
3054        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3055            setScrollContainer(true);
3056        }
3057
3058        computeOpaqueFlags();
3059
3060        a.recycle();
3061    }
3062
3063    /**
3064     * Non-public constructor for use in testing
3065     */
3066    View() {
3067    }
3068
3069    /**
3070     * <p>
3071     * Initializes the fading edges from a given set of styled attributes. This
3072     * method should be called by subclasses that need fading edges and when an
3073     * instance of these subclasses is created programmatically rather than
3074     * being inflated from XML. This method is automatically called when the XML
3075     * is inflated.
3076     * </p>
3077     *
3078     * @param a the styled attributes set to initialize the fading edges from
3079     */
3080    protected void initializeFadingEdge(TypedArray a) {
3081        initScrollCache();
3082
3083        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3084                R.styleable.View_fadingEdgeLength,
3085                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3086    }
3087
3088    /**
3089     * Returns the size of the vertical faded edges used to indicate that more
3090     * content in this view is visible.
3091     *
3092     * @return The size in pixels of the vertical faded edge or 0 if vertical
3093     *         faded edges are not enabled for this view.
3094     * @attr ref android.R.styleable#View_fadingEdgeLength
3095     */
3096    public int getVerticalFadingEdgeLength() {
3097        if (isVerticalFadingEdgeEnabled()) {
3098            ScrollabilityCache cache = mScrollCache;
3099            if (cache != null) {
3100                return cache.fadingEdgeLength;
3101            }
3102        }
3103        return 0;
3104    }
3105
3106    /**
3107     * Set the size of the faded edge used to indicate that more content in this
3108     * view is available.  Will not change whether the fading edge is enabled; use
3109     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3110     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3111     * for the vertical or horizontal fading edges.
3112     *
3113     * @param length The size in pixels of the faded edge used to indicate that more
3114     *        content in this view is visible.
3115     */
3116    public void setFadingEdgeLength(int length) {
3117        initScrollCache();
3118        mScrollCache.fadingEdgeLength = length;
3119    }
3120
3121    /**
3122     * Returns the size of the horizontal faded edges used to indicate that more
3123     * content in this view is visible.
3124     *
3125     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3126     *         faded edges are not enabled for this view.
3127     * @attr ref android.R.styleable#View_fadingEdgeLength
3128     */
3129    public int getHorizontalFadingEdgeLength() {
3130        if (isHorizontalFadingEdgeEnabled()) {
3131            ScrollabilityCache cache = mScrollCache;
3132            if (cache != null) {
3133                return cache.fadingEdgeLength;
3134            }
3135        }
3136        return 0;
3137    }
3138
3139    /**
3140     * Returns the width of the vertical scrollbar.
3141     *
3142     * @return The width in pixels of the vertical scrollbar or 0 if there
3143     *         is no vertical scrollbar.
3144     */
3145    public int getVerticalScrollbarWidth() {
3146        ScrollabilityCache cache = mScrollCache;
3147        if (cache != null) {
3148            ScrollBarDrawable scrollBar = cache.scrollBar;
3149            if (scrollBar != null) {
3150                int size = scrollBar.getSize(true);
3151                if (size <= 0) {
3152                    size = cache.scrollBarSize;
3153                }
3154                return size;
3155            }
3156            return 0;
3157        }
3158        return 0;
3159    }
3160
3161    /**
3162     * Returns the height of the horizontal scrollbar.
3163     *
3164     * @return The height in pixels of the horizontal scrollbar or 0 if
3165     *         there is no horizontal scrollbar.
3166     */
3167    protected int getHorizontalScrollbarHeight() {
3168        ScrollabilityCache cache = mScrollCache;
3169        if (cache != null) {
3170            ScrollBarDrawable scrollBar = cache.scrollBar;
3171            if (scrollBar != null) {
3172                int size = scrollBar.getSize(false);
3173                if (size <= 0) {
3174                    size = cache.scrollBarSize;
3175                }
3176                return size;
3177            }
3178            return 0;
3179        }
3180        return 0;
3181    }
3182
3183    /**
3184     * <p>
3185     * Initializes the scrollbars from a given set of styled attributes. This
3186     * method should be called by subclasses that need scrollbars and when an
3187     * instance of these subclasses is created programmatically rather than
3188     * being inflated from XML. This method is automatically called when the XML
3189     * is inflated.
3190     * </p>
3191     *
3192     * @param a the styled attributes set to initialize the scrollbars from
3193     */
3194    protected void initializeScrollbars(TypedArray a) {
3195        initScrollCache();
3196
3197        final ScrollabilityCache scrollabilityCache = mScrollCache;
3198
3199        if (scrollabilityCache.scrollBar == null) {
3200            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3201        }
3202
3203        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3204
3205        if (!fadeScrollbars) {
3206            scrollabilityCache.state = ScrollabilityCache.ON;
3207        }
3208        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3209
3210
3211        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3212                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3213                        .getScrollBarFadeDuration());
3214        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3215                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3216                ViewConfiguration.getScrollDefaultDelay());
3217
3218
3219        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3220                com.android.internal.R.styleable.View_scrollbarSize,
3221                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3222
3223        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3224        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3225
3226        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3227        if (thumb != null) {
3228            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3229        }
3230
3231        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3232                false);
3233        if (alwaysDraw) {
3234            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3235        }
3236
3237        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3238        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3239
3240        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3241        if (thumb != null) {
3242            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3243        }
3244
3245        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3246                false);
3247        if (alwaysDraw) {
3248            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3249        }
3250
3251        // Re-apply user/background padding so that scrollbar(s) get added
3252        resolvePadding();
3253    }
3254
3255    /**
3256     * <p>
3257     * Initalizes the scrollability cache if necessary.
3258     * </p>
3259     */
3260    private void initScrollCache() {
3261        if (mScrollCache == null) {
3262            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3263        }
3264    }
3265
3266    /**
3267     * Set the position of the vertical scroll bar. Should be one of
3268     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3269     * {@link #SCROLLBAR_POSITION_RIGHT}.
3270     *
3271     * @param position Where the vertical scroll bar should be positioned.
3272     */
3273    public void setVerticalScrollbarPosition(int position) {
3274        if (mVerticalScrollbarPosition != position) {
3275            mVerticalScrollbarPosition = position;
3276            computeOpaqueFlags();
3277            resolvePadding();
3278        }
3279    }
3280
3281    /**
3282     * @return The position where the vertical scroll bar will show, if applicable.
3283     * @see #setVerticalScrollbarPosition(int)
3284     */
3285    public int getVerticalScrollbarPosition() {
3286        return mVerticalScrollbarPosition;
3287    }
3288
3289    /**
3290     * Register a callback to be invoked when focus of this view changed.
3291     *
3292     * @param l The callback that will run.
3293     */
3294    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3295        mOnFocusChangeListener = l;
3296    }
3297
3298    /**
3299     * Add a listener that will be called when the bounds of the view change due to
3300     * layout processing.
3301     *
3302     * @param listener The listener that will be called when layout bounds change.
3303     */
3304    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3305        if (mOnLayoutChangeListeners == null) {
3306            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3307        }
3308        mOnLayoutChangeListeners.add(listener);
3309    }
3310
3311    /**
3312     * Remove a listener for layout changes.
3313     *
3314     * @param listener The listener for layout bounds change.
3315     */
3316    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3317        if (mOnLayoutChangeListeners == null) {
3318            return;
3319        }
3320        mOnLayoutChangeListeners.remove(listener);
3321    }
3322
3323    /**
3324     * Add a listener for attach state changes.
3325     *
3326     * This listener will be called whenever this view is attached or detached
3327     * from a window. Remove the listener using
3328     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3329     *
3330     * @param listener Listener to attach
3331     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3332     */
3333    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3334        if (mOnAttachStateChangeListeners == null) {
3335            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3336        }
3337        mOnAttachStateChangeListeners.add(listener);
3338    }
3339
3340    /**
3341     * Remove a listener for attach state changes. The listener will receive no further
3342     * notification of window attach/detach events.
3343     *
3344     * @param listener Listener to remove
3345     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3346     */
3347    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3348        if (mOnAttachStateChangeListeners == null) {
3349            return;
3350        }
3351        mOnAttachStateChangeListeners.remove(listener);
3352    }
3353
3354    /**
3355     * Returns the focus-change callback registered for this view.
3356     *
3357     * @return The callback, or null if one is not registered.
3358     */
3359    public OnFocusChangeListener getOnFocusChangeListener() {
3360        return mOnFocusChangeListener;
3361    }
3362
3363    /**
3364     * Register a callback to be invoked when this view is clicked. If this view is not
3365     * clickable, it becomes clickable.
3366     *
3367     * @param l The callback that will run
3368     *
3369     * @see #setClickable(boolean)
3370     */
3371    public void setOnClickListener(OnClickListener l) {
3372        if (!isClickable()) {
3373            setClickable(true);
3374        }
3375        mOnClickListener = l;
3376    }
3377
3378    /**
3379     * Register a callback to be invoked when this view is clicked and held. If this view is not
3380     * long clickable, it becomes long clickable.
3381     *
3382     * @param l The callback that will run
3383     *
3384     * @see #setLongClickable(boolean)
3385     */
3386    public void setOnLongClickListener(OnLongClickListener l) {
3387        if (!isLongClickable()) {
3388            setLongClickable(true);
3389        }
3390        mOnLongClickListener = l;
3391    }
3392
3393    /**
3394     * Register a callback to be invoked when the context menu for this view is
3395     * being built. If this view is not long clickable, it becomes long clickable.
3396     *
3397     * @param l The callback that will run
3398     *
3399     */
3400    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3401        if (!isLongClickable()) {
3402            setLongClickable(true);
3403        }
3404        mOnCreateContextMenuListener = l;
3405    }
3406
3407    /**
3408     * Call this view's OnClickListener, if it is defined.
3409     *
3410     * @return True there was an assigned OnClickListener that was called, false
3411     *         otherwise is returned.
3412     */
3413    public boolean performClick() {
3414        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3415
3416        if (mOnClickListener != null) {
3417            playSoundEffect(SoundEffectConstants.CLICK);
3418            mOnClickListener.onClick(this);
3419            return true;
3420        }
3421
3422        return false;
3423    }
3424
3425    /**
3426     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3427     * OnLongClickListener did not consume the event.
3428     *
3429     * @return True if one of the above receivers consumed the event, false otherwise.
3430     */
3431    public boolean performLongClick() {
3432        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3433
3434        boolean handled = false;
3435        if (mOnLongClickListener != null) {
3436            handled = mOnLongClickListener.onLongClick(View.this);
3437        }
3438        if (!handled) {
3439            handled = showContextMenu();
3440        }
3441        if (handled) {
3442            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3443        }
3444        return handled;
3445    }
3446
3447    /**
3448     * Performs button-related actions during a touch down event.
3449     *
3450     * @param event The event.
3451     * @return True if the down was consumed.
3452     *
3453     * @hide
3454     */
3455    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3456        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3457            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3458                return true;
3459            }
3460        }
3461        return false;
3462    }
3463
3464    /**
3465     * Bring up the context menu for this view.
3466     *
3467     * @return Whether a context menu was displayed.
3468     */
3469    public boolean showContextMenu() {
3470        return getParent().showContextMenuForChild(this);
3471    }
3472
3473    /**
3474     * Bring up the context menu for this view, referring to the item under the specified point.
3475     *
3476     * @param x The referenced x coordinate.
3477     * @param y The referenced y coordinate.
3478     * @param metaState The keyboard modifiers that were pressed.
3479     * @return Whether a context menu was displayed.
3480     *
3481     * @hide
3482     */
3483    public boolean showContextMenu(float x, float y, int metaState) {
3484        return showContextMenu();
3485    }
3486
3487    /**
3488     * Start an action mode.
3489     *
3490     * @param callback Callback that will control the lifecycle of the action mode
3491     * @return The new action mode if it is started, null otherwise
3492     *
3493     * @see ActionMode
3494     */
3495    public ActionMode startActionMode(ActionMode.Callback callback) {
3496        return getParent().startActionModeForChild(this, callback);
3497    }
3498
3499    /**
3500     * Register a callback to be invoked when a key is pressed in this view.
3501     * @param l the key listener to attach to this view
3502     */
3503    public void setOnKeyListener(OnKeyListener l) {
3504        mOnKeyListener = l;
3505    }
3506
3507    /**
3508     * Register a callback to be invoked when a touch event is sent to this view.
3509     * @param l the touch listener to attach to this view
3510     */
3511    public void setOnTouchListener(OnTouchListener l) {
3512        mOnTouchListener = l;
3513    }
3514
3515    /**
3516     * Register a callback to be invoked when a generic motion event is sent to this view.
3517     * @param l the generic motion listener to attach to this view
3518     */
3519    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3520        mOnGenericMotionListener = l;
3521    }
3522
3523    /**
3524     * Register a callback to be invoked when a hover event is sent to this view.
3525     * @param l the hover listener to attach to this view
3526     */
3527    public void setOnHoverListener(OnHoverListener l) {
3528        mOnHoverListener = l;
3529    }
3530
3531    /**
3532     * Register a drag event listener callback object for this View. The parameter is
3533     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3534     * View, the system calls the
3535     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3536     * @param l An implementation of {@link android.view.View.OnDragListener}.
3537     */
3538    public void setOnDragListener(OnDragListener l) {
3539        mOnDragListener = l;
3540    }
3541
3542    /**
3543     * Give this view focus. This will cause
3544     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3545     *
3546     * Note: this does not check whether this {@link View} should get focus, it just
3547     * gives it focus no matter what.  It should only be called internally by framework
3548     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3549     *
3550     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3551     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3552     *        focus moved when requestFocus() is called. It may not always
3553     *        apply, in which case use the default View.FOCUS_DOWN.
3554     * @param previouslyFocusedRect The rectangle of the view that had focus
3555     *        prior in this View's coordinate system.
3556     */
3557    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3558        if (DBG) {
3559            System.out.println(this + " requestFocus()");
3560        }
3561
3562        if ((mPrivateFlags & FOCUSED) == 0) {
3563            mPrivateFlags |= FOCUSED;
3564
3565            if (mParent != null) {
3566                mParent.requestChildFocus(this, this);
3567            }
3568
3569            onFocusChanged(true, direction, previouslyFocusedRect);
3570            refreshDrawableState();
3571        }
3572    }
3573
3574    /**
3575     * Request that a rectangle of this view be visible on the screen,
3576     * scrolling if necessary just enough.
3577     *
3578     * <p>A View should call this if it maintains some notion of which part
3579     * of its content is interesting.  For example, a text editing view
3580     * should call this when its cursor moves.
3581     *
3582     * @param rectangle The rectangle.
3583     * @return Whether any parent scrolled.
3584     */
3585    public boolean requestRectangleOnScreen(Rect rectangle) {
3586        return requestRectangleOnScreen(rectangle, false);
3587    }
3588
3589    /**
3590     * Request that a rectangle of this view be visible on the screen,
3591     * scrolling if necessary just enough.
3592     *
3593     * <p>A View should call this if it maintains some notion of which part
3594     * of its content is interesting.  For example, a text editing view
3595     * should call this when its cursor moves.
3596     *
3597     * <p>When <code>immediate</code> is set to true, scrolling will not be
3598     * animated.
3599     *
3600     * @param rectangle The rectangle.
3601     * @param immediate True to forbid animated scrolling, false otherwise
3602     * @return Whether any parent scrolled.
3603     */
3604    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3605        View child = this;
3606        ViewParent parent = mParent;
3607        boolean scrolled = false;
3608        while (parent != null) {
3609            scrolled |= parent.requestChildRectangleOnScreen(child,
3610                    rectangle, immediate);
3611
3612            // offset rect so next call has the rectangle in the
3613            // coordinate system of its direct child.
3614            rectangle.offset(child.getLeft(), child.getTop());
3615            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3616
3617            if (!(parent instanceof View)) {
3618                break;
3619            }
3620
3621            child = (View) parent;
3622            parent = child.getParent();
3623        }
3624        return scrolled;
3625    }
3626
3627    /**
3628     * Called when this view wants to give up focus. This will cause
3629     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3630     */
3631    public void clearFocus() {
3632        if (DBG) {
3633            System.out.println(this + " clearFocus()");
3634        }
3635
3636        if ((mPrivateFlags & FOCUSED) != 0) {
3637            mPrivateFlags &= ~FOCUSED;
3638
3639            if (mParent != null) {
3640                mParent.clearChildFocus(this);
3641            }
3642
3643            onFocusChanged(false, 0, null);
3644            refreshDrawableState();
3645        }
3646    }
3647
3648    /**
3649     * Called to clear the focus of a view that is about to be removed.
3650     * Doesn't call clearChildFocus, which prevents this view from taking
3651     * focus again before it has been removed from the parent
3652     */
3653    void clearFocusForRemoval() {
3654        if ((mPrivateFlags & FOCUSED) != 0) {
3655            mPrivateFlags &= ~FOCUSED;
3656
3657            onFocusChanged(false, 0, null);
3658            refreshDrawableState();
3659        }
3660    }
3661
3662    /**
3663     * Called internally by the view system when a new view is getting focus.
3664     * This is what clears the old focus.
3665     */
3666    void unFocus() {
3667        if (DBG) {
3668            System.out.println(this + " unFocus()");
3669        }
3670
3671        if ((mPrivateFlags & FOCUSED) != 0) {
3672            mPrivateFlags &= ~FOCUSED;
3673
3674            onFocusChanged(false, 0, null);
3675            refreshDrawableState();
3676        }
3677    }
3678
3679    /**
3680     * Returns true if this view has focus iteself, or is the ancestor of the
3681     * view that has focus.
3682     *
3683     * @return True if this view has or contains focus, false otherwise.
3684     */
3685    @ViewDebug.ExportedProperty(category = "focus")
3686    public boolean hasFocus() {
3687        return (mPrivateFlags & FOCUSED) != 0;
3688    }
3689
3690    /**
3691     * Returns true if this view is focusable or if it contains a reachable View
3692     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3693     * is a View whose parents do not block descendants focus.
3694     *
3695     * Only {@link #VISIBLE} views are considered focusable.
3696     *
3697     * @return True if the view is focusable or if the view contains a focusable
3698     *         View, false otherwise.
3699     *
3700     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3701     */
3702    public boolean hasFocusable() {
3703        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3704    }
3705
3706    /**
3707     * Called by the view system when the focus state of this view changes.
3708     * When the focus change event is caused by directional navigation, direction
3709     * and previouslyFocusedRect provide insight into where the focus is coming from.
3710     * When overriding, be sure to call up through to the super class so that
3711     * the standard focus handling will occur.
3712     *
3713     * @param gainFocus True if the View has focus; false otherwise.
3714     * @param direction The direction focus has moved when requestFocus()
3715     *                  is called to give this view focus. Values are
3716     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3717     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3718     *                  It may not always apply, in which case use the default.
3719     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3720     *        system, of the previously focused view.  If applicable, this will be
3721     *        passed in as finer grained information about where the focus is coming
3722     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3723     */
3724    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3725        if (gainFocus) {
3726            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3727        }
3728
3729        InputMethodManager imm = InputMethodManager.peekInstance();
3730        if (!gainFocus) {
3731            if (isPressed()) {
3732                setPressed(false);
3733            }
3734            if (imm != null && mAttachInfo != null
3735                    && mAttachInfo.mHasWindowFocus) {
3736                imm.focusOut(this);
3737            }
3738            onFocusLost();
3739        } else if (imm != null && mAttachInfo != null
3740                && mAttachInfo.mHasWindowFocus) {
3741            imm.focusIn(this);
3742        }
3743
3744        invalidate(true);
3745        if (mOnFocusChangeListener != null) {
3746            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3747        }
3748
3749        if (mAttachInfo != null) {
3750            mAttachInfo.mKeyDispatchState.reset(this);
3751        }
3752    }
3753
3754    /**
3755     * Sends an accessibility event of the given type. If accessiiblity is
3756     * not enabled this method has no effect. The default implementation calls
3757     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3758     * to populate information about the event source (this View), then calls
3759     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3760     * populate the text content of the event source including its descendants,
3761     * and last calls
3762     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3763     * on its parent to resuest sending of the event to interested parties.
3764     *
3765     * @param eventType The type of the event to send.
3766     *
3767     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3768     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3769     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3770     */
3771    public void sendAccessibilityEvent(int eventType) {
3772        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3773            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3774        }
3775    }
3776
3777    /**
3778     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3779     * takes as an argument an empty {@link AccessibilityEvent} and does not
3780     * perfrom a check whether accessibility is enabled.
3781     *
3782     * @param event The event to send.
3783     *
3784     * @see #sendAccessibilityEvent(int)
3785     */
3786    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3787        if (!isShown()) {
3788            return;
3789        }
3790        onInitializeAccessibilityEvent(event);
3791        dispatchPopulateAccessibilityEvent(event);
3792        // In the beginning we called #isShown(), so we know that getParent() is not null.
3793        getParent().requestSendAccessibilityEvent(this, event);
3794    }
3795
3796    /**
3797     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3798     * to its children for adding their text content to the event. Note that the
3799     * event text is populated in a separate dispatch path since we add to the
3800     * event not only the text of the source but also the text of all its descendants.
3801     * </p>
3802     * A typical implementation will call
3803     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3804     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3805     * on each child. Override this method if custom population of the event text
3806     * content is required.
3807     *
3808     * @param event The event.
3809     *
3810     * @return True if the event population was completed.
3811     */
3812    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3813        onPopulateAccessibilityEvent(event);
3814        return false;
3815    }
3816
3817    /**
3818     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3819     * giving a chance to this View to populate the accessibility event with its
3820     * text content. While the implementation is free to modify other event
3821     * attributes this should be performed in
3822     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3823     * <p>
3824     * Example: Adding formatted date string to an accessibility event in addition
3825     *          to the text added by the super implementation.
3826     * </p><p><pre><code>
3827     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3828     *     super.onPopulateAccessibilityEvent(event);
3829     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3830     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3831     *         mCurrentDate.getTimeInMillis(), flags);
3832     *     event.getText().add(selectedDateUtterance);
3833     * }
3834     * </code></pre></p>
3835     *
3836     * @param event The accessibility event which to populate.
3837     *
3838     * @see #sendAccessibilityEvent(int)
3839     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3840     */
3841    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3842    }
3843
3844    /**
3845     * Initializes an {@link AccessibilityEvent} with information about the
3846     * the type of the event and this View which is the event source. In other
3847     * words, the source of an accessibility event is the view whose state
3848     * change triggered firing the event.
3849     * <p>
3850     * Example: Setting the password property of an event in addition
3851     *          to properties set by the super implementation.
3852     * </p><p><pre><code>
3853     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3854     *    super.onInitializeAccessibilityEvent(event);
3855     *    event.setPassword(true);
3856     * }
3857     * </code></pre></p>
3858     * @param event The event to initialeze.
3859     *
3860     * @see #sendAccessibilityEvent(int)
3861     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3862     */
3863    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3864        event.setSource(this);
3865        event.setClassName(getClass().getName());
3866        event.setPackageName(getContext().getPackageName());
3867        event.setEnabled(isEnabled());
3868        event.setContentDescription(mContentDescription);
3869
3870        final int eventType = event.getEventType();
3871        switch (eventType) {
3872            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
3873                if (mAttachInfo != null) {
3874                    ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3875                    getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
3876                            FOCUSABLES_ALL);
3877                    event.setItemCount(focusablesTempList.size());
3878                    event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3879                    focusablesTempList.clear();
3880                }
3881            } break;
3882            case AccessibilityEvent.TYPE_VIEW_SCROLLED: {
3883                event.setScrollX(mScrollX);
3884                event.setScrollY(mScrollY);
3885                event.setItemCount(getHeight());
3886            } break;
3887        }
3888    }
3889
3890    /**
3891     * Returns an {@link AccessibilityNodeInfo} representing this view from the
3892     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
3893     * This method is responsible for obtaining an accessibility node info from a
3894     * pool of reusable instances and calling
3895     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
3896     * initialize the former.
3897     * <p>
3898     * Note: The client is responsible for recycling the obtained instance by calling
3899     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
3900     * </p>
3901     * @return A populated {@link AccessibilityNodeInfo}.
3902     *
3903     * @see AccessibilityNodeInfo
3904     */
3905    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
3906        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
3907        onInitializeAccessibilityNodeInfo(info);
3908        return info;
3909    }
3910
3911    /**
3912     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
3913     * The base implementation sets:
3914     * <ul>
3915     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
3916     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
3917     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
3918     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
3919     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
3920     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
3921     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
3922     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
3923     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
3924     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
3925     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
3926     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
3927     * </ul>
3928     * <p>
3929     * Subclasses should override this method, call the super implementation,
3930     * and set additional attributes.
3931     * </p>
3932     * @param info The instance to initialize.
3933     */
3934    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
3935        Rect bounds = mAttachInfo.mTmpInvalRect;
3936        getDrawingRect(bounds);
3937        info.setBoundsInParent(bounds);
3938
3939        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
3940        getLocationOnScreen(locationOnScreen);
3941        bounds.offsetTo(0, 0);
3942        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
3943        info.setBoundsInScreen(bounds);
3944
3945        ViewParent parent = getParent();
3946        if (parent instanceof View) {
3947            View parentView = (View) parent;
3948            info.setParent(parentView);
3949        }
3950
3951        info.setPackageName(mContext.getPackageName());
3952        info.setClassName(getClass().getName());
3953        info.setContentDescription(getContentDescription());
3954
3955        info.setEnabled(isEnabled());
3956        info.setClickable(isClickable());
3957        info.setFocusable(isFocusable());
3958        info.setFocused(isFocused());
3959        info.setSelected(isSelected());
3960        info.setLongClickable(isLongClickable());
3961
3962        // TODO: These make sense only if we are in an AdapterView but all
3963        // views can be selected. Maybe from accessiiblity perspective
3964        // we should report as selectable view in an AdapterView.
3965        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
3966        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
3967
3968        if (isFocusable()) {
3969            if (isFocused()) {
3970                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
3971            } else {
3972                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
3973            }
3974        }
3975    }
3976
3977    /**
3978     * Gets the unique identifier of this view on the screen for accessibility purposes.
3979     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
3980     *
3981     * @return The view accessibility id.
3982     *
3983     * @hide
3984     */
3985    public int getAccessibilityViewId() {
3986        if (mAccessibilityViewId == NO_ID) {
3987            mAccessibilityViewId = sNextAccessibilityViewId++;
3988        }
3989        return mAccessibilityViewId;
3990    }
3991
3992    /**
3993     * Gets the unique identifier of the window in which this View reseides.
3994     *
3995     * @return The window accessibility id.
3996     *
3997     * @hide
3998     */
3999    public int getAccessibilityWindowId() {
4000        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4001    }
4002
4003    /**
4004     * Gets the {@link View} description. It briefly describes the view and is
4005     * primarily used for accessibility support. Set this property to enable
4006     * better accessibility support for your application. This is especially
4007     * true for views that do not have textual representation (For example,
4008     * ImageButton).
4009     *
4010     * @return The content descriptiopn.
4011     *
4012     * @attr ref android.R.styleable#View_contentDescription
4013     */
4014    public CharSequence getContentDescription() {
4015        return mContentDescription;
4016    }
4017
4018    /**
4019     * Sets the {@link View} description. It briefly describes the view and is
4020     * primarily used for accessibility support. Set this property to enable
4021     * better accessibility support for your application. This is especially
4022     * true for views that do not have textual representation (For example,
4023     * ImageButton).
4024     *
4025     * @param contentDescription The content description.
4026     *
4027     * @attr ref android.R.styleable#View_contentDescription
4028     */
4029    public void setContentDescription(CharSequence contentDescription) {
4030        mContentDescription = contentDescription;
4031    }
4032
4033    /**
4034     * Invoked whenever this view loses focus, either by losing window focus or by losing
4035     * focus within its window. This method can be used to clear any state tied to the
4036     * focus. For instance, if a button is held pressed with the trackball and the window
4037     * loses focus, this method can be used to cancel the press.
4038     *
4039     * Subclasses of View overriding this method should always call super.onFocusLost().
4040     *
4041     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4042     * @see #onWindowFocusChanged(boolean)
4043     *
4044     * @hide pending API council approval
4045     */
4046    protected void onFocusLost() {
4047        resetPressedState();
4048    }
4049
4050    private void resetPressedState() {
4051        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4052            return;
4053        }
4054
4055        if (isPressed()) {
4056            setPressed(false);
4057
4058            if (!mHasPerformedLongPress) {
4059                removeLongPressCallback();
4060            }
4061        }
4062    }
4063
4064    /**
4065     * Returns true if this view has focus
4066     *
4067     * @return True if this view has focus, false otherwise.
4068     */
4069    @ViewDebug.ExportedProperty(category = "focus")
4070    public boolean isFocused() {
4071        return (mPrivateFlags & FOCUSED) != 0;
4072    }
4073
4074    /**
4075     * Find the view in the hierarchy rooted at this view that currently has
4076     * focus.
4077     *
4078     * @return The view that currently has focus, or null if no focused view can
4079     *         be found.
4080     */
4081    public View findFocus() {
4082        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4083    }
4084
4085    /**
4086     * Change whether this view is one of the set of scrollable containers in
4087     * its window.  This will be used to determine whether the window can
4088     * resize or must pan when a soft input area is open -- scrollable
4089     * containers allow the window to use resize mode since the container
4090     * will appropriately shrink.
4091     */
4092    public void setScrollContainer(boolean isScrollContainer) {
4093        if (isScrollContainer) {
4094            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4095                mAttachInfo.mScrollContainers.add(this);
4096                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4097            }
4098            mPrivateFlags |= SCROLL_CONTAINER;
4099        } else {
4100            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4101                mAttachInfo.mScrollContainers.remove(this);
4102            }
4103            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4104        }
4105    }
4106
4107    /**
4108     * Returns the quality of the drawing cache.
4109     *
4110     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4111     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4112     *
4113     * @see #setDrawingCacheQuality(int)
4114     * @see #setDrawingCacheEnabled(boolean)
4115     * @see #isDrawingCacheEnabled()
4116     *
4117     * @attr ref android.R.styleable#View_drawingCacheQuality
4118     */
4119    public int getDrawingCacheQuality() {
4120        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4121    }
4122
4123    /**
4124     * Set the drawing cache quality of this view. This value is used only when the
4125     * drawing cache is enabled
4126     *
4127     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4128     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4129     *
4130     * @see #getDrawingCacheQuality()
4131     * @see #setDrawingCacheEnabled(boolean)
4132     * @see #isDrawingCacheEnabled()
4133     *
4134     * @attr ref android.R.styleable#View_drawingCacheQuality
4135     */
4136    public void setDrawingCacheQuality(int quality) {
4137        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4138    }
4139
4140    /**
4141     * Returns whether the screen should remain on, corresponding to the current
4142     * value of {@link #KEEP_SCREEN_ON}.
4143     *
4144     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4145     *
4146     * @see #setKeepScreenOn(boolean)
4147     *
4148     * @attr ref android.R.styleable#View_keepScreenOn
4149     */
4150    public boolean getKeepScreenOn() {
4151        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4152    }
4153
4154    /**
4155     * Controls whether the screen should remain on, modifying the
4156     * value of {@link #KEEP_SCREEN_ON}.
4157     *
4158     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4159     *
4160     * @see #getKeepScreenOn()
4161     *
4162     * @attr ref android.R.styleable#View_keepScreenOn
4163     */
4164    public void setKeepScreenOn(boolean keepScreenOn) {
4165        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4166    }
4167
4168    /**
4169     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4170     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4171     *
4172     * @attr ref android.R.styleable#View_nextFocusLeft
4173     */
4174    public int getNextFocusLeftId() {
4175        return mNextFocusLeftId;
4176    }
4177
4178    /**
4179     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4180     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4181     * decide automatically.
4182     *
4183     * @attr ref android.R.styleable#View_nextFocusLeft
4184     */
4185    public void setNextFocusLeftId(int nextFocusLeftId) {
4186        mNextFocusLeftId = nextFocusLeftId;
4187    }
4188
4189    /**
4190     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4191     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4192     *
4193     * @attr ref android.R.styleable#View_nextFocusRight
4194     */
4195    public int getNextFocusRightId() {
4196        return mNextFocusRightId;
4197    }
4198
4199    /**
4200     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4201     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4202     * decide automatically.
4203     *
4204     * @attr ref android.R.styleable#View_nextFocusRight
4205     */
4206    public void setNextFocusRightId(int nextFocusRightId) {
4207        mNextFocusRightId = nextFocusRightId;
4208    }
4209
4210    /**
4211     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4212     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4213     *
4214     * @attr ref android.R.styleable#View_nextFocusUp
4215     */
4216    public int getNextFocusUpId() {
4217        return mNextFocusUpId;
4218    }
4219
4220    /**
4221     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4222     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4223     * decide automatically.
4224     *
4225     * @attr ref android.R.styleable#View_nextFocusUp
4226     */
4227    public void setNextFocusUpId(int nextFocusUpId) {
4228        mNextFocusUpId = nextFocusUpId;
4229    }
4230
4231    /**
4232     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4233     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4234     *
4235     * @attr ref android.R.styleable#View_nextFocusDown
4236     */
4237    public int getNextFocusDownId() {
4238        return mNextFocusDownId;
4239    }
4240
4241    /**
4242     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4243     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4244     * decide automatically.
4245     *
4246     * @attr ref android.R.styleable#View_nextFocusDown
4247     */
4248    public void setNextFocusDownId(int nextFocusDownId) {
4249        mNextFocusDownId = nextFocusDownId;
4250    }
4251
4252    /**
4253     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4254     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4255     *
4256     * @attr ref android.R.styleable#View_nextFocusForward
4257     */
4258    public int getNextFocusForwardId() {
4259        return mNextFocusForwardId;
4260    }
4261
4262    /**
4263     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4264     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4265     * decide automatically.
4266     *
4267     * @attr ref android.R.styleable#View_nextFocusForward
4268     */
4269    public void setNextFocusForwardId(int nextFocusForwardId) {
4270        mNextFocusForwardId = nextFocusForwardId;
4271    }
4272
4273    /**
4274     * Returns the visibility of this view and all of its ancestors
4275     *
4276     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4277     */
4278    public boolean isShown() {
4279        View current = this;
4280        //noinspection ConstantConditions
4281        do {
4282            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4283                return false;
4284            }
4285            ViewParent parent = current.mParent;
4286            if (parent == null) {
4287                return false; // We are not attached to the view root
4288            }
4289            if (!(parent instanceof View)) {
4290                return true;
4291            }
4292            current = (View) parent;
4293        } while (current != null);
4294
4295        return false;
4296    }
4297
4298    /**
4299     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4300     * is set
4301     *
4302     * @param insets Insets for system windows
4303     *
4304     * @return True if this view applied the insets, false otherwise
4305     */
4306    protected boolean fitSystemWindows(Rect insets) {
4307        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4308            mPaddingLeft = insets.left;
4309            mPaddingTop = insets.top;
4310            mPaddingRight = insets.right;
4311            mPaddingBottom = insets.bottom;
4312            requestLayout();
4313            return true;
4314        }
4315        return false;
4316    }
4317
4318    /**
4319     * Set whether or not this view should account for system screen decorations
4320     * such as the status bar and inset its content. This allows this view to be
4321     * positioned in absolute screen coordinates and remain visible to the user.
4322     *
4323     * <p>This should only be used by top-level window decor views.
4324     *
4325     * @param fitSystemWindows true to inset content for system screen decorations, false for
4326     *                         default behavior.
4327     *
4328     * @attr ref android.R.styleable#View_fitsSystemWindows
4329     */
4330    public void setFitsSystemWindows(boolean fitSystemWindows) {
4331        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4332    }
4333
4334    /**
4335     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4336     * will account for system screen decorations such as the status bar and inset its
4337     * content. This allows the view to be positioned in absolute screen coordinates
4338     * and remain visible to the user.
4339     *
4340     * @return true if this view will adjust its content bounds for system screen decorations.
4341     *
4342     * @attr ref android.R.styleable#View_fitsSystemWindows
4343     */
4344    public boolean fitsSystemWindows() {
4345        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4346    }
4347
4348    /**
4349     * Returns the visibility status for this view.
4350     *
4351     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4352     * @attr ref android.R.styleable#View_visibility
4353     */
4354    @ViewDebug.ExportedProperty(mapping = {
4355        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4356        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4357        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4358    })
4359    public int getVisibility() {
4360        return mViewFlags & VISIBILITY_MASK;
4361    }
4362
4363    /**
4364     * Set the enabled state of this view.
4365     *
4366     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4367     * @attr ref android.R.styleable#View_visibility
4368     */
4369    @RemotableViewMethod
4370    public void setVisibility(int visibility) {
4371        setFlags(visibility, VISIBILITY_MASK);
4372        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4373    }
4374
4375    /**
4376     * Returns the enabled status for this view. The interpretation of the
4377     * enabled state varies by subclass.
4378     *
4379     * @return True if this view is enabled, false otherwise.
4380     */
4381    @ViewDebug.ExportedProperty
4382    public boolean isEnabled() {
4383        return (mViewFlags & ENABLED_MASK) == ENABLED;
4384    }
4385
4386    /**
4387     * Set the enabled state of this view. The interpretation of the enabled
4388     * state varies by subclass.
4389     *
4390     * @param enabled True if this view is enabled, false otherwise.
4391     */
4392    @RemotableViewMethod
4393    public void setEnabled(boolean enabled) {
4394        if (enabled == isEnabled()) return;
4395
4396        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4397
4398        /*
4399         * The View most likely has to change its appearance, so refresh
4400         * the drawable state.
4401         */
4402        refreshDrawableState();
4403
4404        // Invalidate too, since the default behavior for views is to be
4405        // be drawn at 50% alpha rather than to change the drawable.
4406        invalidate(true);
4407    }
4408
4409    /**
4410     * Set whether this view can receive the focus.
4411     *
4412     * Setting this to false will also ensure that this view is not focusable
4413     * in touch mode.
4414     *
4415     * @param focusable If true, this view can receive the focus.
4416     *
4417     * @see #setFocusableInTouchMode(boolean)
4418     * @attr ref android.R.styleable#View_focusable
4419     */
4420    public void setFocusable(boolean focusable) {
4421        if (!focusable) {
4422            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4423        }
4424        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4425    }
4426
4427    /**
4428     * Set whether this view can receive focus while in touch mode.
4429     *
4430     * Setting this to true will also ensure that this view is focusable.
4431     *
4432     * @param focusableInTouchMode If true, this view can receive the focus while
4433     *   in touch mode.
4434     *
4435     * @see #setFocusable(boolean)
4436     * @attr ref android.R.styleable#View_focusableInTouchMode
4437     */
4438    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4439        // Focusable in touch mode should always be set before the focusable flag
4440        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4441        // which, in touch mode, will not successfully request focus on this view
4442        // because the focusable in touch mode flag is not set
4443        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4444        if (focusableInTouchMode) {
4445            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4446        }
4447    }
4448
4449    /**
4450     * Set whether this view should have sound effects enabled for events such as
4451     * clicking and touching.
4452     *
4453     * <p>You may wish to disable sound effects for a view if you already play sounds,
4454     * for instance, a dial key that plays dtmf tones.
4455     *
4456     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4457     * @see #isSoundEffectsEnabled()
4458     * @see #playSoundEffect(int)
4459     * @attr ref android.R.styleable#View_soundEffectsEnabled
4460     */
4461    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4462        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4463    }
4464
4465    /**
4466     * @return whether this view should have sound effects enabled for events such as
4467     *     clicking and touching.
4468     *
4469     * @see #setSoundEffectsEnabled(boolean)
4470     * @see #playSoundEffect(int)
4471     * @attr ref android.R.styleable#View_soundEffectsEnabled
4472     */
4473    @ViewDebug.ExportedProperty
4474    public boolean isSoundEffectsEnabled() {
4475        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4476    }
4477
4478    /**
4479     * Set whether this view should have haptic feedback for events such as
4480     * long presses.
4481     *
4482     * <p>You may wish to disable haptic feedback if your view already controls
4483     * its own haptic feedback.
4484     *
4485     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4486     * @see #isHapticFeedbackEnabled()
4487     * @see #performHapticFeedback(int)
4488     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4489     */
4490    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4491        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4492    }
4493
4494    /**
4495     * @return whether this view should have haptic feedback enabled for events
4496     * long presses.
4497     *
4498     * @see #setHapticFeedbackEnabled(boolean)
4499     * @see #performHapticFeedback(int)
4500     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4501     */
4502    @ViewDebug.ExportedProperty
4503    public boolean isHapticFeedbackEnabled() {
4504        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4505    }
4506
4507    /**
4508     * Returns the layout direction for this view.
4509     *
4510     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4511     *   {@link #LAYOUT_DIRECTION_RTL},
4512     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4513     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4514     * @attr ref android.R.styleable#View_layoutDirection
4515     *
4516     * @hide
4517     */
4518    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4519        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4520        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4521        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4522        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4523    })
4524    public int getLayoutDirection() {
4525        return mViewFlags & LAYOUT_DIRECTION_MASK;
4526    }
4527
4528    /**
4529     * Set the layout direction for this view. This will propagate a reset of layout direction
4530     * resolution to the view's children and resolve layout direction for this view.
4531     *
4532     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4533     *   {@link #LAYOUT_DIRECTION_RTL},
4534     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4535     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4536     *
4537     * @attr ref android.R.styleable#View_layoutDirection
4538     *
4539     * @hide
4540     */
4541    @RemotableViewMethod
4542    public void setLayoutDirection(int layoutDirection) {
4543        if (getLayoutDirection() != layoutDirection) {
4544            resetResolvedLayoutDirection();
4545            // Setting the flag will also request a layout.
4546            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4547        }
4548    }
4549
4550    /**
4551     * Returns the resolved layout direction for this view.
4552     *
4553     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4554     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4555     *
4556     * @hide
4557     */
4558    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4559        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4560        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4561    })
4562    public int getResolvedLayoutDirection() {
4563        resolveLayoutDirectionIfNeeded();
4564        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4565                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4566    }
4567
4568    /**
4569     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4570     * layout attribute and/or the inherited value from the parent.</p>
4571     *
4572     * @return true if the layout is right-to-left.
4573     *
4574     * @hide
4575     */
4576    @ViewDebug.ExportedProperty(category = "layout")
4577    public boolean isLayoutRtl() {
4578        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4579    }
4580
4581    /**
4582     * If this view doesn't do any drawing on its own, set this flag to
4583     * allow further optimizations. By default, this flag is not set on
4584     * View, but could be set on some View subclasses such as ViewGroup.
4585     *
4586     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4587     * you should clear this flag.
4588     *
4589     * @param willNotDraw whether or not this View draw on its own
4590     */
4591    public void setWillNotDraw(boolean willNotDraw) {
4592        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4593    }
4594
4595    /**
4596     * Returns whether or not this View draws on its own.
4597     *
4598     * @return true if this view has nothing to draw, false otherwise
4599     */
4600    @ViewDebug.ExportedProperty(category = "drawing")
4601    public boolean willNotDraw() {
4602        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4603    }
4604
4605    /**
4606     * When a View's drawing cache is enabled, drawing is redirected to an
4607     * offscreen bitmap. Some views, like an ImageView, must be able to
4608     * bypass this mechanism if they already draw a single bitmap, to avoid
4609     * unnecessary usage of the memory.
4610     *
4611     * @param willNotCacheDrawing true if this view does not cache its
4612     *        drawing, false otherwise
4613     */
4614    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4615        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4616    }
4617
4618    /**
4619     * Returns whether or not this View can cache its drawing or not.
4620     *
4621     * @return true if this view does not cache its drawing, false otherwise
4622     */
4623    @ViewDebug.ExportedProperty(category = "drawing")
4624    public boolean willNotCacheDrawing() {
4625        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4626    }
4627
4628    /**
4629     * Indicates whether this view reacts to click events or not.
4630     *
4631     * @return true if the view is clickable, false otherwise
4632     *
4633     * @see #setClickable(boolean)
4634     * @attr ref android.R.styleable#View_clickable
4635     */
4636    @ViewDebug.ExportedProperty
4637    public boolean isClickable() {
4638        return (mViewFlags & CLICKABLE) == CLICKABLE;
4639    }
4640
4641    /**
4642     * Enables or disables click events for this view. When a view
4643     * is clickable it will change its state to "pressed" on every click.
4644     * Subclasses should set the view clickable to visually react to
4645     * user's clicks.
4646     *
4647     * @param clickable true to make the view clickable, false otherwise
4648     *
4649     * @see #isClickable()
4650     * @attr ref android.R.styleable#View_clickable
4651     */
4652    public void setClickable(boolean clickable) {
4653        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4654    }
4655
4656    /**
4657     * Indicates whether this view reacts to long click events or not.
4658     *
4659     * @return true if the view is long clickable, false otherwise
4660     *
4661     * @see #setLongClickable(boolean)
4662     * @attr ref android.R.styleable#View_longClickable
4663     */
4664    public boolean isLongClickable() {
4665        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4666    }
4667
4668    /**
4669     * Enables or disables long click events for this view. When a view is long
4670     * clickable it reacts to the user holding down the button for a longer
4671     * duration than a tap. This event can either launch the listener or a
4672     * context menu.
4673     *
4674     * @param longClickable true to make the view long clickable, false otherwise
4675     * @see #isLongClickable()
4676     * @attr ref android.R.styleable#View_longClickable
4677     */
4678    public void setLongClickable(boolean longClickable) {
4679        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4680    }
4681
4682    /**
4683     * Sets the pressed state for this view.
4684     *
4685     * @see #isClickable()
4686     * @see #setClickable(boolean)
4687     *
4688     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4689     *        the View's internal state from a previously set "pressed" state.
4690     */
4691    public void setPressed(boolean pressed) {
4692        if (pressed) {
4693            mPrivateFlags |= PRESSED;
4694        } else {
4695            mPrivateFlags &= ~PRESSED;
4696        }
4697        refreshDrawableState();
4698        dispatchSetPressed(pressed);
4699    }
4700
4701    /**
4702     * Dispatch setPressed to all of this View's children.
4703     *
4704     * @see #setPressed(boolean)
4705     *
4706     * @param pressed The new pressed state
4707     */
4708    protected void dispatchSetPressed(boolean pressed) {
4709    }
4710
4711    /**
4712     * Indicates whether the view is currently in pressed state. Unless
4713     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4714     * the pressed state.
4715     *
4716     * @see #setPressed(boolean)
4717     * @see #isClickable()
4718     * @see #setClickable(boolean)
4719     *
4720     * @return true if the view is currently pressed, false otherwise
4721     */
4722    public boolean isPressed() {
4723        return (mPrivateFlags & PRESSED) == PRESSED;
4724    }
4725
4726    /**
4727     * Indicates whether this view will save its state (that is,
4728     * whether its {@link #onSaveInstanceState} method will be called).
4729     *
4730     * @return Returns true if the view state saving is enabled, else false.
4731     *
4732     * @see #setSaveEnabled(boolean)
4733     * @attr ref android.R.styleable#View_saveEnabled
4734     */
4735    public boolean isSaveEnabled() {
4736        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4737    }
4738
4739    /**
4740     * Controls whether the saving of this view's state is
4741     * enabled (that is, whether its {@link #onSaveInstanceState} method
4742     * will be called).  Note that even if freezing is enabled, the
4743     * view still must have an id assigned to it (via {@link #setId(int)})
4744     * for its state to be saved.  This flag can only disable the
4745     * saving of this view; any child views may still have their state saved.
4746     *
4747     * @param enabled Set to false to <em>disable</em> state saving, or true
4748     * (the default) to allow it.
4749     *
4750     * @see #isSaveEnabled()
4751     * @see #setId(int)
4752     * @see #onSaveInstanceState()
4753     * @attr ref android.R.styleable#View_saveEnabled
4754     */
4755    public void setSaveEnabled(boolean enabled) {
4756        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4757    }
4758
4759    /**
4760     * Gets whether the framework should discard touches when the view's
4761     * window is obscured by another visible window.
4762     * Refer to the {@link View} security documentation for more details.
4763     *
4764     * @return True if touch filtering is enabled.
4765     *
4766     * @see #setFilterTouchesWhenObscured(boolean)
4767     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4768     */
4769    @ViewDebug.ExportedProperty
4770    public boolean getFilterTouchesWhenObscured() {
4771        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4772    }
4773
4774    /**
4775     * Sets whether the framework should discard touches when the view's
4776     * window is obscured by another visible window.
4777     * Refer to the {@link View} security documentation for more details.
4778     *
4779     * @param enabled True if touch filtering should be enabled.
4780     *
4781     * @see #getFilterTouchesWhenObscured
4782     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4783     */
4784    public void setFilterTouchesWhenObscured(boolean enabled) {
4785        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4786                FILTER_TOUCHES_WHEN_OBSCURED);
4787    }
4788
4789    /**
4790     * Indicates whether the entire hierarchy under this view will save its
4791     * state when a state saving traversal occurs from its parent.  The default
4792     * is true; if false, these views will not be saved unless
4793     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4794     *
4795     * @return Returns true if the view state saving from parent is enabled, else false.
4796     *
4797     * @see #setSaveFromParentEnabled(boolean)
4798     */
4799    public boolean isSaveFromParentEnabled() {
4800        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4801    }
4802
4803    /**
4804     * Controls whether the entire hierarchy under this view will save its
4805     * state when a state saving traversal occurs from its parent.  The default
4806     * is true; if false, these views will not be saved unless
4807     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4808     *
4809     * @param enabled Set to false to <em>disable</em> state saving, or true
4810     * (the default) to allow it.
4811     *
4812     * @see #isSaveFromParentEnabled()
4813     * @see #setId(int)
4814     * @see #onSaveInstanceState()
4815     */
4816    public void setSaveFromParentEnabled(boolean enabled) {
4817        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4818    }
4819
4820
4821    /**
4822     * Returns whether this View is able to take focus.
4823     *
4824     * @return True if this view can take focus, or false otherwise.
4825     * @attr ref android.R.styleable#View_focusable
4826     */
4827    @ViewDebug.ExportedProperty(category = "focus")
4828    public final boolean isFocusable() {
4829        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4830    }
4831
4832    /**
4833     * When a view is focusable, it may not want to take focus when in touch mode.
4834     * For example, a button would like focus when the user is navigating via a D-pad
4835     * so that the user can click on it, but once the user starts touching the screen,
4836     * the button shouldn't take focus
4837     * @return Whether the view is focusable in touch mode.
4838     * @attr ref android.R.styleable#View_focusableInTouchMode
4839     */
4840    @ViewDebug.ExportedProperty
4841    public final boolean isFocusableInTouchMode() {
4842        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4843    }
4844
4845    /**
4846     * Find the nearest view in the specified direction that can take focus.
4847     * This does not actually give focus to that view.
4848     *
4849     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4850     *
4851     * @return The nearest focusable in the specified direction, or null if none
4852     *         can be found.
4853     */
4854    public View focusSearch(int direction) {
4855        if (mParent != null) {
4856            return mParent.focusSearch(this, direction);
4857        } else {
4858            return null;
4859        }
4860    }
4861
4862    /**
4863     * This method is the last chance for the focused view and its ancestors to
4864     * respond to an arrow key. This is called when the focused view did not
4865     * consume the key internally, nor could the view system find a new view in
4866     * the requested direction to give focus to.
4867     *
4868     * @param focused The currently focused view.
4869     * @param direction The direction focus wants to move. One of FOCUS_UP,
4870     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4871     * @return True if the this view consumed this unhandled move.
4872     */
4873    public boolean dispatchUnhandledMove(View focused, int direction) {
4874        return false;
4875    }
4876
4877    /**
4878     * If a user manually specified the next view id for a particular direction,
4879     * use the root to look up the view.
4880     * @param root The root view of the hierarchy containing this view.
4881     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4882     * or FOCUS_BACKWARD.
4883     * @return The user specified next view, or null if there is none.
4884     */
4885    View findUserSetNextFocus(View root, int direction) {
4886        switch (direction) {
4887            case FOCUS_LEFT:
4888                if (mNextFocusLeftId == View.NO_ID) return null;
4889                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
4890            case FOCUS_RIGHT:
4891                if (mNextFocusRightId == View.NO_ID) return null;
4892                return findViewInsideOutShouldExist(root, mNextFocusRightId);
4893            case FOCUS_UP:
4894                if (mNextFocusUpId == View.NO_ID) return null;
4895                return findViewInsideOutShouldExist(root, mNextFocusUpId);
4896            case FOCUS_DOWN:
4897                if (mNextFocusDownId == View.NO_ID) return null;
4898                return findViewInsideOutShouldExist(root, mNextFocusDownId);
4899            case FOCUS_FORWARD:
4900                if (mNextFocusForwardId == View.NO_ID) return null;
4901                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
4902            case FOCUS_BACKWARD: {
4903                final int id = mID;
4904                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
4905                    @Override
4906                    public boolean apply(View t) {
4907                        return t.mNextFocusForwardId == id;
4908                    }
4909                });
4910            }
4911        }
4912        return null;
4913    }
4914
4915    private View findViewInsideOutShouldExist(View root, final int childViewId) {
4916        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
4917            @Override
4918            public boolean apply(View t) {
4919                return t.mID == childViewId;
4920            }
4921        });
4922
4923        if (result == null) {
4924            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4925                    + "by user for id " + childViewId);
4926        }
4927        return result;
4928    }
4929
4930    /**
4931     * Find and return all focusable views that are descendants of this view,
4932     * possibly including this view if it is focusable itself.
4933     *
4934     * @param direction The direction of the focus
4935     * @return A list of focusable views
4936     */
4937    public ArrayList<View> getFocusables(int direction) {
4938        ArrayList<View> result = new ArrayList<View>(24);
4939        addFocusables(result, direction);
4940        return result;
4941    }
4942
4943    /**
4944     * Add any focusable views that are descendants of this view (possibly
4945     * including this view if it is focusable itself) to views.  If we are in touch mode,
4946     * only add views that are also focusable in touch mode.
4947     *
4948     * @param views Focusable views found so far
4949     * @param direction The direction of the focus
4950     */
4951    public void addFocusables(ArrayList<View> views, int direction) {
4952        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4953    }
4954
4955    /**
4956     * Adds any focusable views that are descendants of this view (possibly
4957     * including this view if it is focusable itself) to views. This method
4958     * adds all focusable views regardless if we are in touch mode or
4959     * only views focusable in touch mode if we are in touch mode depending on
4960     * the focusable mode paramater.
4961     *
4962     * @param views Focusable views found so far or null if all we are interested is
4963     *        the number of focusables.
4964     * @param direction The direction of the focus.
4965     * @param focusableMode The type of focusables to be added.
4966     *
4967     * @see #FOCUSABLES_ALL
4968     * @see #FOCUSABLES_TOUCH_MODE
4969     */
4970    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4971        if (!isFocusable()) {
4972            return;
4973        }
4974
4975        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4976                isInTouchMode() && !isFocusableInTouchMode()) {
4977            return;
4978        }
4979
4980        if (views != null) {
4981            views.add(this);
4982        }
4983    }
4984
4985    /**
4986     * Finds the Views that contain given text. The containment is case insensitive.
4987     * As View's text is considered any text content that View renders.
4988     *
4989     * @param outViews The output list of matching Views.
4990     * @param text The text to match against.
4991     */
4992    public void findViewsWithText(ArrayList<View> outViews, CharSequence text) {
4993    }
4994
4995    /**
4996     * Find and return all touchable views that are descendants of this view,
4997     * possibly including this view if it is touchable itself.
4998     *
4999     * @return A list of touchable views
5000     */
5001    public ArrayList<View> getTouchables() {
5002        ArrayList<View> result = new ArrayList<View>();
5003        addTouchables(result);
5004        return result;
5005    }
5006
5007    /**
5008     * Add any touchable views that are descendants of this view (possibly
5009     * including this view if it is touchable itself) to views.
5010     *
5011     * @param views Touchable views found so far
5012     */
5013    public void addTouchables(ArrayList<View> views) {
5014        final int viewFlags = mViewFlags;
5015
5016        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5017                && (viewFlags & ENABLED_MASK) == ENABLED) {
5018            views.add(this);
5019        }
5020    }
5021
5022    /**
5023     * Call this to try to give focus to a specific view or to one of its
5024     * descendants.
5025     *
5026     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5027     * false), or if it is focusable and it is not focusable in touch mode
5028     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5029     *
5030     * See also {@link #focusSearch(int)}, which is what you call to say that you
5031     * have focus, and you want your parent to look for the next one.
5032     *
5033     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5034     * {@link #FOCUS_DOWN} and <code>null</code>.
5035     *
5036     * @return Whether this view or one of its descendants actually took focus.
5037     */
5038    public final boolean requestFocus() {
5039        return requestFocus(View.FOCUS_DOWN);
5040    }
5041
5042
5043    /**
5044     * Call this to try to give focus to a specific view or to one of its
5045     * descendants and give it a hint about what direction focus is heading.
5046     *
5047     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5048     * false), or if it is focusable and it is not focusable in touch mode
5049     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5050     *
5051     * See also {@link #focusSearch(int)}, which is what you call to say that you
5052     * have focus, and you want your parent to look for the next one.
5053     *
5054     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5055     * <code>null</code> set for the previously focused rectangle.
5056     *
5057     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5058     * @return Whether this view or one of its descendants actually took focus.
5059     */
5060    public final boolean requestFocus(int direction) {
5061        return requestFocus(direction, null);
5062    }
5063
5064    /**
5065     * Call this to try to give focus to a specific view or to one of its descendants
5066     * and give it hints about the direction and a specific rectangle that the focus
5067     * is coming from.  The rectangle can help give larger views a finer grained hint
5068     * about where focus is coming from, and therefore, where to show selection, or
5069     * forward focus change internally.
5070     *
5071     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5072     * false), or if it is focusable and it is not focusable in touch mode
5073     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5074     *
5075     * A View will not take focus if it is not visible.
5076     *
5077     * A View will not take focus if one of its parents has
5078     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5079     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5080     *
5081     * See also {@link #focusSearch(int)}, which is what you call to say that you
5082     * have focus, and you want your parent to look for the next one.
5083     *
5084     * You may wish to override this method if your custom {@link View} has an internal
5085     * {@link View} that it wishes to forward the request to.
5086     *
5087     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5088     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5089     *        to give a finer grained hint about where focus is coming from.  May be null
5090     *        if there is no hint.
5091     * @return Whether this view or one of its descendants actually took focus.
5092     */
5093    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5094        // need to be focusable
5095        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5096                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5097            return false;
5098        }
5099
5100        // need to be focusable in touch mode if in touch mode
5101        if (isInTouchMode() &&
5102            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5103               return false;
5104        }
5105
5106        // need to not have any parents blocking us
5107        if (hasAncestorThatBlocksDescendantFocus()) {
5108            return false;
5109        }
5110
5111        handleFocusGainInternal(direction, previouslyFocusedRect);
5112        return true;
5113    }
5114
5115    /** Gets the ViewAncestor, or null if not attached. */
5116    /*package*/ ViewRootImpl getViewRootImpl() {
5117        View root = getRootView();
5118        return root != null ? (ViewRootImpl)root.getParent() : null;
5119    }
5120
5121    /**
5122     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5123     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5124     * touch mode to request focus when they are touched.
5125     *
5126     * @return Whether this view or one of its descendants actually took focus.
5127     *
5128     * @see #isInTouchMode()
5129     *
5130     */
5131    public final boolean requestFocusFromTouch() {
5132        // Leave touch mode if we need to
5133        if (isInTouchMode()) {
5134            ViewRootImpl viewRoot = getViewRootImpl();
5135            if (viewRoot != null) {
5136                viewRoot.ensureTouchMode(false);
5137            }
5138        }
5139        return requestFocus(View.FOCUS_DOWN);
5140    }
5141
5142    /**
5143     * @return Whether any ancestor of this view blocks descendant focus.
5144     */
5145    private boolean hasAncestorThatBlocksDescendantFocus() {
5146        ViewParent ancestor = mParent;
5147        while (ancestor instanceof ViewGroup) {
5148            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5149            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5150                return true;
5151            } else {
5152                ancestor = vgAncestor.getParent();
5153            }
5154        }
5155        return false;
5156    }
5157
5158    /**
5159     * @hide
5160     */
5161    public void dispatchStartTemporaryDetach() {
5162        onStartTemporaryDetach();
5163    }
5164
5165    /**
5166     * This is called when a container is going to temporarily detach a child, with
5167     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5168     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5169     * {@link #onDetachedFromWindow()} when the container is done.
5170     */
5171    public void onStartTemporaryDetach() {
5172        removeUnsetPressCallback();
5173        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5174    }
5175
5176    /**
5177     * @hide
5178     */
5179    public void dispatchFinishTemporaryDetach() {
5180        onFinishTemporaryDetach();
5181    }
5182
5183    /**
5184     * Called after {@link #onStartTemporaryDetach} when the container is done
5185     * changing the view.
5186     */
5187    public void onFinishTemporaryDetach() {
5188    }
5189
5190    /**
5191     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5192     * for this view's window.  Returns null if the view is not currently attached
5193     * to the window.  Normally you will not need to use this directly, but
5194     * just use the standard high-level event callbacks like
5195     * {@link #onKeyDown(int, KeyEvent)}.
5196     */
5197    public KeyEvent.DispatcherState getKeyDispatcherState() {
5198        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5199    }
5200
5201    /**
5202     * Dispatch a key event before it is processed by any input method
5203     * associated with the view hierarchy.  This can be used to intercept
5204     * key events in special situations before the IME consumes them; a
5205     * typical example would be handling the BACK key to update the application's
5206     * UI instead of allowing the IME to see it and close itself.
5207     *
5208     * @param event The key event to be dispatched.
5209     * @return True if the event was handled, false otherwise.
5210     */
5211    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5212        return onKeyPreIme(event.getKeyCode(), event);
5213    }
5214
5215    /**
5216     * Dispatch a key event to the next view on the focus path. This path runs
5217     * from the top of the view tree down to the currently focused view. If this
5218     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5219     * the next node down the focus path. This method also fires any key
5220     * listeners.
5221     *
5222     * @param event The key event to be dispatched.
5223     * @return True if the event was handled, false otherwise.
5224     */
5225    public boolean dispatchKeyEvent(KeyEvent event) {
5226        if (mInputEventConsistencyVerifier != null) {
5227            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5228        }
5229
5230        // Give any attached key listener a first crack at the event.
5231        //noinspection SimplifiableIfStatement
5232        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5233                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5234            return true;
5235        }
5236
5237        if (event.dispatch(this, mAttachInfo != null
5238                ? mAttachInfo.mKeyDispatchState : null, this)) {
5239            return true;
5240        }
5241
5242        if (mInputEventConsistencyVerifier != null) {
5243            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5244        }
5245        return false;
5246    }
5247
5248    /**
5249     * Dispatches a key shortcut event.
5250     *
5251     * @param event The key event to be dispatched.
5252     * @return True if the event was handled by the view, false otherwise.
5253     */
5254    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5255        return onKeyShortcut(event.getKeyCode(), event);
5256    }
5257
5258    /**
5259     * Pass the touch screen motion event down to the target view, or this
5260     * view if it is the target.
5261     *
5262     * @param event The motion event to be dispatched.
5263     * @return True if the event was handled by the view, false otherwise.
5264     */
5265    public boolean dispatchTouchEvent(MotionEvent event) {
5266        if (mInputEventConsistencyVerifier != null) {
5267            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5268        }
5269
5270        if (onFilterTouchEventForSecurity(event)) {
5271            //noinspection SimplifiableIfStatement
5272            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
5273                    mOnTouchListener.onTouch(this, event)) {
5274                return true;
5275            }
5276
5277            if (onTouchEvent(event)) {
5278                return true;
5279            }
5280        }
5281
5282        if (mInputEventConsistencyVerifier != null) {
5283            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5284        }
5285        return false;
5286    }
5287
5288    /**
5289     * Filter the touch event to apply security policies.
5290     *
5291     * @param event The motion event to be filtered.
5292     * @return True if the event should be dispatched, false if the event should be dropped.
5293     *
5294     * @see #getFilterTouchesWhenObscured
5295     */
5296    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5297        //noinspection RedundantIfStatement
5298        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5299                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5300            // Window is obscured, drop this touch.
5301            return false;
5302        }
5303        return true;
5304    }
5305
5306    /**
5307     * Pass a trackball motion event down to the focused view.
5308     *
5309     * @param event The motion event to be dispatched.
5310     * @return True if the event was handled by the view, false otherwise.
5311     */
5312    public boolean dispatchTrackballEvent(MotionEvent event) {
5313        if (mInputEventConsistencyVerifier != null) {
5314            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5315        }
5316
5317        return onTrackballEvent(event);
5318    }
5319
5320    /**
5321     * Dispatch a generic motion event.
5322     * <p>
5323     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5324     * are delivered to the view under the pointer.  All other generic motion events are
5325     * delivered to the focused view.  Hover events are handled specially and are delivered
5326     * to {@link #onHoverEvent(MotionEvent)}.
5327     * </p>
5328     *
5329     * @param event The motion event to be dispatched.
5330     * @return True if the event was handled by the view, false otherwise.
5331     */
5332    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5333        if (mInputEventConsistencyVerifier != null) {
5334            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5335        }
5336
5337        final int source = event.getSource();
5338        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5339            final int action = event.getAction();
5340            if (action == MotionEvent.ACTION_HOVER_ENTER
5341                    || action == MotionEvent.ACTION_HOVER_MOVE
5342                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5343                if (dispatchHoverEvent(event)) {
5344                    return true;
5345                }
5346            } else if (dispatchGenericPointerEvent(event)) {
5347                return true;
5348            }
5349        } else if (dispatchGenericFocusedEvent(event)) {
5350            return true;
5351        }
5352
5353        if (dispatchGenericMotionEventInternal(event)) {
5354            return true;
5355        }
5356
5357        if (mInputEventConsistencyVerifier != null) {
5358            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5359        }
5360        return false;
5361    }
5362
5363    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5364        //noinspection SimplifiableIfStatement
5365        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5366                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5367            return true;
5368        }
5369
5370        if (onGenericMotionEvent(event)) {
5371            return true;
5372        }
5373
5374        if (mInputEventConsistencyVerifier != null) {
5375            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5376        }
5377        return false;
5378    }
5379
5380    /**
5381     * Dispatch a hover event.
5382     * <p>
5383     * Do not call this method directly.
5384     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5385     * </p>
5386     *
5387     * @param event The motion event to be dispatched.
5388     * @return True if the event was handled by the view, false otherwise.
5389     */
5390    protected boolean dispatchHoverEvent(MotionEvent event) {
5391        //noinspection SimplifiableIfStatement
5392        if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5393                && mOnHoverListener.onHover(this, event)) {
5394            return true;
5395        }
5396
5397        return onHoverEvent(event);
5398    }
5399
5400    /**
5401     * Returns true if the view has a child to which it has recently sent
5402     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5403     * it does not have a hovered child, then it must be the innermost hovered view.
5404     * @hide
5405     */
5406    protected boolean hasHoveredChild() {
5407        return false;
5408    }
5409
5410    /**
5411     * Dispatch a generic motion event to the view under the first pointer.
5412     * <p>
5413     * Do not call this method directly.
5414     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5415     * </p>
5416     *
5417     * @param event The motion event to be dispatched.
5418     * @return True if the event was handled by the view, false otherwise.
5419     */
5420    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5421        return false;
5422    }
5423
5424    /**
5425     * Dispatch a generic motion event to the currently focused view.
5426     * <p>
5427     * Do not call this method directly.
5428     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5429     * </p>
5430     *
5431     * @param event The motion event to be dispatched.
5432     * @return True if the event was handled by the view, false otherwise.
5433     */
5434    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5435        return false;
5436    }
5437
5438    /**
5439     * Dispatch a pointer event.
5440     * <p>
5441     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5442     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5443     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5444     * and should not be expected to handle other pointing device features.
5445     * </p>
5446     *
5447     * @param event The motion event to be dispatched.
5448     * @return True if the event was handled by the view, false otherwise.
5449     * @hide
5450     */
5451    public final boolean dispatchPointerEvent(MotionEvent event) {
5452        if (event.isTouchEvent()) {
5453            return dispatchTouchEvent(event);
5454        } else {
5455            return dispatchGenericMotionEvent(event);
5456        }
5457    }
5458
5459    /**
5460     * Called when the window containing this view gains or loses window focus.
5461     * ViewGroups should override to route to their children.
5462     *
5463     * @param hasFocus True if the window containing this view now has focus,
5464     *        false otherwise.
5465     */
5466    public void dispatchWindowFocusChanged(boolean hasFocus) {
5467        onWindowFocusChanged(hasFocus);
5468    }
5469
5470    /**
5471     * Called when the window containing this view gains or loses focus.  Note
5472     * that this is separate from view focus: to receive key events, both
5473     * your view and its window must have focus.  If a window is displayed
5474     * on top of yours that takes input focus, then your own window will lose
5475     * focus but the view focus will remain unchanged.
5476     *
5477     * @param hasWindowFocus True if the window containing this view now has
5478     *        focus, false otherwise.
5479     */
5480    public void onWindowFocusChanged(boolean hasWindowFocus) {
5481        InputMethodManager imm = InputMethodManager.peekInstance();
5482        if (!hasWindowFocus) {
5483            if (isPressed()) {
5484                setPressed(false);
5485            }
5486            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5487                imm.focusOut(this);
5488            }
5489            removeLongPressCallback();
5490            removeTapCallback();
5491            onFocusLost();
5492        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5493            imm.focusIn(this);
5494        }
5495        refreshDrawableState();
5496    }
5497
5498    /**
5499     * Returns true if this view is in a window that currently has window focus.
5500     * Note that this is not the same as the view itself having focus.
5501     *
5502     * @return True if this view is in a window that currently has window focus.
5503     */
5504    public boolean hasWindowFocus() {
5505        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5506    }
5507
5508    /**
5509     * Dispatch a view visibility change down the view hierarchy.
5510     * ViewGroups should override to route to their children.
5511     * @param changedView The view whose visibility changed. Could be 'this' or
5512     * an ancestor view.
5513     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5514     * {@link #INVISIBLE} or {@link #GONE}.
5515     */
5516    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5517        onVisibilityChanged(changedView, visibility);
5518    }
5519
5520    /**
5521     * Called when the visibility of the view or an ancestor of the view is changed.
5522     * @param changedView The view whose visibility changed. Could be 'this' or
5523     * an ancestor view.
5524     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5525     * {@link #INVISIBLE} or {@link #GONE}.
5526     */
5527    protected void onVisibilityChanged(View changedView, int visibility) {
5528        if (visibility == VISIBLE) {
5529            if (mAttachInfo != null) {
5530                initialAwakenScrollBars();
5531            } else {
5532                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5533            }
5534        }
5535    }
5536
5537    /**
5538     * Dispatch a hint about whether this view is displayed. For instance, when
5539     * a View moves out of the screen, it might receives a display hint indicating
5540     * the view is not displayed. Applications should not <em>rely</em> on this hint
5541     * as there is no guarantee that they will receive one.
5542     *
5543     * @param hint A hint about whether or not this view is displayed:
5544     * {@link #VISIBLE} or {@link #INVISIBLE}.
5545     */
5546    public void dispatchDisplayHint(int hint) {
5547        onDisplayHint(hint);
5548    }
5549
5550    /**
5551     * Gives this view a hint about whether is displayed or not. For instance, when
5552     * a View moves out of the screen, it might receives a display hint indicating
5553     * the view is not displayed. Applications should not <em>rely</em> on this hint
5554     * as there is no guarantee that they will receive one.
5555     *
5556     * @param hint A hint about whether or not this view is displayed:
5557     * {@link #VISIBLE} or {@link #INVISIBLE}.
5558     */
5559    protected void onDisplayHint(int hint) {
5560    }
5561
5562    /**
5563     * Dispatch a window visibility change down the view hierarchy.
5564     * ViewGroups should override to route to their children.
5565     *
5566     * @param visibility The new visibility of the window.
5567     *
5568     * @see #onWindowVisibilityChanged(int)
5569     */
5570    public void dispatchWindowVisibilityChanged(int visibility) {
5571        onWindowVisibilityChanged(visibility);
5572    }
5573
5574    /**
5575     * Called when the window containing has change its visibility
5576     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5577     * that this tells you whether or not your window is being made visible
5578     * to the window manager; this does <em>not</em> tell you whether or not
5579     * your window is obscured by other windows on the screen, even if it
5580     * is itself visible.
5581     *
5582     * @param visibility The new visibility of the window.
5583     */
5584    protected void onWindowVisibilityChanged(int visibility) {
5585        if (visibility == VISIBLE) {
5586            initialAwakenScrollBars();
5587        }
5588    }
5589
5590    /**
5591     * Returns the current visibility of the window this view is attached to
5592     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5593     *
5594     * @return Returns the current visibility of the view's window.
5595     */
5596    public int getWindowVisibility() {
5597        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5598    }
5599
5600    /**
5601     * Retrieve the overall visible display size in which the window this view is
5602     * attached to has been positioned in.  This takes into account screen
5603     * decorations above the window, for both cases where the window itself
5604     * is being position inside of them or the window is being placed under
5605     * then and covered insets are used for the window to position its content
5606     * inside.  In effect, this tells you the available area where content can
5607     * be placed and remain visible to users.
5608     *
5609     * <p>This function requires an IPC back to the window manager to retrieve
5610     * the requested information, so should not be used in performance critical
5611     * code like drawing.
5612     *
5613     * @param outRect Filled in with the visible display frame.  If the view
5614     * is not attached to a window, this is simply the raw display size.
5615     */
5616    public void getWindowVisibleDisplayFrame(Rect outRect) {
5617        if (mAttachInfo != null) {
5618            try {
5619                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5620            } catch (RemoteException e) {
5621                return;
5622            }
5623            // XXX This is really broken, and probably all needs to be done
5624            // in the window manager, and we need to know more about whether
5625            // we want the area behind or in front of the IME.
5626            final Rect insets = mAttachInfo.mVisibleInsets;
5627            outRect.left += insets.left;
5628            outRect.top += insets.top;
5629            outRect.right -= insets.right;
5630            outRect.bottom -= insets.bottom;
5631            return;
5632        }
5633        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5634        d.getRectSize(outRect);
5635    }
5636
5637    /**
5638     * Dispatch a notification about a resource configuration change down
5639     * the view hierarchy.
5640     * ViewGroups should override to route to their children.
5641     *
5642     * @param newConfig The new resource configuration.
5643     *
5644     * @see #onConfigurationChanged(android.content.res.Configuration)
5645     */
5646    public void dispatchConfigurationChanged(Configuration newConfig) {
5647        onConfigurationChanged(newConfig);
5648    }
5649
5650    /**
5651     * Called when the current configuration of the resources being used
5652     * by the application have changed.  You can use this to decide when
5653     * to reload resources that can changed based on orientation and other
5654     * configuration characterstics.  You only need to use this if you are
5655     * not relying on the normal {@link android.app.Activity} mechanism of
5656     * recreating the activity instance upon a configuration change.
5657     *
5658     * @param newConfig The new resource configuration.
5659     */
5660    protected void onConfigurationChanged(Configuration newConfig) {
5661    }
5662
5663    /**
5664     * Private function to aggregate all per-view attributes in to the view
5665     * root.
5666     */
5667    void dispatchCollectViewAttributes(int visibility) {
5668        performCollectViewAttributes(visibility);
5669    }
5670
5671    void performCollectViewAttributes(int visibility) {
5672        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5673            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5674                mAttachInfo.mKeepScreenOn = true;
5675            }
5676            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5677            if (mOnSystemUiVisibilityChangeListener != null) {
5678                mAttachInfo.mHasSystemUiListeners = true;
5679            }
5680        }
5681    }
5682
5683    void needGlobalAttributesUpdate(boolean force) {
5684        final AttachInfo ai = mAttachInfo;
5685        if (ai != null) {
5686            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5687                    || ai.mHasSystemUiListeners) {
5688                ai.mRecomputeGlobalAttributes = true;
5689            }
5690        }
5691    }
5692
5693    /**
5694     * Returns whether the device is currently in touch mode.  Touch mode is entered
5695     * once the user begins interacting with the device by touch, and affects various
5696     * things like whether focus is always visible to the user.
5697     *
5698     * @return Whether the device is in touch mode.
5699     */
5700    @ViewDebug.ExportedProperty
5701    public boolean isInTouchMode() {
5702        if (mAttachInfo != null) {
5703            return mAttachInfo.mInTouchMode;
5704        } else {
5705            return ViewRootImpl.isInTouchMode();
5706        }
5707    }
5708
5709    /**
5710     * Returns the context the view is running in, through which it can
5711     * access the current theme, resources, etc.
5712     *
5713     * @return The view's Context.
5714     */
5715    @ViewDebug.CapturedViewProperty
5716    public final Context getContext() {
5717        return mContext;
5718    }
5719
5720    /**
5721     * Handle a key event before it is processed by any input method
5722     * associated with the view hierarchy.  This can be used to intercept
5723     * key events in special situations before the IME consumes them; a
5724     * typical example would be handling the BACK key to update the application's
5725     * UI instead of allowing the IME to see it and close itself.
5726     *
5727     * @param keyCode The value in event.getKeyCode().
5728     * @param event Description of the key event.
5729     * @return If you handled the event, return true. If you want to allow the
5730     *         event to be handled by the next receiver, return false.
5731     */
5732    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5733        return false;
5734    }
5735
5736    /**
5737     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5738     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5739     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5740     * is released, if the view is enabled and clickable.
5741     *
5742     * @param keyCode A key code that represents the button pressed, from
5743     *                {@link android.view.KeyEvent}.
5744     * @param event   The KeyEvent object that defines the button action.
5745     */
5746    public boolean onKeyDown(int keyCode, KeyEvent event) {
5747        boolean result = false;
5748
5749        switch (keyCode) {
5750            case KeyEvent.KEYCODE_DPAD_CENTER:
5751            case KeyEvent.KEYCODE_ENTER: {
5752                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5753                    return true;
5754                }
5755                // Long clickable items don't necessarily have to be clickable
5756                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5757                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5758                        (event.getRepeatCount() == 0)) {
5759                    setPressed(true);
5760                    checkForLongClick(0);
5761                    return true;
5762                }
5763                break;
5764            }
5765        }
5766        return result;
5767    }
5768
5769    /**
5770     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5771     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5772     * the event).
5773     */
5774    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5775        return false;
5776    }
5777
5778    /**
5779     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5780     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5781     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5782     * {@link KeyEvent#KEYCODE_ENTER} is released.
5783     *
5784     * @param keyCode A key code that represents the button pressed, from
5785     *                {@link android.view.KeyEvent}.
5786     * @param event   The KeyEvent object that defines the button action.
5787     */
5788    public boolean onKeyUp(int keyCode, KeyEvent event) {
5789        boolean result = false;
5790
5791        switch (keyCode) {
5792            case KeyEvent.KEYCODE_DPAD_CENTER:
5793            case KeyEvent.KEYCODE_ENTER: {
5794                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5795                    return true;
5796                }
5797                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5798                    setPressed(false);
5799
5800                    if (!mHasPerformedLongPress) {
5801                        // This is a tap, so remove the longpress check
5802                        removeLongPressCallback();
5803
5804                        result = performClick();
5805                    }
5806                }
5807                break;
5808            }
5809        }
5810        return result;
5811    }
5812
5813    /**
5814     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
5815     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
5816     * the event).
5817     *
5818     * @param keyCode     A key code that represents the button pressed, from
5819     *                    {@link android.view.KeyEvent}.
5820     * @param repeatCount The number of times the action was made.
5821     * @param event       The KeyEvent object that defines the button action.
5822     */
5823    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5824        return false;
5825    }
5826
5827    /**
5828     * Called on the focused view when a key shortcut event is not handled.
5829     * Override this method to implement local key shortcuts for the View.
5830     * Key shortcuts can also be implemented by setting the
5831     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
5832     *
5833     * @param keyCode The value in event.getKeyCode().
5834     * @param event Description of the key event.
5835     * @return If you handled the event, return true. If you want to allow the
5836     *         event to be handled by the next receiver, return false.
5837     */
5838    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
5839        return false;
5840    }
5841
5842    /**
5843     * Check whether the called view is a text editor, in which case it
5844     * would make sense to automatically display a soft input window for
5845     * it.  Subclasses should override this if they implement
5846     * {@link #onCreateInputConnection(EditorInfo)} to return true if
5847     * a call on that method would return a non-null InputConnection, and
5848     * they are really a first-class editor that the user would normally
5849     * start typing on when the go into a window containing your view.
5850     *
5851     * <p>The default implementation always returns false.  This does
5852     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
5853     * will not be called or the user can not otherwise perform edits on your
5854     * view; it is just a hint to the system that this is not the primary
5855     * purpose of this view.
5856     *
5857     * @return Returns true if this view is a text editor, else false.
5858     */
5859    public boolean onCheckIsTextEditor() {
5860        return false;
5861    }
5862
5863    /**
5864     * Create a new InputConnection for an InputMethod to interact
5865     * with the view.  The default implementation returns null, since it doesn't
5866     * support input methods.  You can override this to implement such support.
5867     * This is only needed for views that take focus and text input.
5868     *
5869     * <p>When implementing this, you probably also want to implement
5870     * {@link #onCheckIsTextEditor()} to indicate you will return a
5871     * non-null InputConnection.
5872     *
5873     * @param outAttrs Fill in with attribute information about the connection.
5874     */
5875    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5876        return null;
5877    }
5878
5879    /**
5880     * Called by the {@link android.view.inputmethod.InputMethodManager}
5881     * when a view who is not the current
5882     * input connection target is trying to make a call on the manager.  The
5883     * default implementation returns false; you can override this to return
5884     * true for certain views if you are performing InputConnection proxying
5885     * to them.
5886     * @param view The View that is making the InputMethodManager call.
5887     * @return Return true to allow the call, false to reject.
5888     */
5889    public boolean checkInputConnectionProxy(View view) {
5890        return false;
5891    }
5892
5893    /**
5894     * Show the context menu for this view. It is not safe to hold on to the
5895     * menu after returning from this method.
5896     *
5897     * You should normally not overload this method. Overload
5898     * {@link #onCreateContextMenu(ContextMenu)} or define an
5899     * {@link OnCreateContextMenuListener} to add items to the context menu.
5900     *
5901     * @param menu The context menu to populate
5902     */
5903    public void createContextMenu(ContextMenu menu) {
5904        ContextMenuInfo menuInfo = getContextMenuInfo();
5905
5906        // Sets the current menu info so all items added to menu will have
5907        // my extra info set.
5908        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
5909
5910        onCreateContextMenu(menu);
5911        if (mOnCreateContextMenuListener != null) {
5912            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
5913        }
5914
5915        // Clear the extra information so subsequent items that aren't mine don't
5916        // have my extra info.
5917        ((MenuBuilder)menu).setCurrentMenuInfo(null);
5918
5919        if (mParent != null) {
5920            mParent.createContextMenu(menu);
5921        }
5922    }
5923
5924    /**
5925     * Views should implement this if they have extra information to associate
5926     * with the context menu. The return result is supplied as a parameter to
5927     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5928     * callback.
5929     *
5930     * @return Extra information about the item for which the context menu
5931     *         should be shown. This information will vary across different
5932     *         subclasses of View.
5933     */
5934    protected ContextMenuInfo getContextMenuInfo() {
5935        return null;
5936    }
5937
5938    /**
5939     * Views should implement this if the view itself is going to add items to
5940     * the context menu.
5941     *
5942     * @param menu the context menu to populate
5943     */
5944    protected void onCreateContextMenu(ContextMenu menu) {
5945    }
5946
5947    /**
5948     * Implement this method to handle trackball motion events.  The
5949     * <em>relative</em> movement of the trackball since the last event
5950     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5951     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
5952     * that a movement of 1 corresponds to the user pressing one DPAD key (so
5953     * they will often be fractional values, representing the more fine-grained
5954     * movement information available from a trackball).
5955     *
5956     * @param event The motion event.
5957     * @return True if the event was handled, false otherwise.
5958     */
5959    public boolean onTrackballEvent(MotionEvent event) {
5960        return false;
5961    }
5962
5963    /**
5964     * Implement this method to handle generic motion events.
5965     * <p>
5966     * Generic motion events describe joystick movements, mouse hovers, track pad
5967     * touches, scroll wheel movements and other input events.  The
5968     * {@link MotionEvent#getSource() source} of the motion event specifies
5969     * the class of input that was received.  Implementations of this method
5970     * must examine the bits in the source before processing the event.
5971     * The following code example shows how this is done.
5972     * </p><p>
5973     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5974     * are delivered to the view under the pointer.  All other generic motion events are
5975     * delivered to the focused view.
5976     * </p>
5977     * <code>
5978     * public boolean onGenericMotionEvent(MotionEvent event) {
5979     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
5980     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
5981     *             // process the joystick movement...
5982     *             return true;
5983     *         }
5984     *     }
5985     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
5986     *         switch (event.getAction()) {
5987     *             case MotionEvent.ACTION_HOVER_MOVE:
5988     *                 // process the mouse hover movement...
5989     *                 return true;
5990     *             case MotionEvent.ACTION_SCROLL:
5991     *                 // process the scroll wheel movement...
5992     *                 return true;
5993     *         }
5994     *     }
5995     *     return super.onGenericMotionEvent(event);
5996     * }
5997     * </code>
5998     *
5999     * @param event The generic motion event being processed.
6000     * @return True if the event was handled, false otherwise.
6001     */
6002    public boolean onGenericMotionEvent(MotionEvent event) {
6003        return false;
6004    }
6005
6006    /**
6007     * Implement this method to handle hover events.
6008     * <p>
6009     * This method is called whenever a pointer is hovering into, over, or out of the
6010     * bounds of a view and the view is not currently being touched.
6011     * Hover events are represented as pointer events with action
6012     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6013     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6014     * </p>
6015     * <ul>
6016     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6017     * when the pointer enters the bounds of the view.</li>
6018     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6019     * when the pointer has already entered the bounds of the view and has moved.</li>
6020     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6021     * when the pointer has exited the bounds of the view or when the pointer is
6022     * about to go down due to a button click, tap, or similar user action that
6023     * causes the view to be touched.</li>
6024     * </ul>
6025     * <p>
6026     * The view should implement this method to return true to indicate that it is
6027     * handling the hover event, such as by changing its drawable state.
6028     * </p><p>
6029     * The default implementation calls {@link #setHovered} to update the hovered state
6030     * of the view when a hover enter or hover exit event is received, if the view
6031     * is enabled and is clickable.  The default implementation also sends hover
6032     * accessibility events.
6033     * </p>
6034     *
6035     * @param event The motion event that describes the hover.
6036     * @return True if the view handled the hover event.
6037     *
6038     * @see #isHovered
6039     * @see #setHovered
6040     * @see #onHoverChanged
6041     */
6042    public boolean onHoverEvent(MotionEvent event) {
6043        // The root view may receive hover (or touch) events that are outside the bounds of
6044        // the window.  This code ensures that we only send accessibility events for
6045        // hovers that are actually within the bounds of the root view.
6046        final int action = event.getAction();
6047        if (!mSendingHoverAccessibilityEvents) {
6048            if ((action == MotionEvent.ACTION_HOVER_ENTER
6049                    || action == MotionEvent.ACTION_HOVER_MOVE)
6050                    && !hasHoveredChild()
6051                    && pointInView(event.getX(), event.getY())) {
6052                mSendingHoverAccessibilityEvents = true;
6053                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6054            }
6055        } else {
6056            if (action == MotionEvent.ACTION_HOVER_EXIT
6057                    || (action == MotionEvent.ACTION_HOVER_MOVE
6058                            && !pointInView(event.getX(), event.getY()))) {
6059                mSendingHoverAccessibilityEvents = false;
6060                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6061            }
6062        }
6063
6064        if (isHoverable()) {
6065            switch (action) {
6066                case MotionEvent.ACTION_HOVER_ENTER:
6067                    setHovered(true);
6068                    break;
6069                case MotionEvent.ACTION_HOVER_EXIT:
6070                    setHovered(false);
6071                    break;
6072            }
6073
6074            // Dispatch the event to onGenericMotionEvent before returning true.
6075            // This is to provide compatibility with existing applications that
6076            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6077            // break because of the new default handling for hoverable views
6078            // in onHoverEvent.
6079            // Note that onGenericMotionEvent will be called by default when
6080            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6081            dispatchGenericMotionEventInternal(event);
6082            return true;
6083        }
6084        return false;
6085    }
6086
6087    /**
6088     * Returns true if the view should handle {@link #onHoverEvent}
6089     * by calling {@link #setHovered} to change its hovered state.
6090     *
6091     * @return True if the view is hoverable.
6092     */
6093    private boolean isHoverable() {
6094        final int viewFlags = mViewFlags;
6095        //noinspection SimplifiableIfStatement
6096        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6097            return false;
6098        }
6099
6100        return (viewFlags & CLICKABLE) == CLICKABLE
6101                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6102    }
6103
6104    /**
6105     * Returns true if the view is currently hovered.
6106     *
6107     * @return True if the view is currently hovered.
6108     *
6109     * @see #setHovered
6110     * @see #onHoverChanged
6111     */
6112    @ViewDebug.ExportedProperty
6113    public boolean isHovered() {
6114        return (mPrivateFlags & HOVERED) != 0;
6115    }
6116
6117    /**
6118     * Sets whether the view is currently hovered.
6119     * <p>
6120     * Calling this method also changes the drawable state of the view.  This
6121     * enables the view to react to hover by using different drawable resources
6122     * to change its appearance.
6123     * </p><p>
6124     * The {@link #onHoverChanged} method is called when the hovered state changes.
6125     * </p>
6126     *
6127     * @param hovered True if the view is hovered.
6128     *
6129     * @see #isHovered
6130     * @see #onHoverChanged
6131     */
6132    public void setHovered(boolean hovered) {
6133        if (hovered) {
6134            if ((mPrivateFlags & HOVERED) == 0) {
6135                mPrivateFlags |= HOVERED;
6136                refreshDrawableState();
6137                onHoverChanged(true);
6138            }
6139        } else {
6140            if ((mPrivateFlags & HOVERED) != 0) {
6141                mPrivateFlags &= ~HOVERED;
6142                refreshDrawableState();
6143                onHoverChanged(false);
6144            }
6145        }
6146    }
6147
6148    /**
6149     * Implement this method to handle hover state changes.
6150     * <p>
6151     * This method is called whenever the hover state changes as a result of a
6152     * call to {@link #setHovered}.
6153     * </p>
6154     *
6155     * @param hovered The current hover state, as returned by {@link #isHovered}.
6156     *
6157     * @see #isHovered
6158     * @see #setHovered
6159     */
6160    public void onHoverChanged(boolean hovered) {
6161    }
6162
6163    /**
6164     * Implement this method to handle touch screen motion events.
6165     *
6166     * @param event The motion event.
6167     * @return True if the event was handled, false otherwise.
6168     */
6169    public boolean onTouchEvent(MotionEvent event) {
6170        final int viewFlags = mViewFlags;
6171
6172        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6173            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6174                mPrivateFlags &= ~PRESSED;
6175                refreshDrawableState();
6176            }
6177            // A disabled view that is clickable still consumes the touch
6178            // events, it just doesn't respond to them.
6179            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6180                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6181        }
6182
6183        if (mTouchDelegate != null) {
6184            if (mTouchDelegate.onTouchEvent(event)) {
6185                return true;
6186            }
6187        }
6188
6189        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6190                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6191            switch (event.getAction()) {
6192                case MotionEvent.ACTION_UP:
6193                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6194                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6195                        // take focus if we don't have it already and we should in
6196                        // touch mode.
6197                        boolean focusTaken = false;
6198                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6199                            focusTaken = requestFocus();
6200                        }
6201
6202                        if (prepressed) {
6203                            // The button is being released before we actually
6204                            // showed it as pressed.  Make it show the pressed
6205                            // state now (before scheduling the click) to ensure
6206                            // the user sees it.
6207                            mPrivateFlags |= PRESSED;
6208                            refreshDrawableState();
6209                       }
6210
6211                        if (!mHasPerformedLongPress) {
6212                            // This is a tap, so remove the longpress check
6213                            removeLongPressCallback();
6214
6215                            // Only perform take click actions if we were in the pressed state
6216                            if (!focusTaken) {
6217                                // Use a Runnable and post this rather than calling
6218                                // performClick directly. This lets other visual state
6219                                // of the view update before click actions start.
6220                                if (mPerformClick == null) {
6221                                    mPerformClick = new PerformClick();
6222                                }
6223                                if (!post(mPerformClick)) {
6224                                    performClick();
6225                                }
6226                            }
6227                        }
6228
6229                        if (mUnsetPressedState == null) {
6230                            mUnsetPressedState = new UnsetPressedState();
6231                        }
6232
6233                        if (prepressed) {
6234                            postDelayed(mUnsetPressedState,
6235                                    ViewConfiguration.getPressedStateDuration());
6236                        } else if (!post(mUnsetPressedState)) {
6237                            // If the post failed, unpress right now
6238                            mUnsetPressedState.run();
6239                        }
6240                        removeTapCallback();
6241                    }
6242                    break;
6243
6244                case MotionEvent.ACTION_DOWN:
6245                    mHasPerformedLongPress = false;
6246
6247                    if (performButtonActionOnTouchDown(event)) {
6248                        break;
6249                    }
6250
6251                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6252                    boolean isInScrollingContainer = isInScrollingContainer();
6253
6254                    // For views inside a scrolling container, delay the pressed feedback for
6255                    // a short period in case this is a scroll.
6256                    if (isInScrollingContainer) {
6257                        mPrivateFlags |= PREPRESSED;
6258                        if (mPendingCheckForTap == null) {
6259                            mPendingCheckForTap = new CheckForTap();
6260                        }
6261                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6262                    } else {
6263                        // Not inside a scrolling container, so show the feedback right away
6264                        mPrivateFlags |= PRESSED;
6265                        refreshDrawableState();
6266                        checkForLongClick(0);
6267                    }
6268                    break;
6269
6270                case MotionEvent.ACTION_CANCEL:
6271                    mPrivateFlags &= ~PRESSED;
6272                    refreshDrawableState();
6273                    removeTapCallback();
6274                    break;
6275
6276                case MotionEvent.ACTION_MOVE:
6277                    final int x = (int) event.getX();
6278                    final int y = (int) event.getY();
6279
6280                    // Be lenient about moving outside of buttons
6281                    if (!pointInView(x, y, mTouchSlop)) {
6282                        // Outside button
6283                        removeTapCallback();
6284                        if ((mPrivateFlags & PRESSED) != 0) {
6285                            // Remove any future long press/tap checks
6286                            removeLongPressCallback();
6287
6288                            // Need to switch from pressed to not pressed
6289                            mPrivateFlags &= ~PRESSED;
6290                            refreshDrawableState();
6291                        }
6292                    }
6293                    break;
6294            }
6295            return true;
6296        }
6297
6298        return false;
6299    }
6300
6301    /**
6302     * @hide
6303     */
6304    public boolean isInScrollingContainer() {
6305        ViewParent p = getParent();
6306        while (p != null && p instanceof ViewGroup) {
6307            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6308                return true;
6309            }
6310            p = p.getParent();
6311        }
6312        return false;
6313    }
6314
6315    /**
6316     * Remove the longpress detection timer.
6317     */
6318    private void removeLongPressCallback() {
6319        if (mPendingCheckForLongPress != null) {
6320          removeCallbacks(mPendingCheckForLongPress);
6321        }
6322    }
6323
6324    /**
6325     * Remove the pending click action
6326     */
6327    private void removePerformClickCallback() {
6328        if (mPerformClick != null) {
6329            removeCallbacks(mPerformClick);
6330        }
6331    }
6332
6333    /**
6334     * Remove the prepress detection timer.
6335     */
6336    private void removeUnsetPressCallback() {
6337        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6338            setPressed(false);
6339            removeCallbacks(mUnsetPressedState);
6340        }
6341    }
6342
6343    /**
6344     * Remove the tap detection timer.
6345     */
6346    private void removeTapCallback() {
6347        if (mPendingCheckForTap != null) {
6348            mPrivateFlags &= ~PREPRESSED;
6349            removeCallbacks(mPendingCheckForTap);
6350        }
6351    }
6352
6353    /**
6354     * Cancels a pending long press.  Your subclass can use this if you
6355     * want the context menu to come up if the user presses and holds
6356     * at the same place, but you don't want it to come up if they press
6357     * and then move around enough to cause scrolling.
6358     */
6359    public void cancelLongPress() {
6360        removeLongPressCallback();
6361
6362        /*
6363         * The prepressed state handled by the tap callback is a display
6364         * construct, but the tap callback will post a long press callback
6365         * less its own timeout. Remove it here.
6366         */
6367        removeTapCallback();
6368    }
6369
6370    /**
6371     * Remove the pending callback for sending a
6372     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6373     */
6374    private void removeSendViewScrolledAccessibilityEventCallback() {
6375        if (mSendViewScrolledAccessibilityEvent != null) {
6376            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6377        }
6378    }
6379
6380    /**
6381     * Sets the TouchDelegate for this View.
6382     */
6383    public void setTouchDelegate(TouchDelegate delegate) {
6384        mTouchDelegate = delegate;
6385    }
6386
6387    /**
6388     * Gets the TouchDelegate for this View.
6389     */
6390    public TouchDelegate getTouchDelegate() {
6391        return mTouchDelegate;
6392    }
6393
6394    /**
6395     * Set flags controlling behavior of this view.
6396     *
6397     * @param flags Constant indicating the value which should be set
6398     * @param mask Constant indicating the bit range that should be changed
6399     */
6400    void setFlags(int flags, int mask) {
6401        int old = mViewFlags;
6402        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6403
6404        int changed = mViewFlags ^ old;
6405        if (changed == 0) {
6406            return;
6407        }
6408        int privateFlags = mPrivateFlags;
6409
6410        /* Check if the FOCUSABLE bit has changed */
6411        if (((changed & FOCUSABLE_MASK) != 0) &&
6412                ((privateFlags & HAS_BOUNDS) !=0)) {
6413            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6414                    && ((privateFlags & FOCUSED) != 0)) {
6415                /* Give up focus if we are no longer focusable */
6416                clearFocus();
6417            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6418                    && ((privateFlags & FOCUSED) == 0)) {
6419                /*
6420                 * Tell the view system that we are now available to take focus
6421                 * if no one else already has it.
6422                 */
6423                if (mParent != null) mParent.focusableViewAvailable(this);
6424            }
6425        }
6426
6427        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6428            if ((changed & VISIBILITY_MASK) != 0) {
6429                /*
6430                 * If this view is becoming visible, invalidate it in case it changed while
6431                 * it was not visible. Marking it drawn ensures that the invalidation will
6432                 * go through.
6433                 */
6434                mPrivateFlags |= DRAWN;
6435                invalidate(true);
6436
6437                needGlobalAttributesUpdate(true);
6438
6439                // a view becoming visible is worth notifying the parent
6440                // about in case nothing has focus.  even if this specific view
6441                // isn't focusable, it may contain something that is, so let
6442                // the root view try to give this focus if nothing else does.
6443                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6444                    mParent.focusableViewAvailable(this);
6445                }
6446            }
6447        }
6448
6449        /* Check if the GONE bit has changed */
6450        if ((changed & GONE) != 0) {
6451            needGlobalAttributesUpdate(false);
6452            requestLayout();
6453
6454            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6455                if (hasFocus()) clearFocus();
6456                destroyDrawingCache();
6457                if (mParent instanceof View) {
6458                    // GONE views noop invalidation, so invalidate the parent
6459                    ((View) mParent).invalidate(true);
6460                }
6461                // Mark the view drawn to ensure that it gets invalidated properly the next
6462                // time it is visible and gets invalidated
6463                mPrivateFlags |= DRAWN;
6464            }
6465            if (mAttachInfo != null) {
6466                mAttachInfo.mViewVisibilityChanged = true;
6467            }
6468        }
6469
6470        /* Check if the VISIBLE bit has changed */
6471        if ((changed & INVISIBLE) != 0) {
6472            needGlobalAttributesUpdate(false);
6473            /*
6474             * If this view is becoming invisible, set the DRAWN flag so that
6475             * the next invalidate() will not be skipped.
6476             */
6477            mPrivateFlags |= DRAWN;
6478
6479            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6480                // root view becoming invisible shouldn't clear focus
6481                if (getRootView() != this) {
6482                    clearFocus();
6483                }
6484            }
6485            if (mAttachInfo != null) {
6486                mAttachInfo.mViewVisibilityChanged = true;
6487            }
6488        }
6489
6490        if ((changed & VISIBILITY_MASK) != 0) {
6491            if (mParent instanceof ViewGroup) {
6492                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6493                ((View) mParent).invalidate(true);
6494            } else if (mParent != null) {
6495                mParent.invalidateChild(this, null);
6496            }
6497            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6498        }
6499
6500        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6501            destroyDrawingCache();
6502        }
6503
6504        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6505            destroyDrawingCache();
6506            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6507            invalidateParentCaches();
6508        }
6509
6510        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6511            destroyDrawingCache();
6512            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6513        }
6514
6515        if ((changed & DRAW_MASK) != 0) {
6516            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6517                if (mBGDrawable != null) {
6518                    mPrivateFlags &= ~SKIP_DRAW;
6519                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6520                } else {
6521                    mPrivateFlags |= SKIP_DRAW;
6522                }
6523            } else {
6524                mPrivateFlags &= ~SKIP_DRAW;
6525            }
6526            requestLayout();
6527            invalidate(true);
6528        }
6529
6530        if ((changed & KEEP_SCREEN_ON) != 0) {
6531            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6532                mParent.recomputeViewAttributes(this);
6533            }
6534        }
6535
6536        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6537            requestLayout();
6538        }
6539    }
6540
6541    /**
6542     * Change the view's z order in the tree, so it's on top of other sibling
6543     * views
6544     */
6545    public void bringToFront() {
6546        if (mParent != null) {
6547            mParent.bringChildToFront(this);
6548        }
6549    }
6550
6551    /**
6552     * This is called in response to an internal scroll in this view (i.e., the
6553     * view scrolled its own contents). This is typically as a result of
6554     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6555     * called.
6556     *
6557     * @param l Current horizontal scroll origin.
6558     * @param t Current vertical scroll origin.
6559     * @param oldl Previous horizontal scroll origin.
6560     * @param oldt Previous vertical scroll origin.
6561     */
6562    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6563        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6564            postSendViewScrolledAccessibilityEventCallback();
6565        }
6566
6567        mBackgroundSizeChanged = true;
6568
6569        final AttachInfo ai = mAttachInfo;
6570        if (ai != null) {
6571            ai.mViewScrollChanged = true;
6572        }
6573    }
6574
6575    /**
6576     * Interface definition for a callback to be invoked when the layout bounds of a view
6577     * changes due to layout processing.
6578     */
6579    public interface OnLayoutChangeListener {
6580        /**
6581         * Called when the focus state of a view has changed.
6582         *
6583         * @param v The view whose state has changed.
6584         * @param left The new value of the view's left property.
6585         * @param top The new value of the view's top property.
6586         * @param right The new value of the view's right property.
6587         * @param bottom The new value of the view's bottom property.
6588         * @param oldLeft The previous value of the view's left property.
6589         * @param oldTop The previous value of the view's top property.
6590         * @param oldRight The previous value of the view's right property.
6591         * @param oldBottom The previous value of the view's bottom property.
6592         */
6593        void onLayoutChange(View v, int left, int top, int right, int bottom,
6594            int oldLeft, int oldTop, int oldRight, int oldBottom);
6595    }
6596
6597    /**
6598     * This is called during layout when the size of this view has changed. If
6599     * you were just added to the view hierarchy, you're called with the old
6600     * values of 0.
6601     *
6602     * @param w Current width of this view.
6603     * @param h Current height of this view.
6604     * @param oldw Old width of this view.
6605     * @param oldh Old height of this view.
6606     */
6607    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6608    }
6609
6610    /**
6611     * Called by draw to draw the child views. This may be overridden
6612     * by derived classes to gain control just before its children are drawn
6613     * (but after its own view has been drawn).
6614     * @param canvas the canvas on which to draw the view
6615     */
6616    protected void dispatchDraw(Canvas canvas) {
6617    }
6618
6619    /**
6620     * Gets the parent of this view. Note that the parent is a
6621     * ViewParent and not necessarily a View.
6622     *
6623     * @return Parent of this view.
6624     */
6625    public final ViewParent getParent() {
6626        return mParent;
6627    }
6628
6629    /**
6630     * Set the horizontal scrolled position of your view. This will cause a call to
6631     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6632     * invalidated.
6633     * @param value the x position to scroll to
6634     */
6635    public void setScrollX(int value) {
6636        scrollTo(value, mScrollY);
6637    }
6638
6639    /**
6640     * Set the vertical scrolled position of your view. This will cause a call to
6641     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6642     * invalidated.
6643     * @param value the y position to scroll to
6644     */
6645    public void setScrollY(int value) {
6646        scrollTo(mScrollX, value);
6647    }
6648
6649    /**
6650     * Return the scrolled left position of this view. This is the left edge of
6651     * the displayed part of your view. You do not need to draw any pixels
6652     * farther left, since those are outside of the frame of your view on
6653     * screen.
6654     *
6655     * @return The left edge of the displayed part of your view, in pixels.
6656     */
6657    public final int getScrollX() {
6658        return mScrollX;
6659    }
6660
6661    /**
6662     * Return the scrolled top position of this view. This is the top edge of
6663     * the displayed part of your view. You do not need to draw any pixels above
6664     * it, since those are outside of the frame of your view on screen.
6665     *
6666     * @return The top edge of the displayed part of your view, in pixels.
6667     */
6668    public final int getScrollY() {
6669        return mScrollY;
6670    }
6671
6672    /**
6673     * Return the width of the your view.
6674     *
6675     * @return The width of your view, in pixels.
6676     */
6677    @ViewDebug.ExportedProperty(category = "layout")
6678    public final int getWidth() {
6679        return mRight - mLeft;
6680    }
6681
6682    /**
6683     * Return the height of your view.
6684     *
6685     * @return The height of your view, in pixels.
6686     */
6687    @ViewDebug.ExportedProperty(category = "layout")
6688    public final int getHeight() {
6689        return mBottom - mTop;
6690    }
6691
6692    /**
6693     * Return the visible drawing bounds of your view. Fills in the output
6694     * rectangle with the values from getScrollX(), getScrollY(),
6695     * getWidth(), and getHeight().
6696     *
6697     * @param outRect The (scrolled) drawing bounds of the view.
6698     */
6699    public void getDrawingRect(Rect outRect) {
6700        outRect.left = mScrollX;
6701        outRect.top = mScrollY;
6702        outRect.right = mScrollX + (mRight - mLeft);
6703        outRect.bottom = mScrollY + (mBottom - mTop);
6704    }
6705
6706    /**
6707     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6708     * raw width component (that is the result is masked by
6709     * {@link #MEASURED_SIZE_MASK}).
6710     *
6711     * @return The raw measured width of this view.
6712     */
6713    public final int getMeasuredWidth() {
6714        return mMeasuredWidth & MEASURED_SIZE_MASK;
6715    }
6716
6717    /**
6718     * Return the full width measurement information for this view as computed
6719     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6720     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6721     * This should be used during measurement and layout calculations only. Use
6722     * {@link #getWidth()} to see how wide a view is after layout.
6723     *
6724     * @return The measured width of this view as a bit mask.
6725     */
6726    public final int getMeasuredWidthAndState() {
6727        return mMeasuredWidth;
6728    }
6729
6730    /**
6731     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6732     * raw width component (that is the result is masked by
6733     * {@link #MEASURED_SIZE_MASK}).
6734     *
6735     * @return The raw measured height of this view.
6736     */
6737    public final int getMeasuredHeight() {
6738        return mMeasuredHeight & MEASURED_SIZE_MASK;
6739    }
6740
6741    /**
6742     * Return the full height measurement information for this view as computed
6743     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6744     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6745     * This should be used during measurement and layout calculations only. Use
6746     * {@link #getHeight()} to see how wide a view is after layout.
6747     *
6748     * @return The measured width of this view as a bit mask.
6749     */
6750    public final int getMeasuredHeightAndState() {
6751        return mMeasuredHeight;
6752    }
6753
6754    /**
6755     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6756     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6757     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6758     * and the height component is at the shifted bits
6759     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6760     */
6761    public final int getMeasuredState() {
6762        return (mMeasuredWidth&MEASURED_STATE_MASK)
6763                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6764                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6765    }
6766
6767    /**
6768     * The transform matrix of this view, which is calculated based on the current
6769     * roation, scale, and pivot properties.
6770     *
6771     * @see #getRotation()
6772     * @see #getScaleX()
6773     * @see #getScaleY()
6774     * @see #getPivotX()
6775     * @see #getPivotY()
6776     * @return The current transform matrix for the view
6777     */
6778    public Matrix getMatrix() {
6779        updateMatrix();
6780        return mMatrix;
6781    }
6782
6783    /**
6784     * Utility function to determine if the value is far enough away from zero to be
6785     * considered non-zero.
6786     * @param value A floating point value to check for zero-ness
6787     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6788     */
6789    private static boolean nonzero(float value) {
6790        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6791    }
6792
6793    /**
6794     * Returns true if the transform matrix is the identity matrix.
6795     * Recomputes the matrix if necessary.
6796     *
6797     * @return True if the transform matrix is the identity matrix, false otherwise.
6798     */
6799    final boolean hasIdentityMatrix() {
6800        updateMatrix();
6801        return mMatrixIsIdentity;
6802    }
6803
6804    /**
6805     * Recomputes the transform matrix if necessary.
6806     */
6807    private void updateMatrix() {
6808        if (mMatrixDirty) {
6809            // transform-related properties have changed since the last time someone
6810            // asked for the matrix; recalculate it with the current values
6811
6812            // Figure out if we need to update the pivot point
6813            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6814                if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
6815                    mPrevWidth = mRight - mLeft;
6816                    mPrevHeight = mBottom - mTop;
6817                    mPivotX = mPrevWidth / 2f;
6818                    mPivotY = mPrevHeight / 2f;
6819                }
6820            }
6821            mMatrix.reset();
6822            if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
6823                mMatrix.setTranslate(mTranslationX, mTranslationY);
6824                mMatrix.preRotate(mRotation, mPivotX, mPivotY);
6825                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6826            } else {
6827                if (mCamera == null) {
6828                    mCamera = new Camera();
6829                    matrix3D = new Matrix();
6830                }
6831                mCamera.save();
6832                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6833                mCamera.rotate(mRotationX, mRotationY, -mRotation);
6834                mCamera.getMatrix(matrix3D);
6835                matrix3D.preTranslate(-mPivotX, -mPivotY);
6836                matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
6837                mMatrix.postConcat(matrix3D);
6838                mCamera.restore();
6839            }
6840            mMatrixDirty = false;
6841            mMatrixIsIdentity = mMatrix.isIdentity();
6842            mInverseMatrixDirty = true;
6843        }
6844    }
6845
6846    /**
6847     * Utility method to retrieve the inverse of the current mMatrix property.
6848     * We cache the matrix to avoid recalculating it when transform properties
6849     * have not changed.
6850     *
6851     * @return The inverse of the current matrix of this view.
6852     */
6853    final Matrix getInverseMatrix() {
6854        updateMatrix();
6855        if (mInverseMatrixDirty) {
6856            if (mInverseMatrix == null) {
6857                mInverseMatrix = new Matrix();
6858            }
6859            mMatrix.invert(mInverseMatrix);
6860            mInverseMatrixDirty = false;
6861        }
6862        return mInverseMatrix;
6863    }
6864
6865    /**
6866     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
6867     * views are drawn) from the camera to this view. The camera's distance
6868     * affects 3D transformations, for instance rotations around the X and Y
6869     * axis. If the rotationX or rotationY properties are changed and this view is
6870     * large (more than half the size of the screen), it is recommended to always
6871     * use a camera distance that's greater than the height (X axis rotation) or
6872     * the width (Y axis rotation) of this view.</p>
6873     *
6874     * <p>The distance of the camera from the view plane can have an affect on the
6875     * perspective distortion of the view when it is rotated around the x or y axis.
6876     * For example, a large distance will result in a large viewing angle, and there
6877     * will not be much perspective distortion of the view as it rotates. A short
6878     * distance may cause much more perspective distortion upon rotation, and can
6879     * also result in some drawing artifacts if the rotated view ends up partially
6880     * behind the camera (which is why the recommendation is to use a distance at
6881     * least as far as the size of the view, if the view is to be rotated.)</p>
6882     *
6883     * <p>The distance is expressed in "depth pixels." The default distance depends
6884     * on the screen density. For instance, on a medium density display, the
6885     * default distance is 1280. On a high density display, the default distance
6886     * is 1920.</p>
6887     *
6888     * <p>If you want to specify a distance that leads to visually consistent
6889     * results across various densities, use the following formula:</p>
6890     * <pre>
6891     * float scale = context.getResources().getDisplayMetrics().density;
6892     * view.setCameraDistance(distance * scale);
6893     * </pre>
6894     *
6895     * <p>The density scale factor of a high density display is 1.5,
6896     * and 1920 = 1280 * 1.5.</p>
6897     *
6898     * @param distance The distance in "depth pixels", if negative the opposite
6899     *        value is used
6900     *
6901     * @see #setRotationX(float)
6902     * @see #setRotationY(float)
6903     */
6904    public void setCameraDistance(float distance) {
6905        invalidateParentCaches();
6906        invalidate(false);
6907
6908        final float dpi = mResources.getDisplayMetrics().densityDpi;
6909        if (mCamera == null) {
6910            mCamera = new Camera();
6911            matrix3D = new Matrix();
6912        }
6913
6914        mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
6915        mMatrixDirty = true;
6916
6917        invalidate(false);
6918    }
6919
6920    /**
6921     * The degrees that the view is rotated around the pivot point.
6922     *
6923     * @see #setRotation(float)
6924     * @see #getPivotX()
6925     * @see #getPivotY()
6926     *
6927     * @return The degrees of rotation.
6928     */
6929    public float getRotation() {
6930        return mRotation;
6931    }
6932
6933    /**
6934     * Sets the degrees that the view is rotated around the pivot point. Increasing values
6935     * result in clockwise rotation.
6936     *
6937     * @param rotation The degrees of rotation.
6938     *
6939     * @see #getRotation()
6940     * @see #getPivotX()
6941     * @see #getPivotY()
6942     * @see #setRotationX(float)
6943     * @see #setRotationY(float)
6944     *
6945     * @attr ref android.R.styleable#View_rotation
6946     */
6947    public void setRotation(float rotation) {
6948        if (mRotation != rotation) {
6949            invalidateParentCaches();
6950            // Double-invalidation is necessary to capture view's old and new areas
6951            invalidate(false);
6952            mRotation = rotation;
6953            mMatrixDirty = true;
6954            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6955            invalidate(false);
6956        }
6957    }
6958
6959    /**
6960     * The degrees that the view is rotated around the vertical axis through the pivot point.
6961     *
6962     * @see #getPivotX()
6963     * @see #getPivotY()
6964     * @see #setRotationY(float)
6965     *
6966     * @return The degrees of Y rotation.
6967     */
6968    public float getRotationY() {
6969        return mRotationY;
6970    }
6971
6972    /**
6973     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
6974     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
6975     * down the y axis.
6976     *
6977     * When rotating large views, it is recommended to adjust the camera distance
6978     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
6979     *
6980     * @param rotationY The degrees of Y rotation.
6981     *
6982     * @see #getRotationY()
6983     * @see #getPivotX()
6984     * @see #getPivotY()
6985     * @see #setRotation(float)
6986     * @see #setRotationX(float)
6987     * @see #setCameraDistance(float)
6988     *
6989     * @attr ref android.R.styleable#View_rotationY
6990     */
6991    public void setRotationY(float rotationY) {
6992        if (mRotationY != rotationY) {
6993            invalidateParentCaches();
6994            // Double-invalidation is necessary to capture view's old and new areas
6995            invalidate(false);
6996            mRotationY = rotationY;
6997            mMatrixDirty = true;
6998            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6999            invalidate(false);
7000        }
7001    }
7002
7003    /**
7004     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7005     *
7006     * @see #getPivotX()
7007     * @see #getPivotY()
7008     * @see #setRotationX(float)
7009     *
7010     * @return The degrees of X rotation.
7011     */
7012    public float getRotationX() {
7013        return mRotationX;
7014    }
7015
7016    /**
7017     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7018     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7019     * x axis.
7020     *
7021     * When rotating large views, it is recommended to adjust the camera distance
7022     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7023     *
7024     * @param rotationX The degrees of X rotation.
7025     *
7026     * @see #getRotationX()
7027     * @see #getPivotX()
7028     * @see #getPivotY()
7029     * @see #setRotation(float)
7030     * @see #setRotationY(float)
7031     * @see #setCameraDistance(float)
7032     *
7033     * @attr ref android.R.styleable#View_rotationX
7034     */
7035    public void setRotationX(float rotationX) {
7036        if (mRotationX != rotationX) {
7037            invalidateParentCaches();
7038            // Double-invalidation is necessary to capture view's old and new areas
7039            invalidate(false);
7040            mRotationX = rotationX;
7041            mMatrixDirty = true;
7042            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7043            invalidate(false);
7044        }
7045    }
7046
7047    /**
7048     * The amount that the view is scaled in x around the pivot point, as a proportion of
7049     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7050     *
7051     * <p>By default, this is 1.0f.
7052     *
7053     * @see #getPivotX()
7054     * @see #getPivotY()
7055     * @return The scaling factor.
7056     */
7057    public float getScaleX() {
7058        return mScaleX;
7059    }
7060
7061    /**
7062     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7063     * the view's unscaled width. A value of 1 means that no scaling is applied.
7064     *
7065     * @param scaleX The scaling factor.
7066     * @see #getPivotX()
7067     * @see #getPivotY()
7068     *
7069     * @attr ref android.R.styleable#View_scaleX
7070     */
7071    public void setScaleX(float scaleX) {
7072        if (mScaleX != scaleX) {
7073            invalidateParentCaches();
7074            // Double-invalidation is necessary to capture view's old and new areas
7075            invalidate(false);
7076            mScaleX = scaleX;
7077            mMatrixDirty = true;
7078            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7079            invalidate(false);
7080        }
7081    }
7082
7083    /**
7084     * The amount that the view is scaled in y around the pivot point, as a proportion of
7085     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7086     *
7087     * <p>By default, this is 1.0f.
7088     *
7089     * @see #getPivotX()
7090     * @see #getPivotY()
7091     * @return The scaling factor.
7092     */
7093    public float getScaleY() {
7094        return mScaleY;
7095    }
7096
7097    /**
7098     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7099     * the view's unscaled width. A value of 1 means that no scaling is applied.
7100     *
7101     * @param scaleY The scaling factor.
7102     * @see #getPivotX()
7103     * @see #getPivotY()
7104     *
7105     * @attr ref android.R.styleable#View_scaleY
7106     */
7107    public void setScaleY(float scaleY) {
7108        if (mScaleY != scaleY) {
7109            invalidateParentCaches();
7110            // Double-invalidation is necessary to capture view's old and new areas
7111            invalidate(false);
7112            mScaleY = scaleY;
7113            mMatrixDirty = true;
7114            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7115            invalidate(false);
7116        }
7117    }
7118
7119    /**
7120     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7121     * and {@link #setScaleX(float) scaled}.
7122     *
7123     * @see #getRotation()
7124     * @see #getScaleX()
7125     * @see #getScaleY()
7126     * @see #getPivotY()
7127     * @return The x location of the pivot point.
7128     */
7129    public float getPivotX() {
7130        return mPivotX;
7131    }
7132
7133    /**
7134     * Sets the x location of the point around which the view is
7135     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7136     * By default, the pivot point is centered on the object.
7137     * Setting this property disables this behavior and causes the view to use only the
7138     * explicitly set pivotX and pivotY values.
7139     *
7140     * @param pivotX The x location of the pivot point.
7141     * @see #getRotation()
7142     * @see #getScaleX()
7143     * @see #getScaleY()
7144     * @see #getPivotY()
7145     *
7146     * @attr ref android.R.styleable#View_transformPivotX
7147     */
7148    public void setPivotX(float pivotX) {
7149        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7150        if (mPivotX != pivotX) {
7151            invalidateParentCaches();
7152            // Double-invalidation is necessary to capture view's old and new areas
7153            invalidate(false);
7154            mPivotX = pivotX;
7155            mMatrixDirty = true;
7156            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7157            invalidate(false);
7158        }
7159    }
7160
7161    /**
7162     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7163     * and {@link #setScaleY(float) scaled}.
7164     *
7165     * @see #getRotation()
7166     * @see #getScaleX()
7167     * @see #getScaleY()
7168     * @see #getPivotY()
7169     * @return The y location of the pivot point.
7170     */
7171    public float getPivotY() {
7172        return mPivotY;
7173    }
7174
7175    /**
7176     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7177     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7178     * Setting this property disables this behavior and causes the view to use only the
7179     * explicitly set pivotX and pivotY values.
7180     *
7181     * @param pivotY The y location of the pivot point.
7182     * @see #getRotation()
7183     * @see #getScaleX()
7184     * @see #getScaleY()
7185     * @see #getPivotY()
7186     *
7187     * @attr ref android.R.styleable#View_transformPivotY
7188     */
7189    public void setPivotY(float pivotY) {
7190        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7191        if (mPivotY != pivotY) {
7192            invalidateParentCaches();
7193            // Double-invalidation is necessary to capture view's old and new areas
7194            invalidate(false);
7195            mPivotY = pivotY;
7196            mMatrixDirty = true;
7197            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7198            invalidate(false);
7199        }
7200    }
7201
7202    /**
7203     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7204     * completely transparent and 1 means the view is completely opaque.
7205     *
7206     * <p>By default this is 1.0f.
7207     * @return The opacity of the view.
7208     */
7209    public float getAlpha() {
7210        return mAlpha;
7211    }
7212
7213    /**
7214     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7215     * completely transparent and 1 means the view is completely opaque.</p>
7216     *
7217     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7218     * responsible for applying the opacity itself. Otherwise, calling this method is
7219     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7220     * setting a hardware layer.</p>
7221     *
7222     * @param alpha The opacity of the view.
7223     *
7224     * @see #setLayerType(int, android.graphics.Paint)
7225     *
7226     * @attr ref android.R.styleable#View_alpha
7227     */
7228    public void setAlpha(float alpha) {
7229        mAlpha = alpha;
7230        invalidateParentCaches();
7231        if (onSetAlpha((int) (alpha * 255))) {
7232            mPrivateFlags |= ALPHA_SET;
7233            // subclass is handling alpha - don't optimize rendering cache invalidation
7234            invalidate(true);
7235        } else {
7236            mPrivateFlags &= ~ALPHA_SET;
7237            invalidate(false);
7238        }
7239    }
7240
7241    /**
7242     * Faster version of setAlpha() which performs the same steps except there are
7243     * no calls to invalidate(). The caller of this function should perform proper invalidation
7244     * on the parent and this object. The return value indicates whether the subclass handles
7245     * alpha (the return value for onSetAlpha()).
7246     *
7247     * @param alpha The new value for the alpha property
7248     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
7249     */
7250    boolean setAlphaNoInvalidation(float alpha) {
7251        mAlpha = alpha;
7252        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7253        if (subclassHandlesAlpha) {
7254            mPrivateFlags |= ALPHA_SET;
7255        } else {
7256            mPrivateFlags &= ~ALPHA_SET;
7257        }
7258        return subclassHandlesAlpha;
7259    }
7260
7261    /**
7262     * Top position of this view relative to its parent.
7263     *
7264     * @return The top of this view, in pixels.
7265     */
7266    @ViewDebug.CapturedViewProperty
7267    public final int getTop() {
7268        return mTop;
7269    }
7270
7271    /**
7272     * Sets the top position of this view relative to its parent. This method is meant to be called
7273     * by the layout system and should not generally be called otherwise, because the property
7274     * may be changed at any time by the layout.
7275     *
7276     * @param top The top of this view, in pixels.
7277     */
7278    public final void setTop(int top) {
7279        if (top != mTop) {
7280            updateMatrix();
7281            if (mMatrixIsIdentity) {
7282                if (mAttachInfo != null) {
7283                    int minTop;
7284                    int yLoc;
7285                    if (top < mTop) {
7286                        minTop = top;
7287                        yLoc = top - mTop;
7288                    } else {
7289                        minTop = mTop;
7290                        yLoc = 0;
7291                    }
7292                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7293                }
7294            } else {
7295                // Double-invalidation is necessary to capture view's old and new areas
7296                invalidate(true);
7297            }
7298
7299            int width = mRight - mLeft;
7300            int oldHeight = mBottom - mTop;
7301
7302            mTop = top;
7303
7304            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7305
7306            if (!mMatrixIsIdentity) {
7307                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7308                    // A change in dimension means an auto-centered pivot point changes, too
7309                    mMatrixDirty = true;
7310                }
7311                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7312                invalidate(true);
7313            }
7314            mBackgroundSizeChanged = true;
7315            invalidateParentIfNeeded();
7316        }
7317    }
7318
7319    /**
7320     * Bottom position of this view relative to its parent.
7321     *
7322     * @return The bottom of this view, in pixels.
7323     */
7324    @ViewDebug.CapturedViewProperty
7325    public final int getBottom() {
7326        return mBottom;
7327    }
7328
7329    /**
7330     * True if this view has changed since the last time being drawn.
7331     *
7332     * @return The dirty state of this view.
7333     */
7334    public boolean isDirty() {
7335        return (mPrivateFlags & DIRTY_MASK) != 0;
7336    }
7337
7338    /**
7339     * Sets the bottom position of this view relative to its parent. This method is meant to be
7340     * called by the layout system and should not generally be called otherwise, because the
7341     * property may be changed at any time by the layout.
7342     *
7343     * @param bottom The bottom of this view, in pixels.
7344     */
7345    public final void setBottom(int bottom) {
7346        if (bottom != mBottom) {
7347            updateMatrix();
7348            if (mMatrixIsIdentity) {
7349                if (mAttachInfo != null) {
7350                    int maxBottom;
7351                    if (bottom < mBottom) {
7352                        maxBottom = mBottom;
7353                    } else {
7354                        maxBottom = bottom;
7355                    }
7356                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7357                }
7358            } else {
7359                // Double-invalidation is necessary to capture view's old and new areas
7360                invalidate(true);
7361            }
7362
7363            int width = mRight - mLeft;
7364            int oldHeight = mBottom - mTop;
7365
7366            mBottom = bottom;
7367
7368            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7369
7370            if (!mMatrixIsIdentity) {
7371                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7372                    // A change in dimension means an auto-centered pivot point changes, too
7373                    mMatrixDirty = true;
7374                }
7375                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7376                invalidate(true);
7377            }
7378            mBackgroundSizeChanged = true;
7379            invalidateParentIfNeeded();
7380        }
7381    }
7382
7383    /**
7384     * Left position of this view relative to its parent.
7385     *
7386     * @return The left edge of this view, in pixels.
7387     */
7388    @ViewDebug.CapturedViewProperty
7389    public final int getLeft() {
7390        return mLeft;
7391    }
7392
7393    /**
7394     * Sets the left position of this view relative to its parent. This method is meant to be called
7395     * by the layout system and should not generally be called otherwise, because the property
7396     * may be changed at any time by the layout.
7397     *
7398     * @param left The bottom of this view, in pixels.
7399     */
7400    public final void setLeft(int left) {
7401        if (left != mLeft) {
7402            updateMatrix();
7403            if (mMatrixIsIdentity) {
7404                if (mAttachInfo != null) {
7405                    int minLeft;
7406                    int xLoc;
7407                    if (left < mLeft) {
7408                        minLeft = left;
7409                        xLoc = left - mLeft;
7410                    } else {
7411                        minLeft = mLeft;
7412                        xLoc = 0;
7413                    }
7414                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7415                }
7416            } else {
7417                // Double-invalidation is necessary to capture view's old and new areas
7418                invalidate(true);
7419            }
7420
7421            int oldWidth = mRight - mLeft;
7422            int height = mBottom - mTop;
7423
7424            mLeft = left;
7425
7426            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7427
7428            if (!mMatrixIsIdentity) {
7429                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7430                    // A change in dimension means an auto-centered pivot point changes, too
7431                    mMatrixDirty = true;
7432                }
7433                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7434                invalidate(true);
7435            }
7436            mBackgroundSizeChanged = true;
7437            invalidateParentIfNeeded();
7438        }
7439    }
7440
7441    /**
7442     * Right position of this view relative to its parent.
7443     *
7444     * @return The right edge of this view, in pixels.
7445     */
7446    @ViewDebug.CapturedViewProperty
7447    public final int getRight() {
7448        return mRight;
7449    }
7450
7451    /**
7452     * Sets the right position of this view relative to its parent. This method is meant to be called
7453     * by the layout system and should not generally be called otherwise, because the property
7454     * may be changed at any time by the layout.
7455     *
7456     * @param right The bottom of this view, in pixels.
7457     */
7458    public final void setRight(int right) {
7459        if (right != mRight) {
7460            updateMatrix();
7461            if (mMatrixIsIdentity) {
7462                if (mAttachInfo != null) {
7463                    int maxRight;
7464                    if (right < mRight) {
7465                        maxRight = mRight;
7466                    } else {
7467                        maxRight = right;
7468                    }
7469                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7470                }
7471            } else {
7472                // Double-invalidation is necessary to capture view's old and new areas
7473                invalidate(true);
7474            }
7475
7476            int oldWidth = mRight - mLeft;
7477            int height = mBottom - mTop;
7478
7479            mRight = right;
7480
7481            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7482
7483            if (!mMatrixIsIdentity) {
7484                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7485                    // A change in dimension means an auto-centered pivot point changes, too
7486                    mMatrixDirty = true;
7487                }
7488                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7489                invalidate(true);
7490            }
7491            mBackgroundSizeChanged = true;
7492            invalidateParentIfNeeded();
7493        }
7494    }
7495
7496    /**
7497     * The visual x position of this view, in pixels. This is equivalent to the
7498     * {@link #setTranslationX(float) translationX} property plus the current
7499     * {@link #getLeft() left} property.
7500     *
7501     * @return The visual x position of this view, in pixels.
7502     */
7503    public float getX() {
7504        return mLeft + mTranslationX;
7505    }
7506
7507    /**
7508     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7509     * {@link #setTranslationX(float) translationX} property to be the difference between
7510     * the x value passed in and the current {@link #getLeft() left} property.
7511     *
7512     * @param x The visual x position of this view, in pixels.
7513     */
7514    public void setX(float x) {
7515        setTranslationX(x - mLeft);
7516    }
7517
7518    /**
7519     * The visual y position of this view, in pixels. This is equivalent to the
7520     * {@link #setTranslationY(float) translationY} property plus the current
7521     * {@link #getTop() top} property.
7522     *
7523     * @return The visual y position of this view, in pixels.
7524     */
7525    public float getY() {
7526        return mTop + mTranslationY;
7527    }
7528
7529    /**
7530     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7531     * {@link #setTranslationY(float) translationY} property to be the difference between
7532     * the y value passed in and the current {@link #getTop() top} property.
7533     *
7534     * @param y The visual y position of this view, in pixels.
7535     */
7536    public void setY(float y) {
7537        setTranslationY(y - mTop);
7538    }
7539
7540
7541    /**
7542     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7543     * This position is post-layout, in addition to wherever the object's
7544     * layout placed it.
7545     *
7546     * @return The horizontal position of this view relative to its left position, in pixels.
7547     */
7548    public float getTranslationX() {
7549        return mTranslationX;
7550    }
7551
7552    /**
7553     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7554     * This effectively positions the object post-layout, in addition to wherever the object's
7555     * layout placed it.
7556     *
7557     * @param translationX The horizontal position of this view relative to its left position,
7558     * in pixels.
7559     *
7560     * @attr ref android.R.styleable#View_translationX
7561     */
7562    public void setTranslationX(float translationX) {
7563        if (mTranslationX != translationX) {
7564            invalidateParentCaches();
7565            // Double-invalidation is necessary to capture view's old and new areas
7566            invalidate(false);
7567            mTranslationX = translationX;
7568            mMatrixDirty = true;
7569            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7570            invalidate(false);
7571        }
7572    }
7573
7574    /**
7575     * The horizontal location of this view relative to its {@link #getTop() top} position.
7576     * This position is post-layout, in addition to wherever the object's
7577     * layout placed it.
7578     *
7579     * @return The vertical position of this view relative to its top position,
7580     * in pixels.
7581     */
7582    public float getTranslationY() {
7583        return mTranslationY;
7584    }
7585
7586    /**
7587     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7588     * This effectively positions the object post-layout, in addition to wherever the object's
7589     * layout placed it.
7590     *
7591     * @param translationY The vertical position of this view relative to its top position,
7592     * in pixels.
7593     *
7594     * @attr ref android.R.styleable#View_translationY
7595     */
7596    public void setTranslationY(float translationY) {
7597        if (mTranslationY != translationY) {
7598            invalidateParentCaches();
7599            // Double-invalidation is necessary to capture view's old and new areas
7600            invalidate(false);
7601            mTranslationY = translationY;
7602            mMatrixDirty = true;
7603            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7604            invalidate(false);
7605        }
7606    }
7607
7608    /**
7609     * @hide
7610     */
7611    public void setFastTranslationX(float x) {
7612        mTranslationX = x;
7613        mMatrixDirty = true;
7614    }
7615
7616    /**
7617     * @hide
7618     */
7619    public void setFastTranslationY(float y) {
7620        mTranslationY = y;
7621        mMatrixDirty = true;
7622    }
7623
7624    /**
7625     * @hide
7626     */
7627    public void setFastX(float x) {
7628        mTranslationX = x - mLeft;
7629        mMatrixDirty = true;
7630    }
7631
7632    /**
7633     * @hide
7634     */
7635    public void setFastY(float y) {
7636        mTranslationY = y - mTop;
7637        mMatrixDirty = true;
7638    }
7639
7640    /**
7641     * @hide
7642     */
7643    public void setFastScaleX(float x) {
7644        mScaleX = x;
7645        mMatrixDirty = true;
7646    }
7647
7648    /**
7649     * @hide
7650     */
7651    public void setFastScaleY(float y) {
7652        mScaleY = y;
7653        mMatrixDirty = true;
7654    }
7655
7656    /**
7657     * @hide
7658     */
7659    public void setFastAlpha(float alpha) {
7660        mAlpha = alpha;
7661    }
7662
7663    /**
7664     * @hide
7665     */
7666    public void setFastRotationY(float y) {
7667        mRotationY = y;
7668        mMatrixDirty = true;
7669    }
7670
7671    /**
7672     * Hit rectangle in parent's coordinates
7673     *
7674     * @param outRect The hit rectangle of the view.
7675     */
7676    public void getHitRect(Rect outRect) {
7677        updateMatrix();
7678        if (mMatrixIsIdentity || mAttachInfo == null) {
7679            outRect.set(mLeft, mTop, mRight, mBottom);
7680        } else {
7681            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7682            tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
7683            mMatrix.mapRect(tmpRect);
7684            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7685                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7686        }
7687    }
7688
7689    /**
7690     * Determines whether the given point, in local coordinates is inside the view.
7691     */
7692    /*package*/ final boolean pointInView(float localX, float localY) {
7693        return localX >= 0 && localX < (mRight - mLeft)
7694                && localY >= 0 && localY < (mBottom - mTop);
7695    }
7696
7697    /**
7698     * Utility method to determine whether the given point, in local coordinates,
7699     * is inside the view, where the area of the view is expanded by the slop factor.
7700     * This method is called while processing touch-move events to determine if the event
7701     * is still within the view.
7702     */
7703    private boolean pointInView(float localX, float localY, float slop) {
7704        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7705                localY < ((mBottom - mTop) + slop);
7706    }
7707
7708    /**
7709     * When a view has focus and the user navigates away from it, the next view is searched for
7710     * starting from the rectangle filled in by this method.
7711     *
7712     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7713     * of the view.  However, if your view maintains some idea of internal selection,
7714     * such as a cursor, or a selected row or column, you should override this method and
7715     * fill in a more specific rectangle.
7716     *
7717     * @param r The rectangle to fill in, in this view's coordinates.
7718     */
7719    public void getFocusedRect(Rect r) {
7720        getDrawingRect(r);
7721    }
7722
7723    /**
7724     * If some part of this view is not clipped by any of its parents, then
7725     * return that area in r in global (root) coordinates. To convert r to local
7726     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7727     * -globalOffset.y)) If the view is completely clipped or translated out,
7728     * return false.
7729     *
7730     * @param r If true is returned, r holds the global coordinates of the
7731     *        visible portion of this view.
7732     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7733     *        between this view and its root. globalOffet may be null.
7734     * @return true if r is non-empty (i.e. part of the view is visible at the
7735     *         root level.
7736     */
7737    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7738        int width = mRight - mLeft;
7739        int height = mBottom - mTop;
7740        if (width > 0 && height > 0) {
7741            r.set(0, 0, width, height);
7742            if (globalOffset != null) {
7743                globalOffset.set(-mScrollX, -mScrollY);
7744            }
7745            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
7746        }
7747        return false;
7748    }
7749
7750    public final boolean getGlobalVisibleRect(Rect r) {
7751        return getGlobalVisibleRect(r, null);
7752    }
7753
7754    public final boolean getLocalVisibleRect(Rect r) {
7755        Point offset = new Point();
7756        if (getGlobalVisibleRect(r, offset)) {
7757            r.offset(-offset.x, -offset.y); // make r local
7758            return true;
7759        }
7760        return false;
7761    }
7762
7763    /**
7764     * Offset this view's vertical location by the specified number of pixels.
7765     *
7766     * @param offset the number of pixels to offset the view by
7767     */
7768    public void offsetTopAndBottom(int offset) {
7769        if (offset != 0) {
7770            updateMatrix();
7771            if (mMatrixIsIdentity) {
7772                final ViewParent p = mParent;
7773                if (p != null && mAttachInfo != null) {
7774                    final Rect r = mAttachInfo.mTmpInvalRect;
7775                    int minTop;
7776                    int maxBottom;
7777                    int yLoc;
7778                    if (offset < 0) {
7779                        minTop = mTop + offset;
7780                        maxBottom = mBottom;
7781                        yLoc = offset;
7782                    } else {
7783                        minTop = mTop;
7784                        maxBottom = mBottom + offset;
7785                        yLoc = 0;
7786                    }
7787                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
7788                    p.invalidateChild(this, r);
7789                }
7790            } else {
7791                invalidate(false);
7792            }
7793
7794            mTop += offset;
7795            mBottom += offset;
7796
7797            if (!mMatrixIsIdentity) {
7798                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7799                invalidate(false);
7800            }
7801            invalidateParentIfNeeded();
7802        }
7803    }
7804
7805    /**
7806     * Offset this view's horizontal location by the specified amount of pixels.
7807     *
7808     * @param offset the numer of pixels to offset the view by
7809     */
7810    public void offsetLeftAndRight(int offset) {
7811        if (offset != 0) {
7812            updateMatrix();
7813            if (mMatrixIsIdentity) {
7814                final ViewParent p = mParent;
7815                if (p != null && mAttachInfo != null) {
7816                    final Rect r = mAttachInfo.mTmpInvalRect;
7817                    int minLeft;
7818                    int maxRight;
7819                    if (offset < 0) {
7820                        minLeft = mLeft + offset;
7821                        maxRight = mRight;
7822                    } else {
7823                        minLeft = mLeft;
7824                        maxRight = mRight + offset;
7825                    }
7826                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
7827                    p.invalidateChild(this, r);
7828                }
7829            } else {
7830                invalidate(false);
7831            }
7832
7833            mLeft += offset;
7834            mRight += offset;
7835
7836            if (!mMatrixIsIdentity) {
7837                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7838                invalidate(false);
7839            }
7840            invalidateParentIfNeeded();
7841        }
7842    }
7843
7844    /**
7845     * Get the LayoutParams associated with this view. All views should have
7846     * layout parameters. These supply parameters to the <i>parent</i> of this
7847     * view specifying how it should be arranged. There are many subclasses of
7848     * ViewGroup.LayoutParams, and these correspond to the different subclasses
7849     * of ViewGroup that are responsible for arranging their children.
7850     *
7851     * This method may return null if this View is not attached to a parent
7852     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
7853     * was not invoked successfully. When a View is attached to a parent
7854     * ViewGroup, this method must not return null.
7855     *
7856     * @return The LayoutParams associated with this view, or null if no
7857     *         parameters have been set yet
7858     */
7859    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
7860    public ViewGroup.LayoutParams getLayoutParams() {
7861        return mLayoutParams;
7862    }
7863
7864    /**
7865     * Set the layout parameters associated with this view. These supply
7866     * parameters to the <i>parent</i> of this view specifying how it should be
7867     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
7868     * correspond to the different subclasses of ViewGroup that are responsible
7869     * for arranging their children.
7870     *
7871     * @param params The layout parameters for this view, cannot be null
7872     */
7873    public void setLayoutParams(ViewGroup.LayoutParams params) {
7874        if (params == null) {
7875            throw new NullPointerException("Layout parameters cannot be null");
7876        }
7877        mLayoutParams = params;
7878        requestLayout();
7879    }
7880
7881    /**
7882     * Set the scrolled position of your view. This will cause a call to
7883     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7884     * invalidated.
7885     * @param x the x position to scroll to
7886     * @param y the y position to scroll to
7887     */
7888    public void scrollTo(int x, int y) {
7889        if (mScrollX != x || mScrollY != y) {
7890            int oldX = mScrollX;
7891            int oldY = mScrollY;
7892            mScrollX = x;
7893            mScrollY = y;
7894            invalidateParentCaches();
7895            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
7896            if (!awakenScrollBars()) {
7897                invalidate(true);
7898            }
7899        }
7900    }
7901
7902    /**
7903     * Move the scrolled position of your view. This will cause a call to
7904     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7905     * invalidated.
7906     * @param x the amount of pixels to scroll by horizontally
7907     * @param y the amount of pixels to scroll by vertically
7908     */
7909    public void scrollBy(int x, int y) {
7910        scrollTo(mScrollX + x, mScrollY + y);
7911    }
7912
7913    /**
7914     * <p>Trigger the scrollbars to draw. When invoked this method starts an
7915     * animation to fade the scrollbars out after a default delay. If a subclass
7916     * provides animated scrolling, the start delay should equal the duration
7917     * of the scrolling animation.</p>
7918     *
7919     * <p>The animation starts only if at least one of the scrollbars is
7920     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
7921     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7922     * this method returns true, and false otherwise. If the animation is
7923     * started, this method calls {@link #invalidate()}; in that case the
7924     * caller should not call {@link #invalidate()}.</p>
7925     *
7926     * <p>This method should be invoked every time a subclass directly updates
7927     * the scroll parameters.</p>
7928     *
7929     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
7930     * and {@link #scrollTo(int, int)}.</p>
7931     *
7932     * @return true if the animation is played, false otherwise
7933     *
7934     * @see #awakenScrollBars(int)
7935     * @see #scrollBy(int, int)
7936     * @see #scrollTo(int, int)
7937     * @see #isHorizontalScrollBarEnabled()
7938     * @see #isVerticalScrollBarEnabled()
7939     * @see #setHorizontalScrollBarEnabled(boolean)
7940     * @see #setVerticalScrollBarEnabled(boolean)
7941     */
7942    protected boolean awakenScrollBars() {
7943        return mScrollCache != null &&
7944                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
7945    }
7946
7947    /**
7948     * Trigger the scrollbars to draw.
7949     * This method differs from awakenScrollBars() only in its default duration.
7950     * initialAwakenScrollBars() will show the scroll bars for longer than
7951     * usual to give the user more of a chance to notice them.
7952     *
7953     * @return true if the animation is played, false otherwise.
7954     */
7955    private boolean initialAwakenScrollBars() {
7956        return mScrollCache != null &&
7957                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
7958    }
7959
7960    /**
7961     * <p>
7962     * Trigger the scrollbars to draw. When invoked this method starts an
7963     * animation to fade the scrollbars out after a fixed delay. If a subclass
7964     * provides animated scrolling, the start delay should equal the duration of
7965     * the scrolling animation.
7966     * </p>
7967     *
7968     * <p>
7969     * The animation starts only if at least one of the scrollbars is enabled,
7970     * as specified by {@link #isHorizontalScrollBarEnabled()} and
7971     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7972     * this method returns true, and false otherwise. If the animation is
7973     * started, this method calls {@link #invalidate()}; in that case the caller
7974     * should not call {@link #invalidate()}.
7975     * </p>
7976     *
7977     * <p>
7978     * This method should be invoked everytime a subclass directly updates the
7979     * scroll parameters.
7980     * </p>
7981     *
7982     * @param startDelay the delay, in milliseconds, after which the animation
7983     *        should start; when the delay is 0, the animation starts
7984     *        immediately
7985     * @return true if the animation is played, false otherwise
7986     *
7987     * @see #scrollBy(int, int)
7988     * @see #scrollTo(int, int)
7989     * @see #isHorizontalScrollBarEnabled()
7990     * @see #isVerticalScrollBarEnabled()
7991     * @see #setHorizontalScrollBarEnabled(boolean)
7992     * @see #setVerticalScrollBarEnabled(boolean)
7993     */
7994    protected boolean awakenScrollBars(int startDelay) {
7995        return awakenScrollBars(startDelay, true);
7996    }
7997
7998    /**
7999     * <p>
8000     * Trigger the scrollbars to draw. When invoked this method starts an
8001     * animation to fade the scrollbars out after a fixed delay. If a subclass
8002     * provides animated scrolling, the start delay should equal the duration of
8003     * the scrolling animation.
8004     * </p>
8005     *
8006     * <p>
8007     * The animation starts only if at least one of the scrollbars is enabled,
8008     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8009     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8010     * this method returns true, and false otherwise. If the animation is
8011     * started, this method calls {@link #invalidate()} if the invalidate parameter
8012     * is set to true; in that case the caller
8013     * should not call {@link #invalidate()}.
8014     * </p>
8015     *
8016     * <p>
8017     * This method should be invoked everytime a subclass directly updates the
8018     * scroll parameters.
8019     * </p>
8020     *
8021     * @param startDelay the delay, in milliseconds, after which the animation
8022     *        should start; when the delay is 0, the animation starts
8023     *        immediately
8024     *
8025     * @param invalidate Wheter this method should call invalidate
8026     *
8027     * @return true if the animation is played, false otherwise
8028     *
8029     * @see #scrollBy(int, int)
8030     * @see #scrollTo(int, int)
8031     * @see #isHorizontalScrollBarEnabled()
8032     * @see #isVerticalScrollBarEnabled()
8033     * @see #setHorizontalScrollBarEnabled(boolean)
8034     * @see #setVerticalScrollBarEnabled(boolean)
8035     */
8036    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8037        final ScrollabilityCache scrollCache = mScrollCache;
8038
8039        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8040            return false;
8041        }
8042
8043        if (scrollCache.scrollBar == null) {
8044            scrollCache.scrollBar = new ScrollBarDrawable();
8045        }
8046
8047        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8048
8049            if (invalidate) {
8050                // Invalidate to show the scrollbars
8051                invalidate(true);
8052            }
8053
8054            if (scrollCache.state == ScrollabilityCache.OFF) {
8055                // FIXME: this is copied from WindowManagerService.
8056                // We should get this value from the system when it
8057                // is possible to do so.
8058                final int KEY_REPEAT_FIRST_DELAY = 750;
8059                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8060            }
8061
8062            // Tell mScrollCache when we should start fading. This may
8063            // extend the fade start time if one was already scheduled
8064            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8065            scrollCache.fadeStartTime = fadeStartTime;
8066            scrollCache.state = ScrollabilityCache.ON;
8067
8068            // Schedule our fader to run, unscheduling any old ones first
8069            if (mAttachInfo != null) {
8070                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8071                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8072            }
8073
8074            return true;
8075        }
8076
8077        return false;
8078    }
8079
8080    /**
8081     * Do not invalidate views which are not visible and which are not running an animation. They
8082     * will not get drawn and they should not set dirty flags as if they will be drawn
8083     */
8084    private boolean skipInvalidate() {
8085        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8086                (!(mParent instanceof ViewGroup) ||
8087                        !((ViewGroup) mParent).isViewTransitioning(this));
8088    }
8089    /**
8090     * Mark the the area defined by dirty as needing to be drawn. If the view is
8091     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8092     * in the future. This must be called from a UI thread. To call from a non-UI
8093     * thread, call {@link #postInvalidate()}.
8094     *
8095     * WARNING: This method is destructive to dirty.
8096     * @param dirty the rectangle representing the bounds of the dirty region
8097     */
8098    public void invalidate(Rect dirty) {
8099        if (ViewDebug.TRACE_HIERARCHY) {
8100            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8101        }
8102
8103        if (skipInvalidate()) {
8104            return;
8105        }
8106        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8107                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8108                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8109            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8110            mPrivateFlags |= INVALIDATED;
8111            mPrivateFlags |= DIRTY;
8112            final ViewParent p = mParent;
8113            final AttachInfo ai = mAttachInfo;
8114            //noinspection PointlessBooleanExpression,ConstantConditions
8115            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8116                if (p != null && ai != null && ai.mHardwareAccelerated) {
8117                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8118                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8119                    p.invalidateChild(this, null);
8120                    return;
8121                }
8122            }
8123            if (p != null && ai != null) {
8124                final int scrollX = mScrollX;
8125                final int scrollY = mScrollY;
8126                final Rect r = ai.mTmpInvalRect;
8127                r.set(dirty.left - scrollX, dirty.top - scrollY,
8128                        dirty.right - scrollX, dirty.bottom - scrollY);
8129                mParent.invalidateChild(this, r);
8130            }
8131        }
8132    }
8133
8134    /**
8135     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
8136     * The coordinates of the dirty rect are relative to the view.
8137     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8138     * will be called at some point in the future. This must be called from
8139     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8140     * @param l the left position of the dirty region
8141     * @param t the top position of the dirty region
8142     * @param r the right position of the dirty region
8143     * @param b the bottom position of the dirty region
8144     */
8145    public void invalidate(int l, int t, int r, int b) {
8146        if (ViewDebug.TRACE_HIERARCHY) {
8147            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8148        }
8149
8150        if (skipInvalidate()) {
8151            return;
8152        }
8153        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8154                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8155                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8156            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8157            mPrivateFlags |= INVALIDATED;
8158            mPrivateFlags |= DIRTY;
8159            final ViewParent p = mParent;
8160            final AttachInfo ai = mAttachInfo;
8161            //noinspection PointlessBooleanExpression,ConstantConditions
8162            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8163                if (p != null && ai != null && ai.mHardwareAccelerated) {
8164                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8165                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8166                    p.invalidateChild(this, null);
8167                    return;
8168                }
8169            }
8170            if (p != null && ai != null && l < r && t < b) {
8171                final int scrollX = mScrollX;
8172                final int scrollY = mScrollY;
8173                final Rect tmpr = ai.mTmpInvalRect;
8174                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8175                p.invalidateChild(this, tmpr);
8176            }
8177        }
8178    }
8179
8180    /**
8181     * Invalidate the whole view. If the view is visible,
8182     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8183     * the future. This must be called from a UI thread. To call from a non-UI thread,
8184     * call {@link #postInvalidate()}.
8185     */
8186    public void invalidate() {
8187        invalidate(true);
8188    }
8189
8190    /**
8191     * This is where the invalidate() work actually happens. A full invalidate()
8192     * causes the drawing cache to be invalidated, but this function can be called with
8193     * invalidateCache set to false to skip that invalidation step for cases that do not
8194     * need it (for example, a component that remains at the same dimensions with the same
8195     * content).
8196     *
8197     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8198     * well. This is usually true for a full invalidate, but may be set to false if the
8199     * View's contents or dimensions have not changed.
8200     */
8201    void invalidate(boolean invalidateCache) {
8202        if (ViewDebug.TRACE_HIERARCHY) {
8203            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8204        }
8205
8206        if (skipInvalidate()) {
8207            return;
8208        }
8209        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8210                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8211                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8212            mLastIsOpaque = isOpaque();
8213            mPrivateFlags &= ~DRAWN;
8214            mPrivateFlags |= DIRTY;
8215            if (invalidateCache) {
8216                mPrivateFlags |= INVALIDATED;
8217                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8218            }
8219            final AttachInfo ai = mAttachInfo;
8220            final ViewParent p = mParent;
8221            //noinspection PointlessBooleanExpression,ConstantConditions
8222            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8223                if (p != null && ai != null && ai.mHardwareAccelerated) {
8224                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8225                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8226                    p.invalidateChild(this, null);
8227                    return;
8228                }
8229            }
8230
8231            if (p != null && ai != null) {
8232                final Rect r = ai.mTmpInvalRect;
8233                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8234                // Don't call invalidate -- we don't want to internally scroll
8235                // our own bounds
8236                p.invalidateChild(this, r);
8237            }
8238        }
8239    }
8240
8241    /**
8242     * @hide
8243     */
8244    public void fastInvalidate() {
8245        if (skipInvalidate()) {
8246            return;
8247        }
8248        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8249            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8250            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8251            if (mParent instanceof View) {
8252                ((View) mParent).mPrivateFlags |= INVALIDATED;
8253            }
8254            mPrivateFlags &= ~DRAWN;
8255            mPrivateFlags |= DIRTY;
8256            mPrivateFlags |= INVALIDATED;
8257            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8258            if (mParent != null && mAttachInfo != null) {
8259                if (mAttachInfo.mHardwareAccelerated) {
8260                    mParent.invalidateChild(this, null);
8261                } else {
8262                    final Rect r = mAttachInfo.mTmpInvalRect;
8263                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
8264                    // Don't call invalidate -- we don't want to internally scroll
8265                    // our own bounds
8266                    mParent.invalidateChild(this, r);
8267                }
8268            }
8269        }
8270    }
8271
8272    /**
8273     * Used to indicate that the parent of this view should clear its caches. This functionality
8274     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8275     * which is necessary when various parent-managed properties of the view change, such as
8276     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8277     * clears the parent caches and does not causes an invalidate event.
8278     *
8279     * @hide
8280     */
8281    protected void invalidateParentCaches() {
8282        if (mParent instanceof View) {
8283            ((View) mParent).mPrivateFlags |= INVALIDATED;
8284        }
8285    }
8286
8287    /**
8288     * Used to indicate that the parent of this view should be invalidated. This functionality
8289     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8290     * which is necessary when various parent-managed properties of the view change, such as
8291     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8292     * an invalidation event to the parent.
8293     *
8294     * @hide
8295     */
8296    protected void invalidateParentIfNeeded() {
8297        if (isHardwareAccelerated() && mParent instanceof View) {
8298            ((View) mParent).invalidate(true);
8299        }
8300    }
8301
8302    /**
8303     * Indicates whether this View is opaque. An opaque View guarantees that it will
8304     * draw all the pixels overlapping its bounds using a fully opaque color.
8305     *
8306     * Subclasses of View should override this method whenever possible to indicate
8307     * whether an instance is opaque. Opaque Views are treated in a special way by
8308     * the View hierarchy, possibly allowing it to perform optimizations during
8309     * invalidate/draw passes.
8310     *
8311     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8312     */
8313    @ViewDebug.ExportedProperty(category = "drawing")
8314    public boolean isOpaque() {
8315        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8316                (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8317    }
8318
8319    /**
8320     * @hide
8321     */
8322    protected void computeOpaqueFlags() {
8323        // Opaque if:
8324        //   - Has a background
8325        //   - Background is opaque
8326        //   - Doesn't have scrollbars or scrollbars are inside overlay
8327
8328        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8329            mPrivateFlags |= OPAQUE_BACKGROUND;
8330        } else {
8331            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8332        }
8333
8334        final int flags = mViewFlags;
8335        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8336                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8337            mPrivateFlags |= OPAQUE_SCROLLBARS;
8338        } else {
8339            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8340        }
8341    }
8342
8343    /**
8344     * @hide
8345     */
8346    protected boolean hasOpaqueScrollbars() {
8347        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8348    }
8349
8350    /**
8351     * @return A handler associated with the thread running the View. This
8352     * handler can be used to pump events in the UI events queue.
8353     */
8354    public Handler getHandler() {
8355        if (mAttachInfo != null) {
8356            return mAttachInfo.mHandler;
8357        }
8358        return null;
8359    }
8360
8361    /**
8362     * <p>Causes the Runnable to be added to the message queue.
8363     * The runnable will be run on the user interface thread.</p>
8364     *
8365     * <p>This method can be invoked from outside of the UI thread
8366     * only when this View is attached to a window.</p>
8367     *
8368     * @param action The Runnable that will be executed.
8369     *
8370     * @return Returns true if the Runnable was successfully placed in to the
8371     *         message queue.  Returns false on failure, usually because the
8372     *         looper processing the message queue is exiting.
8373     */
8374    public boolean post(Runnable action) {
8375        Handler handler;
8376        AttachInfo attachInfo = mAttachInfo;
8377        if (attachInfo != null) {
8378            handler = attachInfo.mHandler;
8379        } else {
8380            // Assume that post will succeed later
8381            ViewRootImpl.getRunQueue().post(action);
8382            return true;
8383        }
8384
8385        return handler.post(action);
8386    }
8387
8388    /**
8389     * <p>Causes the Runnable to be added to the message queue, to be run
8390     * after the specified amount of time elapses.
8391     * The runnable will be run on the user interface thread.</p>
8392     *
8393     * <p>This method can be invoked from outside of the UI thread
8394     * only when this View is attached to a window.</p>
8395     *
8396     * @param action The Runnable that will be executed.
8397     * @param delayMillis The delay (in milliseconds) until the Runnable
8398     *        will be executed.
8399     *
8400     * @return true if the Runnable was successfully placed in to the
8401     *         message queue.  Returns false on failure, usually because the
8402     *         looper processing the message queue is exiting.  Note that a
8403     *         result of true does not mean the Runnable will be processed --
8404     *         if the looper is quit before the delivery time of the message
8405     *         occurs then the message will be dropped.
8406     */
8407    public boolean postDelayed(Runnable action, long delayMillis) {
8408        Handler handler;
8409        AttachInfo attachInfo = mAttachInfo;
8410        if (attachInfo != null) {
8411            handler = attachInfo.mHandler;
8412        } else {
8413            // Assume that post will succeed later
8414            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8415            return true;
8416        }
8417
8418        return handler.postDelayed(action, delayMillis);
8419    }
8420
8421    /**
8422     * <p>Removes the specified Runnable from the message queue.</p>
8423     *
8424     * <p>This method can be invoked from outside of the UI thread
8425     * only when this View is attached to a window.</p>
8426     *
8427     * @param action The Runnable to remove from the message handling queue
8428     *
8429     * @return true if this view could ask the Handler to remove the Runnable,
8430     *         false otherwise. When the returned value is true, the Runnable
8431     *         may or may not have been actually removed from the message queue
8432     *         (for instance, if the Runnable was not in the queue already.)
8433     */
8434    public boolean removeCallbacks(Runnable action) {
8435        Handler handler;
8436        AttachInfo attachInfo = mAttachInfo;
8437        if (attachInfo != null) {
8438            handler = attachInfo.mHandler;
8439        } else {
8440            // Assume that post will succeed later
8441            ViewRootImpl.getRunQueue().removeCallbacks(action);
8442            return true;
8443        }
8444
8445        handler.removeCallbacks(action);
8446        return true;
8447    }
8448
8449    /**
8450     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8451     * Use this to invalidate the View from a non-UI thread.</p>
8452     *
8453     * <p>This method can be invoked from outside of the UI thread
8454     * only when this View is attached to a window.</p>
8455     *
8456     * @see #invalidate()
8457     */
8458    public void postInvalidate() {
8459        postInvalidateDelayed(0);
8460    }
8461
8462    /**
8463     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8464     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8465     *
8466     * <p>This method can be invoked from outside of the UI thread
8467     * only when this View is attached to a window.</p>
8468     *
8469     * @param left The left coordinate of the rectangle to invalidate.
8470     * @param top The top coordinate of the rectangle to invalidate.
8471     * @param right The right coordinate of the rectangle to invalidate.
8472     * @param bottom The bottom coordinate of the rectangle to invalidate.
8473     *
8474     * @see #invalidate(int, int, int, int)
8475     * @see #invalidate(Rect)
8476     */
8477    public void postInvalidate(int left, int top, int right, int bottom) {
8478        postInvalidateDelayed(0, left, top, right, bottom);
8479    }
8480
8481    /**
8482     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8483     * loop. Waits for the specified amount of time.</p>
8484     *
8485     * <p>This method can be invoked from outside of the UI thread
8486     * only when this View is attached to a window.</p>
8487     *
8488     * @param delayMilliseconds the duration in milliseconds to delay the
8489     *         invalidation by
8490     */
8491    public void postInvalidateDelayed(long delayMilliseconds) {
8492        // We try only with the AttachInfo because there's no point in invalidating
8493        // if we are not attached to our window
8494        AttachInfo attachInfo = mAttachInfo;
8495        if (attachInfo != null) {
8496            Message msg = Message.obtain();
8497            msg.what = AttachInfo.INVALIDATE_MSG;
8498            msg.obj = this;
8499            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8500        }
8501    }
8502
8503    /**
8504     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8505     * through the event loop. Waits for the specified amount of time.</p>
8506     *
8507     * <p>This method can be invoked from outside of the UI thread
8508     * only when this View is attached to a window.</p>
8509     *
8510     * @param delayMilliseconds the duration in milliseconds to delay the
8511     *         invalidation by
8512     * @param left The left coordinate of the rectangle to invalidate.
8513     * @param top The top coordinate of the rectangle to invalidate.
8514     * @param right The right coordinate of the rectangle to invalidate.
8515     * @param bottom The bottom coordinate of the rectangle to invalidate.
8516     */
8517    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8518            int right, int bottom) {
8519
8520        // We try only with the AttachInfo because there's no point in invalidating
8521        // if we are not attached to our window
8522        AttachInfo attachInfo = mAttachInfo;
8523        if (attachInfo != null) {
8524            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8525            info.target = this;
8526            info.left = left;
8527            info.top = top;
8528            info.right = right;
8529            info.bottom = bottom;
8530
8531            final Message msg = Message.obtain();
8532            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8533            msg.obj = info;
8534            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8535        }
8536    }
8537
8538    /**
8539     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8540     * This event is sent at most once every
8541     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8542     */
8543    private void postSendViewScrolledAccessibilityEventCallback() {
8544        if (mSendViewScrolledAccessibilityEvent == null) {
8545            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8546        }
8547        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8548            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8549            postDelayed(mSendViewScrolledAccessibilityEvent,
8550                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8551        }
8552    }
8553
8554    /**
8555     * Called by a parent to request that a child update its values for mScrollX
8556     * and mScrollY if necessary. This will typically be done if the child is
8557     * animating a scroll using a {@link android.widget.Scroller Scroller}
8558     * object.
8559     */
8560    public void computeScroll() {
8561    }
8562
8563    /**
8564     * <p>Indicate whether the horizontal edges are faded when the view is
8565     * scrolled horizontally.</p>
8566     *
8567     * @return true if the horizontal edges should are faded on scroll, false
8568     *         otherwise
8569     *
8570     * @see #setHorizontalFadingEdgeEnabled(boolean)
8571     * @attr ref android.R.styleable#View_fadingEdge
8572     */
8573    public boolean isHorizontalFadingEdgeEnabled() {
8574        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8575    }
8576
8577    /**
8578     * <p>Define whether the horizontal edges should be faded when this view
8579     * is scrolled horizontally.</p>
8580     *
8581     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8582     *                                    be faded when the view is scrolled
8583     *                                    horizontally
8584     *
8585     * @see #isHorizontalFadingEdgeEnabled()
8586     * @attr ref android.R.styleable#View_fadingEdge
8587     */
8588    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8589        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8590            if (horizontalFadingEdgeEnabled) {
8591                initScrollCache();
8592            }
8593
8594            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8595        }
8596    }
8597
8598    /**
8599     * <p>Indicate whether the vertical edges are faded when the view is
8600     * scrolled horizontally.</p>
8601     *
8602     * @return true if the vertical edges should are faded on scroll, false
8603     *         otherwise
8604     *
8605     * @see #setVerticalFadingEdgeEnabled(boolean)
8606     * @attr ref android.R.styleable#View_fadingEdge
8607     */
8608    public boolean isVerticalFadingEdgeEnabled() {
8609        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8610    }
8611
8612    /**
8613     * <p>Define whether the vertical edges should be faded when this view
8614     * is scrolled vertically.</p>
8615     *
8616     * @param verticalFadingEdgeEnabled true if the vertical edges should
8617     *                                  be faded when the view is scrolled
8618     *                                  vertically
8619     *
8620     * @see #isVerticalFadingEdgeEnabled()
8621     * @attr ref android.R.styleable#View_fadingEdge
8622     */
8623    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8624        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8625            if (verticalFadingEdgeEnabled) {
8626                initScrollCache();
8627            }
8628
8629            mViewFlags ^= FADING_EDGE_VERTICAL;
8630        }
8631    }
8632
8633    /**
8634     * Returns the strength, or intensity, of the top faded edge. The strength is
8635     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8636     * returns 0.0 or 1.0 but no value in between.
8637     *
8638     * Subclasses should override this method to provide a smoother fade transition
8639     * when scrolling occurs.
8640     *
8641     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8642     */
8643    protected float getTopFadingEdgeStrength() {
8644        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8645    }
8646
8647    /**
8648     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8649     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8650     * returns 0.0 or 1.0 but no value in between.
8651     *
8652     * Subclasses should override this method to provide a smoother fade transition
8653     * when scrolling occurs.
8654     *
8655     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8656     */
8657    protected float getBottomFadingEdgeStrength() {
8658        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8659                computeVerticalScrollRange() ? 1.0f : 0.0f;
8660    }
8661
8662    /**
8663     * Returns the strength, or intensity, of the left faded edge. The strength is
8664     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8665     * returns 0.0 or 1.0 but no value in between.
8666     *
8667     * Subclasses should override this method to provide a smoother fade transition
8668     * when scrolling occurs.
8669     *
8670     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8671     */
8672    protected float getLeftFadingEdgeStrength() {
8673        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8674    }
8675
8676    /**
8677     * Returns the strength, or intensity, of the right faded edge. The strength is
8678     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8679     * returns 0.0 or 1.0 but no value in between.
8680     *
8681     * Subclasses should override this method to provide a smoother fade transition
8682     * when scrolling occurs.
8683     *
8684     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8685     */
8686    protected float getRightFadingEdgeStrength() {
8687        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8688                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8689    }
8690
8691    /**
8692     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8693     * scrollbar is not drawn by default.</p>
8694     *
8695     * @return true if the horizontal scrollbar should be painted, false
8696     *         otherwise
8697     *
8698     * @see #setHorizontalScrollBarEnabled(boolean)
8699     */
8700    public boolean isHorizontalScrollBarEnabled() {
8701        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8702    }
8703
8704    /**
8705     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8706     * scrollbar is not drawn by default.</p>
8707     *
8708     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8709     *                                   be painted
8710     *
8711     * @see #isHorizontalScrollBarEnabled()
8712     */
8713    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8714        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8715            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8716            computeOpaqueFlags();
8717            resolvePadding();
8718        }
8719    }
8720
8721    /**
8722     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8723     * scrollbar is not drawn by default.</p>
8724     *
8725     * @return true if the vertical scrollbar should be painted, false
8726     *         otherwise
8727     *
8728     * @see #setVerticalScrollBarEnabled(boolean)
8729     */
8730    public boolean isVerticalScrollBarEnabled() {
8731        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8732    }
8733
8734    /**
8735     * <p>Define whether the vertical scrollbar should be drawn or not. The
8736     * scrollbar is not drawn by default.</p>
8737     *
8738     * @param verticalScrollBarEnabled true if the vertical scrollbar should
8739     *                                 be painted
8740     *
8741     * @see #isVerticalScrollBarEnabled()
8742     */
8743    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
8744        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
8745            mViewFlags ^= SCROLLBARS_VERTICAL;
8746            computeOpaqueFlags();
8747            resolvePadding();
8748        }
8749    }
8750
8751    /**
8752     * @hide
8753     */
8754    protected void recomputePadding() {
8755        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
8756    }
8757
8758    /**
8759     * Define whether scrollbars will fade when the view is not scrolling.
8760     *
8761     * @param fadeScrollbars wheter to enable fading
8762     *
8763     */
8764    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
8765        initScrollCache();
8766        final ScrollabilityCache scrollabilityCache = mScrollCache;
8767        scrollabilityCache.fadeScrollBars = fadeScrollbars;
8768        if (fadeScrollbars) {
8769            scrollabilityCache.state = ScrollabilityCache.OFF;
8770        } else {
8771            scrollabilityCache.state = ScrollabilityCache.ON;
8772        }
8773    }
8774
8775    /**
8776     *
8777     * Returns true if scrollbars will fade when this view is not scrolling
8778     *
8779     * @return true if scrollbar fading is enabled
8780     */
8781    public boolean isScrollbarFadingEnabled() {
8782        return mScrollCache != null && mScrollCache.fadeScrollBars;
8783    }
8784
8785    /**
8786     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
8787     * inset. When inset, they add to the padding of the view. And the scrollbars
8788     * can be drawn inside the padding area or on the edge of the view. For example,
8789     * if a view has a background drawable and you want to draw the scrollbars
8790     * inside the padding specified by the drawable, you can use
8791     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
8792     * appear at the edge of the view, ignoring the padding, then you can use
8793     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
8794     * @param style the style of the scrollbars. Should be one of
8795     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
8796     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
8797     * @see #SCROLLBARS_INSIDE_OVERLAY
8798     * @see #SCROLLBARS_INSIDE_INSET
8799     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8800     * @see #SCROLLBARS_OUTSIDE_INSET
8801     */
8802    public void setScrollBarStyle(int style) {
8803        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
8804            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
8805            computeOpaqueFlags();
8806            resolvePadding();
8807        }
8808    }
8809
8810    /**
8811     * <p>Returns the current scrollbar style.</p>
8812     * @return the current scrollbar style
8813     * @see #SCROLLBARS_INSIDE_OVERLAY
8814     * @see #SCROLLBARS_INSIDE_INSET
8815     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8816     * @see #SCROLLBARS_OUTSIDE_INSET
8817     */
8818    @ViewDebug.ExportedProperty(mapping = {
8819            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
8820            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
8821            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
8822            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
8823    })
8824    public int getScrollBarStyle() {
8825        return mViewFlags & SCROLLBARS_STYLE_MASK;
8826    }
8827
8828    /**
8829     * <p>Compute the horizontal range that the horizontal scrollbar
8830     * represents.</p>
8831     *
8832     * <p>The range is expressed in arbitrary units that must be the same as the
8833     * units used by {@link #computeHorizontalScrollExtent()} and
8834     * {@link #computeHorizontalScrollOffset()}.</p>
8835     *
8836     * <p>The default range is the drawing width of this view.</p>
8837     *
8838     * @return the total horizontal range represented by the horizontal
8839     *         scrollbar
8840     *
8841     * @see #computeHorizontalScrollExtent()
8842     * @see #computeHorizontalScrollOffset()
8843     * @see android.widget.ScrollBarDrawable
8844     */
8845    protected int computeHorizontalScrollRange() {
8846        return getWidth();
8847    }
8848
8849    /**
8850     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
8851     * within the horizontal range. This value is used to compute the position
8852     * of the thumb within the scrollbar's track.</p>
8853     *
8854     * <p>The range is expressed in arbitrary units that must be the same as the
8855     * units used by {@link #computeHorizontalScrollRange()} and
8856     * {@link #computeHorizontalScrollExtent()}.</p>
8857     *
8858     * <p>The default offset is the scroll offset of this view.</p>
8859     *
8860     * @return the horizontal offset of the scrollbar's thumb
8861     *
8862     * @see #computeHorizontalScrollRange()
8863     * @see #computeHorizontalScrollExtent()
8864     * @see android.widget.ScrollBarDrawable
8865     */
8866    protected int computeHorizontalScrollOffset() {
8867        return mScrollX;
8868    }
8869
8870    /**
8871     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
8872     * within the horizontal range. This value is used to compute the length
8873     * of the thumb within the scrollbar's track.</p>
8874     *
8875     * <p>The range is expressed in arbitrary units that must be the same as the
8876     * units used by {@link #computeHorizontalScrollRange()} and
8877     * {@link #computeHorizontalScrollOffset()}.</p>
8878     *
8879     * <p>The default extent is the drawing width of this view.</p>
8880     *
8881     * @return the horizontal extent of the scrollbar's thumb
8882     *
8883     * @see #computeHorizontalScrollRange()
8884     * @see #computeHorizontalScrollOffset()
8885     * @see android.widget.ScrollBarDrawable
8886     */
8887    protected int computeHorizontalScrollExtent() {
8888        return getWidth();
8889    }
8890
8891    /**
8892     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
8893     *
8894     * <p>The range is expressed in arbitrary units that must be the same as the
8895     * units used by {@link #computeVerticalScrollExtent()} and
8896     * {@link #computeVerticalScrollOffset()}.</p>
8897     *
8898     * @return the total vertical range represented by the vertical scrollbar
8899     *
8900     * <p>The default range is the drawing height of this view.</p>
8901     *
8902     * @see #computeVerticalScrollExtent()
8903     * @see #computeVerticalScrollOffset()
8904     * @see android.widget.ScrollBarDrawable
8905     */
8906    protected int computeVerticalScrollRange() {
8907        return getHeight();
8908    }
8909
8910    /**
8911     * <p>Compute the vertical offset of the vertical scrollbar's thumb
8912     * within the horizontal range. This value is used to compute the position
8913     * of the thumb within the scrollbar's track.</p>
8914     *
8915     * <p>The range is expressed in arbitrary units that must be the same as the
8916     * units used by {@link #computeVerticalScrollRange()} and
8917     * {@link #computeVerticalScrollExtent()}.</p>
8918     *
8919     * <p>The default offset is the scroll offset of this view.</p>
8920     *
8921     * @return the vertical offset of the scrollbar's thumb
8922     *
8923     * @see #computeVerticalScrollRange()
8924     * @see #computeVerticalScrollExtent()
8925     * @see android.widget.ScrollBarDrawable
8926     */
8927    protected int computeVerticalScrollOffset() {
8928        return mScrollY;
8929    }
8930
8931    /**
8932     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
8933     * within the vertical range. This value is used to compute the length
8934     * of the thumb within the scrollbar's track.</p>
8935     *
8936     * <p>The range is expressed in arbitrary units that must be the same as the
8937     * units used by {@link #computeVerticalScrollRange()} and
8938     * {@link #computeVerticalScrollOffset()}.</p>
8939     *
8940     * <p>The default extent is the drawing height of this view.</p>
8941     *
8942     * @return the vertical extent of the scrollbar's thumb
8943     *
8944     * @see #computeVerticalScrollRange()
8945     * @see #computeVerticalScrollOffset()
8946     * @see android.widget.ScrollBarDrawable
8947     */
8948    protected int computeVerticalScrollExtent() {
8949        return getHeight();
8950    }
8951
8952    /**
8953     * Check if this view can be scrolled horizontally in a certain direction.
8954     *
8955     * @param direction Negative to check scrolling left, positive to check scrolling right.
8956     * @return true if this view can be scrolled in the specified direction, false otherwise.
8957     */
8958    public boolean canScrollHorizontally(int direction) {
8959        final int offset = computeHorizontalScrollOffset();
8960        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
8961        if (range == 0) return false;
8962        if (direction < 0) {
8963            return offset > 0;
8964        } else {
8965            return offset < range - 1;
8966        }
8967    }
8968
8969    /**
8970     * Check if this view can be scrolled vertically in a certain direction.
8971     *
8972     * @param direction Negative to check scrolling up, positive to check scrolling down.
8973     * @return true if this view can be scrolled in the specified direction, false otherwise.
8974     */
8975    public boolean canScrollVertically(int direction) {
8976        final int offset = computeVerticalScrollOffset();
8977        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
8978        if (range == 0) return false;
8979        if (direction < 0) {
8980            return offset > 0;
8981        } else {
8982            return offset < range - 1;
8983        }
8984    }
8985
8986    /**
8987     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
8988     * scrollbars are painted only if they have been awakened first.</p>
8989     *
8990     * @param canvas the canvas on which to draw the scrollbars
8991     *
8992     * @see #awakenScrollBars(int)
8993     */
8994    protected final void onDrawScrollBars(Canvas canvas) {
8995        // scrollbars are drawn only when the animation is running
8996        final ScrollabilityCache cache = mScrollCache;
8997        if (cache != null) {
8998
8999            int state = cache.state;
9000
9001            if (state == ScrollabilityCache.OFF) {
9002                return;
9003            }
9004
9005            boolean invalidate = false;
9006
9007            if (state == ScrollabilityCache.FADING) {
9008                // We're fading -- get our fade interpolation
9009                if (cache.interpolatorValues == null) {
9010                    cache.interpolatorValues = new float[1];
9011                }
9012
9013                float[] values = cache.interpolatorValues;
9014
9015                // Stops the animation if we're done
9016                if (cache.scrollBarInterpolator.timeToValues(values) ==
9017                        Interpolator.Result.FREEZE_END) {
9018                    cache.state = ScrollabilityCache.OFF;
9019                } else {
9020                    cache.scrollBar.setAlpha(Math.round(values[0]));
9021                }
9022
9023                // This will make the scroll bars inval themselves after
9024                // drawing. We only want this when we're fading so that
9025                // we prevent excessive redraws
9026                invalidate = true;
9027            } else {
9028                // We're just on -- but we may have been fading before so
9029                // reset alpha
9030                cache.scrollBar.setAlpha(255);
9031            }
9032
9033
9034            final int viewFlags = mViewFlags;
9035
9036            final boolean drawHorizontalScrollBar =
9037                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9038            final boolean drawVerticalScrollBar =
9039                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9040                && !isVerticalScrollBarHidden();
9041
9042            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9043                final int width = mRight - mLeft;
9044                final int height = mBottom - mTop;
9045
9046                final ScrollBarDrawable scrollBar = cache.scrollBar;
9047
9048                final int scrollX = mScrollX;
9049                final int scrollY = mScrollY;
9050                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9051
9052                int left, top, right, bottom;
9053
9054                if (drawHorizontalScrollBar) {
9055                    int size = scrollBar.getSize(false);
9056                    if (size <= 0) {
9057                        size = cache.scrollBarSize;
9058                    }
9059
9060                    scrollBar.setParameters(computeHorizontalScrollRange(),
9061                                            computeHorizontalScrollOffset(),
9062                                            computeHorizontalScrollExtent(), false);
9063                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9064                            getVerticalScrollbarWidth() : 0;
9065                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9066                    left = scrollX + (mPaddingLeft & inside);
9067                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9068                    bottom = top + size;
9069                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9070                    if (invalidate) {
9071                        invalidate(left, top, right, bottom);
9072                    }
9073                }
9074
9075                if (drawVerticalScrollBar) {
9076                    int size = scrollBar.getSize(true);
9077                    if (size <= 0) {
9078                        size = cache.scrollBarSize;
9079                    }
9080
9081                    scrollBar.setParameters(computeVerticalScrollRange(),
9082                                            computeVerticalScrollOffset(),
9083                                            computeVerticalScrollExtent(), true);
9084                    switch (mVerticalScrollbarPosition) {
9085                        default:
9086                        case SCROLLBAR_POSITION_DEFAULT:
9087                        case SCROLLBAR_POSITION_RIGHT:
9088                            left = scrollX + width - size - (mUserPaddingRight & inside);
9089                            break;
9090                        case SCROLLBAR_POSITION_LEFT:
9091                            left = scrollX + (mUserPaddingLeft & inside);
9092                            break;
9093                    }
9094                    top = scrollY + (mPaddingTop & inside);
9095                    right = left + size;
9096                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9097                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9098                    if (invalidate) {
9099                        invalidate(left, top, right, bottom);
9100                    }
9101                }
9102            }
9103        }
9104    }
9105
9106    /**
9107     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9108     * FastScroller is visible.
9109     * @return whether to temporarily hide the vertical scrollbar
9110     * @hide
9111     */
9112    protected boolean isVerticalScrollBarHidden() {
9113        return false;
9114    }
9115
9116    /**
9117     * <p>Draw the horizontal scrollbar if
9118     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9119     *
9120     * @param canvas the canvas on which to draw the scrollbar
9121     * @param scrollBar the scrollbar's drawable
9122     *
9123     * @see #isHorizontalScrollBarEnabled()
9124     * @see #computeHorizontalScrollRange()
9125     * @see #computeHorizontalScrollExtent()
9126     * @see #computeHorizontalScrollOffset()
9127     * @see android.widget.ScrollBarDrawable
9128     * @hide
9129     */
9130    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9131            int l, int t, int r, int b) {
9132        scrollBar.setBounds(l, t, r, b);
9133        scrollBar.draw(canvas);
9134    }
9135
9136    /**
9137     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9138     * returns true.</p>
9139     *
9140     * @param canvas the canvas on which to draw the scrollbar
9141     * @param scrollBar the scrollbar's drawable
9142     *
9143     * @see #isVerticalScrollBarEnabled()
9144     * @see #computeVerticalScrollRange()
9145     * @see #computeVerticalScrollExtent()
9146     * @see #computeVerticalScrollOffset()
9147     * @see android.widget.ScrollBarDrawable
9148     * @hide
9149     */
9150    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9151            int l, int t, int r, int b) {
9152        scrollBar.setBounds(l, t, r, b);
9153        scrollBar.draw(canvas);
9154    }
9155
9156    /**
9157     * Implement this to do your drawing.
9158     *
9159     * @param canvas the canvas on which the background will be drawn
9160     */
9161    protected void onDraw(Canvas canvas) {
9162    }
9163
9164    /*
9165     * Caller is responsible for calling requestLayout if necessary.
9166     * (This allows addViewInLayout to not request a new layout.)
9167     */
9168    void assignParent(ViewParent parent) {
9169        if (mParent == null) {
9170            mParent = parent;
9171        } else if (parent == null) {
9172            mParent = null;
9173        } else {
9174            throw new RuntimeException("view " + this + " being added, but"
9175                    + " it already has a parent");
9176        }
9177    }
9178
9179    /**
9180     * This is called when the view is attached to a window.  At this point it
9181     * has a Surface and will start drawing.  Note that this function is
9182     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9183     * however it may be called any time before the first onDraw -- including
9184     * before or after {@link #onMeasure(int, int)}.
9185     *
9186     * @see #onDetachedFromWindow()
9187     */
9188    protected void onAttachedToWindow() {
9189        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9190            mParent.requestTransparentRegion(this);
9191        }
9192        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9193            initialAwakenScrollBars();
9194            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9195        }
9196        jumpDrawablesToCurrentState();
9197        // Order is important here: LayoutDirection MUST be resolved before Padding
9198        // and TextDirection
9199        resolveLayoutDirectionIfNeeded();
9200        resolvePadding();
9201        resolveTextDirection();
9202        if (isFocused()) {
9203            InputMethodManager imm = InputMethodManager.peekInstance();
9204            imm.focusIn(this);
9205        }
9206    }
9207
9208    /**
9209     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9210     * that the parent directionality can and will be resolved before its children.
9211     */
9212    private void resolveLayoutDirectionIfNeeded() {
9213        // Do not resolve if it is not needed
9214        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9215
9216        // Clear any previous layout direction resolution
9217        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9218
9219        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9220        // TextDirectionHeuristic
9221        resetResolvedTextDirection();
9222
9223        // Set resolved depending on layout direction
9224        switch (getLayoutDirection()) {
9225            case LAYOUT_DIRECTION_INHERIT:
9226                // We cannot do the resolution if there is no parent
9227                if (mParent == null) return;
9228
9229                // If this is root view, no need to look at parent's layout dir.
9230                if (mParent instanceof ViewGroup) {
9231                    ViewGroup viewGroup = ((ViewGroup) mParent);
9232
9233                    // Check if the parent view group can resolve
9234                    if (! viewGroup.canResolveLayoutDirection()) {
9235                        return;
9236                    }
9237                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9238                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9239                    }
9240                }
9241                break;
9242            case LAYOUT_DIRECTION_RTL:
9243                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9244                break;
9245            case LAYOUT_DIRECTION_LOCALE:
9246                if(isLayoutDirectionRtl(Locale.getDefault())) {
9247                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9248                }
9249                break;
9250            default:
9251                // Nothing to do, LTR by default
9252        }
9253
9254        // Set to resolved
9255        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9256    }
9257
9258    /**
9259     * @hide
9260     */
9261    protected void resolvePadding() {
9262        // If the user specified the absolute padding (either with android:padding or
9263        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9264        // use the default padding or the padding from the background drawable
9265        // (stored at this point in mPadding*)
9266        switch (getResolvedLayoutDirection()) {
9267            case LAYOUT_DIRECTION_RTL:
9268                // Start user padding override Right user padding. Otherwise, if Right user
9269                // padding is not defined, use the default Right padding. If Right user padding
9270                // is defined, just use it.
9271                if (mUserPaddingStart >= 0) {
9272                    mUserPaddingRight = mUserPaddingStart;
9273                } else if (mUserPaddingRight < 0) {
9274                    mUserPaddingRight = mPaddingRight;
9275                }
9276                if (mUserPaddingEnd >= 0) {
9277                    mUserPaddingLeft = mUserPaddingEnd;
9278                } else if (mUserPaddingLeft < 0) {
9279                    mUserPaddingLeft = mPaddingLeft;
9280                }
9281                break;
9282            case LAYOUT_DIRECTION_LTR:
9283            default:
9284                // Start user padding override Left user padding. Otherwise, if Left user
9285                // padding is not defined, use the default left padding. If Left user padding
9286                // is defined, just use it.
9287                if (mUserPaddingStart >= 0) {
9288                    mUserPaddingLeft = mUserPaddingStart;
9289                } else if (mUserPaddingLeft < 0) {
9290                    mUserPaddingLeft = mPaddingLeft;
9291                }
9292                if (mUserPaddingEnd >= 0) {
9293                    mUserPaddingRight = mUserPaddingEnd;
9294                } else if (mUserPaddingRight < 0) {
9295                    mUserPaddingRight = mPaddingRight;
9296                }
9297        }
9298
9299        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9300
9301        recomputePadding();
9302    }
9303
9304    /**
9305     * Return true if layout direction resolution can be done
9306     *
9307     * @hide
9308     */
9309    protected boolean canResolveLayoutDirection() {
9310        switch (getLayoutDirection()) {
9311            case LAYOUT_DIRECTION_INHERIT:
9312                return (mParent != null);
9313            default:
9314                return true;
9315        }
9316    }
9317
9318    /**
9319     * Reset the resolved layout direction.
9320     *
9321     * Subclasses need to override this method to clear cached information that depends on the
9322     * resolved layout direction, or to inform child views that inherit their layout direction.
9323     * Overrides must also call the superclass implementation at the start of their implementation.
9324     *
9325     * @hide
9326     */
9327    protected void resetResolvedLayoutDirection() {
9328        // Reset the current View resolution
9329        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9330    }
9331
9332    /**
9333     * Check if a Locale is corresponding to a RTL script.
9334     *
9335     * @param locale Locale to check
9336     * @return true if a Locale is corresponding to a RTL script.
9337     *
9338     * @hide
9339     */
9340    protected static boolean isLayoutDirectionRtl(Locale locale) {
9341        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9342                LocaleUtil.getLayoutDirectionFromLocale(locale));
9343    }
9344
9345    /**
9346     * This is called when the view is detached from a window.  At this point it
9347     * no longer has a surface for drawing.
9348     *
9349     * @see #onAttachedToWindow()
9350     */
9351    protected void onDetachedFromWindow() {
9352        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9353
9354        removeUnsetPressCallback();
9355        removeLongPressCallback();
9356        removePerformClickCallback();
9357        removeSendViewScrolledAccessibilityEventCallback();
9358
9359        destroyDrawingCache();
9360
9361        destroyLayer();
9362
9363        if (mDisplayList != null) {
9364            mDisplayList.invalidate();
9365        }
9366
9367        if (mAttachInfo != null) {
9368            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9369        }
9370
9371        mCurrentAnimation = null;
9372
9373        resetResolvedLayoutDirection();
9374        resetResolvedTextDirection();
9375    }
9376
9377    /**
9378     * @return The number of times this view has been attached to a window
9379     */
9380    protected int getWindowAttachCount() {
9381        return mWindowAttachCount;
9382    }
9383
9384    /**
9385     * Retrieve a unique token identifying the window this view is attached to.
9386     * @return Return the window's token for use in
9387     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9388     */
9389    public IBinder getWindowToken() {
9390        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9391    }
9392
9393    /**
9394     * Retrieve a unique token identifying the top-level "real" window of
9395     * the window that this view is attached to.  That is, this is like
9396     * {@link #getWindowToken}, except if the window this view in is a panel
9397     * window (attached to another containing window), then the token of
9398     * the containing window is returned instead.
9399     *
9400     * @return Returns the associated window token, either
9401     * {@link #getWindowToken()} or the containing window's token.
9402     */
9403    public IBinder getApplicationWindowToken() {
9404        AttachInfo ai = mAttachInfo;
9405        if (ai != null) {
9406            IBinder appWindowToken = ai.mPanelParentWindowToken;
9407            if (appWindowToken == null) {
9408                appWindowToken = ai.mWindowToken;
9409            }
9410            return appWindowToken;
9411        }
9412        return null;
9413    }
9414
9415    /**
9416     * Retrieve private session object this view hierarchy is using to
9417     * communicate with the window manager.
9418     * @return the session object to communicate with the window manager
9419     */
9420    /*package*/ IWindowSession getWindowSession() {
9421        return mAttachInfo != null ? mAttachInfo.mSession : null;
9422    }
9423
9424    /**
9425     * @param info the {@link android.view.View.AttachInfo} to associated with
9426     *        this view
9427     */
9428    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9429        //System.out.println("Attached! " + this);
9430        mAttachInfo = info;
9431        mWindowAttachCount++;
9432        // We will need to evaluate the drawable state at least once.
9433        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9434        if (mFloatingTreeObserver != null) {
9435            info.mTreeObserver.merge(mFloatingTreeObserver);
9436            mFloatingTreeObserver = null;
9437        }
9438        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9439            mAttachInfo.mScrollContainers.add(this);
9440            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9441        }
9442        performCollectViewAttributes(visibility);
9443        onAttachedToWindow();
9444
9445        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9446                mOnAttachStateChangeListeners;
9447        if (listeners != null && listeners.size() > 0) {
9448            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9449            // perform the dispatching. The iterator is a safe guard against listeners that
9450            // could mutate the list by calling the various add/remove methods. This prevents
9451            // the array from being modified while we iterate it.
9452            for (OnAttachStateChangeListener listener : listeners) {
9453                listener.onViewAttachedToWindow(this);
9454            }
9455        }
9456
9457        int vis = info.mWindowVisibility;
9458        if (vis != GONE) {
9459            onWindowVisibilityChanged(vis);
9460        }
9461        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9462            // If nobody has evaluated the drawable state yet, then do it now.
9463            refreshDrawableState();
9464        }
9465    }
9466
9467    void dispatchDetachedFromWindow() {
9468        AttachInfo info = mAttachInfo;
9469        if (info != null) {
9470            int vis = info.mWindowVisibility;
9471            if (vis != GONE) {
9472                onWindowVisibilityChanged(GONE);
9473            }
9474        }
9475
9476        onDetachedFromWindow();
9477
9478        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9479                mOnAttachStateChangeListeners;
9480        if (listeners != null && listeners.size() > 0) {
9481            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9482            // perform the dispatching. The iterator is a safe guard against listeners that
9483            // could mutate the list by calling the various add/remove methods. This prevents
9484            // the array from being modified while we iterate it.
9485            for (OnAttachStateChangeListener listener : listeners) {
9486                listener.onViewDetachedFromWindow(this);
9487            }
9488        }
9489
9490        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9491            mAttachInfo.mScrollContainers.remove(this);
9492            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9493        }
9494
9495        mAttachInfo = null;
9496    }
9497
9498    /**
9499     * Store this view hierarchy's frozen state into the given container.
9500     *
9501     * @param container The SparseArray in which to save the view's state.
9502     *
9503     * @see #restoreHierarchyState(android.util.SparseArray)
9504     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9505     * @see #onSaveInstanceState()
9506     */
9507    public void saveHierarchyState(SparseArray<Parcelable> container) {
9508        dispatchSaveInstanceState(container);
9509    }
9510
9511    /**
9512     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9513     * this view and its children. May be overridden to modify how freezing happens to a
9514     * view's children; for example, some views may want to not store state for their children.
9515     *
9516     * @param container The SparseArray in which to save the view's state.
9517     *
9518     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9519     * @see #saveHierarchyState(android.util.SparseArray)
9520     * @see #onSaveInstanceState()
9521     */
9522    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9523        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9524            mPrivateFlags &= ~SAVE_STATE_CALLED;
9525            Parcelable state = onSaveInstanceState();
9526            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9527                throw new IllegalStateException(
9528                        "Derived class did not call super.onSaveInstanceState()");
9529            }
9530            if (state != null) {
9531                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9532                // + ": " + state);
9533                container.put(mID, state);
9534            }
9535        }
9536    }
9537
9538    /**
9539     * Hook allowing a view to generate a representation of its internal state
9540     * that can later be used to create a new instance with that same state.
9541     * This state should only contain information that is not persistent or can
9542     * not be reconstructed later. For example, you will never store your
9543     * current position on screen because that will be computed again when a
9544     * new instance of the view is placed in its view hierarchy.
9545     * <p>
9546     * Some examples of things you may store here: the current cursor position
9547     * in a text view (but usually not the text itself since that is stored in a
9548     * content provider or other persistent storage), the currently selected
9549     * item in a list view.
9550     *
9551     * @return Returns a Parcelable object containing the view's current dynamic
9552     *         state, or null if there is nothing interesting to save. The
9553     *         default implementation returns null.
9554     * @see #onRestoreInstanceState(android.os.Parcelable)
9555     * @see #saveHierarchyState(android.util.SparseArray)
9556     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9557     * @see #setSaveEnabled(boolean)
9558     */
9559    protected Parcelable onSaveInstanceState() {
9560        mPrivateFlags |= SAVE_STATE_CALLED;
9561        return BaseSavedState.EMPTY_STATE;
9562    }
9563
9564    /**
9565     * Restore this view hierarchy's frozen state from the given container.
9566     *
9567     * @param container The SparseArray which holds previously frozen states.
9568     *
9569     * @see #saveHierarchyState(android.util.SparseArray)
9570     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9571     * @see #onRestoreInstanceState(android.os.Parcelable)
9572     */
9573    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9574        dispatchRestoreInstanceState(container);
9575    }
9576
9577    /**
9578     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9579     * state for this view and its children. May be overridden to modify how restoring
9580     * happens to a view's children; for example, some views may want to not store state
9581     * for their children.
9582     *
9583     * @param container The SparseArray which holds previously saved state.
9584     *
9585     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9586     * @see #restoreHierarchyState(android.util.SparseArray)
9587     * @see #onRestoreInstanceState(android.os.Parcelable)
9588     */
9589    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9590        if (mID != NO_ID) {
9591            Parcelable state = container.get(mID);
9592            if (state != null) {
9593                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9594                // + ": " + state);
9595                mPrivateFlags &= ~SAVE_STATE_CALLED;
9596                onRestoreInstanceState(state);
9597                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9598                    throw new IllegalStateException(
9599                            "Derived class did not call super.onRestoreInstanceState()");
9600                }
9601            }
9602        }
9603    }
9604
9605    /**
9606     * Hook allowing a view to re-apply a representation of its internal state that had previously
9607     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9608     * null state.
9609     *
9610     * @param state The frozen state that had previously been returned by
9611     *        {@link #onSaveInstanceState}.
9612     *
9613     * @see #onSaveInstanceState()
9614     * @see #restoreHierarchyState(android.util.SparseArray)
9615     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9616     */
9617    protected void onRestoreInstanceState(Parcelable state) {
9618        mPrivateFlags |= SAVE_STATE_CALLED;
9619        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9620            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9621                    + "received " + state.getClass().toString() + " instead. This usually happens "
9622                    + "when two views of different type have the same id in the same hierarchy. "
9623                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9624                    + "other views do not use the same id.");
9625        }
9626    }
9627
9628    /**
9629     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9630     *
9631     * @return the drawing start time in milliseconds
9632     */
9633    public long getDrawingTime() {
9634        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9635    }
9636
9637    /**
9638     * <p>Enables or disables the duplication of the parent's state into this view. When
9639     * duplication is enabled, this view gets its drawable state from its parent rather
9640     * than from its own internal properties.</p>
9641     *
9642     * <p>Note: in the current implementation, setting this property to true after the
9643     * view was added to a ViewGroup might have no effect at all. This property should
9644     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9645     *
9646     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9647     * property is enabled, an exception will be thrown.</p>
9648     *
9649     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9650     * parent, these states should not be affected by this method.</p>
9651     *
9652     * @param enabled True to enable duplication of the parent's drawable state, false
9653     *                to disable it.
9654     *
9655     * @see #getDrawableState()
9656     * @see #isDuplicateParentStateEnabled()
9657     */
9658    public void setDuplicateParentStateEnabled(boolean enabled) {
9659        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9660    }
9661
9662    /**
9663     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9664     *
9665     * @return True if this view's drawable state is duplicated from the parent,
9666     *         false otherwise
9667     *
9668     * @see #getDrawableState()
9669     * @see #setDuplicateParentStateEnabled(boolean)
9670     */
9671    public boolean isDuplicateParentStateEnabled() {
9672        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9673    }
9674
9675    /**
9676     * <p>Specifies the type of layer backing this view. The layer can be
9677     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9678     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9679     *
9680     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9681     * instance that controls how the layer is composed on screen. The following
9682     * properties of the paint are taken into account when composing the layer:</p>
9683     * <ul>
9684     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9685     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9686     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9687     * </ul>
9688     *
9689     * <p>If this view has an alpha value set to < 1.0 by calling
9690     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9691     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9692     * equivalent to setting a hardware layer on this view and providing a paint with
9693     * the desired alpha value.<p>
9694     *
9695     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9696     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9697     * for more information on when and how to use layers.</p>
9698     *
9699     * @param layerType The ype of layer to use with this view, must be one of
9700     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9701     *        {@link #LAYER_TYPE_HARDWARE}
9702     * @param paint The paint used to compose the layer. This argument is optional
9703     *        and can be null. It is ignored when the layer type is
9704     *        {@link #LAYER_TYPE_NONE}
9705     *
9706     * @see #getLayerType()
9707     * @see #LAYER_TYPE_NONE
9708     * @see #LAYER_TYPE_SOFTWARE
9709     * @see #LAYER_TYPE_HARDWARE
9710     * @see #setAlpha(float)
9711     *
9712     * @attr ref android.R.styleable#View_layerType
9713     */
9714    public void setLayerType(int layerType, Paint paint) {
9715        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9716            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9717                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9718        }
9719
9720        if (layerType == mLayerType) {
9721            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9722                mLayerPaint = paint == null ? new Paint() : paint;
9723                invalidateParentCaches();
9724                invalidate(true);
9725            }
9726            return;
9727        }
9728
9729        // Destroy any previous software drawing cache if needed
9730        switch (mLayerType) {
9731            case LAYER_TYPE_HARDWARE:
9732                destroyLayer();
9733                // fall through - unaccelerated views may use software layer mechanism instead
9734            case LAYER_TYPE_SOFTWARE:
9735                destroyDrawingCache();
9736                break;
9737            default:
9738                break;
9739        }
9740
9741        mLayerType = layerType;
9742        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
9743        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
9744        mLocalDirtyRect = layerDisabled ? null : new Rect();
9745
9746        invalidateParentCaches();
9747        invalidate(true);
9748    }
9749
9750    /**
9751     * Indicates what type of layer is currently associated with this view. By default
9752     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
9753     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
9754     * for more information on the different types of layers.
9755     *
9756     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9757     *         {@link #LAYER_TYPE_HARDWARE}
9758     *
9759     * @see #setLayerType(int, android.graphics.Paint)
9760     * @see #buildLayer()
9761     * @see #LAYER_TYPE_NONE
9762     * @see #LAYER_TYPE_SOFTWARE
9763     * @see #LAYER_TYPE_HARDWARE
9764     */
9765    public int getLayerType() {
9766        return mLayerType;
9767    }
9768
9769    /**
9770     * Forces this view's layer to be created and this view to be rendered
9771     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
9772     * invoking this method will have no effect.
9773     *
9774     * This method can for instance be used to render a view into its layer before
9775     * starting an animation. If this view is complex, rendering into the layer
9776     * before starting the animation will avoid skipping frames.
9777     *
9778     * @throws IllegalStateException If this view is not attached to a window
9779     *
9780     * @see #setLayerType(int, android.graphics.Paint)
9781     */
9782    public void buildLayer() {
9783        if (mLayerType == LAYER_TYPE_NONE) return;
9784
9785        if (mAttachInfo == null) {
9786            throw new IllegalStateException("This view must be attached to a window first");
9787        }
9788
9789        switch (mLayerType) {
9790            case LAYER_TYPE_HARDWARE:
9791                getHardwareLayer();
9792                break;
9793            case LAYER_TYPE_SOFTWARE:
9794                buildDrawingCache(true);
9795                break;
9796        }
9797    }
9798
9799    /**
9800     * <p>Returns a hardware layer that can be used to draw this view again
9801     * without executing its draw method.</p>
9802     *
9803     * @return A HardwareLayer ready to render, or null if an error occurred.
9804     */
9805    HardwareLayer getHardwareLayer() {
9806        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
9807                !mAttachInfo.mHardwareRenderer.isEnabled()) {
9808            return null;
9809        }
9810
9811        final int width = mRight - mLeft;
9812        final int height = mBottom - mTop;
9813
9814        if (width == 0 || height == 0) {
9815            return null;
9816        }
9817
9818        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
9819            if (mHardwareLayer == null) {
9820                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
9821                        width, height, isOpaque());
9822                mLocalDirtyRect.setEmpty();
9823            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
9824                mHardwareLayer.resize(width, height);
9825                mLocalDirtyRect.setEmpty();
9826            }
9827
9828            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
9829            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
9830            mAttachInfo.mHardwareCanvas = canvas;
9831            try {
9832                canvas.setViewport(width, height);
9833                canvas.onPreDraw(mLocalDirtyRect);
9834                mLocalDirtyRect.setEmpty();
9835
9836                final int restoreCount = canvas.save();
9837
9838                computeScroll();
9839                canvas.translate(-mScrollX, -mScrollY);
9840
9841                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9842
9843                // Fast path for layouts with no backgrounds
9844                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9845                    mPrivateFlags &= ~DIRTY_MASK;
9846                    dispatchDraw(canvas);
9847                } else {
9848                    draw(canvas);
9849                }
9850
9851                canvas.restoreToCount(restoreCount);
9852            } finally {
9853                canvas.onPostDraw();
9854                mHardwareLayer.end(currentCanvas);
9855                mAttachInfo.mHardwareCanvas = currentCanvas;
9856            }
9857        }
9858
9859        return mHardwareLayer;
9860    }
9861
9862    boolean destroyLayer() {
9863        if (mHardwareLayer != null) {
9864            mHardwareLayer.destroy();
9865            mHardwareLayer = null;
9866            return true;
9867        }
9868        return false;
9869    }
9870
9871    /**
9872     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
9873     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
9874     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
9875     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
9876     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
9877     * null.</p>
9878     *
9879     * <p>Enabling the drawing cache is similar to
9880     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
9881     * acceleration is turned off. When hardware acceleration is turned on, enabling the
9882     * drawing cache has no effect on rendering because the system uses a different mechanism
9883     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
9884     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
9885     * for information on how to enable software and hardware layers.</p>
9886     *
9887     * <p>This API can be used to manually generate
9888     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
9889     * {@link #getDrawingCache()}.</p>
9890     *
9891     * @param enabled true to enable the drawing cache, false otherwise
9892     *
9893     * @see #isDrawingCacheEnabled()
9894     * @see #getDrawingCache()
9895     * @see #buildDrawingCache()
9896     * @see #setLayerType(int, android.graphics.Paint)
9897     */
9898    public void setDrawingCacheEnabled(boolean enabled) {
9899        mCachingFailed = false;
9900        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
9901    }
9902
9903    /**
9904     * <p>Indicates whether the drawing cache is enabled for this view.</p>
9905     *
9906     * @return true if the drawing cache is enabled
9907     *
9908     * @see #setDrawingCacheEnabled(boolean)
9909     * @see #getDrawingCache()
9910     */
9911    @ViewDebug.ExportedProperty(category = "drawing")
9912    public boolean isDrawingCacheEnabled() {
9913        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
9914    }
9915
9916    /**
9917     * Debugging utility which recursively outputs the dirty state of a view and its
9918     * descendants.
9919     *
9920     * @hide
9921     */
9922    @SuppressWarnings({"UnusedDeclaration"})
9923    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
9924        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
9925                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
9926                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
9927                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
9928        if (clear) {
9929            mPrivateFlags &= clearMask;
9930        }
9931        if (this instanceof ViewGroup) {
9932            ViewGroup parent = (ViewGroup) this;
9933            final int count = parent.getChildCount();
9934            for (int i = 0; i < count; i++) {
9935                final View child = parent.getChildAt(i);
9936                child.outputDirtyFlags(indent + "  ", clear, clearMask);
9937            }
9938        }
9939    }
9940
9941    /**
9942     * This method is used by ViewGroup to cause its children to restore or recreate their
9943     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
9944     * to recreate its own display list, which would happen if it went through the normal
9945     * draw/dispatchDraw mechanisms.
9946     *
9947     * @hide
9948     */
9949    protected void dispatchGetDisplayList() {}
9950
9951    /**
9952     * A view that is not attached or hardware accelerated cannot create a display list.
9953     * This method checks these conditions and returns the appropriate result.
9954     *
9955     * @return true if view has the ability to create a display list, false otherwise.
9956     *
9957     * @hide
9958     */
9959    public boolean canHaveDisplayList() {
9960        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
9961    }
9962
9963    /**
9964     * <p>Returns a display list that can be used to draw this view again
9965     * without executing its draw method.</p>
9966     *
9967     * @return A DisplayList ready to replay, or null if caching is not enabled.
9968     *
9969     * @hide
9970     */
9971    public DisplayList getDisplayList() {
9972        if (!canHaveDisplayList()) {
9973            return null;
9974        }
9975
9976        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
9977                mDisplayList == null || !mDisplayList.isValid() ||
9978                mRecreateDisplayList)) {
9979            // Don't need to recreate the display list, just need to tell our
9980            // children to restore/recreate theirs
9981            if (mDisplayList != null && mDisplayList.isValid() &&
9982                    !mRecreateDisplayList) {
9983                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9984                mPrivateFlags &= ~DIRTY_MASK;
9985                dispatchGetDisplayList();
9986
9987                return mDisplayList;
9988            }
9989
9990            // If we got here, we're recreating it. Mark it as such to ensure that
9991            // we copy in child display lists into ours in drawChild()
9992            mRecreateDisplayList = true;
9993            if (mDisplayList == null) {
9994                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
9995                // If we're creating a new display list, make sure our parent gets invalidated
9996                // since they will need to recreate their display list to account for this
9997                // new child display list.
9998                invalidateParentCaches();
9999            }
10000
10001            final HardwareCanvas canvas = mDisplayList.start();
10002            try {
10003                int width = mRight - mLeft;
10004                int height = mBottom - mTop;
10005
10006                canvas.setViewport(width, height);
10007                // The dirty rect should always be null for a display list
10008                canvas.onPreDraw(null);
10009
10010                computeScroll();
10011                canvas.translate(-mScrollX, -mScrollY);
10012                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10013                mPrivateFlags &= ~DIRTY_MASK;
10014
10015                // Fast path for layouts with no backgrounds
10016                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10017                    dispatchDraw(canvas);
10018                } else {
10019                    draw(canvas);
10020                }
10021            } finally {
10022                canvas.onPostDraw();
10023
10024                mDisplayList.end();
10025            }
10026        } else {
10027            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10028            mPrivateFlags &= ~DIRTY_MASK;
10029        }
10030
10031        return mDisplayList;
10032    }
10033
10034    /**
10035     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10036     *
10037     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10038     *
10039     * @see #getDrawingCache(boolean)
10040     */
10041    public Bitmap getDrawingCache() {
10042        return getDrawingCache(false);
10043    }
10044
10045    /**
10046     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10047     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10048     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10049     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10050     * request the drawing cache by calling this method and draw it on screen if the
10051     * returned bitmap is not null.</p>
10052     *
10053     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10054     * this method will create a bitmap of the same size as this view. Because this bitmap
10055     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10056     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10057     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10058     * size than the view. This implies that your application must be able to handle this
10059     * size.</p>
10060     *
10061     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10062     *        the current density of the screen when the application is in compatibility
10063     *        mode.
10064     *
10065     * @return A bitmap representing this view or null if cache is disabled.
10066     *
10067     * @see #setDrawingCacheEnabled(boolean)
10068     * @see #isDrawingCacheEnabled()
10069     * @see #buildDrawingCache(boolean)
10070     * @see #destroyDrawingCache()
10071     */
10072    public Bitmap getDrawingCache(boolean autoScale) {
10073        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10074            return null;
10075        }
10076        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10077            buildDrawingCache(autoScale);
10078        }
10079        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10080    }
10081
10082    /**
10083     * <p>Frees the resources used by the drawing cache. If you call
10084     * {@link #buildDrawingCache()} manually without calling
10085     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10086     * should cleanup the cache with this method afterwards.</p>
10087     *
10088     * @see #setDrawingCacheEnabled(boolean)
10089     * @see #buildDrawingCache()
10090     * @see #getDrawingCache()
10091     */
10092    public void destroyDrawingCache() {
10093        if (mDrawingCache != null) {
10094            mDrawingCache.recycle();
10095            mDrawingCache = null;
10096        }
10097        if (mUnscaledDrawingCache != null) {
10098            mUnscaledDrawingCache.recycle();
10099            mUnscaledDrawingCache = null;
10100        }
10101    }
10102
10103    /**
10104     * Setting a solid background color for the drawing cache's bitmaps will improve
10105     * perfromance and memory usage. Note, though that this should only be used if this
10106     * view will always be drawn on top of a solid color.
10107     *
10108     * @param color The background color to use for the drawing cache's bitmap
10109     *
10110     * @see #setDrawingCacheEnabled(boolean)
10111     * @see #buildDrawingCache()
10112     * @see #getDrawingCache()
10113     */
10114    public void setDrawingCacheBackgroundColor(int color) {
10115        if (color != mDrawingCacheBackgroundColor) {
10116            mDrawingCacheBackgroundColor = color;
10117            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10118        }
10119    }
10120
10121    /**
10122     * @see #setDrawingCacheBackgroundColor(int)
10123     *
10124     * @return The background color to used for the drawing cache's bitmap
10125     */
10126    public int getDrawingCacheBackgroundColor() {
10127        return mDrawingCacheBackgroundColor;
10128    }
10129
10130    /**
10131     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10132     *
10133     * @see #buildDrawingCache(boolean)
10134     */
10135    public void buildDrawingCache() {
10136        buildDrawingCache(false);
10137    }
10138
10139    /**
10140     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10141     *
10142     * <p>If you call {@link #buildDrawingCache()} manually without calling
10143     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10144     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10145     *
10146     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10147     * this method will create a bitmap of the same size as this view. Because this bitmap
10148     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10149     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10150     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10151     * size than the view. This implies that your application must be able to handle this
10152     * size.</p>
10153     *
10154     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10155     * you do not need the drawing cache bitmap, calling this method will increase memory
10156     * usage and cause the view to be rendered in software once, thus negatively impacting
10157     * performance.</p>
10158     *
10159     * @see #getDrawingCache()
10160     * @see #destroyDrawingCache()
10161     */
10162    public void buildDrawingCache(boolean autoScale) {
10163        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10164                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10165            mCachingFailed = false;
10166
10167            if (ViewDebug.TRACE_HIERARCHY) {
10168                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10169            }
10170
10171            int width = mRight - mLeft;
10172            int height = mBottom - mTop;
10173
10174            final AttachInfo attachInfo = mAttachInfo;
10175            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10176
10177            if (autoScale && scalingRequired) {
10178                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10179                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10180            }
10181
10182            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10183            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10184            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10185
10186            if (width <= 0 || height <= 0 ||
10187                     // Projected bitmap size in bytes
10188                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10189                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10190                destroyDrawingCache();
10191                mCachingFailed = true;
10192                return;
10193            }
10194
10195            boolean clear = true;
10196            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10197
10198            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10199                Bitmap.Config quality;
10200                if (!opaque) {
10201                    // Never pick ARGB_4444 because it looks awful
10202                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10203                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10204                        case DRAWING_CACHE_QUALITY_AUTO:
10205                            quality = Bitmap.Config.ARGB_8888;
10206                            break;
10207                        case DRAWING_CACHE_QUALITY_LOW:
10208                            quality = Bitmap.Config.ARGB_8888;
10209                            break;
10210                        case DRAWING_CACHE_QUALITY_HIGH:
10211                            quality = Bitmap.Config.ARGB_8888;
10212                            break;
10213                        default:
10214                            quality = Bitmap.Config.ARGB_8888;
10215                            break;
10216                    }
10217                } else {
10218                    // Optimization for translucent windows
10219                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10220                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10221                }
10222
10223                // Try to cleanup memory
10224                if (bitmap != null) bitmap.recycle();
10225
10226                try {
10227                    bitmap = Bitmap.createBitmap(width, height, quality);
10228                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10229                    if (autoScale) {
10230                        mDrawingCache = bitmap;
10231                    } else {
10232                        mUnscaledDrawingCache = bitmap;
10233                    }
10234                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10235                } catch (OutOfMemoryError e) {
10236                    // If there is not enough memory to create the bitmap cache, just
10237                    // ignore the issue as bitmap caches are not required to draw the
10238                    // view hierarchy
10239                    if (autoScale) {
10240                        mDrawingCache = null;
10241                    } else {
10242                        mUnscaledDrawingCache = null;
10243                    }
10244                    mCachingFailed = true;
10245                    return;
10246                }
10247
10248                clear = drawingCacheBackgroundColor != 0;
10249            }
10250
10251            Canvas canvas;
10252            if (attachInfo != null) {
10253                canvas = attachInfo.mCanvas;
10254                if (canvas == null) {
10255                    canvas = new Canvas();
10256                }
10257                canvas.setBitmap(bitmap);
10258                // Temporarily clobber the cached Canvas in case one of our children
10259                // is also using a drawing cache. Without this, the children would
10260                // steal the canvas by attaching their own bitmap to it and bad, bad
10261                // thing would happen (invisible views, corrupted drawings, etc.)
10262                attachInfo.mCanvas = null;
10263            } else {
10264                // This case should hopefully never or seldom happen
10265                canvas = new Canvas(bitmap);
10266            }
10267
10268            if (clear) {
10269                bitmap.eraseColor(drawingCacheBackgroundColor);
10270            }
10271
10272            computeScroll();
10273            final int restoreCount = canvas.save();
10274
10275            if (autoScale && scalingRequired) {
10276                final float scale = attachInfo.mApplicationScale;
10277                canvas.scale(scale, scale);
10278            }
10279
10280            canvas.translate(-mScrollX, -mScrollY);
10281
10282            mPrivateFlags |= DRAWN;
10283            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10284                    mLayerType != LAYER_TYPE_NONE) {
10285                mPrivateFlags |= DRAWING_CACHE_VALID;
10286            }
10287
10288            // Fast path for layouts with no backgrounds
10289            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10290                if (ViewDebug.TRACE_HIERARCHY) {
10291                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10292                }
10293                mPrivateFlags &= ~DIRTY_MASK;
10294                dispatchDraw(canvas);
10295            } else {
10296                draw(canvas);
10297            }
10298
10299            canvas.restoreToCount(restoreCount);
10300            canvas.setBitmap(null);
10301
10302            if (attachInfo != null) {
10303                // Restore the cached Canvas for our siblings
10304                attachInfo.mCanvas = canvas;
10305            }
10306        }
10307    }
10308
10309    /**
10310     * Create a snapshot of the view into a bitmap.  We should probably make
10311     * some form of this public, but should think about the API.
10312     */
10313    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10314        int width = mRight - mLeft;
10315        int height = mBottom - mTop;
10316
10317        final AttachInfo attachInfo = mAttachInfo;
10318        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10319        width = (int) ((width * scale) + 0.5f);
10320        height = (int) ((height * scale) + 0.5f);
10321
10322        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10323        if (bitmap == null) {
10324            throw new OutOfMemoryError();
10325        }
10326
10327        Resources resources = getResources();
10328        if (resources != null) {
10329            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10330        }
10331
10332        Canvas canvas;
10333        if (attachInfo != null) {
10334            canvas = attachInfo.mCanvas;
10335            if (canvas == null) {
10336                canvas = new Canvas();
10337            }
10338            canvas.setBitmap(bitmap);
10339            // Temporarily clobber the cached Canvas in case one of our children
10340            // is also using a drawing cache. Without this, the children would
10341            // steal the canvas by attaching their own bitmap to it and bad, bad
10342            // things would happen (invisible views, corrupted drawings, etc.)
10343            attachInfo.mCanvas = null;
10344        } else {
10345            // This case should hopefully never or seldom happen
10346            canvas = new Canvas(bitmap);
10347        }
10348
10349        if ((backgroundColor & 0xff000000) != 0) {
10350            bitmap.eraseColor(backgroundColor);
10351        }
10352
10353        computeScroll();
10354        final int restoreCount = canvas.save();
10355        canvas.scale(scale, scale);
10356        canvas.translate(-mScrollX, -mScrollY);
10357
10358        // Temporarily remove the dirty mask
10359        int flags = mPrivateFlags;
10360        mPrivateFlags &= ~DIRTY_MASK;
10361
10362        // Fast path for layouts with no backgrounds
10363        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10364            dispatchDraw(canvas);
10365        } else {
10366            draw(canvas);
10367        }
10368
10369        mPrivateFlags = flags;
10370
10371        canvas.restoreToCount(restoreCount);
10372        canvas.setBitmap(null);
10373
10374        if (attachInfo != null) {
10375            // Restore the cached Canvas for our siblings
10376            attachInfo.mCanvas = canvas;
10377        }
10378
10379        return bitmap;
10380    }
10381
10382    /**
10383     * Indicates whether this View is currently in edit mode. A View is usually
10384     * in edit mode when displayed within a developer tool. For instance, if
10385     * this View is being drawn by a visual user interface builder, this method
10386     * should return true.
10387     *
10388     * Subclasses should check the return value of this method to provide
10389     * different behaviors if their normal behavior might interfere with the
10390     * host environment. For instance: the class spawns a thread in its
10391     * constructor, the drawing code relies on device-specific features, etc.
10392     *
10393     * This method is usually checked in the drawing code of custom widgets.
10394     *
10395     * @return True if this View is in edit mode, false otherwise.
10396     */
10397    public boolean isInEditMode() {
10398        return false;
10399    }
10400
10401    /**
10402     * If the View draws content inside its padding and enables fading edges,
10403     * it needs to support padding offsets. Padding offsets are added to the
10404     * fading edges to extend the length of the fade so that it covers pixels
10405     * drawn inside the padding.
10406     *
10407     * Subclasses of this class should override this method if they need
10408     * to draw content inside the padding.
10409     *
10410     * @return True if padding offset must be applied, false otherwise.
10411     *
10412     * @see #getLeftPaddingOffset()
10413     * @see #getRightPaddingOffset()
10414     * @see #getTopPaddingOffset()
10415     * @see #getBottomPaddingOffset()
10416     *
10417     * @since CURRENT
10418     */
10419    protected boolean isPaddingOffsetRequired() {
10420        return false;
10421    }
10422
10423    /**
10424     * Amount by which to extend the left fading region. Called only when
10425     * {@link #isPaddingOffsetRequired()} returns true.
10426     *
10427     * @return The left padding offset in pixels.
10428     *
10429     * @see #isPaddingOffsetRequired()
10430     *
10431     * @since CURRENT
10432     */
10433    protected int getLeftPaddingOffset() {
10434        return 0;
10435    }
10436
10437    /**
10438     * Amount by which to extend the right fading region. Called only when
10439     * {@link #isPaddingOffsetRequired()} returns true.
10440     *
10441     * @return The right padding offset in pixels.
10442     *
10443     * @see #isPaddingOffsetRequired()
10444     *
10445     * @since CURRENT
10446     */
10447    protected int getRightPaddingOffset() {
10448        return 0;
10449    }
10450
10451    /**
10452     * Amount by which to extend the top fading region. Called only when
10453     * {@link #isPaddingOffsetRequired()} returns true.
10454     *
10455     * @return The top padding offset in pixels.
10456     *
10457     * @see #isPaddingOffsetRequired()
10458     *
10459     * @since CURRENT
10460     */
10461    protected int getTopPaddingOffset() {
10462        return 0;
10463    }
10464
10465    /**
10466     * Amount by which to extend the bottom fading region. Called only when
10467     * {@link #isPaddingOffsetRequired()} returns true.
10468     *
10469     * @return The bottom padding offset in pixels.
10470     *
10471     * @see #isPaddingOffsetRequired()
10472     *
10473     * @since CURRENT
10474     */
10475    protected int getBottomPaddingOffset() {
10476        return 0;
10477    }
10478
10479    /**
10480     * @hide
10481     * @param offsetRequired
10482     */
10483    protected int getFadeTop(boolean offsetRequired) {
10484        int top = mPaddingTop;
10485        if (offsetRequired) top += getTopPaddingOffset();
10486        return top;
10487    }
10488
10489    /**
10490     * @hide
10491     * @param offsetRequired
10492     */
10493    protected int getFadeHeight(boolean offsetRequired) {
10494        int padding = mPaddingTop;
10495        if (offsetRequired) padding += getTopPaddingOffset();
10496        return mBottom - mTop - mPaddingBottom - padding;
10497    }
10498
10499    /**
10500     * <p>Indicates whether this view is attached to an hardware accelerated
10501     * window or not.</p>
10502     *
10503     * <p>Even if this method returns true, it does not mean that every call
10504     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10505     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10506     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10507     * window is hardware accelerated,
10508     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10509     * return false, and this method will return true.</p>
10510     *
10511     * @return True if the view is attached to a window and the window is
10512     *         hardware accelerated; false in any other case.
10513     */
10514    public boolean isHardwareAccelerated() {
10515        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10516    }
10517
10518    /**
10519     * Manually render this view (and all of its children) to the given Canvas.
10520     * The view must have already done a full layout before this function is
10521     * called.  When implementing a view, implement
10522     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10523     * If you do need to override this method, call the superclass version.
10524     *
10525     * @param canvas The Canvas to which the View is rendered.
10526     */
10527    public void draw(Canvas canvas) {
10528        if (ViewDebug.TRACE_HIERARCHY) {
10529            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10530        }
10531
10532        final int privateFlags = mPrivateFlags;
10533        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10534                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10535        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10536
10537        /*
10538         * Draw traversal performs several drawing steps which must be executed
10539         * in the appropriate order:
10540         *
10541         *      1. Draw the background
10542         *      2. If necessary, save the canvas' layers to prepare for fading
10543         *      3. Draw view's content
10544         *      4. Draw children
10545         *      5. If necessary, draw the fading edges and restore layers
10546         *      6. Draw decorations (scrollbars for instance)
10547         */
10548
10549        // Step 1, draw the background, if needed
10550        int saveCount;
10551
10552        if (!dirtyOpaque) {
10553            final Drawable background = mBGDrawable;
10554            if (background != null) {
10555                final int scrollX = mScrollX;
10556                final int scrollY = mScrollY;
10557
10558                if (mBackgroundSizeChanged) {
10559                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10560                    mBackgroundSizeChanged = false;
10561                }
10562
10563                if ((scrollX | scrollY) == 0) {
10564                    background.draw(canvas);
10565                } else {
10566                    canvas.translate(scrollX, scrollY);
10567                    background.draw(canvas);
10568                    canvas.translate(-scrollX, -scrollY);
10569                }
10570            }
10571        }
10572
10573        // skip step 2 & 5 if possible (common case)
10574        final int viewFlags = mViewFlags;
10575        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10576        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10577        if (!verticalEdges && !horizontalEdges) {
10578            // Step 3, draw the content
10579            if (!dirtyOpaque) onDraw(canvas);
10580
10581            // Step 4, draw the children
10582            dispatchDraw(canvas);
10583
10584            // Step 6, draw decorations (scrollbars)
10585            onDrawScrollBars(canvas);
10586
10587            // we're done...
10588            return;
10589        }
10590
10591        /*
10592         * Here we do the full fledged routine...
10593         * (this is an uncommon case where speed matters less,
10594         * this is why we repeat some of the tests that have been
10595         * done above)
10596         */
10597
10598        boolean drawTop = false;
10599        boolean drawBottom = false;
10600        boolean drawLeft = false;
10601        boolean drawRight = false;
10602
10603        float topFadeStrength = 0.0f;
10604        float bottomFadeStrength = 0.0f;
10605        float leftFadeStrength = 0.0f;
10606        float rightFadeStrength = 0.0f;
10607
10608        // Step 2, save the canvas' layers
10609        int paddingLeft = mPaddingLeft;
10610
10611        final boolean offsetRequired = isPaddingOffsetRequired();
10612        if (offsetRequired) {
10613            paddingLeft += getLeftPaddingOffset();
10614        }
10615
10616        int left = mScrollX + paddingLeft;
10617        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
10618        int top = mScrollY + getFadeTop(offsetRequired);
10619        int bottom = top + getFadeHeight(offsetRequired);
10620
10621        if (offsetRequired) {
10622            right += getRightPaddingOffset();
10623            bottom += getBottomPaddingOffset();
10624        }
10625
10626        final ScrollabilityCache scrollabilityCache = mScrollCache;
10627        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
10628        int length = (int) fadeHeight;
10629
10630        // clip the fade length if top and bottom fades overlap
10631        // overlapping fades produce odd-looking artifacts
10632        if (verticalEdges && (top + length > bottom - length)) {
10633            length = (bottom - top) / 2;
10634        }
10635
10636        // also clip horizontal fades if necessary
10637        if (horizontalEdges && (left + length > right - length)) {
10638            length = (right - left) / 2;
10639        }
10640
10641        if (verticalEdges) {
10642            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
10643            drawTop = topFadeStrength * fadeHeight > 1.0f;
10644            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
10645            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
10646        }
10647
10648        if (horizontalEdges) {
10649            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
10650            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
10651            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
10652            drawRight = rightFadeStrength * fadeHeight > 1.0f;
10653        }
10654
10655        saveCount = canvas.getSaveCount();
10656
10657        int solidColor = getSolidColor();
10658        if (solidColor == 0) {
10659            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
10660
10661            if (drawTop) {
10662                canvas.saveLayer(left, top, right, top + length, null, flags);
10663            }
10664
10665            if (drawBottom) {
10666                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
10667            }
10668
10669            if (drawLeft) {
10670                canvas.saveLayer(left, top, left + length, bottom, null, flags);
10671            }
10672
10673            if (drawRight) {
10674                canvas.saveLayer(right - length, top, right, bottom, null, flags);
10675            }
10676        } else {
10677            scrollabilityCache.setFadeColor(solidColor);
10678        }
10679
10680        // Step 3, draw the content
10681        if (!dirtyOpaque) onDraw(canvas);
10682
10683        // Step 4, draw the children
10684        dispatchDraw(canvas);
10685
10686        // Step 5, draw the fade effect and restore layers
10687        final Paint p = scrollabilityCache.paint;
10688        final Matrix matrix = scrollabilityCache.matrix;
10689        final Shader fade = scrollabilityCache.shader;
10690
10691        if (drawTop) {
10692            matrix.setScale(1, fadeHeight * topFadeStrength);
10693            matrix.postTranslate(left, top);
10694            fade.setLocalMatrix(matrix);
10695            canvas.drawRect(left, top, right, top + length, p);
10696        }
10697
10698        if (drawBottom) {
10699            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10700            matrix.postRotate(180);
10701            matrix.postTranslate(left, bottom);
10702            fade.setLocalMatrix(matrix);
10703            canvas.drawRect(left, bottom - length, right, bottom, p);
10704        }
10705
10706        if (drawLeft) {
10707            matrix.setScale(1, fadeHeight * leftFadeStrength);
10708            matrix.postRotate(-90);
10709            matrix.postTranslate(left, top);
10710            fade.setLocalMatrix(matrix);
10711            canvas.drawRect(left, top, left + length, bottom, p);
10712        }
10713
10714        if (drawRight) {
10715            matrix.setScale(1, fadeHeight * rightFadeStrength);
10716            matrix.postRotate(90);
10717            matrix.postTranslate(right, top);
10718            fade.setLocalMatrix(matrix);
10719            canvas.drawRect(right - length, top, right, bottom, p);
10720        }
10721
10722        canvas.restoreToCount(saveCount);
10723
10724        // Step 6, draw decorations (scrollbars)
10725        onDrawScrollBars(canvas);
10726    }
10727
10728    /**
10729     * Override this if your view is known to always be drawn on top of a solid color background,
10730     * and needs to draw fading edges. Returning a non-zero color enables the view system to
10731     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
10732     * should be set to 0xFF.
10733     *
10734     * @see #setVerticalFadingEdgeEnabled(boolean)
10735     * @see #setHorizontalFadingEdgeEnabled(boolean)
10736     *
10737     * @return The known solid color background for this view, or 0 if the color may vary
10738     */
10739    @ViewDebug.ExportedProperty(category = "drawing")
10740    public int getSolidColor() {
10741        return 0;
10742    }
10743
10744    /**
10745     * Build a human readable string representation of the specified view flags.
10746     *
10747     * @param flags the view flags to convert to a string
10748     * @return a String representing the supplied flags
10749     */
10750    private static String printFlags(int flags) {
10751        String output = "";
10752        int numFlags = 0;
10753        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
10754            output += "TAKES_FOCUS";
10755            numFlags++;
10756        }
10757
10758        switch (flags & VISIBILITY_MASK) {
10759        case INVISIBLE:
10760            if (numFlags > 0) {
10761                output += " ";
10762            }
10763            output += "INVISIBLE";
10764            // USELESS HERE numFlags++;
10765            break;
10766        case GONE:
10767            if (numFlags > 0) {
10768                output += " ";
10769            }
10770            output += "GONE";
10771            // USELESS HERE numFlags++;
10772            break;
10773        default:
10774            break;
10775        }
10776        return output;
10777    }
10778
10779    /**
10780     * Build a human readable string representation of the specified private
10781     * view flags.
10782     *
10783     * @param privateFlags the private view flags to convert to a string
10784     * @return a String representing the supplied flags
10785     */
10786    private static String printPrivateFlags(int privateFlags) {
10787        String output = "";
10788        int numFlags = 0;
10789
10790        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
10791            output += "WANTS_FOCUS";
10792            numFlags++;
10793        }
10794
10795        if ((privateFlags & FOCUSED) == FOCUSED) {
10796            if (numFlags > 0) {
10797                output += " ";
10798            }
10799            output += "FOCUSED";
10800            numFlags++;
10801        }
10802
10803        if ((privateFlags & SELECTED) == SELECTED) {
10804            if (numFlags > 0) {
10805                output += " ";
10806            }
10807            output += "SELECTED";
10808            numFlags++;
10809        }
10810
10811        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
10812            if (numFlags > 0) {
10813                output += " ";
10814            }
10815            output += "IS_ROOT_NAMESPACE";
10816            numFlags++;
10817        }
10818
10819        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
10820            if (numFlags > 0) {
10821                output += " ";
10822            }
10823            output += "HAS_BOUNDS";
10824            numFlags++;
10825        }
10826
10827        if ((privateFlags & DRAWN) == DRAWN) {
10828            if (numFlags > 0) {
10829                output += " ";
10830            }
10831            output += "DRAWN";
10832            // USELESS HERE numFlags++;
10833        }
10834        return output;
10835    }
10836
10837    /**
10838     * <p>Indicates whether or not this view's layout will be requested during
10839     * the next hierarchy layout pass.</p>
10840     *
10841     * @return true if the layout will be forced during next layout pass
10842     */
10843    public boolean isLayoutRequested() {
10844        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
10845    }
10846
10847    /**
10848     * Assign a size and position to a view and all of its
10849     * descendants
10850     *
10851     * <p>This is the second phase of the layout mechanism.
10852     * (The first is measuring). In this phase, each parent calls
10853     * layout on all of its children to position them.
10854     * This is typically done using the child measurements
10855     * that were stored in the measure pass().</p>
10856     *
10857     * <p>Derived classes should not override this method.
10858     * Derived classes with children should override
10859     * onLayout. In that method, they should
10860     * call layout on each of their children.</p>
10861     *
10862     * @param l Left position, relative to parent
10863     * @param t Top position, relative to parent
10864     * @param r Right position, relative to parent
10865     * @param b Bottom position, relative to parent
10866     */
10867    @SuppressWarnings({"unchecked"})
10868    public void layout(int l, int t, int r, int b) {
10869        int oldL = mLeft;
10870        int oldT = mTop;
10871        int oldB = mBottom;
10872        int oldR = mRight;
10873        boolean changed = setFrame(l, t, r, b);
10874        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
10875            if (ViewDebug.TRACE_HIERARCHY) {
10876                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
10877            }
10878
10879            onLayout(changed, l, t, r, b);
10880            mPrivateFlags &= ~LAYOUT_REQUIRED;
10881
10882            if (mOnLayoutChangeListeners != null) {
10883                ArrayList<OnLayoutChangeListener> listenersCopy =
10884                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
10885                int numListeners = listenersCopy.size();
10886                for (int i = 0; i < numListeners; ++i) {
10887                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
10888                }
10889            }
10890        }
10891        mPrivateFlags &= ~FORCE_LAYOUT;
10892    }
10893
10894    /**
10895     * Called from layout when this view should
10896     * assign a size and position to each of its children.
10897     *
10898     * Derived classes with children should override
10899     * this method and call layout on each of
10900     * their children.
10901     * @param changed This is a new size or position for this view
10902     * @param left Left position, relative to parent
10903     * @param top Top position, relative to parent
10904     * @param right Right position, relative to parent
10905     * @param bottom Bottom position, relative to parent
10906     */
10907    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
10908    }
10909
10910    /**
10911     * Assign a size and position to this view.
10912     *
10913     * This is called from layout.
10914     *
10915     * @param left Left position, relative to parent
10916     * @param top Top position, relative to parent
10917     * @param right Right position, relative to parent
10918     * @param bottom Bottom position, relative to parent
10919     * @return true if the new size and position are different than the
10920     *         previous ones
10921     * {@hide}
10922     */
10923    protected boolean setFrame(int left, int top, int right, int bottom) {
10924        boolean changed = false;
10925
10926        if (DBG) {
10927            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
10928                    + right + "," + bottom + ")");
10929        }
10930
10931        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
10932            changed = true;
10933
10934            // Remember our drawn bit
10935            int drawn = mPrivateFlags & DRAWN;
10936
10937            int oldWidth = mRight - mLeft;
10938            int oldHeight = mBottom - mTop;
10939            int newWidth = right - left;
10940            int newHeight = bottom - top;
10941            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
10942
10943            // Invalidate our old position
10944            invalidate(sizeChanged);
10945
10946            mLeft = left;
10947            mTop = top;
10948            mRight = right;
10949            mBottom = bottom;
10950
10951            mPrivateFlags |= HAS_BOUNDS;
10952
10953
10954            if (sizeChanged) {
10955                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
10956                    // A change in dimension means an auto-centered pivot point changes, too
10957                    mMatrixDirty = true;
10958                }
10959                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
10960            }
10961
10962            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
10963                // If we are visible, force the DRAWN bit to on so that
10964                // this invalidate will go through (at least to our parent).
10965                // This is because someone may have invalidated this view
10966                // before this call to setFrame came in, thereby clearing
10967                // the DRAWN bit.
10968                mPrivateFlags |= DRAWN;
10969                invalidate(sizeChanged);
10970                // parent display list may need to be recreated based on a change in the bounds
10971                // of any child
10972                invalidateParentCaches();
10973            }
10974
10975            // Reset drawn bit to original value (invalidate turns it off)
10976            mPrivateFlags |= drawn;
10977
10978            mBackgroundSizeChanged = true;
10979        }
10980        return changed;
10981    }
10982
10983    /**
10984     * Finalize inflating a view from XML.  This is called as the last phase
10985     * of inflation, after all child views have been added.
10986     *
10987     * <p>Even if the subclass overrides onFinishInflate, they should always be
10988     * sure to call the super method, so that we get called.
10989     */
10990    protected void onFinishInflate() {
10991    }
10992
10993    /**
10994     * Returns the resources associated with this view.
10995     *
10996     * @return Resources object.
10997     */
10998    public Resources getResources() {
10999        return mResources;
11000    }
11001
11002    /**
11003     * Invalidates the specified Drawable.
11004     *
11005     * @param drawable the drawable to invalidate
11006     */
11007    public void invalidateDrawable(Drawable drawable) {
11008        if (verifyDrawable(drawable)) {
11009            final Rect dirty = drawable.getBounds();
11010            final int scrollX = mScrollX;
11011            final int scrollY = mScrollY;
11012
11013            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11014                    dirty.right + scrollX, dirty.bottom + scrollY);
11015        }
11016    }
11017
11018    /**
11019     * Schedules an action on a drawable to occur at a specified time.
11020     *
11021     * @param who the recipient of the action
11022     * @param what the action to run on the drawable
11023     * @param when the time at which the action must occur. Uses the
11024     *        {@link SystemClock#uptimeMillis} timebase.
11025     */
11026    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11027        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11028            mAttachInfo.mHandler.postAtTime(what, who, when);
11029        }
11030    }
11031
11032    /**
11033     * Cancels a scheduled action on a drawable.
11034     *
11035     * @param who the recipient of the action
11036     * @param what the action to cancel
11037     */
11038    public void unscheduleDrawable(Drawable who, Runnable what) {
11039        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11040            mAttachInfo.mHandler.removeCallbacks(what, who);
11041        }
11042    }
11043
11044    /**
11045     * Unschedule any events associated with the given Drawable.  This can be
11046     * used when selecting a new Drawable into a view, so that the previous
11047     * one is completely unscheduled.
11048     *
11049     * @param who The Drawable to unschedule.
11050     *
11051     * @see #drawableStateChanged
11052     */
11053    public void unscheduleDrawable(Drawable who) {
11054        if (mAttachInfo != null) {
11055            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11056        }
11057    }
11058
11059    /**
11060    * Return the layout direction of a given Drawable.
11061    *
11062    * @param who the Drawable to query
11063    *
11064    * @hide
11065    */
11066    public int getResolvedLayoutDirection(Drawable who) {
11067        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11068    }
11069
11070    /**
11071     * If your view subclass is displaying its own Drawable objects, it should
11072     * override this function and return true for any Drawable it is
11073     * displaying.  This allows animations for those drawables to be
11074     * scheduled.
11075     *
11076     * <p>Be sure to call through to the super class when overriding this
11077     * function.
11078     *
11079     * @param who The Drawable to verify.  Return true if it is one you are
11080     *            displaying, else return the result of calling through to the
11081     *            super class.
11082     *
11083     * @return boolean If true than the Drawable is being displayed in the
11084     *         view; else false and it is not allowed to animate.
11085     *
11086     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11087     * @see #drawableStateChanged()
11088     */
11089    protected boolean verifyDrawable(Drawable who) {
11090        return who == mBGDrawable;
11091    }
11092
11093    /**
11094     * This function is called whenever the state of the view changes in such
11095     * a way that it impacts the state of drawables being shown.
11096     *
11097     * <p>Be sure to call through to the superclass when overriding this
11098     * function.
11099     *
11100     * @see Drawable#setState(int[])
11101     */
11102    protected void drawableStateChanged() {
11103        Drawable d = mBGDrawable;
11104        if (d != null && d.isStateful()) {
11105            d.setState(getDrawableState());
11106        }
11107    }
11108
11109    /**
11110     * Call this to force a view to update its drawable state. This will cause
11111     * drawableStateChanged to be called on this view. Views that are interested
11112     * in the new state should call getDrawableState.
11113     *
11114     * @see #drawableStateChanged
11115     * @see #getDrawableState
11116     */
11117    public void refreshDrawableState() {
11118        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11119        drawableStateChanged();
11120
11121        ViewParent parent = mParent;
11122        if (parent != null) {
11123            parent.childDrawableStateChanged(this);
11124        }
11125    }
11126
11127    /**
11128     * Return an array of resource IDs of the drawable states representing the
11129     * current state of the view.
11130     *
11131     * @return The current drawable state
11132     *
11133     * @see Drawable#setState(int[])
11134     * @see #drawableStateChanged()
11135     * @see #onCreateDrawableState(int)
11136     */
11137    public final int[] getDrawableState() {
11138        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11139            return mDrawableState;
11140        } else {
11141            mDrawableState = onCreateDrawableState(0);
11142            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11143            return mDrawableState;
11144        }
11145    }
11146
11147    /**
11148     * Generate the new {@link android.graphics.drawable.Drawable} state for
11149     * this view. This is called by the view
11150     * system when the cached Drawable state is determined to be invalid.  To
11151     * retrieve the current state, you should use {@link #getDrawableState}.
11152     *
11153     * @param extraSpace if non-zero, this is the number of extra entries you
11154     * would like in the returned array in which you can place your own
11155     * states.
11156     *
11157     * @return Returns an array holding the current {@link Drawable} state of
11158     * the view.
11159     *
11160     * @see #mergeDrawableStates(int[], int[])
11161     */
11162    protected int[] onCreateDrawableState(int extraSpace) {
11163        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11164                mParent instanceof View) {
11165            return ((View) mParent).onCreateDrawableState(extraSpace);
11166        }
11167
11168        int[] drawableState;
11169
11170        int privateFlags = mPrivateFlags;
11171
11172        int viewStateIndex = 0;
11173        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11174        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11175        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11176        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11177        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11178        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11179        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11180                HardwareRenderer.isAvailable()) {
11181            // This is set if HW acceleration is requested, even if the current
11182            // process doesn't allow it.  This is just to allow app preview
11183            // windows to better match their app.
11184            viewStateIndex |= VIEW_STATE_ACCELERATED;
11185        }
11186        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11187
11188        final int privateFlags2 = mPrivateFlags2;
11189        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11190        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11191
11192        drawableState = VIEW_STATE_SETS[viewStateIndex];
11193
11194        //noinspection ConstantIfStatement
11195        if (false) {
11196            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11197            Log.i("View", toString()
11198                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11199                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11200                    + " fo=" + hasFocus()
11201                    + " sl=" + ((privateFlags & SELECTED) != 0)
11202                    + " wf=" + hasWindowFocus()
11203                    + ": " + Arrays.toString(drawableState));
11204        }
11205
11206        if (extraSpace == 0) {
11207            return drawableState;
11208        }
11209
11210        final int[] fullState;
11211        if (drawableState != null) {
11212            fullState = new int[drawableState.length + extraSpace];
11213            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11214        } else {
11215            fullState = new int[extraSpace];
11216        }
11217
11218        return fullState;
11219    }
11220
11221    /**
11222     * Merge your own state values in <var>additionalState</var> into the base
11223     * state values <var>baseState</var> that were returned by
11224     * {@link #onCreateDrawableState(int)}.
11225     *
11226     * @param baseState The base state values returned by
11227     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11228     * own additional state values.
11229     *
11230     * @param additionalState The additional state values you would like
11231     * added to <var>baseState</var>; this array is not modified.
11232     *
11233     * @return As a convenience, the <var>baseState</var> array you originally
11234     * passed into the function is returned.
11235     *
11236     * @see #onCreateDrawableState(int)
11237     */
11238    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11239        final int N = baseState.length;
11240        int i = N - 1;
11241        while (i >= 0 && baseState[i] == 0) {
11242            i--;
11243        }
11244        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11245        return baseState;
11246    }
11247
11248    /**
11249     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11250     * on all Drawable objects associated with this view.
11251     */
11252    public void jumpDrawablesToCurrentState() {
11253        if (mBGDrawable != null) {
11254            mBGDrawable.jumpToCurrentState();
11255        }
11256    }
11257
11258    /**
11259     * Sets the background color for this view.
11260     * @param color the color of the background
11261     */
11262    @RemotableViewMethod
11263    public void setBackgroundColor(int color) {
11264        if (mBGDrawable instanceof ColorDrawable) {
11265            ((ColorDrawable) mBGDrawable).setColor(color);
11266        } else {
11267            setBackgroundDrawable(new ColorDrawable(color));
11268        }
11269    }
11270
11271    /**
11272     * Set the background to a given resource. The resource should refer to
11273     * a Drawable object or 0 to remove the background.
11274     * @param resid The identifier of the resource.
11275     * @attr ref android.R.styleable#View_background
11276     */
11277    @RemotableViewMethod
11278    public void setBackgroundResource(int resid) {
11279        if (resid != 0 && resid == mBackgroundResource) {
11280            return;
11281        }
11282
11283        Drawable d= null;
11284        if (resid != 0) {
11285            d = mResources.getDrawable(resid);
11286        }
11287        setBackgroundDrawable(d);
11288
11289        mBackgroundResource = resid;
11290    }
11291
11292    /**
11293     * Set the background to a given Drawable, or remove the background. If the
11294     * background has padding, this View's padding is set to the background's
11295     * padding. However, when a background is removed, this View's padding isn't
11296     * touched. If setting the padding is desired, please use
11297     * {@link #setPadding(int, int, int, int)}.
11298     *
11299     * @param d The Drawable to use as the background, or null to remove the
11300     *        background
11301     */
11302    public void setBackgroundDrawable(Drawable d) {
11303        if (d == mBGDrawable) {
11304            return;
11305        }
11306
11307        boolean requestLayout = false;
11308
11309        mBackgroundResource = 0;
11310
11311        /*
11312         * Regardless of whether we're setting a new background or not, we want
11313         * to clear the previous drawable.
11314         */
11315        if (mBGDrawable != null) {
11316            mBGDrawable.setCallback(null);
11317            unscheduleDrawable(mBGDrawable);
11318        }
11319
11320        if (d != null) {
11321            Rect padding = sThreadLocal.get();
11322            if (padding == null) {
11323                padding = new Rect();
11324                sThreadLocal.set(padding);
11325            }
11326            if (d.getPadding(padding)) {
11327                switch (d.getResolvedLayoutDirectionSelf()) {
11328                    case LAYOUT_DIRECTION_RTL:
11329                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11330                        break;
11331                    case LAYOUT_DIRECTION_LTR:
11332                    default:
11333                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11334                }
11335            }
11336
11337            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11338            // if it has a different minimum size, we should layout again
11339            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11340                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11341                requestLayout = true;
11342            }
11343
11344            d.setCallback(this);
11345            if (d.isStateful()) {
11346                d.setState(getDrawableState());
11347            }
11348            d.setVisible(getVisibility() == VISIBLE, false);
11349            mBGDrawable = d;
11350
11351            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11352                mPrivateFlags &= ~SKIP_DRAW;
11353                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11354                requestLayout = true;
11355            }
11356        } else {
11357            /* Remove the background */
11358            mBGDrawable = null;
11359
11360            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11361                /*
11362                 * This view ONLY drew the background before and we're removing
11363                 * the background, so now it won't draw anything
11364                 * (hence we SKIP_DRAW)
11365                 */
11366                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11367                mPrivateFlags |= SKIP_DRAW;
11368            }
11369
11370            /*
11371             * When the background is set, we try to apply its padding to this
11372             * View. When the background is removed, we don't touch this View's
11373             * padding. This is noted in the Javadocs. Hence, we don't need to
11374             * requestLayout(), the invalidate() below is sufficient.
11375             */
11376
11377            // The old background's minimum size could have affected this
11378            // View's layout, so let's requestLayout
11379            requestLayout = true;
11380        }
11381
11382        computeOpaqueFlags();
11383
11384        if (requestLayout) {
11385            requestLayout();
11386        }
11387
11388        mBackgroundSizeChanged = true;
11389        invalidate(true);
11390    }
11391
11392    /**
11393     * Gets the background drawable
11394     * @return The drawable used as the background for this view, if any.
11395     */
11396    public Drawable getBackground() {
11397        return mBGDrawable;
11398    }
11399
11400    /**
11401     * Sets the padding. The view may add on the space required to display
11402     * the scrollbars, depending on the style and visibility of the scrollbars.
11403     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11404     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11405     * from the values set in this call.
11406     *
11407     * @attr ref android.R.styleable#View_padding
11408     * @attr ref android.R.styleable#View_paddingBottom
11409     * @attr ref android.R.styleable#View_paddingLeft
11410     * @attr ref android.R.styleable#View_paddingRight
11411     * @attr ref android.R.styleable#View_paddingTop
11412     * @param left the left padding in pixels
11413     * @param top the top padding in pixels
11414     * @param right the right padding in pixels
11415     * @param bottom the bottom padding in pixels
11416     */
11417    public void setPadding(int left, int top, int right, int bottom) {
11418        boolean changed = false;
11419
11420        mUserPaddingRelative = false;
11421
11422        mUserPaddingLeft = left;
11423        mUserPaddingRight = right;
11424        mUserPaddingBottom = bottom;
11425
11426        final int viewFlags = mViewFlags;
11427
11428        // Common case is there are no scroll bars.
11429        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11430            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11431                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11432                        ? 0 : getVerticalScrollbarWidth();
11433                switch (mVerticalScrollbarPosition) {
11434                    case SCROLLBAR_POSITION_DEFAULT:
11435                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11436                            left += offset;
11437                        } else {
11438                            right += offset;
11439                        }
11440                        break;
11441                    case SCROLLBAR_POSITION_RIGHT:
11442                        right += offset;
11443                        break;
11444                    case SCROLLBAR_POSITION_LEFT:
11445                        left += offset;
11446                        break;
11447                }
11448            }
11449            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11450                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11451                        ? 0 : getHorizontalScrollbarHeight();
11452            }
11453        }
11454
11455        if (mPaddingLeft != left) {
11456            changed = true;
11457            mPaddingLeft = left;
11458        }
11459        if (mPaddingTop != top) {
11460            changed = true;
11461            mPaddingTop = top;
11462        }
11463        if (mPaddingRight != right) {
11464            changed = true;
11465            mPaddingRight = right;
11466        }
11467        if (mPaddingBottom != bottom) {
11468            changed = true;
11469            mPaddingBottom = bottom;
11470        }
11471
11472        if (changed) {
11473            requestLayout();
11474        }
11475    }
11476
11477    /**
11478     * Sets the relative padding. The view may add on the space required to display
11479     * the scrollbars, depending on the style and visibility of the scrollbars.
11480     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11481     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11482     * from the values set in this call.
11483     *
11484     * @attr ref android.R.styleable#View_padding
11485     * @attr ref android.R.styleable#View_paddingBottom
11486     * @attr ref android.R.styleable#View_paddingStart
11487     * @attr ref android.R.styleable#View_paddingEnd
11488     * @attr ref android.R.styleable#View_paddingTop
11489     * @param start the start padding in pixels
11490     * @param top the top padding in pixels
11491     * @param end the end padding in pixels
11492     * @param bottom the bottom padding in pixels
11493     *
11494     * @hide
11495     */
11496    public void setPaddingRelative(int start, int top, int end, int bottom) {
11497        mUserPaddingRelative = true;
11498
11499        mUserPaddingStart = start;
11500        mUserPaddingEnd = end;
11501
11502        switch(getResolvedLayoutDirection()) {
11503            case LAYOUT_DIRECTION_RTL:
11504                setPadding(end, top, start, bottom);
11505                break;
11506            case LAYOUT_DIRECTION_LTR:
11507            default:
11508                setPadding(start, top, end, bottom);
11509        }
11510    }
11511
11512    /**
11513     * Returns the top padding of this view.
11514     *
11515     * @return the top padding in pixels
11516     */
11517    public int getPaddingTop() {
11518        return mPaddingTop;
11519    }
11520
11521    /**
11522     * Returns the bottom padding of this view. If there are inset and enabled
11523     * scrollbars, this value may include the space required to display the
11524     * scrollbars as well.
11525     *
11526     * @return the bottom padding in pixels
11527     */
11528    public int getPaddingBottom() {
11529        return mPaddingBottom;
11530    }
11531
11532    /**
11533     * Returns the left padding of this view. If there are inset and enabled
11534     * scrollbars, this value may include the space required to display the
11535     * scrollbars as well.
11536     *
11537     * @return the left padding in pixels
11538     */
11539    public int getPaddingLeft() {
11540        return mPaddingLeft;
11541    }
11542
11543    /**
11544     * Returns the start padding of this view. If there are inset and enabled
11545     * scrollbars, this value may include the space required to display the
11546     * scrollbars as well.
11547     *
11548     * @return the start padding in pixels
11549     *
11550     * @hide
11551     */
11552    public int getPaddingStart() {
11553        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11554                mPaddingRight : mPaddingLeft;
11555    }
11556
11557    /**
11558     * Returns the right padding of this view. If there are inset and enabled
11559     * scrollbars, this value may include the space required to display the
11560     * scrollbars as well.
11561     *
11562     * @return the right padding in pixels
11563     */
11564    public int getPaddingRight() {
11565        return mPaddingRight;
11566    }
11567
11568    /**
11569     * Returns the end padding of this view. If there are inset and enabled
11570     * scrollbars, this value may include the space required to display the
11571     * scrollbars as well.
11572     *
11573     * @return the end padding in pixels
11574     *
11575     * @hide
11576     */
11577    public int getPaddingEnd() {
11578        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11579                mPaddingLeft : mPaddingRight;
11580    }
11581
11582    /**
11583     * Return if the padding as been set thru relative values
11584     * {@link #setPaddingRelative(int, int, int, int)} or thru
11585     * @attr ref android.R.styleable#View_paddingStart or
11586     * @attr ref android.R.styleable#View_paddingEnd
11587     *
11588     * @return true if the padding is relative or false if it is not.
11589     *
11590     * @hide
11591     */
11592    public boolean isPaddingRelative() {
11593        return mUserPaddingRelative;
11594    }
11595
11596    /**
11597     * Changes the selection state of this view. A view can be selected or not.
11598     * Note that selection is not the same as focus. Views are typically
11599     * selected in the context of an AdapterView like ListView or GridView;
11600     * the selected view is the view that is highlighted.
11601     *
11602     * @param selected true if the view must be selected, false otherwise
11603     */
11604    public void setSelected(boolean selected) {
11605        if (((mPrivateFlags & SELECTED) != 0) != selected) {
11606            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
11607            if (!selected) resetPressedState();
11608            invalidate(true);
11609            refreshDrawableState();
11610            dispatchSetSelected(selected);
11611        }
11612    }
11613
11614    /**
11615     * Dispatch setSelected to all of this View's children.
11616     *
11617     * @see #setSelected(boolean)
11618     *
11619     * @param selected The new selected state
11620     */
11621    protected void dispatchSetSelected(boolean selected) {
11622    }
11623
11624    /**
11625     * Indicates the selection state of this view.
11626     *
11627     * @return true if the view is selected, false otherwise
11628     */
11629    @ViewDebug.ExportedProperty
11630    public boolean isSelected() {
11631        return (mPrivateFlags & SELECTED) != 0;
11632    }
11633
11634    /**
11635     * Changes the activated state of this view. A view can be activated or not.
11636     * Note that activation is not the same as selection.  Selection is
11637     * a transient property, representing the view (hierarchy) the user is
11638     * currently interacting with.  Activation is a longer-term state that the
11639     * user can move views in and out of.  For example, in a list view with
11640     * single or multiple selection enabled, the views in the current selection
11641     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
11642     * here.)  The activated state is propagated down to children of the view it
11643     * is set on.
11644     *
11645     * @param activated true if the view must be activated, false otherwise
11646     */
11647    public void setActivated(boolean activated) {
11648        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
11649            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
11650            invalidate(true);
11651            refreshDrawableState();
11652            dispatchSetActivated(activated);
11653        }
11654    }
11655
11656    /**
11657     * Dispatch setActivated to all of this View's children.
11658     *
11659     * @see #setActivated(boolean)
11660     *
11661     * @param activated The new activated state
11662     */
11663    protected void dispatchSetActivated(boolean activated) {
11664    }
11665
11666    /**
11667     * Indicates the activation state of this view.
11668     *
11669     * @return true if the view is activated, false otherwise
11670     */
11671    @ViewDebug.ExportedProperty
11672    public boolean isActivated() {
11673        return (mPrivateFlags & ACTIVATED) != 0;
11674    }
11675
11676    /**
11677     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
11678     * observer can be used to get notifications when global events, like
11679     * layout, happen.
11680     *
11681     * The returned ViewTreeObserver observer is not guaranteed to remain
11682     * valid for the lifetime of this View. If the caller of this method keeps
11683     * a long-lived reference to ViewTreeObserver, it should always check for
11684     * the return value of {@link ViewTreeObserver#isAlive()}.
11685     *
11686     * @return The ViewTreeObserver for this view's hierarchy.
11687     */
11688    public ViewTreeObserver getViewTreeObserver() {
11689        if (mAttachInfo != null) {
11690            return mAttachInfo.mTreeObserver;
11691        }
11692        if (mFloatingTreeObserver == null) {
11693            mFloatingTreeObserver = new ViewTreeObserver();
11694        }
11695        return mFloatingTreeObserver;
11696    }
11697
11698    /**
11699     * <p>Finds the topmost view in the current view hierarchy.</p>
11700     *
11701     * @return the topmost view containing this view
11702     */
11703    public View getRootView() {
11704        if (mAttachInfo != null) {
11705            final View v = mAttachInfo.mRootView;
11706            if (v != null) {
11707                return v;
11708            }
11709        }
11710
11711        View parent = this;
11712
11713        while (parent.mParent != null && parent.mParent instanceof View) {
11714            parent = (View) parent.mParent;
11715        }
11716
11717        return parent;
11718    }
11719
11720    /**
11721     * <p>Computes the coordinates of this view on the screen. The argument
11722     * must be an array of two integers. After the method returns, the array
11723     * contains the x and y location in that order.</p>
11724     *
11725     * @param location an array of two integers in which to hold the coordinates
11726     */
11727    public void getLocationOnScreen(int[] location) {
11728        getLocationInWindow(location);
11729
11730        final AttachInfo info = mAttachInfo;
11731        if (info != null) {
11732            location[0] += info.mWindowLeft;
11733            location[1] += info.mWindowTop;
11734        }
11735    }
11736
11737    /**
11738     * <p>Computes the coordinates of this view in its window. The argument
11739     * must be an array of two integers. After the method returns, the array
11740     * contains the x and y location in that order.</p>
11741     *
11742     * @param location an array of two integers in which to hold the coordinates
11743     */
11744    public void getLocationInWindow(int[] location) {
11745        if (location == null || location.length < 2) {
11746            throw new IllegalArgumentException("location must be an array of "
11747                    + "two integers");
11748        }
11749
11750        location[0] = mLeft + (int) (mTranslationX + 0.5f);
11751        location[1] = mTop + (int) (mTranslationY + 0.5f);
11752
11753        ViewParent viewParent = mParent;
11754        while (viewParent instanceof View) {
11755            final View view = (View)viewParent;
11756            location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
11757            location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
11758            viewParent = view.mParent;
11759        }
11760
11761        if (viewParent instanceof ViewRootImpl) {
11762            // *cough*
11763            final ViewRootImpl vr = (ViewRootImpl)viewParent;
11764            location[1] -= vr.mCurScrollY;
11765        }
11766    }
11767
11768    /**
11769     * {@hide}
11770     * @param id the id of the view to be found
11771     * @return the view of the specified id, null if cannot be found
11772     */
11773    protected View findViewTraversal(int id) {
11774        if (id == mID) {
11775            return this;
11776        }
11777        return null;
11778    }
11779
11780    /**
11781     * {@hide}
11782     * @param tag the tag of the view to be found
11783     * @return the view of specified tag, null if cannot be found
11784     */
11785    protected View findViewWithTagTraversal(Object tag) {
11786        if (tag != null && tag.equals(mTag)) {
11787            return this;
11788        }
11789        return null;
11790    }
11791
11792    /**
11793     * {@hide}
11794     * @param predicate The predicate to evaluate.
11795     * @param childToSkip If not null, ignores this child during the recursive traversal.
11796     * @return The first view that matches the predicate or null.
11797     */
11798    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
11799        if (predicate.apply(this)) {
11800            return this;
11801        }
11802        return null;
11803    }
11804
11805    /**
11806     * Look for a child view with the given id.  If this view has the given
11807     * id, return this view.
11808     *
11809     * @param id The id to search for.
11810     * @return The view that has the given id in the hierarchy or null
11811     */
11812    public final View findViewById(int id) {
11813        if (id < 0) {
11814            return null;
11815        }
11816        return findViewTraversal(id);
11817    }
11818
11819    /**
11820     * Look for a child view with the given tag.  If this view has the given
11821     * tag, return this view.
11822     *
11823     * @param tag The tag to search for, using "tag.equals(getTag())".
11824     * @return The View that has the given tag in the hierarchy or null
11825     */
11826    public final View findViewWithTag(Object tag) {
11827        if (tag == null) {
11828            return null;
11829        }
11830        return findViewWithTagTraversal(tag);
11831    }
11832
11833    /**
11834     * {@hide}
11835     * Look for a child view that matches the specified predicate.
11836     * If this view matches the predicate, return this view.
11837     *
11838     * @param predicate The predicate to evaluate.
11839     * @return The first view that matches the predicate or null.
11840     */
11841    public final View findViewByPredicate(Predicate<View> predicate) {
11842        return findViewByPredicateTraversal(predicate, null);
11843    }
11844
11845    /**
11846     * {@hide}
11847     * Look for a child view that matches the specified predicate,
11848     * starting with the specified view and its descendents and then
11849     * recusively searching the ancestors and siblings of that view
11850     * until this view is reached.
11851     *
11852     * This method is useful in cases where the predicate does not match
11853     * a single unique view (perhaps multiple views use the same id)
11854     * and we are trying to find the view that is "closest" in scope to the
11855     * starting view.
11856     *
11857     * @param start The view to start from.
11858     * @param predicate The predicate to evaluate.
11859     * @return The first view that matches the predicate or null.
11860     */
11861    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
11862        View childToSkip = null;
11863        for (;;) {
11864            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
11865            if (view != null || start == this) {
11866                return view;
11867            }
11868
11869            ViewParent parent = start.getParent();
11870            if (parent == null || !(parent instanceof View)) {
11871                return null;
11872            }
11873
11874            childToSkip = start;
11875            start = (View) parent;
11876        }
11877    }
11878
11879    /**
11880     * Sets the identifier for this view. The identifier does not have to be
11881     * unique in this view's hierarchy. The identifier should be a positive
11882     * number.
11883     *
11884     * @see #NO_ID
11885     * @see #getId()
11886     * @see #findViewById(int)
11887     *
11888     * @param id a number used to identify the view
11889     *
11890     * @attr ref android.R.styleable#View_id
11891     */
11892    public void setId(int id) {
11893        mID = id;
11894    }
11895
11896    /**
11897     * {@hide}
11898     *
11899     * @param isRoot true if the view belongs to the root namespace, false
11900     *        otherwise
11901     */
11902    public void setIsRootNamespace(boolean isRoot) {
11903        if (isRoot) {
11904            mPrivateFlags |= IS_ROOT_NAMESPACE;
11905        } else {
11906            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
11907        }
11908    }
11909
11910    /**
11911     * {@hide}
11912     *
11913     * @return true if the view belongs to the root namespace, false otherwise
11914     */
11915    public boolean isRootNamespace() {
11916        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
11917    }
11918
11919    /**
11920     * Returns this view's identifier.
11921     *
11922     * @return a positive integer used to identify the view or {@link #NO_ID}
11923     *         if the view has no ID
11924     *
11925     * @see #setId(int)
11926     * @see #findViewById(int)
11927     * @attr ref android.R.styleable#View_id
11928     */
11929    @ViewDebug.CapturedViewProperty
11930    public int getId() {
11931        return mID;
11932    }
11933
11934    /**
11935     * Returns this view's tag.
11936     *
11937     * @return the Object stored in this view as a tag
11938     *
11939     * @see #setTag(Object)
11940     * @see #getTag(int)
11941     */
11942    @ViewDebug.ExportedProperty
11943    public Object getTag() {
11944        return mTag;
11945    }
11946
11947    /**
11948     * Sets the tag associated with this view. A tag can be used to mark
11949     * a view in its hierarchy and does not have to be unique within the
11950     * hierarchy. Tags can also be used to store data within a view without
11951     * resorting to another data structure.
11952     *
11953     * @param tag an Object to tag the view with
11954     *
11955     * @see #getTag()
11956     * @see #setTag(int, Object)
11957     */
11958    public void setTag(final Object tag) {
11959        mTag = tag;
11960    }
11961
11962    /**
11963     * Returns the tag associated with this view and the specified key.
11964     *
11965     * @param key The key identifying the tag
11966     *
11967     * @return the Object stored in this view as a tag
11968     *
11969     * @see #setTag(int, Object)
11970     * @see #getTag()
11971     */
11972    public Object getTag(int key) {
11973        SparseArray<Object> tags = null;
11974        synchronized (sTagsLock) {
11975            if (sTags != null) {
11976                tags = sTags.get(this);
11977            }
11978        }
11979
11980        if (tags != null) return tags.get(key);
11981        return null;
11982    }
11983
11984    /**
11985     * Sets a tag associated with this view and a key. A tag can be used
11986     * to mark a view in its hierarchy and does not have to be unique within
11987     * the hierarchy. Tags can also be used to store data within a view
11988     * without resorting to another data structure.
11989     *
11990     * The specified key should be an id declared in the resources of the
11991     * application to ensure it is unique (see the <a
11992     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
11993     * Keys identified as belonging to
11994     * the Android framework or not associated with any package will cause
11995     * an {@link IllegalArgumentException} to be thrown.
11996     *
11997     * @param key The key identifying the tag
11998     * @param tag An Object to tag the view with
11999     *
12000     * @throws IllegalArgumentException If they specified key is not valid
12001     *
12002     * @see #setTag(Object)
12003     * @see #getTag(int)
12004     */
12005    public void setTag(int key, final Object tag) {
12006        // If the package id is 0x00 or 0x01, it's either an undefined package
12007        // or a framework id
12008        if ((key >>> 24) < 2) {
12009            throw new IllegalArgumentException("The key must be an application-specific "
12010                    + "resource id.");
12011        }
12012
12013        setTagInternal(this, key, tag);
12014    }
12015
12016    /**
12017     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12018     * framework id.
12019     *
12020     * @hide
12021     */
12022    public void setTagInternal(int key, Object tag) {
12023        if ((key >>> 24) != 0x1) {
12024            throw new IllegalArgumentException("The key must be a framework-specific "
12025                    + "resource id.");
12026        }
12027
12028        setTagInternal(this, key, tag);
12029    }
12030
12031    private static void setTagInternal(View view, int key, Object tag) {
12032        SparseArray<Object> tags = null;
12033        synchronized (sTagsLock) {
12034            if (sTags == null) {
12035                sTags = new WeakHashMap<View, SparseArray<Object>>();
12036            } else {
12037                tags = sTags.get(view);
12038            }
12039        }
12040
12041        if (tags == null) {
12042            tags = new SparseArray<Object>(2);
12043            synchronized (sTagsLock) {
12044                sTags.put(view, tags);
12045            }
12046        }
12047
12048        tags.put(key, tag);
12049    }
12050
12051    /**
12052     * @param consistency The type of consistency. See ViewDebug for more information.
12053     *
12054     * @hide
12055     */
12056    protected boolean dispatchConsistencyCheck(int consistency) {
12057        return onConsistencyCheck(consistency);
12058    }
12059
12060    /**
12061     * Method that subclasses should implement to check their consistency. The type of
12062     * consistency check is indicated by the bit field passed as a parameter.
12063     *
12064     * @param consistency The type of consistency. See ViewDebug for more information.
12065     *
12066     * @throws IllegalStateException if the view is in an inconsistent state.
12067     *
12068     * @hide
12069     */
12070    protected boolean onConsistencyCheck(int consistency) {
12071        boolean result = true;
12072
12073        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12074        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12075
12076        if (checkLayout) {
12077            if (getParent() == null) {
12078                result = false;
12079                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12080                        "View " + this + " does not have a parent.");
12081            }
12082
12083            if (mAttachInfo == null) {
12084                result = false;
12085                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12086                        "View " + this + " is not attached to a window.");
12087            }
12088        }
12089
12090        if (checkDrawing) {
12091            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12092            // from their draw() method
12093
12094            if ((mPrivateFlags & DRAWN) != DRAWN &&
12095                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12096                result = false;
12097                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12098                        "View " + this + " was invalidated but its drawing cache is valid.");
12099            }
12100        }
12101
12102        return result;
12103    }
12104
12105    /**
12106     * Prints information about this view in the log output, with the tag
12107     * {@link #VIEW_LOG_TAG}.
12108     *
12109     * @hide
12110     */
12111    public void debug() {
12112        debug(0);
12113    }
12114
12115    /**
12116     * Prints information about this view in the log output, with the tag
12117     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12118     * indentation defined by the <code>depth</code>.
12119     *
12120     * @param depth the indentation level
12121     *
12122     * @hide
12123     */
12124    protected void debug(int depth) {
12125        String output = debugIndent(depth - 1);
12126
12127        output += "+ " + this;
12128        int id = getId();
12129        if (id != -1) {
12130            output += " (id=" + id + ")";
12131        }
12132        Object tag = getTag();
12133        if (tag != null) {
12134            output += " (tag=" + tag + ")";
12135        }
12136        Log.d(VIEW_LOG_TAG, output);
12137
12138        if ((mPrivateFlags & FOCUSED) != 0) {
12139            output = debugIndent(depth) + " FOCUSED";
12140            Log.d(VIEW_LOG_TAG, output);
12141        }
12142
12143        output = debugIndent(depth);
12144        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12145                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12146                + "} ";
12147        Log.d(VIEW_LOG_TAG, output);
12148
12149        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12150                || mPaddingBottom != 0) {
12151            output = debugIndent(depth);
12152            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12153                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12154            Log.d(VIEW_LOG_TAG, output);
12155        }
12156
12157        output = debugIndent(depth);
12158        output += "mMeasureWidth=" + mMeasuredWidth +
12159                " mMeasureHeight=" + mMeasuredHeight;
12160        Log.d(VIEW_LOG_TAG, output);
12161
12162        output = debugIndent(depth);
12163        if (mLayoutParams == null) {
12164            output += "BAD! no layout params";
12165        } else {
12166            output = mLayoutParams.debug(output);
12167        }
12168        Log.d(VIEW_LOG_TAG, output);
12169
12170        output = debugIndent(depth);
12171        output += "flags={";
12172        output += View.printFlags(mViewFlags);
12173        output += "}";
12174        Log.d(VIEW_LOG_TAG, output);
12175
12176        output = debugIndent(depth);
12177        output += "privateFlags={";
12178        output += View.printPrivateFlags(mPrivateFlags);
12179        output += "}";
12180        Log.d(VIEW_LOG_TAG, output);
12181    }
12182
12183    /**
12184     * Creates an string of whitespaces used for indentation.
12185     *
12186     * @param depth the indentation level
12187     * @return a String containing (depth * 2 + 3) * 2 white spaces
12188     *
12189     * @hide
12190     */
12191    protected static String debugIndent(int depth) {
12192        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12193        for (int i = 0; i < (depth * 2) + 3; i++) {
12194            spaces.append(' ').append(' ');
12195        }
12196        return spaces.toString();
12197    }
12198
12199    /**
12200     * <p>Return the offset of the widget's text baseline from the widget's top
12201     * boundary. If this widget does not support baseline alignment, this
12202     * method returns -1. </p>
12203     *
12204     * @return the offset of the baseline within the widget's bounds or -1
12205     *         if baseline alignment is not supported
12206     */
12207    @ViewDebug.ExportedProperty(category = "layout")
12208    public int getBaseline() {
12209        return -1;
12210    }
12211
12212    /**
12213     * Call this when something has changed which has invalidated the
12214     * layout of this view. This will schedule a layout pass of the view
12215     * tree.
12216     */
12217    public void requestLayout() {
12218        if (ViewDebug.TRACE_HIERARCHY) {
12219            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12220        }
12221
12222        mPrivateFlags |= FORCE_LAYOUT;
12223        mPrivateFlags |= INVALIDATED;
12224
12225        if (mParent != null) {
12226            if (mLayoutParams != null) {
12227                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12228            }
12229            if (!mParent.isLayoutRequested()) {
12230                mParent.requestLayout();
12231            }
12232        }
12233    }
12234
12235    /**
12236     * Forces this view to be laid out during the next layout pass.
12237     * This method does not call requestLayout() or forceLayout()
12238     * on the parent.
12239     */
12240    public void forceLayout() {
12241        mPrivateFlags |= FORCE_LAYOUT;
12242        mPrivateFlags |= INVALIDATED;
12243    }
12244
12245    /**
12246     * <p>
12247     * This is called to find out how big a view should be. The parent
12248     * supplies constraint information in the width and height parameters.
12249     * </p>
12250     *
12251     * <p>
12252     * The actual mesurement work of a view is performed in
12253     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12254     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12255     * </p>
12256     *
12257     *
12258     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12259     *        parent
12260     * @param heightMeasureSpec Vertical space requirements as imposed by the
12261     *        parent
12262     *
12263     * @see #onMeasure(int, int)
12264     */
12265    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12266        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12267                widthMeasureSpec != mOldWidthMeasureSpec ||
12268                heightMeasureSpec != mOldHeightMeasureSpec) {
12269
12270            // first clears the measured dimension flag
12271            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12272
12273            if (ViewDebug.TRACE_HIERARCHY) {
12274                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12275            }
12276
12277            // measure ourselves, this should set the measured dimension flag back
12278            onMeasure(widthMeasureSpec, heightMeasureSpec);
12279
12280            // flag not set, setMeasuredDimension() was not invoked, we raise
12281            // an exception to warn the developer
12282            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12283                throw new IllegalStateException("onMeasure() did not set the"
12284                        + " measured dimension by calling"
12285                        + " setMeasuredDimension()");
12286            }
12287
12288            mPrivateFlags |= LAYOUT_REQUIRED;
12289        }
12290
12291        mOldWidthMeasureSpec = widthMeasureSpec;
12292        mOldHeightMeasureSpec = heightMeasureSpec;
12293    }
12294
12295    /**
12296     * <p>
12297     * Measure the view and its content to determine the measured width and the
12298     * measured height. This method is invoked by {@link #measure(int, int)} and
12299     * should be overriden by subclasses to provide accurate and efficient
12300     * measurement of their contents.
12301     * </p>
12302     *
12303     * <p>
12304     * <strong>CONTRACT:</strong> When overriding this method, you
12305     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12306     * measured width and height of this view. Failure to do so will trigger an
12307     * <code>IllegalStateException</code>, thrown by
12308     * {@link #measure(int, int)}. Calling the superclass'
12309     * {@link #onMeasure(int, int)} is a valid use.
12310     * </p>
12311     *
12312     * <p>
12313     * The base class implementation of measure defaults to the background size,
12314     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12315     * override {@link #onMeasure(int, int)} to provide better measurements of
12316     * their content.
12317     * </p>
12318     *
12319     * <p>
12320     * If this method is overridden, it is the subclass's responsibility to make
12321     * sure the measured height and width are at least the view's minimum height
12322     * and width ({@link #getSuggestedMinimumHeight()} and
12323     * {@link #getSuggestedMinimumWidth()}).
12324     * </p>
12325     *
12326     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12327     *                         The requirements are encoded with
12328     *                         {@link android.view.View.MeasureSpec}.
12329     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12330     *                         The requirements are encoded with
12331     *                         {@link android.view.View.MeasureSpec}.
12332     *
12333     * @see #getMeasuredWidth()
12334     * @see #getMeasuredHeight()
12335     * @see #setMeasuredDimension(int, int)
12336     * @see #getSuggestedMinimumHeight()
12337     * @see #getSuggestedMinimumWidth()
12338     * @see android.view.View.MeasureSpec#getMode(int)
12339     * @see android.view.View.MeasureSpec#getSize(int)
12340     */
12341    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12342        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12343                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12344    }
12345
12346    /**
12347     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12348     * measured width and measured height. Failing to do so will trigger an
12349     * exception at measurement time.</p>
12350     *
12351     * @param measuredWidth The measured width of this view.  May be a complex
12352     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12353     * {@link #MEASURED_STATE_TOO_SMALL}.
12354     * @param measuredHeight The measured height of this view.  May be a complex
12355     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12356     * {@link #MEASURED_STATE_TOO_SMALL}.
12357     */
12358    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12359        mMeasuredWidth = measuredWidth;
12360        mMeasuredHeight = measuredHeight;
12361
12362        mPrivateFlags |= MEASURED_DIMENSION_SET;
12363    }
12364
12365    /**
12366     * Merge two states as returned by {@link #getMeasuredState()}.
12367     * @param curState The current state as returned from a view or the result
12368     * of combining multiple views.
12369     * @param newState The new view state to combine.
12370     * @return Returns a new integer reflecting the combination of the two
12371     * states.
12372     */
12373    public static int combineMeasuredStates(int curState, int newState) {
12374        return curState | newState;
12375    }
12376
12377    /**
12378     * Version of {@link #resolveSizeAndState(int, int, int)}
12379     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12380     */
12381    public static int resolveSize(int size, int measureSpec) {
12382        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12383    }
12384
12385    /**
12386     * Utility to reconcile a desired size and state, with constraints imposed
12387     * by a MeasureSpec.  Will take the desired size, unless a different size
12388     * is imposed by the constraints.  The returned value is a compound integer,
12389     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12390     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12391     * size is smaller than the size the view wants to be.
12392     *
12393     * @param size How big the view wants to be
12394     * @param measureSpec Constraints imposed by the parent
12395     * @return Size information bit mask as defined by
12396     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12397     */
12398    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12399        int result = size;
12400        int specMode = MeasureSpec.getMode(measureSpec);
12401        int specSize =  MeasureSpec.getSize(measureSpec);
12402        switch (specMode) {
12403        case MeasureSpec.UNSPECIFIED:
12404            result = size;
12405            break;
12406        case MeasureSpec.AT_MOST:
12407            if (specSize < size) {
12408                result = specSize | MEASURED_STATE_TOO_SMALL;
12409            } else {
12410                result = size;
12411            }
12412            break;
12413        case MeasureSpec.EXACTLY:
12414            result = specSize;
12415            break;
12416        }
12417        return result | (childMeasuredState&MEASURED_STATE_MASK);
12418    }
12419
12420    /**
12421     * Utility to return a default size. Uses the supplied size if the
12422     * MeasureSpec imposed no constraints. Will get larger if allowed
12423     * by the MeasureSpec.
12424     *
12425     * @param size Default size for this view
12426     * @param measureSpec Constraints imposed by the parent
12427     * @return The size this view should be.
12428     */
12429    public static int getDefaultSize(int size, int measureSpec) {
12430        int result = size;
12431        int specMode = MeasureSpec.getMode(measureSpec);
12432        int specSize = MeasureSpec.getSize(measureSpec);
12433
12434        switch (specMode) {
12435        case MeasureSpec.UNSPECIFIED:
12436            result = size;
12437            break;
12438        case MeasureSpec.AT_MOST:
12439        case MeasureSpec.EXACTLY:
12440            result = specSize;
12441            break;
12442        }
12443        return result;
12444    }
12445
12446    /**
12447     * Returns the suggested minimum height that the view should use. This
12448     * returns the maximum of the view's minimum height
12449     * and the background's minimum height
12450     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12451     * <p>
12452     * When being used in {@link #onMeasure(int, int)}, the caller should still
12453     * ensure the returned height is within the requirements of the parent.
12454     *
12455     * @return The suggested minimum height of the view.
12456     */
12457    protected int getSuggestedMinimumHeight() {
12458        int suggestedMinHeight = mMinHeight;
12459
12460        if (mBGDrawable != null) {
12461            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12462            if (suggestedMinHeight < bgMinHeight) {
12463                suggestedMinHeight = bgMinHeight;
12464            }
12465        }
12466
12467        return suggestedMinHeight;
12468    }
12469
12470    /**
12471     * Returns the suggested minimum width that the view should use. This
12472     * returns the maximum of the view's minimum width)
12473     * and the background's minimum width
12474     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12475     * <p>
12476     * When being used in {@link #onMeasure(int, int)}, the caller should still
12477     * ensure the returned width is within the requirements of the parent.
12478     *
12479     * @return The suggested minimum width of the view.
12480     */
12481    protected int getSuggestedMinimumWidth() {
12482        int suggestedMinWidth = mMinWidth;
12483
12484        if (mBGDrawable != null) {
12485            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12486            if (suggestedMinWidth < bgMinWidth) {
12487                suggestedMinWidth = bgMinWidth;
12488            }
12489        }
12490
12491        return suggestedMinWidth;
12492    }
12493
12494    /**
12495     * Sets the minimum height of the view. It is not guaranteed the view will
12496     * be able to achieve this minimum height (for example, if its parent layout
12497     * constrains it with less available height).
12498     *
12499     * @param minHeight The minimum height the view will try to be.
12500     */
12501    public void setMinimumHeight(int minHeight) {
12502        mMinHeight = minHeight;
12503    }
12504
12505    /**
12506     * Sets the minimum width of the view. It is not guaranteed the view will
12507     * be able to achieve this minimum width (for example, if its parent layout
12508     * constrains it with less available width).
12509     *
12510     * @param minWidth The minimum width the view will try to be.
12511     */
12512    public void setMinimumWidth(int minWidth) {
12513        mMinWidth = minWidth;
12514    }
12515
12516    /**
12517     * Get the animation currently associated with this view.
12518     *
12519     * @return The animation that is currently playing or
12520     *         scheduled to play for this view.
12521     */
12522    public Animation getAnimation() {
12523        return mCurrentAnimation;
12524    }
12525
12526    /**
12527     * Start the specified animation now.
12528     *
12529     * @param animation the animation to start now
12530     */
12531    public void startAnimation(Animation animation) {
12532        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12533        setAnimation(animation);
12534        invalidateParentCaches();
12535        invalidate(true);
12536    }
12537
12538    /**
12539     * Cancels any animations for this view.
12540     */
12541    public void clearAnimation() {
12542        if (mCurrentAnimation != null) {
12543            mCurrentAnimation.detach();
12544        }
12545        mCurrentAnimation = null;
12546        invalidateParentIfNeeded();
12547    }
12548
12549    /**
12550     * Sets the next animation to play for this view.
12551     * If you want the animation to play immediately, use
12552     * startAnimation. This method provides allows fine-grained
12553     * control over the start time and invalidation, but you
12554     * must make sure that 1) the animation has a start time set, and
12555     * 2) the view will be invalidated when the animation is supposed to
12556     * start.
12557     *
12558     * @param animation The next animation, or null.
12559     */
12560    public void setAnimation(Animation animation) {
12561        mCurrentAnimation = animation;
12562        if (animation != null) {
12563            animation.reset();
12564        }
12565    }
12566
12567    /**
12568     * Invoked by a parent ViewGroup to notify the start of the animation
12569     * currently associated with this view. If you override this method,
12570     * always call super.onAnimationStart();
12571     *
12572     * @see #setAnimation(android.view.animation.Animation)
12573     * @see #getAnimation()
12574     */
12575    protected void onAnimationStart() {
12576        mPrivateFlags |= ANIMATION_STARTED;
12577    }
12578
12579    /**
12580     * Invoked by a parent ViewGroup to notify the end of the animation
12581     * currently associated with this view. If you override this method,
12582     * always call super.onAnimationEnd();
12583     *
12584     * @see #setAnimation(android.view.animation.Animation)
12585     * @see #getAnimation()
12586     */
12587    protected void onAnimationEnd() {
12588        mPrivateFlags &= ~ANIMATION_STARTED;
12589    }
12590
12591    /**
12592     * Invoked if there is a Transform that involves alpha. Subclass that can
12593     * draw themselves with the specified alpha should return true, and then
12594     * respect that alpha when their onDraw() is called. If this returns false
12595     * then the view may be redirected to draw into an offscreen buffer to
12596     * fulfill the request, which will look fine, but may be slower than if the
12597     * subclass handles it internally. The default implementation returns false.
12598     *
12599     * @param alpha The alpha (0..255) to apply to the view's drawing
12600     * @return true if the view can draw with the specified alpha.
12601     */
12602    protected boolean onSetAlpha(int alpha) {
12603        return false;
12604    }
12605
12606    /**
12607     * This is used by the RootView to perform an optimization when
12608     * the view hierarchy contains one or several SurfaceView.
12609     * SurfaceView is always considered transparent, but its children are not,
12610     * therefore all View objects remove themselves from the global transparent
12611     * region (passed as a parameter to this function).
12612     *
12613     * @param region The transparent region for this ViewAncestor (window).
12614     *
12615     * @return Returns true if the effective visibility of the view at this
12616     * point is opaque, regardless of the transparent region; returns false
12617     * if it is possible for underlying windows to be seen behind the view.
12618     *
12619     * {@hide}
12620     */
12621    public boolean gatherTransparentRegion(Region region) {
12622        final AttachInfo attachInfo = mAttachInfo;
12623        if (region != null && attachInfo != null) {
12624            final int pflags = mPrivateFlags;
12625            if ((pflags & SKIP_DRAW) == 0) {
12626                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
12627                // remove it from the transparent region.
12628                final int[] location = attachInfo.mTransparentLocation;
12629                getLocationInWindow(location);
12630                region.op(location[0], location[1], location[0] + mRight - mLeft,
12631                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
12632            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
12633                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
12634                // exists, so we remove the background drawable's non-transparent
12635                // parts from this transparent region.
12636                applyDrawableToTransparentRegion(mBGDrawable, region);
12637            }
12638        }
12639        return true;
12640    }
12641
12642    /**
12643     * Play a sound effect for this view.
12644     *
12645     * <p>The framework will play sound effects for some built in actions, such as
12646     * clicking, but you may wish to play these effects in your widget,
12647     * for instance, for internal navigation.
12648     *
12649     * <p>The sound effect will only be played if sound effects are enabled by the user, and
12650     * {@link #isSoundEffectsEnabled()} is true.
12651     *
12652     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
12653     */
12654    public void playSoundEffect(int soundConstant) {
12655        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
12656            return;
12657        }
12658        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
12659    }
12660
12661    /**
12662     * BZZZTT!!1!
12663     *
12664     * <p>Provide haptic feedback to the user for this view.
12665     *
12666     * <p>The framework will provide haptic feedback for some built in actions,
12667     * such as long presses, but you may wish to provide feedback for your
12668     * own widget.
12669     *
12670     * <p>The feedback will only be performed if
12671     * {@link #isHapticFeedbackEnabled()} is true.
12672     *
12673     * @param feedbackConstant One of the constants defined in
12674     * {@link HapticFeedbackConstants}
12675     */
12676    public boolean performHapticFeedback(int feedbackConstant) {
12677        return performHapticFeedback(feedbackConstant, 0);
12678    }
12679
12680    /**
12681     * BZZZTT!!1!
12682     *
12683     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
12684     *
12685     * @param feedbackConstant One of the constants defined in
12686     * {@link HapticFeedbackConstants}
12687     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
12688     */
12689    public boolean performHapticFeedback(int feedbackConstant, int flags) {
12690        if (mAttachInfo == null) {
12691            return false;
12692        }
12693        //noinspection SimplifiableIfStatement
12694        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
12695                && !isHapticFeedbackEnabled()) {
12696            return false;
12697        }
12698        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
12699                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
12700    }
12701
12702    /**
12703     * Request that the visibility of the status bar be changed.
12704     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12705     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12706     *
12707     * This value will be re-applied immediately, even if the flags have not changed, so a view may
12708     * easily reassert a particular SystemUiVisibility condition even if the system UI itself has
12709     * since countermanded the original request.
12710     */
12711    public void setSystemUiVisibility(int visibility) {
12712        mSystemUiVisibility = visibility;
12713        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12714            mParent.recomputeViewAttributes(this);
12715        }
12716    }
12717
12718    /**
12719     * Returns the status bar visibility that this view has requested.
12720     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12721     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12722     */
12723    public int getSystemUiVisibility() {
12724        return mSystemUiVisibility;
12725    }
12726
12727    /**
12728     * Set a listener to receive callbacks when the visibility of the system bar changes.
12729     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
12730     */
12731    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
12732        mOnSystemUiVisibilityChangeListener = l;
12733        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12734            mParent.recomputeViewAttributes(this);
12735        }
12736    }
12737
12738    /**
12739     */
12740    public void dispatchSystemUiVisibilityChanged(int visibility) {
12741        if (mOnSystemUiVisibilityChangeListener != null) {
12742            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
12743                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
12744        }
12745    }
12746
12747    /**
12748     * Creates an image that the system displays during the drag and drop
12749     * operation. This is called a &quot;drag shadow&quot;. The default implementation
12750     * for a DragShadowBuilder based on a View returns an image that has exactly the same
12751     * appearance as the given View. The default also positions the center of the drag shadow
12752     * directly under the touch point. If no View is provided (the constructor with no parameters
12753     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
12754     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
12755     * default is an invisible drag shadow.
12756     * <p>
12757     * You are not required to use the View you provide to the constructor as the basis of the
12758     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
12759     * anything you want as the drag shadow.
12760     * </p>
12761     * <p>
12762     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
12763     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
12764     *  size and position of the drag shadow. It uses this data to construct a
12765     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
12766     *  so that your application can draw the shadow image in the Canvas.
12767     * </p>
12768     */
12769    public static class DragShadowBuilder {
12770        private final WeakReference<View> mView;
12771
12772        /**
12773         * Constructs a shadow image builder based on a View. By default, the resulting drag
12774         * shadow will have the same appearance and dimensions as the View, with the touch point
12775         * over the center of the View.
12776         * @param view A View. Any View in scope can be used.
12777         */
12778        public DragShadowBuilder(View view) {
12779            mView = new WeakReference<View>(view);
12780        }
12781
12782        /**
12783         * Construct a shadow builder object with no associated View.  This
12784         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
12785         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
12786         * to supply the drag shadow's dimensions and appearance without
12787         * reference to any View object. If they are not overridden, then the result is an
12788         * invisible drag shadow.
12789         */
12790        public DragShadowBuilder() {
12791            mView = new WeakReference<View>(null);
12792        }
12793
12794        /**
12795         * Returns the View object that had been passed to the
12796         * {@link #View.DragShadowBuilder(View)}
12797         * constructor.  If that View parameter was {@code null} or if the
12798         * {@link #View.DragShadowBuilder()}
12799         * constructor was used to instantiate the builder object, this method will return
12800         * null.
12801         *
12802         * @return The View object associate with this builder object.
12803         */
12804        @SuppressWarnings({"JavadocReference"})
12805        final public View getView() {
12806            return mView.get();
12807        }
12808
12809        /**
12810         * Provides the metrics for the shadow image. These include the dimensions of
12811         * the shadow image, and the point within that shadow that should
12812         * be centered under the touch location while dragging.
12813         * <p>
12814         * The default implementation sets the dimensions of the shadow to be the
12815         * same as the dimensions of the View itself and centers the shadow under
12816         * the touch point.
12817         * </p>
12818         *
12819         * @param shadowSize A {@link android.graphics.Point} containing the width and height
12820         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
12821         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
12822         * image.
12823         *
12824         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
12825         * shadow image that should be underneath the touch point during the drag and drop
12826         * operation. Your application must set {@link android.graphics.Point#x} to the
12827         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
12828         */
12829        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
12830            final View view = mView.get();
12831            if (view != null) {
12832                shadowSize.set(view.getWidth(), view.getHeight());
12833                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
12834            } else {
12835                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
12836            }
12837        }
12838
12839        /**
12840         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
12841         * based on the dimensions it received from the
12842         * {@link #onProvideShadowMetrics(Point, Point)} callback.
12843         *
12844         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
12845         */
12846        public void onDrawShadow(Canvas canvas) {
12847            final View view = mView.get();
12848            if (view != null) {
12849                view.draw(canvas);
12850            } else {
12851                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
12852            }
12853        }
12854    }
12855
12856    /**
12857     * Starts a drag and drop operation. When your application calls this method, it passes a
12858     * {@link android.view.View.DragShadowBuilder} object to the system. The
12859     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
12860     * to get metrics for the drag shadow, and then calls the object's
12861     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
12862     * <p>
12863     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
12864     *  drag events to all the View objects in your application that are currently visible. It does
12865     *  this either by calling the View object's drag listener (an implementation of
12866     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
12867     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
12868     *  Both are passed a {@link android.view.DragEvent} object that has a
12869     *  {@link android.view.DragEvent#getAction()} value of
12870     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
12871     * </p>
12872     * <p>
12873     * Your application can invoke startDrag() on any attached View object. The View object does not
12874     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
12875     * be related to the View the user selected for dragging.
12876     * </p>
12877     * @param data A {@link android.content.ClipData} object pointing to the data to be
12878     * transferred by the drag and drop operation.
12879     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
12880     * drag shadow.
12881     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
12882     * drop operation. This Object is put into every DragEvent object sent by the system during the
12883     * current drag.
12884     * <p>
12885     * myLocalState is a lightweight mechanism for the sending information from the dragged View
12886     * to the target Views. For example, it can contain flags that differentiate between a
12887     * a copy operation and a move operation.
12888     * </p>
12889     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
12890     * so the parameter should be set to 0.
12891     * @return {@code true} if the method completes successfully, or
12892     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
12893     * do a drag, and so no drag operation is in progress.
12894     */
12895    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
12896            Object myLocalState, int flags) {
12897        if (ViewDebug.DEBUG_DRAG) {
12898            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
12899        }
12900        boolean okay = false;
12901
12902        Point shadowSize = new Point();
12903        Point shadowTouchPoint = new Point();
12904        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
12905
12906        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
12907                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
12908            throw new IllegalStateException("Drag shadow dimensions must not be negative");
12909        }
12910
12911        if (ViewDebug.DEBUG_DRAG) {
12912            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
12913                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
12914        }
12915        Surface surface = new Surface();
12916        try {
12917            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
12918                    flags, shadowSize.x, shadowSize.y, surface);
12919            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
12920                    + " surface=" + surface);
12921            if (token != null) {
12922                Canvas canvas = surface.lockCanvas(null);
12923                try {
12924                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
12925                    shadowBuilder.onDrawShadow(canvas);
12926                } finally {
12927                    surface.unlockCanvasAndPost(canvas);
12928                }
12929
12930                final ViewRootImpl root = getViewRootImpl();
12931
12932                // Cache the local state object for delivery with DragEvents
12933                root.setLocalDragState(myLocalState);
12934
12935                // repurpose 'shadowSize' for the last touch point
12936                root.getLastTouchPoint(shadowSize);
12937
12938                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
12939                        shadowSize.x, shadowSize.y,
12940                        shadowTouchPoint.x, shadowTouchPoint.y, data);
12941                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
12942            }
12943        } catch (Exception e) {
12944            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
12945            surface.destroy();
12946        }
12947
12948        return okay;
12949    }
12950
12951    /**
12952     * Handles drag events sent by the system following a call to
12953     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
12954     *<p>
12955     * When the system calls this method, it passes a
12956     * {@link android.view.DragEvent} object. A call to
12957     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
12958     * in DragEvent. The method uses these to determine what is happening in the drag and drop
12959     * operation.
12960     * @param event The {@link android.view.DragEvent} sent by the system.
12961     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
12962     * in DragEvent, indicating the type of drag event represented by this object.
12963     * @return {@code true} if the method was successful, otherwise {@code false}.
12964     * <p>
12965     *  The method should return {@code true} in response to an action type of
12966     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
12967     *  operation.
12968     * </p>
12969     * <p>
12970     *  The method should also return {@code true} in response to an action type of
12971     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
12972     *  {@code false} if it didn't.
12973     * </p>
12974     */
12975    public boolean onDragEvent(DragEvent event) {
12976        return false;
12977    }
12978
12979    /**
12980     * Detects if this View is enabled and has a drag event listener.
12981     * If both are true, then it calls the drag event listener with the
12982     * {@link android.view.DragEvent} it received. If the drag event listener returns
12983     * {@code true}, then dispatchDragEvent() returns {@code true}.
12984     * <p>
12985     * For all other cases, the method calls the
12986     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
12987     * method and returns its result.
12988     * </p>
12989     * <p>
12990     * This ensures that a drag event is always consumed, even if the View does not have a drag
12991     * event listener. However, if the View has a listener and the listener returns true, then
12992     * onDragEvent() is not called.
12993     * </p>
12994     */
12995    public boolean dispatchDragEvent(DragEvent event) {
12996        //noinspection SimplifiableIfStatement
12997        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
12998                && mOnDragListener.onDrag(this, event)) {
12999            return true;
13000        }
13001        return onDragEvent(event);
13002    }
13003
13004    boolean canAcceptDrag() {
13005        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13006    }
13007
13008    /**
13009     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13010     * it is ever exposed at all.
13011     * @hide
13012     */
13013    public void onCloseSystemDialogs(String reason) {
13014    }
13015
13016    /**
13017     * Given a Drawable whose bounds have been set to draw into this view,
13018     * update a Region being computed for
13019     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13020     * that any non-transparent parts of the Drawable are removed from the
13021     * given transparent region.
13022     *
13023     * @param dr The Drawable whose transparency is to be applied to the region.
13024     * @param region A Region holding the current transparency information,
13025     * where any parts of the region that are set are considered to be
13026     * transparent.  On return, this region will be modified to have the
13027     * transparency information reduced by the corresponding parts of the
13028     * Drawable that are not transparent.
13029     * {@hide}
13030     */
13031    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13032        if (DBG) {
13033            Log.i("View", "Getting transparent region for: " + this);
13034        }
13035        final Region r = dr.getTransparentRegion();
13036        final Rect db = dr.getBounds();
13037        final AttachInfo attachInfo = mAttachInfo;
13038        if (r != null && attachInfo != null) {
13039            final int w = getRight()-getLeft();
13040            final int h = getBottom()-getTop();
13041            if (db.left > 0) {
13042                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13043                r.op(0, 0, db.left, h, Region.Op.UNION);
13044            }
13045            if (db.right < w) {
13046                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13047                r.op(db.right, 0, w, h, Region.Op.UNION);
13048            }
13049            if (db.top > 0) {
13050                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13051                r.op(0, 0, w, db.top, Region.Op.UNION);
13052            }
13053            if (db.bottom < h) {
13054                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13055                r.op(0, db.bottom, w, h, Region.Op.UNION);
13056            }
13057            final int[] location = attachInfo.mTransparentLocation;
13058            getLocationInWindow(location);
13059            r.translate(location[0], location[1]);
13060            region.op(r, Region.Op.INTERSECT);
13061        } else {
13062            region.op(db, Region.Op.DIFFERENCE);
13063        }
13064    }
13065
13066    private void checkForLongClick(int delayOffset) {
13067        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13068            mHasPerformedLongPress = false;
13069
13070            if (mPendingCheckForLongPress == null) {
13071                mPendingCheckForLongPress = new CheckForLongPress();
13072            }
13073            mPendingCheckForLongPress.rememberWindowAttachCount();
13074            postDelayed(mPendingCheckForLongPress,
13075                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13076        }
13077    }
13078
13079    /**
13080     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13081     * LayoutInflater} class, which provides a full range of options for view inflation.
13082     *
13083     * @param context The Context object for your activity or application.
13084     * @param resource The resource ID to inflate
13085     * @param root A view group that will be the parent.  Used to properly inflate the
13086     * layout_* parameters.
13087     * @see LayoutInflater
13088     */
13089    public static View inflate(Context context, int resource, ViewGroup root) {
13090        LayoutInflater factory = LayoutInflater.from(context);
13091        return factory.inflate(resource, root);
13092    }
13093
13094    /**
13095     * Scroll the view with standard behavior for scrolling beyond the normal
13096     * content boundaries. Views that call this method should override
13097     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13098     * results of an over-scroll operation.
13099     *
13100     * Views can use this method to handle any touch or fling-based scrolling.
13101     *
13102     * @param deltaX Change in X in pixels
13103     * @param deltaY Change in Y in pixels
13104     * @param scrollX Current X scroll value in pixels before applying deltaX
13105     * @param scrollY Current Y scroll value in pixels before applying deltaY
13106     * @param scrollRangeX Maximum content scroll range along the X axis
13107     * @param scrollRangeY Maximum content scroll range along the Y axis
13108     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13109     *          along the X axis.
13110     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13111     *          along the Y axis.
13112     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13113     * @return true if scrolling was clamped to an over-scroll boundary along either
13114     *          axis, false otherwise.
13115     */
13116    @SuppressWarnings({"UnusedParameters"})
13117    protected boolean overScrollBy(int deltaX, int deltaY,
13118            int scrollX, int scrollY,
13119            int scrollRangeX, int scrollRangeY,
13120            int maxOverScrollX, int maxOverScrollY,
13121            boolean isTouchEvent) {
13122        final int overScrollMode = mOverScrollMode;
13123        final boolean canScrollHorizontal =
13124                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13125        final boolean canScrollVertical =
13126                computeVerticalScrollRange() > computeVerticalScrollExtent();
13127        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13128                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13129        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13130                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13131
13132        int newScrollX = scrollX + deltaX;
13133        if (!overScrollHorizontal) {
13134            maxOverScrollX = 0;
13135        }
13136
13137        int newScrollY = scrollY + deltaY;
13138        if (!overScrollVertical) {
13139            maxOverScrollY = 0;
13140        }
13141
13142        // Clamp values if at the limits and record
13143        final int left = -maxOverScrollX;
13144        final int right = maxOverScrollX + scrollRangeX;
13145        final int top = -maxOverScrollY;
13146        final int bottom = maxOverScrollY + scrollRangeY;
13147
13148        boolean clampedX = false;
13149        if (newScrollX > right) {
13150            newScrollX = right;
13151            clampedX = true;
13152        } else if (newScrollX < left) {
13153            newScrollX = left;
13154            clampedX = true;
13155        }
13156
13157        boolean clampedY = false;
13158        if (newScrollY > bottom) {
13159            newScrollY = bottom;
13160            clampedY = true;
13161        } else if (newScrollY < top) {
13162            newScrollY = top;
13163            clampedY = true;
13164        }
13165
13166        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13167
13168        return clampedX || clampedY;
13169    }
13170
13171    /**
13172     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13173     * respond to the results of an over-scroll operation.
13174     *
13175     * @param scrollX New X scroll value in pixels
13176     * @param scrollY New Y scroll value in pixels
13177     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13178     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13179     */
13180    protected void onOverScrolled(int scrollX, int scrollY,
13181            boolean clampedX, boolean clampedY) {
13182        // Intentionally empty.
13183    }
13184
13185    /**
13186     * Returns the over-scroll mode for this view. The result will be
13187     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13188     * (allow over-scrolling only if the view content is larger than the container),
13189     * or {@link #OVER_SCROLL_NEVER}.
13190     *
13191     * @return This view's over-scroll mode.
13192     */
13193    public int getOverScrollMode() {
13194        return mOverScrollMode;
13195    }
13196
13197    /**
13198     * Set the over-scroll mode for this view. Valid over-scroll modes are
13199     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13200     * (allow over-scrolling only if the view content is larger than the container),
13201     * or {@link #OVER_SCROLL_NEVER}.
13202     *
13203     * Setting the over-scroll mode of a view will have an effect only if the
13204     * view is capable of scrolling.
13205     *
13206     * @param overScrollMode The new over-scroll mode for this view.
13207     */
13208    public void setOverScrollMode(int overScrollMode) {
13209        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13210                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13211                overScrollMode != OVER_SCROLL_NEVER) {
13212            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13213        }
13214        mOverScrollMode = overScrollMode;
13215    }
13216
13217    /**
13218     * Gets a scale factor that determines the distance the view should scroll
13219     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13220     * @return The vertical scroll scale factor.
13221     * @hide
13222     */
13223    protected float getVerticalScrollFactor() {
13224        if (mVerticalScrollFactor == 0) {
13225            TypedValue outValue = new TypedValue();
13226            if (!mContext.getTheme().resolveAttribute(
13227                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13228                throw new IllegalStateException(
13229                        "Expected theme to define listPreferredItemHeight.");
13230            }
13231            mVerticalScrollFactor = outValue.getDimension(
13232                    mContext.getResources().getDisplayMetrics());
13233        }
13234        return mVerticalScrollFactor;
13235    }
13236
13237    /**
13238     * Gets a scale factor that determines the distance the view should scroll
13239     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13240     * @return The horizontal scroll scale factor.
13241     * @hide
13242     */
13243    protected float getHorizontalScrollFactor() {
13244        // TODO: Should use something else.
13245        return getVerticalScrollFactor();
13246    }
13247
13248    /**
13249     * Return the value specifying the text direction or policy that was set with
13250     * {@link #setTextDirection(int)}.
13251     *
13252     * @return the defined text direction. It can be one of:
13253     *
13254     * {@link #TEXT_DIRECTION_INHERIT},
13255     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13256     * {@link #TEXT_DIRECTION_ANY_RTL},
13257     * {@link #TEXT_DIRECTION_LTR},
13258     * {@link #TEXT_DIRECTION_RTL},
13259     *
13260     * @hide
13261     */
13262    public int getTextDirection() {
13263        return mTextDirection;
13264    }
13265
13266    /**
13267     * Set the text direction.
13268     *
13269     * @param textDirection the direction to set. Should be one of:
13270     *
13271     * {@link #TEXT_DIRECTION_INHERIT},
13272     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13273     * {@link #TEXT_DIRECTION_ANY_RTL},
13274     * {@link #TEXT_DIRECTION_LTR},
13275     * {@link #TEXT_DIRECTION_RTL},
13276     *
13277     * @hide
13278     */
13279    public void setTextDirection(int textDirection) {
13280        if (textDirection != mTextDirection) {
13281            mTextDirection = textDirection;
13282            resetResolvedTextDirection();
13283            requestLayout();
13284        }
13285    }
13286
13287    /**
13288     * Return the resolved text direction.
13289     *
13290     * @return the resolved text direction. Return one of:
13291     *
13292     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13293     * {@link #TEXT_DIRECTION_ANY_RTL},
13294     * {@link #TEXT_DIRECTION_LTR},
13295     * {@link #TEXT_DIRECTION_RTL},
13296     *
13297     * @hide
13298     */
13299    public int getResolvedTextDirection() {
13300        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13301            resolveTextDirection();
13302        }
13303        return mResolvedTextDirection;
13304    }
13305
13306    /**
13307     * Resolve the text direction.
13308     *
13309     * @hide
13310     */
13311    protected void resolveTextDirection() {
13312        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13313            mResolvedTextDirection = mTextDirection;
13314            return;
13315        }
13316        if (mParent != null && mParent instanceof ViewGroup) {
13317            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13318            return;
13319        }
13320        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13321    }
13322
13323    /**
13324     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13325     *
13326     * @hide
13327     */
13328    protected void resetResolvedTextDirection() {
13329        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13330    }
13331
13332    //
13333    // Properties
13334    //
13335    /**
13336     * A Property wrapper around the <code>alpha</code> functionality handled by the
13337     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13338     */
13339    public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13340        @Override
13341        public void setValue(View object, float value) {
13342            object.setAlpha(value);
13343        }
13344
13345        @Override
13346        public Float get(View object) {
13347            return object.getAlpha();
13348        }
13349    };
13350
13351    /**
13352     * A Property wrapper around the <code>translationX</code> functionality handled by the
13353     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13354     */
13355    public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13356        @Override
13357        public void setValue(View object, float value) {
13358            object.setTranslationX(value);
13359        }
13360
13361                @Override
13362        public Float get(View object) {
13363            return object.getTranslationX();
13364        }
13365    };
13366
13367    /**
13368     * A Property wrapper around the <code>translationY</code> functionality handled by the
13369     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13370     */
13371    public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13372        @Override
13373        public void setValue(View object, float value) {
13374            object.setTranslationY(value);
13375        }
13376
13377        @Override
13378        public Float get(View object) {
13379            return object.getTranslationY();
13380        }
13381    };
13382
13383    /**
13384     * A Property wrapper around the <code>x</code> functionality handled by the
13385     * {@link View#setX(float)} and {@link View#getX()} methods.
13386     */
13387    public static Property<View, Float> X = new FloatProperty<View>("x") {
13388        @Override
13389        public void setValue(View object, float value) {
13390            object.setX(value);
13391        }
13392
13393        @Override
13394        public Float get(View object) {
13395            return object.getX();
13396        }
13397    };
13398
13399    /**
13400     * A Property wrapper around the <code>y</code> functionality handled by the
13401     * {@link View#setY(float)} and {@link View#getY()} methods.
13402     */
13403    public static Property<View, Float> Y = new FloatProperty<View>("y") {
13404        @Override
13405        public void setValue(View object, float value) {
13406            object.setY(value);
13407        }
13408
13409        @Override
13410        public Float get(View object) {
13411            return object.getY();
13412        }
13413    };
13414
13415    /**
13416     * A Property wrapper around the <code>rotation</code> functionality handled by the
13417     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13418     */
13419    public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13420        @Override
13421        public void setValue(View object, float value) {
13422            object.setRotation(value);
13423        }
13424
13425        @Override
13426        public Float get(View object) {
13427            return object.getRotation();
13428        }
13429    };
13430
13431    /**
13432     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13433     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13434     */
13435    public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13436        @Override
13437        public void setValue(View object, float value) {
13438            object.setRotationX(value);
13439        }
13440
13441        @Override
13442        public Float get(View object) {
13443            return object.getRotationX();
13444        }
13445    };
13446
13447    /**
13448     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13449     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13450     */
13451    public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13452        @Override
13453        public void setValue(View object, float value) {
13454            object.setRotationY(value);
13455        }
13456
13457        @Override
13458        public Float get(View object) {
13459            return object.getRotationY();
13460        }
13461    };
13462
13463    /**
13464     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13465     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13466     */
13467    public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13468        @Override
13469        public void setValue(View object, float value) {
13470            object.setScaleX(value);
13471        }
13472
13473        @Override
13474        public Float get(View object) {
13475            return object.getScaleX();
13476        }
13477    };
13478
13479    /**
13480     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13481     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13482     */
13483    public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13484        @Override
13485        public void setValue(View object, float value) {
13486            object.setScaleY(value);
13487        }
13488
13489        @Override
13490        public Float get(View object) {
13491            return object.getScaleY();
13492        }
13493    };
13494
13495    /**
13496     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13497     * Each MeasureSpec represents a requirement for either the width or the height.
13498     * A MeasureSpec is comprised of a size and a mode. There are three possible
13499     * modes:
13500     * <dl>
13501     * <dt>UNSPECIFIED</dt>
13502     * <dd>
13503     * The parent has not imposed any constraint on the child. It can be whatever size
13504     * it wants.
13505     * </dd>
13506     *
13507     * <dt>EXACTLY</dt>
13508     * <dd>
13509     * The parent has determined an exact size for the child. The child is going to be
13510     * given those bounds regardless of how big it wants to be.
13511     * </dd>
13512     *
13513     * <dt>AT_MOST</dt>
13514     * <dd>
13515     * The child can be as large as it wants up to the specified size.
13516     * </dd>
13517     * </dl>
13518     *
13519     * MeasureSpecs are implemented as ints to reduce object allocation. This class
13520     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
13521     */
13522    public static class MeasureSpec {
13523        private static final int MODE_SHIFT = 30;
13524        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
13525
13526        /**
13527         * Measure specification mode: The parent has not imposed any constraint
13528         * on the child. It can be whatever size it wants.
13529         */
13530        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
13531
13532        /**
13533         * Measure specification mode: The parent has determined an exact size
13534         * for the child. The child is going to be given those bounds regardless
13535         * of how big it wants to be.
13536         */
13537        public static final int EXACTLY     = 1 << MODE_SHIFT;
13538
13539        /**
13540         * Measure specification mode: The child can be as large as it wants up
13541         * to the specified size.
13542         */
13543        public static final int AT_MOST     = 2 << MODE_SHIFT;
13544
13545        /**
13546         * Creates a measure specification based on the supplied size and mode.
13547         *
13548         * The mode must always be one of the following:
13549         * <ul>
13550         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
13551         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
13552         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
13553         * </ul>
13554         *
13555         * @param size the size of the measure specification
13556         * @param mode the mode of the measure specification
13557         * @return the measure specification based on size and mode
13558         */
13559        public static int makeMeasureSpec(int size, int mode) {
13560            return size + mode;
13561        }
13562
13563        /**
13564         * Extracts the mode from the supplied measure specification.
13565         *
13566         * @param measureSpec the measure specification to extract the mode from
13567         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
13568         *         {@link android.view.View.MeasureSpec#AT_MOST} or
13569         *         {@link android.view.View.MeasureSpec#EXACTLY}
13570         */
13571        public static int getMode(int measureSpec) {
13572            return (measureSpec & MODE_MASK);
13573        }
13574
13575        /**
13576         * Extracts the size from the supplied measure specification.
13577         *
13578         * @param measureSpec the measure specification to extract the size from
13579         * @return the size in pixels defined in the supplied measure specification
13580         */
13581        public static int getSize(int measureSpec) {
13582            return (measureSpec & ~MODE_MASK);
13583        }
13584
13585        /**
13586         * Returns a String representation of the specified measure
13587         * specification.
13588         *
13589         * @param measureSpec the measure specification to convert to a String
13590         * @return a String with the following format: "MeasureSpec: MODE SIZE"
13591         */
13592        public static String toString(int measureSpec) {
13593            int mode = getMode(measureSpec);
13594            int size = getSize(measureSpec);
13595
13596            StringBuilder sb = new StringBuilder("MeasureSpec: ");
13597
13598            if (mode == UNSPECIFIED)
13599                sb.append("UNSPECIFIED ");
13600            else if (mode == EXACTLY)
13601                sb.append("EXACTLY ");
13602            else if (mode == AT_MOST)
13603                sb.append("AT_MOST ");
13604            else
13605                sb.append(mode).append(" ");
13606
13607            sb.append(size);
13608            return sb.toString();
13609        }
13610    }
13611
13612    class CheckForLongPress implements Runnable {
13613
13614        private int mOriginalWindowAttachCount;
13615
13616        public void run() {
13617            if (isPressed() && (mParent != null)
13618                    && mOriginalWindowAttachCount == mWindowAttachCount) {
13619                if (performLongClick()) {
13620                    mHasPerformedLongPress = true;
13621                }
13622            }
13623        }
13624
13625        public void rememberWindowAttachCount() {
13626            mOriginalWindowAttachCount = mWindowAttachCount;
13627        }
13628    }
13629
13630    private final class CheckForTap implements Runnable {
13631        public void run() {
13632            mPrivateFlags &= ~PREPRESSED;
13633            mPrivateFlags |= PRESSED;
13634            refreshDrawableState();
13635            checkForLongClick(ViewConfiguration.getTapTimeout());
13636        }
13637    }
13638
13639    private final class PerformClick implements Runnable {
13640        public void run() {
13641            performClick();
13642        }
13643    }
13644
13645    /** @hide */
13646    public void hackTurnOffWindowResizeAnim(boolean off) {
13647        mAttachInfo.mTurnOffWindowResizeAnim = off;
13648    }
13649
13650    /**
13651     * This method returns a ViewPropertyAnimator object, which can be used to animate
13652     * specific properties on this View.
13653     *
13654     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
13655     */
13656    public ViewPropertyAnimator animate() {
13657        if (mAnimator == null) {
13658            mAnimator = new ViewPropertyAnimator(this);
13659        }
13660        return mAnimator;
13661    }
13662
13663    /**
13664     * Interface definition for a callback to be invoked when a key event is
13665     * dispatched to this view. The callback will be invoked before the key
13666     * event is given to the view.
13667     */
13668    public interface OnKeyListener {
13669        /**
13670         * Called when a key is dispatched to a view. This allows listeners to
13671         * get a chance to respond before the target view.
13672         *
13673         * @param v The view the key has been dispatched to.
13674         * @param keyCode The code for the physical key that was pressed
13675         * @param event The KeyEvent object containing full information about
13676         *        the event.
13677         * @return True if the listener has consumed the event, false otherwise.
13678         */
13679        boolean onKey(View v, int keyCode, KeyEvent event);
13680    }
13681
13682    /**
13683     * Interface definition for a callback to be invoked when a touch event is
13684     * dispatched to this view. The callback will be invoked before the touch
13685     * event is given to the view.
13686     */
13687    public interface OnTouchListener {
13688        /**
13689         * Called when a touch event is dispatched to a view. This allows listeners to
13690         * get a chance to respond before the target view.
13691         *
13692         * @param v The view the touch event has been dispatched to.
13693         * @param event The MotionEvent object containing full information about
13694         *        the event.
13695         * @return True if the listener has consumed the event, false otherwise.
13696         */
13697        boolean onTouch(View v, MotionEvent event);
13698    }
13699
13700    /**
13701     * Interface definition for a callback to be invoked when a hover event is
13702     * dispatched to this view. The callback will be invoked before the hover
13703     * event is given to the view.
13704     */
13705    public interface OnHoverListener {
13706        /**
13707         * Called when a hover event is dispatched to a view. This allows listeners to
13708         * get a chance to respond before the target view.
13709         *
13710         * @param v The view the hover event has been dispatched to.
13711         * @param event The MotionEvent object containing full information about
13712         *        the event.
13713         * @return True if the listener has consumed the event, false otherwise.
13714         */
13715        boolean onHover(View v, MotionEvent event);
13716    }
13717
13718    /**
13719     * Interface definition for a callback to be invoked when a generic motion event is
13720     * dispatched to this view. The callback will be invoked before the generic motion
13721     * event is given to the view.
13722     */
13723    public interface OnGenericMotionListener {
13724        /**
13725         * Called when a generic motion event is dispatched to a view. This allows listeners to
13726         * get a chance to respond before the target view.
13727         *
13728         * @param v The view the generic motion event has been dispatched to.
13729         * @param event The MotionEvent object containing full information about
13730         *        the event.
13731         * @return True if the listener has consumed the event, false otherwise.
13732         */
13733        boolean onGenericMotion(View v, MotionEvent event);
13734    }
13735
13736    /**
13737     * Interface definition for a callback to be invoked when a view has been clicked and held.
13738     */
13739    public interface OnLongClickListener {
13740        /**
13741         * Called when a view has been clicked and held.
13742         *
13743         * @param v The view that was clicked and held.
13744         *
13745         * @return true if the callback consumed the long click, false otherwise.
13746         */
13747        boolean onLongClick(View v);
13748    }
13749
13750    /**
13751     * Interface definition for a callback to be invoked when a drag is being dispatched
13752     * to this view.  The callback will be invoked before the hosting view's own
13753     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
13754     * onDrag(event) behavior, it should return 'false' from this callback.
13755     */
13756    public interface OnDragListener {
13757        /**
13758         * Called when a drag event is dispatched to a view. This allows listeners
13759         * to get a chance to override base View behavior.
13760         *
13761         * @param v The View that received the drag event.
13762         * @param event The {@link android.view.DragEvent} object for the drag event.
13763         * @return {@code true} if the drag event was handled successfully, or {@code false}
13764         * if the drag event was not handled. Note that {@code false} will trigger the View
13765         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
13766         */
13767        boolean onDrag(View v, DragEvent event);
13768    }
13769
13770    /**
13771     * Interface definition for a callback to be invoked when the focus state of
13772     * a view changed.
13773     */
13774    public interface OnFocusChangeListener {
13775        /**
13776         * Called when the focus state of a view has changed.
13777         *
13778         * @param v The view whose state has changed.
13779         * @param hasFocus The new focus state of v.
13780         */
13781        void onFocusChange(View v, boolean hasFocus);
13782    }
13783
13784    /**
13785     * Interface definition for a callback to be invoked when a view is clicked.
13786     */
13787    public interface OnClickListener {
13788        /**
13789         * Called when a view has been clicked.
13790         *
13791         * @param v The view that was clicked.
13792         */
13793        void onClick(View v);
13794    }
13795
13796    /**
13797     * Interface definition for a callback to be invoked when the context menu
13798     * for this view is being built.
13799     */
13800    public interface OnCreateContextMenuListener {
13801        /**
13802         * Called when the context menu for this view is being built. It is not
13803         * safe to hold onto the menu after this method returns.
13804         *
13805         * @param menu The context menu that is being built
13806         * @param v The view for which the context menu is being built
13807         * @param menuInfo Extra information about the item for which the
13808         *            context menu should be shown. This information will vary
13809         *            depending on the class of v.
13810         */
13811        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
13812    }
13813
13814    /**
13815     * Interface definition for a callback to be invoked when the status bar changes
13816     * visibility.
13817     *
13818     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
13819     */
13820    public interface OnSystemUiVisibilityChangeListener {
13821        /**
13822         * Called when the status bar changes visibility because of a call to
13823         * {@link View#setSystemUiVisibility(int)}.
13824         *
13825         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13826         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13827         */
13828        public void onSystemUiVisibilityChange(int visibility);
13829    }
13830
13831    /**
13832     * Interface definition for a callback to be invoked when this view is attached
13833     * or detached from its window.
13834     */
13835    public interface OnAttachStateChangeListener {
13836        /**
13837         * Called when the view is attached to a window.
13838         * @param v The view that was attached
13839         */
13840        public void onViewAttachedToWindow(View v);
13841        /**
13842         * Called when the view is detached from a window.
13843         * @param v The view that was detached
13844         */
13845        public void onViewDetachedFromWindow(View v);
13846    }
13847
13848    private final class UnsetPressedState implements Runnable {
13849        public void run() {
13850            setPressed(false);
13851        }
13852    }
13853
13854    /**
13855     * Base class for derived classes that want to save and restore their own
13856     * state in {@link android.view.View#onSaveInstanceState()}.
13857     */
13858    public static class BaseSavedState extends AbsSavedState {
13859        /**
13860         * Constructor used when reading from a parcel. Reads the state of the superclass.
13861         *
13862         * @param source
13863         */
13864        public BaseSavedState(Parcel source) {
13865            super(source);
13866        }
13867
13868        /**
13869         * Constructor called by derived classes when creating their SavedState objects
13870         *
13871         * @param superState The state of the superclass of this view
13872         */
13873        public BaseSavedState(Parcelable superState) {
13874            super(superState);
13875        }
13876
13877        public static final Parcelable.Creator<BaseSavedState> CREATOR =
13878                new Parcelable.Creator<BaseSavedState>() {
13879            public BaseSavedState createFromParcel(Parcel in) {
13880                return new BaseSavedState(in);
13881            }
13882
13883            public BaseSavedState[] newArray(int size) {
13884                return new BaseSavedState[size];
13885            }
13886        };
13887    }
13888
13889    /**
13890     * A set of information given to a view when it is attached to its parent
13891     * window.
13892     */
13893    static class AttachInfo {
13894        interface Callbacks {
13895            void playSoundEffect(int effectId);
13896            boolean performHapticFeedback(int effectId, boolean always);
13897        }
13898
13899        /**
13900         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
13901         * to a Handler. This class contains the target (View) to invalidate and
13902         * the coordinates of the dirty rectangle.
13903         *
13904         * For performance purposes, this class also implements a pool of up to
13905         * POOL_LIMIT objects that get reused. This reduces memory allocations
13906         * whenever possible.
13907         */
13908        static class InvalidateInfo implements Poolable<InvalidateInfo> {
13909            private static final int POOL_LIMIT = 10;
13910            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
13911                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
13912                        public InvalidateInfo newInstance() {
13913                            return new InvalidateInfo();
13914                        }
13915
13916                        public void onAcquired(InvalidateInfo element) {
13917                        }
13918
13919                        public void onReleased(InvalidateInfo element) {
13920                            element.target = null;
13921                        }
13922                    }, POOL_LIMIT)
13923            );
13924
13925            private InvalidateInfo mNext;
13926            private boolean mIsPooled;
13927
13928            View target;
13929
13930            int left;
13931            int top;
13932            int right;
13933            int bottom;
13934
13935            public void setNextPoolable(InvalidateInfo element) {
13936                mNext = element;
13937            }
13938
13939            public InvalidateInfo getNextPoolable() {
13940                return mNext;
13941            }
13942
13943            static InvalidateInfo acquire() {
13944                return sPool.acquire();
13945            }
13946
13947            void release() {
13948                sPool.release(this);
13949            }
13950
13951            public boolean isPooled() {
13952                return mIsPooled;
13953            }
13954
13955            public void setPooled(boolean isPooled) {
13956                mIsPooled = isPooled;
13957            }
13958        }
13959
13960        final IWindowSession mSession;
13961
13962        final IWindow mWindow;
13963
13964        final IBinder mWindowToken;
13965
13966        final Callbacks mRootCallbacks;
13967
13968        HardwareCanvas mHardwareCanvas;
13969
13970        /**
13971         * The top view of the hierarchy.
13972         */
13973        View mRootView;
13974
13975        IBinder mPanelParentWindowToken;
13976        Surface mSurface;
13977
13978        boolean mHardwareAccelerated;
13979        boolean mHardwareAccelerationRequested;
13980        HardwareRenderer mHardwareRenderer;
13981
13982        /**
13983         * Scale factor used by the compatibility mode
13984         */
13985        float mApplicationScale;
13986
13987        /**
13988         * Indicates whether the application is in compatibility mode
13989         */
13990        boolean mScalingRequired;
13991
13992        /**
13993         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
13994         */
13995        boolean mTurnOffWindowResizeAnim;
13996
13997        /**
13998         * Left position of this view's window
13999         */
14000        int mWindowLeft;
14001
14002        /**
14003         * Top position of this view's window
14004         */
14005        int mWindowTop;
14006
14007        /**
14008         * Indicates whether views need to use 32-bit drawing caches
14009         */
14010        boolean mUse32BitDrawingCache;
14011
14012        /**
14013         * For windows that are full-screen but using insets to layout inside
14014         * of the screen decorations, these are the current insets for the
14015         * content of the window.
14016         */
14017        final Rect mContentInsets = new Rect();
14018
14019        /**
14020         * For windows that are full-screen but using insets to layout inside
14021         * of the screen decorations, these are the current insets for the
14022         * actual visible parts of the window.
14023         */
14024        final Rect mVisibleInsets = new Rect();
14025
14026        /**
14027         * The internal insets given by this window.  This value is
14028         * supplied by the client (through
14029         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14030         * be given to the window manager when changed to be used in laying
14031         * out windows behind it.
14032         */
14033        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14034                = new ViewTreeObserver.InternalInsetsInfo();
14035
14036        /**
14037         * All views in the window's hierarchy that serve as scroll containers,
14038         * used to determine if the window can be resized or must be panned
14039         * to adjust for a soft input area.
14040         */
14041        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14042
14043        final KeyEvent.DispatcherState mKeyDispatchState
14044                = new KeyEvent.DispatcherState();
14045
14046        /**
14047         * Indicates whether the view's window currently has the focus.
14048         */
14049        boolean mHasWindowFocus;
14050
14051        /**
14052         * The current visibility of the window.
14053         */
14054        int mWindowVisibility;
14055
14056        /**
14057         * Indicates the time at which drawing started to occur.
14058         */
14059        long mDrawingTime;
14060
14061        /**
14062         * Indicates whether or not ignoring the DIRTY_MASK flags.
14063         */
14064        boolean mIgnoreDirtyState;
14065
14066        /**
14067         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14068         * to avoid clearing that flag prematurely.
14069         */
14070        boolean mSetIgnoreDirtyState = false;
14071
14072        /**
14073         * Indicates whether the view's window is currently in touch mode.
14074         */
14075        boolean mInTouchMode;
14076
14077        /**
14078         * Indicates that ViewAncestor should trigger a global layout change
14079         * the next time it performs a traversal
14080         */
14081        boolean mRecomputeGlobalAttributes;
14082
14083        /**
14084         * Set during a traveral if any views want to keep the screen on.
14085         */
14086        boolean mKeepScreenOn;
14087
14088        /**
14089         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14090         */
14091        int mSystemUiVisibility;
14092
14093        /**
14094         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14095         * attached.
14096         */
14097        boolean mHasSystemUiListeners;
14098
14099        /**
14100         * Set if the visibility of any views has changed.
14101         */
14102        boolean mViewVisibilityChanged;
14103
14104        /**
14105         * Set to true if a view has been scrolled.
14106         */
14107        boolean mViewScrollChanged;
14108
14109        /**
14110         * Global to the view hierarchy used as a temporary for dealing with
14111         * x/y points in the transparent region computations.
14112         */
14113        final int[] mTransparentLocation = new int[2];
14114
14115        /**
14116         * Global to the view hierarchy used as a temporary for dealing with
14117         * x/y points in the ViewGroup.invalidateChild implementation.
14118         */
14119        final int[] mInvalidateChildLocation = new int[2];
14120
14121
14122        /**
14123         * Global to the view hierarchy used as a temporary for dealing with
14124         * x/y location when view is transformed.
14125         */
14126        final float[] mTmpTransformLocation = new float[2];
14127
14128        /**
14129         * The view tree observer used to dispatch global events like
14130         * layout, pre-draw, touch mode change, etc.
14131         */
14132        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14133
14134        /**
14135         * A Canvas used by the view hierarchy to perform bitmap caching.
14136         */
14137        Canvas mCanvas;
14138
14139        /**
14140         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14141         * handler can be used to pump events in the UI events queue.
14142         */
14143        final Handler mHandler;
14144
14145        /**
14146         * Identifier for messages requesting the view to be invalidated.
14147         * Such messages should be sent to {@link #mHandler}.
14148         */
14149        static final int INVALIDATE_MSG = 0x1;
14150
14151        /**
14152         * Identifier for messages requesting the view to invalidate a region.
14153         * Such messages should be sent to {@link #mHandler}.
14154         */
14155        static final int INVALIDATE_RECT_MSG = 0x2;
14156
14157        /**
14158         * Temporary for use in computing invalidate rectangles while
14159         * calling up the hierarchy.
14160         */
14161        final Rect mTmpInvalRect = new Rect();
14162
14163        /**
14164         * Temporary for use in computing hit areas with transformed views
14165         */
14166        final RectF mTmpTransformRect = new RectF();
14167
14168        /**
14169         * Temporary list for use in collecting focusable descendents of a view.
14170         */
14171        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14172
14173        /**
14174         * The id of the window for accessibility purposes.
14175         */
14176        int mAccessibilityWindowId = View.NO_ID;
14177
14178        /**
14179         * Creates a new set of attachment information with the specified
14180         * events handler and thread.
14181         *
14182         * @param handler the events handler the view must use
14183         */
14184        AttachInfo(IWindowSession session, IWindow window,
14185                Handler handler, Callbacks effectPlayer) {
14186            mSession = session;
14187            mWindow = window;
14188            mWindowToken = window.asBinder();
14189            mHandler = handler;
14190            mRootCallbacks = effectPlayer;
14191        }
14192    }
14193
14194    /**
14195     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14196     * is supported. This avoids keeping too many unused fields in most
14197     * instances of View.</p>
14198     */
14199    private static class ScrollabilityCache implements Runnable {
14200
14201        /**
14202         * Scrollbars are not visible
14203         */
14204        public static final int OFF = 0;
14205
14206        /**
14207         * Scrollbars are visible
14208         */
14209        public static final int ON = 1;
14210
14211        /**
14212         * Scrollbars are fading away
14213         */
14214        public static final int FADING = 2;
14215
14216        public boolean fadeScrollBars;
14217
14218        public int fadingEdgeLength;
14219        public int scrollBarDefaultDelayBeforeFade;
14220        public int scrollBarFadeDuration;
14221
14222        public int scrollBarSize;
14223        public ScrollBarDrawable scrollBar;
14224        public float[] interpolatorValues;
14225        public View host;
14226
14227        public final Paint paint;
14228        public final Matrix matrix;
14229        public Shader shader;
14230
14231        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14232
14233        private static final float[] OPAQUE = { 255 };
14234        private static final float[] TRANSPARENT = { 0.0f };
14235
14236        /**
14237         * When fading should start. This time moves into the future every time
14238         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14239         */
14240        public long fadeStartTime;
14241
14242
14243        /**
14244         * The current state of the scrollbars: ON, OFF, or FADING
14245         */
14246        public int state = OFF;
14247
14248        private int mLastColor;
14249
14250        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14251            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14252            scrollBarSize = configuration.getScaledScrollBarSize();
14253            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14254            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14255
14256            paint = new Paint();
14257            matrix = new Matrix();
14258            // use use a height of 1, and then wack the matrix each time we
14259            // actually use it.
14260            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14261
14262            paint.setShader(shader);
14263            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14264            this.host = host;
14265        }
14266
14267        public void setFadeColor(int color) {
14268            if (color != 0 && color != mLastColor) {
14269                mLastColor = color;
14270                color |= 0xFF000000;
14271
14272                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14273                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14274
14275                paint.setShader(shader);
14276                // Restore the default transfer mode (src_over)
14277                paint.setXfermode(null);
14278            }
14279        }
14280
14281        public void run() {
14282            long now = AnimationUtils.currentAnimationTimeMillis();
14283            if (now >= fadeStartTime) {
14284
14285                // the animation fades the scrollbars out by changing
14286                // the opacity (alpha) from fully opaque to fully
14287                // transparent
14288                int nextFrame = (int) now;
14289                int framesCount = 0;
14290
14291                Interpolator interpolator = scrollBarInterpolator;
14292
14293                // Start opaque
14294                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14295
14296                // End transparent
14297                nextFrame += scrollBarFadeDuration;
14298                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14299
14300                state = FADING;
14301
14302                // Kick off the fade animation
14303                host.invalidate(true);
14304            }
14305        }
14306    }
14307
14308    /**
14309     * Resuable callback for sending
14310     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14311     */
14312    private class SendViewScrolledAccessibilityEvent implements Runnable {
14313        public volatile boolean mIsPending;
14314
14315        public void run() {
14316            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14317            mIsPending = false;
14318        }
14319    }
14320}
14321